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
4,935
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models from odoo.tests.common import TransactionCase from ..models.mis_kpi_data import ACC_AVG, ACC_SUM from .common import setup_test_model, teardown_test_model class TestKpiData(TransactionCase): class MisKpiDataTestItem(models.Model): _name = "mis.kpi.data.test.item" _inherit = "mis.kpi.data" _description = "MIS Kpi Data test item" @classmethod def setUpClass(cls): super().setUpClass() setup_test_model(cls.env, cls.MisKpiDataTestItem) report = cls.env["mis.report"].create(dict(name="test report")) cls.kpi1 = cls.env["mis.report.kpi"].create( dict( report_id=report.id, name="k1", description="kpi 1", expression="AccountingNone", ) ) cls.expr1 = cls.kpi1.expression_ids[0] cls.kpi2 = cls.env["mis.report.kpi"].create( dict( report_id=report.id, name="k2", description="kpi 2", expression="AccountingNone", ) ) cls.expr2 = cls.kpi2.expression_ids[0] cls.kd11 = cls.env["mis.kpi.data.test.item"].create( dict( kpi_expression_id=cls.expr1.id, date_from="2017-05-01", date_to="2017-05-10", amount=10, ) ) cls.kd12 = cls.env["mis.kpi.data.test.item"].create( dict( kpi_expression_id=cls.expr1.id, date_from="2017-05-11", date_to="2017-05-20", amount=20, ) ) cls.kd13 = cls.env["mis.kpi.data.test.item"].create( dict( kpi_expression_id=cls.expr1.id, date_from="2017-05-21", date_to="2017-05-25", amount=30, ) ) cls.kd21 = cls.env["mis.kpi.data.test.item"].create( dict( kpi_expression_id=cls.expr2.id, date_from="2017-06-01", date_to="2017-06-30", amount=3, ) ) @classmethod def tearDownClass(cls): teardown_test_model(cls.env, cls.MisKpiDataTestItem) return super().tearDownClass() def test_kpi_data_name(self): self.assertEqual(self.kd11.name, "k1: 2017-05-01 - 2017-05-10") self.assertEqual(self.kd12.name, "k1: 2017-05-11 - 2017-05-20") def test_kpi_data_sum(self): self.assertEqual(self.kpi1.accumulation_method, ACC_SUM) # one full r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-01", "2017-05-10", [] ) self.assertEqual(r, {self.expr1: 10}) # one half r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-01", "2017-05-05", [] ) self.assertEqual(r, {self.expr1: 5}) # two full r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-01", "2017-05-20", [] ) self.assertEqual(r, {self.expr1: 30}) # two half r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-06", "2017-05-15", [] ) self.assertEqual(r, {self.expr1: 15}) # more than covered range r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-01-01", "2017-05-31", [] ) self.assertEqual(r, {self.expr1: 60}) # two kpis r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-21", "2017-06-30", [] ) self.assertEqual(r, {self.expr1: 30, self.expr2: 3}) def test_kpi_data_avg(self): self.kpi1.accumulation_method = ACC_AVG # one full r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-01", "2017-05-10", [] ) self.assertEqual(r, {self.expr1: 10}) # one half r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-01", "2017-05-05", [] ) self.assertEqual(r, {self.expr1: 10}) # two full r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-01", "2017-05-20", [] ) self.assertEqual(r, {self.expr1: (10 * 10 + 20 * 10) / 20}) # two half r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-05-06", "2017-05-15", [] ) self.assertEqual(r, {self.expr1: (10 * 5 + 20 * 5) / 10}) # more than covered range r = self.env["mis.kpi.data.test.item"]._query_kpi_data( "2017-01-01", "2017-05-31", [] ) self.assertEqual(r, {self.expr1: (10 * 10 + 20 * 10 + 30 * 5) / 25})
34.51049
4,935
7,602
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from ..models.accounting_none import AccountingNone from ..models.mis_report import CMP_DIFF from ..models.mis_report_instance import ( MODE_NONE, SRC_ACTUALS_ALT, SRC_CMPCOL, SRC_SUMCOL, ) from .common import assert_matrix class TestMisReportInstanceDataSources(common.TransactionCase): """Test sum and comparison data source.""" def _create_move(self, date, amount, debit_acc, credit_acc): move = self.move_model.create( { "journal_id": self.journal.id, "date": date, "line_ids": [ (0, 0, {"name": "/", "debit": amount, "account_id": debit_acc.id}), ( 0, 0, {"name": "/", "credit": amount, "account_id": credit_acc.id}, ), ], } ) move._post() return move def setUp(self): super().setUp() self.account_model = self.env["account.account"] self.move_model = self.env["account.move"] self.journal_model = self.env["account.journal"] # create receivable bs account type_ar = self.browse_ref("account.data_account_type_receivable") self.account_ar = self.account_model.create( { "company_id": self.env.user.company_id.id, "code": "400AR", "name": "Receivable", "user_type_id": type_ar.id, "reconcile": True, } ) # create income account type_in = self.browse_ref("account.data_account_type_revenue") self.account_in = self.account_model.create( { "company_id": self.env.user.company_id.id, "code": "700IN", "name": "Income", "user_type_id": type_in.id, } ) self.account_in2 = self.account_model.create( { "company_id": self.env.user.company_id.id, "code": "700IN2", "name": "Income", "user_type_id": type_in.id, } ) # create journal self.journal = self.journal_model.create( { "company_id": self.env.user.company_id.id, "name": "Sale journal", "code": "VEN", "type": "sale", } ) # create move self._create_move( date="2017-01-01", amount=11, debit_acc=self.account_ar, credit_acc=self.account_in, ) # create move self._create_move( date="2017-02-01", amount=13, debit_acc=self.account_ar, credit_acc=self.account_in, ) self._create_move( date="2017-02-01", amount=17, debit_acc=self.account_ar, credit_acc=self.account_in2, ) # create report self.report = self.env["mis.report"].create(dict(name="test report")) self.kpi1 = self.env["mis.report.kpi"].create( dict( report_id=self.report.id, name="k1", description="kpi 1", expression="-balp[700IN]", compare_method=CMP_DIFF, ) ) self.expr1 = self.kpi1.expression_ids[0] self.kpi2 = self.env["mis.report.kpi"].create( dict( report_id=self.report.id, name="k2", description="kpi 2", expression="-balp[700%]", compare_method=CMP_DIFF, auto_expand_accounts=True, ) ) self.instance = self.env["mis.report.instance"].create( dict(name="test instance", report_id=self.report.id, comparison_mode=True) ) self.p1 = self.env["mis.report.instance.period"].create( dict( name="p1", report_instance_id=self.instance.id, manual_date_from="2017-01-01", manual_date_to="2017-01-31", ) ) self.p2 = self.env["mis.report.instance.period"].create( dict( name="p2", report_instance_id=self.instance.id, manual_date_from="2017-02-01", manual_date_to="2017-02-28", ) ) def test_sum(self): self.psum = self.env["mis.report.instance.period"].create( dict( name="psum", report_instance_id=self.instance.id, mode=MODE_NONE, source=SRC_SUMCOL, source_sumcol_ids=[ (0, 0, dict(period_to_sum_id=self.p1.id, sign="+")), (0, 0, dict(period_to_sum_id=self.p2.id, sign="+")), ], ) ) matrix = self.instance._compute_matrix() # None in last col because account details are not summed by default assert_matrix( matrix, [ [11, 13, 24], [11, 30, 41], [11, 13, AccountingNone], [AccountingNone, 17, AccountingNone], ], ) def test_sum_diff(self): self.psum = self.env["mis.report.instance.period"].create( dict( name="psum", report_instance_id=self.instance.id, mode=MODE_NONE, source=SRC_SUMCOL, source_sumcol_ids=[ (0, 0, dict(period_to_sum_id=self.p1.id, sign="+")), (0, 0, dict(period_to_sum_id=self.p2.id, sign="-")), ], source_sumcol_accdet=True, ) ) matrix = self.instance._compute_matrix() assert_matrix( matrix, [[11, 13, -2], [11, 30, -19], [11, 13, -2], [AccountingNone, 17, -17]], ) def test_cmp(self): self.pcmp = self.env["mis.report.instance.period"].create( dict( name="pcmp", report_instance_id=self.instance.id, mode=MODE_NONE, source=SRC_CMPCOL, source_cmpcol_from_id=self.p1.id, source_cmpcol_to_id=self.p2.id, ) ) matrix = self.instance._compute_matrix() assert_matrix( matrix, [[11, 13, 2], [11, 30, 19], [11, 13, 2], [AccountingNone, 17, 17]] ) def test_actuals(self): matrix = self.instance._compute_matrix() assert_matrix(matrix, [[11, 13], [11, 30], [11, 13], [AccountingNone, 17]]) def test_actuals_disable_auto_expand_accounts(self): self.instance.no_auto_expand_accounts = True matrix = self.instance._compute_matrix() assert_matrix(matrix, [[11, 13], [11, 30]]) def test_actuals_alt(self): aml_model = self.env["ir.model"].search([("name", "=", "account.move.line")]) self.kpi2.auto_expand_accounts = False self.p1.source = SRC_ACTUALS_ALT self.p1.source_aml_model_id = aml_model.id self.p2.source = SRC_ACTUALS_ALT self.p1.source_aml_model_id = aml_model.id matrix = self.instance._compute_matrix() assert_matrix(matrix, [[11, 13], [11, 30]])
34.39819
7,602
6,486
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from odoo import fields from ..models.mis_report_instance import ( MODE_FIX, MODE_NONE, MODE_REL, SRC_SUMCOL, DateFilterForbidden, DateFilterRequired, ) from .common import assert_matrix class TestPeriodDates(common.TransactionCase): def setUp(self): super().setUp() self.report_obj = self.env["mis.report"] self.instance_obj = self.env["mis.report.instance"] self.period_obj = self.env["mis.report.instance.period"] self.report = self.report_obj.create(dict(name="test-report")) self.instance = self.instance_obj.create( dict(name="test-instance", report_id=self.report.id, comparison_mode=False) ) self.assertEqual(len(self.instance.period_ids), 1) self.period = self.instance.period_ids[0] def assertDateEqual(self, first, second, msg=None): self.assertEqual(first, fields.Date.from_string(second), msg) def test_date_filter_constraints(self): self.instance.comparison_mode = True with self.assertRaises(DateFilterRequired): self.period.write(dict(mode=MODE_NONE)) with self.assertRaises(DateFilterForbidden): self.period.write(dict(mode=MODE_FIX, source=SRC_SUMCOL)) def test_simple_mode(self): # not comparison_mode self.assertFalse(self.instance.comparison_mode) period = self.instance.period_ids[0] self.assertEqual(period.date_from, self.instance.date_from) self.assertEqual(period.date_to, self.instance.date_to) def tests_mode_none(self): self.instance.comparison_mode = True self.period.write(dict(mode=MODE_NONE, source=SRC_SUMCOL)) self.assertFalse(self.period.date_from) self.assertFalse(self.period.date_to) self.assertTrue(self.period.valid) def tests_mode_fix(self): self.instance.comparison_mode = True self.period.write( dict( mode=MODE_FIX, manual_date_from="2017-01-01", manual_date_to="2017-12-31", ) ) self.assertDateEqual(self.period.date_from, "2017-01-01") self.assertDateEqual(self.period.date_to, "2017-12-31") self.assertTrue(self.period.valid) def test_rel_day(self): self.instance.write(dict(comparison_mode=True, date="2017-01-01")) self.period.write(dict(mode=MODE_REL, type="d", offset="-2")) self.assertDateEqual(self.period.date_from, "2016-12-30") self.assertDateEqual(self.period.date_to, "2016-12-30") self.assertTrue(self.period.valid) def test_rel_day_ytd(self): self.instance.write(dict(comparison_mode=True, date="2019-05-03")) self.period.write(dict(mode=MODE_REL, type="d", offset="-2", is_ytd=True)) self.assertDateEqual(self.period.date_from, "2019-01-01") self.assertDateEqual(self.period.date_to, "2019-05-01") self.assertTrue(self.period.valid) def test_rel_week(self): self.instance.write(dict(comparison_mode=True, date="2016-12-30")) self.period.write(dict(mode=MODE_REL, type="w", offset="1", duration=2)) # from Monday to Sunday, the week after 2016-12-30 self.assertDateEqual(self.period.date_from, "2017-01-02") self.assertDateEqual(self.period.date_to, "2017-01-15") self.assertTrue(self.period.valid) def test_rel_week_ytd(self): self.instance.write(dict(comparison_mode=True, date="2019-05-27")) self.period.write( dict(mode=MODE_REL, type="w", offset="1", duration=2, is_ytd=True) ) self.assertDateEqual(self.period.date_from, "2019-01-01") self.assertDateEqual(self.period.date_to, "2019-06-16") self.assertTrue(self.period.valid) def test_rel_month(self): self.instance.write(dict(comparison_mode=True, date="2017-01-05")) self.period.write(dict(mode=MODE_REL, type="m", offset="1")) self.assertDateEqual(self.period.date_from, "2017-02-01") self.assertDateEqual(self.period.date_to, "2017-02-28") self.assertTrue(self.period.valid) def test_rel_month_ytd(self): self.instance.write(dict(comparison_mode=True, date="2019-05-15")) self.period.write(dict(mode=MODE_REL, type="m", offset="-1", is_ytd=True)) self.assertDateEqual(self.period.date_from, "2019-01-01") self.assertDateEqual(self.period.date_to, "2019-04-30") self.assertTrue(self.period.valid) def test_rel_year(self): self.instance.write(dict(comparison_mode=True, date="2017-05-06")) self.period.write(dict(mode=MODE_REL, type="y", offset="1")) self.assertDateEqual(self.period.date_from, "2018-01-01") self.assertDateEqual(self.period.date_to, "2018-12-31") self.assertTrue(self.period.valid) def test_rel_date_range(self): # create a few date ranges date_range_type = self.env["date.range.type"].create(dict(name="Year")) for year in (2016, 2017, 2018): self.env["date.range"].create( dict( type_id=date_range_type.id, name="%d" % year, date_start="%d-01-01" % year, date_end="%d-12-31" % year, company_id=False, ) ) self.instance.write(dict(comparison_mode=True, date="2017-06-15")) self.period.write( dict( mode=MODE_REL, type="date_range", date_range_type_id=date_range_type.id, offset="-1", duration=3, ) ) self.assertDateEqual(self.period.date_from, "2016-01-01") self.assertDateEqual(self.period.date_to, "2018-12-31") self.assertTrue(self.period.valid) def test_dates_in_expr(self): self.env["mis.report.kpi"].create( dict( report_id=self.report.id, name="k1", description="kpi 1", expression="(date_to - date_from).days + 1", ) ) self.instance.date_from = "2017-01-01" self.instance.date_to = "2017-01-31" matrix = self.instance._compute_matrix() assert_matrix(matrix, [[31]])
40.792453
6,486
22,152
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from odoo.tools import test_reports from ..models.accounting_none import AccountingNone from ..models.mis_report import TYPE_STR, SubKPITupleLengthError, SubKPIUnknownTypeError class TestMisReportInstance(common.HttpCase): """Basic integration test to exercise mis.report.instance. We don't check the actual results here too much as computation correctness should be covered by lower level unit tests. """ def setUp(self): super().setUp() partner_model_id = self.env.ref("base.model_res_partner").id partner_create_date_field_id = self.env.ref( "base.field_res_partner__create_date" ).id partner_debit_field_id = self.env.ref("account.field_res_partner__debit").id # create a report with 2 subkpis and one query self.report = self.env["mis.report"].create( dict( name="test report", subkpi_ids=[ (0, 0, dict(name="sk1", description="subkpi 1", sequence=1)), (0, 0, dict(name="sk2", description="subkpi 2", sequence=2)), ], query_ids=[ ( 0, 0, dict( name="partner", model_id=partner_model_id, field_ids=[(4, partner_debit_field_id, None)], date_field=partner_create_date_field_id, aggregate="sum", ), ) ], ) ) # create another report with 2 subkpis, no query self.report_2 = self.env["mis.report"].create( dict( name="another test report", subkpi_ids=[ ( 0, 0, dict( name="subkpi1_report2", description="subkpi 1, report 2", sequence=1, ), ), ( 0, 0, dict( name="subkpi2_report2", description="subkpi 2, report 2", sequence=2, ), ), ], ) ) # Third report, 2 subkpis, no query self.report_3 = self.env["mis.report"].create( dict( name="test report 3", subkpi_ids=[ ( 0, 0, dict( name="subkpi1_report3", description="subkpi 1, report 3", sequence=1, ), ), ( 0, 0, dict( name="subkpi2_report3", description="subkpi 2, report 3", sequence=2, ), ), ], ) ) # kpi with accounting formulas self.kpi1 = self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 1", name="k1", multi=True, expression_ids=[ ( 0, 0, dict(name="bale[200%]", subkpi_id=self.report.subkpi_ids[0].id), ), ( 0, 0, dict(name="balp[200%]", subkpi_id=self.report.subkpi_ids[1].id), ), ], ) ) # kpi with accounting formula and query self.kpi2 = self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 2", name="k2", multi=True, expression_ids=[ ( 0, 0, dict(name="balp[200%]", subkpi_id=self.report.subkpi_ids[0].id), ), ( 0, 0, dict( name="partner.debit", subkpi_id=self.report.subkpi_ids[1].id ), ), ], ) ) # kpi with a simple expression summing other multi-valued kpis self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 4", name="k4", multi=False, expression="k1 + k2 + k3", ) ) # kpi with 2 constants self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 3", name="k3", multi=True, expression_ids=[ ( 0, 0, dict( name="AccountingNone", subkpi_id=self.report.subkpi_ids[0].id, ), ), (0, 0, dict(name="1.0", subkpi_id=self.report.subkpi_ids[1].id)), ], ) ) # kpi with a NameError (x not defined) self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 5", name="k5", multi=True, expression_ids=[ (0, 0, dict(name="x", subkpi_id=self.report.subkpi_ids[0].id)), (0, 0, dict(name="1.0", subkpi_id=self.report.subkpi_ids[1].id)), ], ) ) # string-type kpi self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 6", name="k6", multi=True, type=TYPE_STR, expression_ids=[ (0, 0, dict(name='"bla"', subkpi_id=self.report.subkpi_ids[0].id)), ( 0, 0, dict(name='"blabla"', subkpi_id=self.report.subkpi_ids[1].id), ), ], ) ) # kpi that references another subkpi by name self.env["mis.report.kpi"].create( dict( report_id=self.report.id, description="kpi 7", name="k7", multi=True, expression_ids=[ (0, 0, dict(name="k3.sk1", subkpi_id=self.report.subkpi_ids[0].id)), (0, 0, dict(name="k3.sk2", subkpi_id=self.report.subkpi_ids[1].id)), ], ) ) # Report 2 : kpi with AccountingNone value self.env["mis.report.kpi"].create( dict( report_id=self.report_2.id, description="AccountingNone kpi", name="AccountingNoneKPI", multi=False, ) ) # Report 2 : 'classic' kpi with values for each sub-KPI self.env["mis.report.kpi"].create( dict( report_id=self.report_2.id, description="Classic kpi", name="classic_kpi_r2", multi=True, expression_ids=[ ( 0, 0, dict( name="bale[200%]", subkpi_id=self.report_2.subkpi_ids[0].id ), ), ( 0, 0, dict( name="balp[200%]", subkpi_id=self.report_2.subkpi_ids[1].id ), ), ], ) ) # Report 3 : kpi with wrong tuple length self.env["mis.report.kpi"].create( dict( report_id=self.report_3.id, description="Wrong tuple length kpi", name="wrongTupleLen", multi=False, expression="('hello', 'does', 'this', 'work')", ) ) # Report 3 : 'classic' kpi self.env["mis.report.kpi"].create( dict( report_id=self.report_3.id, description="Classic kpi", name="classic_kpi_r2", multi=True, expression_ids=[ ( 0, 0, dict( name="bale[200%]", subkpi_id=self.report_3.subkpi_ids[0].id ), ), ( 0, 0, dict( name="balp[200%]", subkpi_id=self.report_3.subkpi_ids[1].id ), ), ], ) ) # create a report instance self.report_instance = self.env["mis.report.instance"].create( dict( name="test instance", report_id=self.report.id, company_id=self.env.ref("base.main_company").id, period_ids=[ ( 0, 0, dict( name="p1", mode="relative", type="d", subkpi_ids=[(4, self.report.subkpi_ids[0].id, None)], ), ), ( 0, 0, dict( name="p2", mode="fix", manual_date_from="2014-01-01", manual_date_to="2014-12-31", ), ), ], ) ) # same for report 2 self.report_instance_2 = self.env["mis.report.instance"].create( dict( name="test instance 2", report_id=self.report_2.id, company_id=self.env.ref("base.main_company").id, period_ids=[ ( 0, 0, dict( name="p3", mode="fix", manual_date_from="2019-01-01", manual_date_to="2019-12-31", ), ) ], ) ) # and for report 3 self.report_instance_3 = self.env["mis.report.instance"].create( dict( name="test instance 3", report_id=self.report_3.id, company_id=self.env.ref("base.main_company").id, period_ids=[ ( 0, 0, dict( name="p4", mode="fix", manual_date_from="2019-01-01", manual_date_to="2019-12-31", ), ) ], ) ) def test_compute(self): matrix = self.report_instance._compute_matrix() for row in matrix.iter_rows(): vals = [c.val for c in row.iter_cells()] if row.kpi.name == "k3": # k3 is constant self.assertEqual(vals, [AccountingNone, AccountingNone, 1.0]) elif row.kpi.name == "k6": # k6 is a string kpi self.assertEqual(vals, ["bla", "bla", "blabla"]) elif row.kpi.name == "k7": # k7 references k3 via subkpi names self.assertEqual(vals, [AccountingNone, AccountingNone, 1.0]) def test_multi_company_compute(self): self.report_instance.write( { "multi_company": True, "company_ids": [(6, 0, self.report_instance.company_id.ids)], } ) self.report_instance.report_id.kpi_ids.write({"auto_expand_accounts": True}) matrix = self.report_instance._compute_matrix() for row in matrix.iter_rows(): if row.account_id: account = self.env["account.account"].browse(row.account_id) self.assertEqual( row.label, "%s %s [%s]" % (account.code, account.name, account.company_id.name), ) self.report_instance.write({"multi_company": False}) matrix = self.report_instance._compute_matrix() for row in matrix.iter_rows(): if row.account_id: account = self.env["account.account"].browse(row.account_id) self.assertEqual(row.label, "{} {}".format(account.code, account.name)) def test_evaluate(self): company = self.env.ref("base.main_company") aep = self.report._prepare_aep(company) r = self.report.evaluate(aep, date_from="2014-01-01", date_to="2014-12-31") self.assertEqual(r["k3"], (AccountingNone, 1.0)) self.assertEqual(r["k6"], ("bla", "blabla")) self.assertEqual(r["k7"], (AccountingNone, 1.0)) def test_json(self): self.report_instance.compute() def test_drilldown(self): action = self.report_instance.drilldown( dict(expr="balp[200%]", period_id=self.report_instance.period_ids[0].id) ) account_ids = ( self.env["account.account"] .search( [ ("code", "=like", "200%"), ("company_id", "=", self.env.ref("base.main_company").id), ] ) .ids ) self.assertTrue(("account_id", "in", tuple(account_ids)) in action["domain"]) self.assertEqual(action["res_model"], "account.move.line") def test_drilldown_action_name_with_account(self): period = self.report_instance.period_ids[0] account = self.env["account.account"].search([], limit=1) args = { "period_id": period.id, "kpi_id": self.kpi1.id, "account_id": account.id, } action_name = self.report_instance._get_drilldown_action_name(args) expected_name = "{kpi} - {account} - {period}".format( kpi=self.kpi1.description, account=account.display_name, period=period.display_name, ) assert action_name == expected_name def test_drilldown_action_name_without_account(self): period = self.report_instance.period_ids[0] args = { "period_id": period.id, "kpi_id": self.kpi1.id, } action_name = self.report_instance._get_drilldown_action_name(args) expected_name = "{kpi} - {period}".format( kpi=self.kpi1.description, period=period.display_name, ) assert action_name == expected_name def test_qweb(self): self.report_instance.print_pdf() # get action test_reports.try_report( self.env.cr, self.env.uid, "mis_builder.report_mis_report_instance", [self.report_instance.id], report_type="qweb-pdf", ) def test_xlsx(self): self.report_instance.export_xls() # get action test_reports.try_report( self.env.cr, self.env.uid, "mis_builder.mis_report_instance_xlsx", [self.report_instance.id], report_type="xlsx", ) def test_get_kpis_by_account_id(self): account_ids = ( self.env["account.account"] .search( [ ("code", "=like", "200%"), ("company_id", "=", self.env.ref("base.main_company").id), ] ) .ids ) kpi200 = {self.kpi1, self.kpi2} res = self.report.get_kpis_by_account_id(self.env.ref("base.main_company")) for account_id in account_ids: self.assertTrue(account_id in res) self.assertEqual(res[account_id], kpi200) def test_kpi_name_get_name_search(self): r = self.env["mis.report.kpi"].name_search("k1") self.assertEqual(len(r), 1) self.assertEqual(r[0][0], self.kpi1.id) self.assertEqual(r[0][1], "kpi 1 (k1)") r = self.env["mis.report.kpi"].name_search("kpi 1") self.assertEqual(len(r), 1) self.assertEqual(r[0][0], self.kpi1.id) self.assertEqual(r[0][1], "kpi 1 (k1)") def test_kpi_expr_name_get_name_search(self): r = self.env["mis.report.kpi.expression"].name_search("k1") self.assertEqual( [i[1] for i in r], ["kpi 1 / subkpi 1 (k1.sk1)", "kpi 1 / subkpi 2 (k1.sk2)"], ) r = self.env["mis.report.kpi.expression"].name_search("k1.sk1") self.assertEqual([i[1] for i in r], ["kpi 1 / subkpi 1 (k1.sk1)"]) r = self.env["mis.report.kpi.expression"].name_search("k4") self.assertEqual([i[1] for i in r], ["kpi 4 (k4)"]) def test_query_company_ids(self): # sanity check single company mode assert not self.report_instance.multi_company assert self.report_instance.company_id assert self.report_instance.query_company_ids == self.report_instance.company_id # create a second company c1 = self.report_instance.company_id c2 = self.env["res.company"].create( dict( name="company 2", ) ) self.report_instance.write(dict(multi_company=True, company_id=False)) self.report_instance.company_ids |= c1 self.report_instance.company_ids |= c2 assert len(self.report_instance.company_ids) == 2 self.assertFalse(self.report_instance.query_company_ids - self.env.companies) # In a user context where there is only one company, ensure # query_company_ids only has one company too. assert ( self.report_instance.with_context( allowed_company_ids=(c1.id,) ).query_company_ids == c1 ) def test_multi_company_onchange(self): # not multi company self.assertTrue(self.report_instance.company_id) self.assertFalse(self.report_instance.multi_company) self.assertFalse(self.report_instance.company_ids) self.assertEqual( self.report_instance.query_company_ids[0], self.report_instance.company_id ) # create a child company self.env["res.company"].create( dict(name="company 2", parent_id=self.report_instance.company_id.id) ) self.report_instance.multi_company = True # multi company, company_ids not set self.assertEqual(self.report_instance.query_company_ids, self.env.companies) # set company_ids previous_company = self.report_instance.company_id self.report_instance._onchange_company() self.assertFalse(self.report_instance.company_id) self.assertTrue(self.report_instance.multi_company) self.assertEqual(self.report_instance.company_ids, previous_company) self.assertEqual(self.report_instance.query_company_ids, previous_company) # reset single company mode self.report_instance.multi_company = False self.report_instance._onchange_company() self.assertEqual( self.report_instance.query_company_ids[0], self.report_instance.company_id ) self.assertFalse(self.report_instance.company_ids) def test_mis_report_analytic_filters(self): # Check that matrix has no values when using a filter with a non # existing account matrix = self.report_instance.with_context( mis_report_filters={"analytic_account_id": {"value": 999}} )._compute_matrix() for row in matrix.iter_rows(): vals = [c.val for c in row.iter_cells()] if row.kpi.name == "k1": self.assertEqual(vals, [AccountingNone, AccountingNone, AccountingNone]) elif row.kpi.name == "k2": self.assertEqual(vals, [AccountingNone, AccountingNone, None]) elif row.kpi.name == "k4": self.assertEqual(vals, [AccountingNone, AccountingNone, 1.0]) def test_raise_when_unknown_kpi_value_type(self): with self.assertRaises(SubKPIUnknownTypeError): self.report_instance_2.compute() def test_raise_when_wrong_tuple_length_with_subkpis(self): with self.assertRaises(SubKPITupleLengthError): self.report_instance_3.compute() def test_unprivileged(self): test_user = common.new_test_user( self.env, "mis_you", groups="base.group_user,account.group_account_user" ) self.report_instance.with_user(test_user).compute()
37.292929
22,152
2,287
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import doctest from odoo.tests import BaseCase, tagged def setup_test_model(env, model_cls): model_cls._build_model(env.registry, env.cr) env.registry.setup_models(env.cr) env.registry.init_models( env.cr, [model_cls._name], dict(env.context, update_custom_fields=True) ) def teardown_test_model(env, model_cls): del env.registry.models[model_cls._name] env.registry.setup_models(env.cr) def _zip(iter1, iter2): i = 0 iter1 = iter(iter1) iter2 = iter(iter2) while True: i1 = next(iter1, None) i2 = next(iter2, None) if i1 is None and i2 is None: return yield i, i1, i2 i += 1 def assert_matrix(matrix, expected): for i, row, expected_row in _zip(matrix.iter_rows(), expected): if row is None and expected_row is not None: raise AssertionError("not enough rows") if row is not None and expected_row is None: raise AssertionError("too many rows") for j, cell, expected_val in _zip(row.iter_cells(), expected_row): assert ( cell and cell.val ) == expected_val, "{} != {} in row {} col {}".format( cell and cell.val, expected_val, i, j ) @tagged("doctest") class OdooDocTestCase(BaseCase): """ We need a custom DocTestCase class in order to: - define test_tags to run as part of standard tests - output a more meaningful test name than default "DocTestCase.runTest" """ __qualname__ = "doctests for " def __init__(self, test): self.__test = test self.__name = test._dt_test.name super().__init__(self.__name) def __getattr__(self, item): if item == self.__name: return self.__test def load_doctests(module): """ Generates a tests loading method for the doctests of the given module https://docs.python.org/3/library/unittest.html#load-tests-protocol """ def load_tests(loader, tests, ignore): for test in doctest.DocTestSuite(module): tests.addTest(OdooDocTestCase(test)) return tests return load_tests
28.5875
2,287
232
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from ..models import simple_array from .common import load_doctests load_tests = load_doctests(simple_array)
33.142857
232
226
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from ..models import aggregate from .common import load_doctests load_tests = load_doctests(aggregate)
32.285714
226
12,095
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from ..models.accounting_none import AccountingNone from ..models.data_error import DataError from ..models.mis_report_style import CMP_DIFF, CMP_PCT, TYPE_NUM, TYPE_PCT, TYPE_STR class TestRendering(common.TransactionCase): def setUp(self): super().setUp() self.style_obj = self.env["mis.report.style"] self.kpi_obj = self.env["mis.report.kpi"] self.style = self.style_obj.create(dict(name="teststyle")) self.lang = ( self.env["res.lang"] .with_context(active_test=False) .search([("code", "=", "en_US")])[0] ) def _render(self, value, type=TYPE_NUM): style_props = self.style_obj.merge([self.style]) return self.style_obj.render(self.lang, style_props, type, value) def _compare_and_render( self, value, base_value, type=TYPE_NUM, compare_method=CMP_PCT ): style_props = self.style_obj.merge([self.style]) r = self.style_obj.compare_and_render( self.lang, style_props, type, compare_method, value, base_value )[:2] if r[0]: return (round(r[0], 8), r[1]) else: return r def test_render(self): self.assertEqual("1", self._render(1)) self.assertEqual("1", self._render(1.1)) self.assertEqual("2", self._render(1.6)) self.style.dp_inherit = False self.style.dp = 2 self.assertEqual("1.00", self._render(1)) self.assertEqual("1.10", self._render(1.1)) self.assertEqual("1.60", self._render(1.6)) self.assertEqual("1.61", self._render(1.606)) self.assertEqual("12,345.67", self._render(12345.67)) def test_render_negative(self): # non breaking hyphen self.assertEqual("\u20111", self._render(-1)) def test_render_zero(self): self.assertEqual("0", self._render(0)) self.assertEqual("", self._render(None)) self.assertEqual("", self._render(AccountingNone)) def test_render_suffix(self): self.style.suffix_inherit = False self.style.suffix = "€" self.assertEqual("1\xa0€", self._render(1)) self.style.suffix = "k€" self.style.divider_inherit = False self.style.divider = "1e3" self.assertEqual("1\xa0k€", self._render(1000)) def test_render_prefix(self): self.style.prefix_inherit = False self.style.prefix = "$" self.assertEqual("$\xa01", self._render(1)) self.style.prefix = "k$" self.style.divider_inherit = False self.style.divider = "1e3" self.assertEqual("k$\xa01", self._render(1000)) def test_render_divider(self): self.style.divider_inherit = False self.style.divider = "1e3" self.style.dp_inherit = False self.style.dp = 0 self.assertEqual("1", self._render(1000)) self.style.divider = "1e6" self.style.dp = 3 self.assertEqual("0.001", self._render(1000)) self.style.divider = "1e-3" self.style.dp = 0 self.assertEqual("1,000", self._render(1)) self.style.divider = "1e-6" self.style.dp = 0 self.assertEqual("1,000,000", self._render(1)) def test_render_pct(self): self.assertEqual("100\xa0%", self._render(1, TYPE_PCT)) self.assertEqual("50\xa0%", self._render(0.5, TYPE_PCT)) self.style.dp_inherit = False self.style.dp = 2 self.assertEqual("51.23\xa0%", self._render(0.5123, TYPE_PCT)) def test_render_string(self): self.assertEqual("", self._render("", TYPE_STR)) self.assertEqual("", self._render(None, TYPE_STR)) self.assertEqual("abcdé", self._render("abcdé", TYPE_STR)) def test_compare_num_pct(self): self.assertEqual((1.0, "+100.0\xa0%"), self._compare_and_render(100, 50)) self.assertEqual((0.5, "+50.0\xa0%"), self._compare_and_render(75, 50)) self.assertEqual((0.5, "+50.0\xa0%"), self._compare_and_render(-25, -50)) self.assertEqual((1.0, "+100.0\xa0%"), self._compare_and_render(0, -50)) self.assertEqual((2.0, "+200.0\xa0%"), self._compare_and_render(50, -50)) self.assertEqual((-0.5, "\u201150.0\xa0%"), self._compare_and_render(25, 50)) self.assertEqual((-1.0, "\u2011100.0\xa0%"), self._compare_and_render(0, 50)) self.assertEqual((-2.0, "\u2011200.0\xa0%"), self._compare_and_render(-50, 50)) self.assertEqual((-0.5, "\u201150.0\xa0%"), self._compare_and_render(-75, -50)) self.assertEqual( (AccountingNone, ""), self._compare_and_render(50, AccountingNone) ) self.assertEqual((AccountingNone, ""), self._compare_and_render(50, None)) self.assertEqual((AccountingNone, ""), self._compare_and_render(50, 50)) self.assertEqual((0.002, "+0.2\xa0%"), self._compare_and_render(50.1, 50)) self.assertEqual((AccountingNone, ""), self._compare_and_render(50.01, 50)) self.assertEqual( (-1.0, "\u2011100.0\xa0%"), self._compare_and_render(AccountingNone, 50) ) self.assertEqual((-1.0, "\u2011100.0\xa0%"), self._compare_and_render(None, 50)) self.assertEqual( (AccountingNone, ""), self._compare_and_render(DataError("#ERR", "."), 1) ) self.assertEqual( (AccountingNone, ""), self._compare_and_render(1, DataError("#ERR", ".")) ) def test_compare_num_diff(self): self.assertEqual( (25, "+25"), self._compare_and_render(75, 50, TYPE_NUM, CMP_DIFF) ) self.assertEqual( (-25, "\u201125"), self._compare_and_render(25, 50, TYPE_NUM, CMP_DIFF) ) self.style.suffix_inherit = False self.style.suffix = "€" self.assertEqual( (-25, "\u201125\xa0€"), self._compare_and_render(25, 50, TYPE_NUM, CMP_DIFF), ) self.style.suffix = "" self.assertEqual( (50.0, "+50"), self._compare_and_render(50, AccountingNone, TYPE_NUM, CMP_DIFF), ) self.assertEqual( (50.0, "+50"), self._compare_and_render(50, None, TYPE_NUM, CMP_DIFF) ) self.assertEqual( (-50.0, "\u201150"), self._compare_and_render(AccountingNone, 50, TYPE_NUM, CMP_DIFF), ) self.assertEqual( (-50.0, "\u201150"), self._compare_and_render(None, 50, TYPE_NUM, CMP_DIFF) ) self.style.dp_inherit = False self.style.dp = 2 self.assertEqual( (0.1, "+0.10"), self._compare_and_render(1.1, 1.0, TYPE_NUM, CMP_DIFF) ) self.assertEqual( (AccountingNone, ""), self._compare_and_render(1.001, 1.0, TYPE_NUM, CMP_DIFF), ) def test_compare_pct(self): self.assertEqual( (0.25, "+25\xa0pp"), self._compare_and_render(0.75, 0.50, TYPE_PCT) ) self.assertEqual( (AccountingNone, ""), self._compare_and_render(0.751, 0.750, TYPE_PCT) ) def test_compare_pct_result_type(self): style_props = self.style_obj.merge([self.style]) result = self.style_obj.compare_and_render( self.lang, style_props, TYPE_PCT, CMP_DIFF, 0.75, 0.50 ) self.assertEqual(result[3], TYPE_NUM) def test_merge(self): self.style.color = "#FF0000" self.style.color_inherit = False style_props = self.style_obj.merge([self.style]) self.assertEqual(style_props, {"color": "#FF0000"}) style_dict = {"color": "#00FF00", "dp": 0} style_props = self.style_obj.merge([self.style, style_dict]) self.assertEqual(style_props, {"color": "#00FF00", "dp": 0}) style2 = self.style_obj.create( dict( name="teststyle2", dp_inherit=False, dp=1, # color_inherit=True: will not be applied color="#0000FF", ) ) style_props = self.style_obj.merge([self.style, style_dict, style2]) self.assertEqual(style_props, {"color": "#00FF00", "dp": 1}) def test_css(self): self.style.color_inherit = False self.style.color = "#FF0000" self.style.background_color_inherit = False self.style.background_color = "#0000FF" self.style.suffix_inherit = False self.style.suffix = "s" self.style.prefix_inherit = False self.style.prefix = "p" self.style.font_style_inherit = False self.style.font_style = "italic" self.style.font_weight_inherit = False self.style.font_weight = "bold" self.style.font_size_inherit = False self.style.font_size = "small" self.style.indent_level_inherit = False self.style.indent_level = 2 style_props = self.style_obj.merge([self.style]) css = self.style_obj.to_css_style(style_props) self.assertEqual( css, "font-style: italic; " "font-weight: bold; " "font-size: small; " "color: #FF0000; " "background-color: #0000FF; " "text-indent: 2em", ) css = self.style_obj.to_css_style(style_props, no_indent=True) self.assertEqual( css, "font-style: italic; " "font-weight: bold; " "font-size: small; " "color: #FF0000; " "background-color: #0000FF", ) def test_xslx(self): self.style.color_inherit = False self.style.color = "#FF0000" self.style.background_color_inherit = False self.style.background_color = "#0000FF" self.style.suffix_inherit = False self.style.suffix = "s" self.style.prefix_inherit = False self.style.prefix = "p" self.style.dp_inherit = False self.style.dp = 2 self.style.font_style_inherit = False self.style.font_style = "italic" self.style.font_weight_inherit = False self.style.font_weight = "bold" self.style.font_size_inherit = False self.style.font_size = "small" self.style.indent_level_inherit = False self.style.indent_level = 2 style_props = self.style_obj.merge([self.style]) xlsx = self.style_obj.to_xlsx_style(TYPE_NUM, style_props) self.assertEqual( xlsx, { "italic": True, "bold": True, "size": 9, "font_color": "#FF0000", "bg_color": "#0000FF", "num_format": '"p "#,##0.00" s"', "indent": 2, }, ) xlsx = self.style_obj.to_xlsx_style(TYPE_NUM, style_props, no_indent=True) self.assertEqual( xlsx, { "italic": True, "bold": True, "size": 9, "font_color": "#FF0000", "bg_color": "#0000FF", "num_format": '"p "#,##0.00" s"', }, ) # percent type ignore prefix and suffix xlsx = self.style_obj.to_xlsx_style(TYPE_PCT, style_props, no_indent=True) self.assertEqual( xlsx, { "italic": True, "bold": True, "size": 9, "font_color": "#FF0000", "bg_color": "#0000FF", "num_format": "0.00%", }, ) # str type have no num_format style xlsx = self.style_obj.to_xlsx_style(TYPE_STR, style_props, no_indent=True) self.assertEqual( xlsx, { "italic": True, "bold": True, "size": 9, "font_color": "#FF0000", "bg_color": "#0000FF", }, )
38.352381
12,081
900
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from ..models.mis_safe_eval import DataError, NameDataError, mis_safe_eval class TestMisSafeEval(common.TransactionCase): def test_nominal(self): val = mis_safe_eval("a + 1", {"a": 1}) self.assertEqual(val, 2) def test_exceptions(self): val = mis_safe_eval("1/0", {}) # division by zero self.assertTrue(isinstance(val, DataError)) self.assertEqual(val.name, "#DIV/0") val = mis_safe_eval("1a", {}) # syntax error self.assertTrue(isinstance(val, DataError)) self.assertEqual(val.name, "#ERR") def test_name_error(self): val = mis_safe_eval("a + 1", {}) self.assertTrue(isinstance(val, NameDataError)) self.assertEqual(val.name, "#NAME")
36
900
1,296
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common class TestMisReportInstance(common.TransactionCase): def test_supports_target_move_filter(self): self.assertTrue( self.env["mis.report"]._supports_target_move_filter("account.move.line") ) def test_supports_target_move_filter_no_parent_state(self): self.assertFalse( self.env["mis.report"]._supports_target_move_filter("account.move") ) def test_target_move_domain_posted(self): self.assertEqual( self.env["mis.report"]._get_target_move_domain( "posted", "account.move.line" ), [("parent_state", "=", "posted")], ) def test_target_move_domain_all(self): self.assertEqual( self.env["mis.report"]._get_target_move_domain("all", "account.move.line"), [("parent_state", "in", ("posted", "draft"))], ) def test_target_move_domain_no_parent_state(self): """Test get_target_move_domain on a model that has no parent_state.""" self.assertEqual( self.env["mis.report"]._get_target_move_domain("all", "account.move"), [] )
36
1,296
15,832
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import datetime import time import odoo.tests.common as common from odoo import fields from odoo.tools.safe_eval import safe_eval from ..models.accounting_none import AccountingNone from ..models.aep import AccountingExpressionProcessor as AEP, _is_domain class TestAEP(common.TransactionCase): def setUp(self): super().setUp() self.res_company = self.env["res.company"] self.account_model = self.env["account.account"] self.move_model = self.env["account.move"] self.journal_model = self.env["account.journal"] self.curr_year = datetime.date.today().year self.prev_year = self.curr_year - 1 # create company self.company = self.res_company.create({"name": "AEP Company"}) # create receivable bs account type_ar = self.browse_ref("account.data_account_type_receivable") self.account_ar = self.account_model.create( { "company_id": self.company.id, "code": "400AR", "name": "Receivable", "user_type_id": type_ar.id, "reconcile": True, } ) # create income pl account type_in = self.browse_ref("account.data_account_type_revenue") self.account_in = self.account_model.create( { "company_id": self.company.id, "code": "700IN", "name": "Income", "user_type_id": type_in.id, } ) # create journal self.journal = self.journal_model.create( { "company_id": self.company.id, "name": "Sale journal", "code": "VEN", "type": "sale", } ) # create move in December last year self._create_move( date=datetime.date(self.prev_year, 12, 1), amount=100, debit_acc=self.account_ar, credit_acc=self.account_in, ) # create move in January this year self._create_move( date=datetime.date(self.curr_year, 1, 1), amount=300, debit_acc=self.account_ar, credit_acc=self.account_in, ) # create move in March this year self._create_move( date=datetime.date(self.curr_year, 3, 1), amount=500, debit_acc=self.account_ar, credit_acc=self.account_in, ) # create the AEP, and prepare the expressions we'll need self.aep = AEP(self.company) self.aep.parse_expr("bali[]") self.aep.parse_expr("bale[]") self.aep.parse_expr("balp[]") self.aep.parse_expr("balu[]") self.aep.parse_expr("bali[700IN]") self.aep.parse_expr("bale[700IN]") self.aep.parse_expr("balp[700IN]") self.aep.parse_expr("bali[400AR]") self.aep.parse_expr("bale[400AR]") self.aep.parse_expr("balp[400AR]") self.aep.parse_expr("debp[400A%]") self.aep.parse_expr("crdp[700I%]") self.aep.parse_expr("bali[400%]") self.aep.parse_expr("bale[700%]") self.aep.parse_expr("balp[]" "[('account_id.code', '=', '400AR')]") self.aep.parse_expr( "balp[]" "[('account_id.user_type_id', '=', " " ref('account.data_account_type_receivable').id)]" ) self.aep.parse_expr( "balp[('user_type_id', '=', " " ref('account.data_account_type_receivable').id)]" ) self.aep.parse_expr( "balp['&', " " ('user_type_id', '=', " " ref('account.data_account_type_receivable').id), " " ('code', '=', '400AR')]" ) self.aep.parse_expr("bal_700IN") # deprecated self.aep.parse_expr("bals[700IN]") # deprecated def _create_move(self, date, amount, debit_acc, credit_acc, post=True): move = self.move_model.create( { "journal_id": self.journal.id, "date": fields.Date.to_string(date), "line_ids": [ (0, 0, {"name": "/", "debit": amount, "account_id": debit_acc.id}), ( 0, 0, {"name": "/", "credit": amount, "account_id": credit_acc.id}, ), ], } ) if post: move._post() return move def _do_queries(self, date_from, date_to): self.aep.do_queries( date_from=fields.Date.to_string(date_from), date_to=fields.Date.to_string(date_to), ) def _eval(self, expr): eval_dict = {"AccountingNone": AccountingNone} return safe_eval(self.aep.replace_expr(expr), eval_dict) def _eval_by_account_id(self, expr): res = {} eval_dict = {"AccountingNone": AccountingNone} for account_id, replaced_exprs in self.aep.replace_exprs_by_account_id([expr]): res[account_id] = safe_eval(replaced_exprs[0], eval_dict) return res def test_sanity_check(self): self.assertEqual(self.company.fiscalyear_last_day, 31) self.assertEqual(self.company.fiscalyear_last_month, "12") def test_aep_basic(self): self.aep.done_parsing() # let's query for december self._do_queries( datetime.date(self.prev_year, 12, 1), datetime.date(self.prev_year, 12, 31) ) # initial balance must be None self.assertIs(self._eval("bali[400AR]"), AccountingNone) self.assertIs(self._eval("bali[700IN]"), AccountingNone) # check variation self.assertEqual(self._eval("balp[400AR]"), 100) self.assertEqual(self._eval("balp[][('account_id.code', '=', '400AR')]"), 100) self.assertEqual( self._eval( "balp[]" "[('account_id.user_type_id', '=', " " ref('account.data_account_type_receivable').id)]" ), 100, ) self.assertEqual( self._eval( "balp[('user_type_id', '=', " " ref('account.data_account_type_receivable').id)]" ), 100, ) self.assertEqual( self._eval( "balp['&', " " ('user_type_id', '=', " " ref('account.data_account_type_receivable').id), " " ('code', '=', '400AR')]" ), 100, ) self.assertEqual(self._eval("balp[700IN]"), -100) # check ending balance self.assertEqual(self._eval("bale[400AR]"), 100) self.assertEqual(self._eval("bale[700IN]"), -100) # let's query for January self._do_queries( datetime.date(self.curr_year, 1, 1), datetime.date(self.curr_year, 1, 31) ) # initial balance is None for income account (it's not carried over) self.assertEqual(self._eval("bali[400AR]"), 100) self.assertIs(self._eval("bali[700IN]"), AccountingNone) # check variation self.assertEqual(self._eval("balp[400AR]"), 300) self.assertEqual(self._eval("balp[700IN]"), -300) # check ending balance self.assertEqual(self._eval("bale[400AR]"), 400) self.assertEqual(self._eval("bale[700IN]"), -300) # let's query for March self._do_queries( datetime.date(self.curr_year, 3, 1), datetime.date(self.curr_year, 3, 31) ) # initial balance is the ending balance fo January self.assertEqual(self._eval("bali[400AR]"), 400) self.assertEqual(self._eval("bali[700IN]"), -300) self.assertEqual(self._eval("pbali[400AR]"), 400) self.assertEqual(self._eval("nbali[400AR]"), 0) self.assertEqual(self._eval("nbali[700IN]"), -300) self.assertEqual(self._eval("pbali[700IN]"), 0) # check variation self.assertEqual(self._eval("balp[400AR]"), 500) self.assertEqual(self._eval("balp[700IN]"), -500) self.assertEqual(self._eval("nbalp[400AR]"), 0) self.assertEqual(self._eval("pbalp[400AR]"), 500) self.assertEqual(self._eval("nbalp[700IN]"), -500) self.assertEqual(self._eval("pbalp[700IN]"), 0) # check ending balance self.assertEqual(self._eval("bale[400AR]"), 900) self.assertEqual(self._eval("nbale[400AR]"), 0) self.assertEqual(self._eval("pbale[400AR]"), 900) self.assertEqual(self._eval("bale[700IN]"), -800) self.assertEqual(self._eval("nbale[700IN]"), -800) self.assertEqual(self._eval("pbale[700IN]"), 0) # check some variant expressions, for coverage self.assertEqual(self._eval("crdp[700I%]"), 500) self.assertEqual(self._eval("debp[400A%]"), 500) self.assertEqual(self._eval("bal_700IN"), -500) self.assertEqual(self._eval("bals[700IN]"), -800) # unallocated p&l from previous year self.assertEqual(self._eval("balu[]"), -100) # TODO allocate profits, and then... def test_aep_by_account(self): self.aep.done_parsing() self._do_queries( datetime.date(self.curr_year, 3, 1), datetime.date(self.curr_year, 3, 31) ) variation = self._eval_by_account_id("balp[]") self.assertEqual(variation, {self.account_ar.id: 500, self.account_in.id: -500}) variation = self._eval_by_account_id("pbalp[]") self.assertEqual( variation, {self.account_ar.id: 500, self.account_in.id: AccountingNone} ) variation = self._eval_by_account_id("nbalp[]") self.assertEqual( variation, {self.account_ar.id: AccountingNone, self.account_in.id: -500} ) variation = self._eval_by_account_id("balp[700IN]") self.assertEqual(variation, {self.account_in.id: -500}) variation = self._eval_by_account_id("crdp[700IN] - debp[400AR]") self.assertEqual(variation, {self.account_ar.id: -500, self.account_in.id: 500}) end = self._eval_by_account_id("bale[]") self.assertEqual(end, {self.account_ar.id: 900, self.account_in.id: -800}) def test_aep_convenience_methods(self): initial = AEP.get_balances_initial(self.company, time.strftime("%Y") + "-03-01") self.assertEqual( initial, {self.account_ar.id: (400, 0), self.account_in.id: (0, 300)} ) variation = AEP.get_balances_variation( self.company, time.strftime("%Y") + "-03-01", time.strftime("%Y") + "-03-31", ) self.assertEqual( variation, {self.account_ar.id: (500, 0), self.account_in.id: (0, 500)} ) end = AEP.get_balances_end(self.company, time.strftime("%Y") + "-03-31") self.assertEqual( end, {self.account_ar.id: (900, 0), self.account_in.id: (0, 800)} ) unallocated = AEP.get_unallocated_pl( self.company, time.strftime("%Y") + "-03-15" ) self.assertEqual(unallocated, (0, 100)) def test_float_is_zero(self): dp = self.company.currency_id.decimal_places self.assertEqual(dp, 2) # make initial balance at Jan 1st equal to 0.01 self._create_move( date=datetime.date(self.prev_year, 12, 1), amount=100.01, debit_acc=self.account_in, credit_acc=self.account_ar, ) initial = AEP.get_balances_initial(self.company, time.strftime("%Y") + "-01-01") self.assertEqual(initial, {self.account_ar.id: (100.00, 100.01)}) # make initial balance at Jan 1st equal to 0.001 self._create_move( date=datetime.date(self.prev_year, 12, 1), amount=0.009, debit_acc=self.account_ar, credit_acc=self.account_in, ) initial = AEP.get_balances_initial(self.company, time.strftime("%Y") + "-01-01") # epsilon initial balances is reported as empty self.assertEqual(initial, {}) def test_get_account_ids_for_expr(self): self.aep.done_parsing() expr = "balp[700IN]" account_ids = self.aep.get_account_ids_for_expr(expr) self.assertEqual(account_ids, {self.account_in.id}) expr = "balp[700%]" account_ids = self.aep.get_account_ids_for_expr(expr) self.assertEqual(account_ids, {self.account_in.id}) expr = "bali[400%], bale[700%]" # subkpis combined expression account_ids = self.aep.get_account_ids_for_expr(expr) self.assertEqual(account_ids, {self.account_in.id, self.account_ar.id}) def test_get_aml_domain_for_expr(self): self.aep.done_parsing() expr = "balp[700IN]" domain = self.aep.get_aml_domain_for_expr(expr, "2017-01-01", "2017-03-31") self.assertEqual( domain, [ ("account_id", "in", (self.account_in.id,)), "&", ("date", ">=", "2017-01-01"), ("date", "<=", "2017-03-31"), ], ) expr = "debi[700IN] - crdi[400AR]" domain = self.aep.get_aml_domain_for_expr(expr, "2017-02-01", "2017-03-31") self.assertEqual( domain, [ "|", # debi[700IN] "&", ("account_id", "in", (self.account_in.id,)), ("debit", "<>", 0.0), # crdi[400AR] "&", ("account_id", "in", (self.account_ar.id,)), ("credit", "<>", 0.0), "&", # for P&L accounts, only after fy start "|", ("date", ">=", "2017-01-01"), ("account_id.user_type_id.include_initial_balance", "=", True), # everything must be before from_date for initial balance ("date", "<", "2017-02-01"), ], ) def test_is_domain(self): self.assertTrue(_is_domain("('a', '=' 1)")) self.assertTrue(_is_domain("'&', ('a', '=' 1), ('b', '=', 1)")) self.assertTrue(_is_domain("'|', ('a', '=' 1), ('b', '=', 1)")) self.assertTrue(_is_domain("'!', ('a', '=' 1), ('b', '=', 1)")) self.assertTrue(_is_domain("\"&\", ('a', '=' 1), ('b', '=', 1)")) self.assertTrue(_is_domain("\"|\", ('a', '=' 1), ('b', '=', 1)")) self.assertTrue(_is_domain("\"!\", ('a', '=' 1), ('b', '=', 1)")) self.assertFalse(_is_domain("123%")) self.assertFalse(_is_domain("123%,456")) self.assertFalse(_is_domain("")) def test_inactive_tax(self): expr = 'balp[][("tax_ids.name", "=", "test tax")]' self.aep.parse_expr(expr) self.aep.done_parsing() tax = self.env["account.tax"].create( dict(name="test tax", active=True, amount=0, company_id=self.company.id) ) move = self._create_move( date=datetime.date(self.prev_year, 12, 1), amount=100, debit_acc=self.account_ar, credit_acc=self.account_in, post=False, ) for ml in move.line_ids: if ml.credit: ml.write(dict(tax_ids=[(6, 0, [tax.id])])) tax.active = False move._post() # let's query for december 1st self._do_queries( datetime.date(self.prev_year, 12, 1), datetime.date(self.prev_year, 12, 1) ) # let's see if there was a match self.assertEqual(self._eval(expr), -100)
39.979798
15,832
917
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from ..models.mis_report import _utc_midnight class TestUtcMidnight(common.TransactionCase): def test_utc_midnight(self): date_to_convert = "2014-07-05" date_time_convert = _utc_midnight(date_to_convert, "Europe/Brussels") self.assertEqual(date_time_convert, "2014-07-04 22:00:00") date_time_convert = _utc_midnight(date_to_convert, "Europe/Brussels", add_day=1) self.assertEqual(date_time_convert, "2014-07-05 22:00:00") date_time_convert = _utc_midnight(date_to_convert, "US/Pacific") self.assertEqual(date_time_convert, "2014-07-05 07:00:00") date_time_convert = _utc_midnight(date_to_convert, "US/Pacific", add_day=1) self.assertEqual(date_time_convert, "2014-07-06 07:00:00")
48.263158
917
3,311
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2020 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from lxml import etree from odoo import api, fields, models class AddMisReportInstanceDashboard(models.TransientModel): _name = "add.mis.report.instance.dashboard.wizard" _description = "MIS Report Add to Dashboard Wizard" name = fields.Char(required=True) dashboard_id = fields.Many2one( "ir.actions.act_window", string="Dashboard", required=True, domain="[('res_model', '=', " "'board.board')]", ) @api.model def default_get(self, fields_list): res = {} if self.env.context.get("active_id", False): res = super().default_get(fields_list) # get report instance name res["name"] = ( self.env["mis.report.instance"] .browse(self.env.context["active_id"]) .name ) return res def action_add_to_dashboard(self): active_model = self.env.context.get("active_model") assert active_model == "mis.report.instance" active_id = self.env.context.get("active_id") assert active_id mis_report_instance = self.env[active_model].browse(active_id) # create the act_window corresponding to this report self.env.ref("mis_builder.mis_report_instance_result_view_form") view = self.env.ref("mis_builder.mis_report_instance_result_view_form") report_result = ( self.env["ir.actions.act_window"] .sudo() .create( { "name": "mis.report.instance.result.view.action.%d" % self.env.context["active_id"], "res_model": active_model, "res_id": active_id, "target": "current", "view_mode": "form", "view_id": view.id, "context": mis_report_instance._context_with_filters(), } ) ) # add this result in the selected dashboard last_customization = self.env["ir.ui.view.custom"].search( [ ("user_id", "=", self.env.uid), ("ref_id", "=", self.dashboard_id.view_id.id), ], limit=1, ) arch = self.dashboard_id.view_id.arch if last_customization: arch = self.env["ir.ui.view.custom"].browse(last_customization[0].id).arch new_arch = etree.fromstring(arch) column = new_arch.xpath("//column")[0] column.append( etree.Element( "action", { "context": str(self.env.context), "name": str(report_result.id), "string": self.name, "view_mode": "form", }, ) ) self.env["ir.ui.view.custom"].create( { "user_id": self.env.uid, "ref_id": self.dashboard_id.view_id.id, "arch": etree.tostring(new_arch, pretty_print=True), } ) return {"type": "ir.actions.act_window_close"}
35.602151
3,311
2,860
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). def _sum(lst): """Same as stdlib sum but returns None instead of 0 in case of empty sequence. >>> sum([1]) 1 >>> _sum([1]) 1 >>> sum([1, 2]) 3 >>> _sum([1, 2]) 3 >>> sum([]) 0 >>> _sum([]) """ if not lst: return None return sum(lst) def _avg(lst): """Arithmetic mean of a sequence. Returns None in case of empty sequence. >>> _avg([1]) 1.0 >>> _avg([1, 2]) 1.5 >>> _avg([]) """ if not lst: return None return sum(lst) / float(len(lst)) def _min(*args): """Same as stdlib min but returns None instead of exception in case of empty sequence. >>> min(1, 2) 1 >>> _min(1, 2) 1 >>> min([1, 2]) 1 >>> _min([1, 2]) 1 >>> min(1) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'int' object is not iterable >>> _min(1) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'int' object is not iterable >>> min([1]) 1 >>> _min([1]) 1 >>> min() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: min expected 1 arguments, got 0 >>> _min() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: min expected 1 arguments, got 0 >>> min([]) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: min() arg is an empty sequence >>> _min([]) """ if len(args) == 1 and not args[0]: return None return min(*args) def _max(*args): """Same as stdlib max but returns None instead of exception in case of empty sequence. >>> max(1, 2) 2 >>> _max(1, 2) 2 >>> max([1, 2]) 2 >>> _max([1, 2]) 2 >>> max(1) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'int' object is not iterable >>> _max(1) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'int' object is not iterable >>> max([1]) 1 >>> _max([1]) 1 >>> max() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: max expected 1 arguments, got 0 >>> _max() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: max expected 1 arguments, got 0 >>> max([]) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: max() arg is an empty sequence >>> _max([]) """ if len(args) == 1 and not args[0]: return None return max(*args) if __name__ == "__main__": # pragma: no cover import doctest doctest.testmod()
22.170543
2,860
2,102
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError from .mis_report import _is_valid_python_var class ParentLoopError(ValidationError): pass class InvalidNameError(ValidationError): pass class MisReportSubReport(models.Model): _name = "mis.report.subreport" _description = "MIS Report - Sub Reports Relation" name = fields.Char(required=True) report_id = fields.Many2one( comodel_name="mis.report", required=True, ondelete="cascade", ) subreport_id = fields.Many2one( comodel_name="mis.report", required=True, ondelete="restrict", ) _sql_constraints = [ ( "name_unique", "unique(name, report_id)", "Subreport name should be unique by report", ), ( "subreport_unique", "unique(subreport_id, report_id)", "Should not include the same report more than once as sub report " "of a given report", ), ] @api.constrains("name") def _check_name(self): for rec in self: if not _is_valid_python_var(rec.name): raise InvalidNameError( _("Subreport name ({}) must be a valid python identifier").format( rec.name ) ) @api.constrains("report_id", "subreport_id") def _check_loop(self): def _has_subreport(reports, report): if not reports: return False if report in reports: return True return any( _has_subreport(r.subreport_ids.mapped("subreport_id"), report) for r in reports ) for rec in self: if _has_subreport(rec.subreport_id, rec.report_id): raise ParentLoopError(_("Subreport loop detected")) # TODO check subkpi compatibility in subreports
28.405405
2,102
452
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2016 Akretion (<http://akretion.com>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). class DataError(Exception): def __init__(self, name, msg): super().__init__() self.name = name self.msg = msg def __repr__(self): return "{}({})".format(self.__class__.__name__, repr(self.name)) class NameDataError(DataError): pass
26.588235
452
2,453
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from .mis_safe_eval import NameDataError, mis_safe_eval class ExpressionEvaluator(object): def __init__( self, aep, date_from, date_to, additional_move_line_filter=None, aml_model=None, ): self.aep = aep self.date_from = date_from self.date_to = date_to self.additional_move_line_filter = additional_move_line_filter self.aml_model = aml_model self._aep_queries_done = False def aep_do_queries(self): if self.aep and not self._aep_queries_done: self.aep.do_queries( self.date_from, self.date_to, self.additional_move_line_filter, self.aml_model, ) self._aep_queries_done = True def eval_expressions(self, expressions, locals_dict): vals = [] drilldown_args = [] name_error = False for expression in expressions: expr = expression and expression.name or "AccountingNone" if self.aep: replaced_expr = self.aep.replace_expr(expr) else: replaced_expr = expr val = mis_safe_eval(replaced_expr, locals_dict) vals.append(val) if isinstance(val, NameDataError): name_error = True if replaced_expr != expr: drilldown_args.append({"expr": expr}) else: drilldown_args.append(None) return vals, drilldown_args, name_error def eval_expressions_by_account(self, expressions, locals_dict): if not self.aep: return exprs = [e and e.name or "AccountingNone" for e in expressions] for account_id, replaced_exprs in self.aep.replace_exprs_by_account_id(exprs): vals = [] drilldown_args = [] name_error = False for expr, replaced_expr in zip(exprs, replaced_exprs): val = mis_safe_eval(replaced_expr, locals_dict) vals.append(val) if replaced_expr != expr: drilldown_args.append({"expr": expr, "account_id": account_id}) else: drilldown_args.append(None) yield account_id, vals, drilldown_args, name_error
36.073529
2,453
4,185
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.osv import expression ACC_SUM = "sum" ACC_AVG = "avg" ACC_NONE = "none" def intersect_days(item_dt_from, item_dt_to, dt_from, dt_to): item_days = (item_dt_to - item_dt_from).days + 1.0 i_dt_from = max(dt_from, item_dt_from) i_dt_to = min(dt_to, item_dt_to) i_days = (i_dt_to - i_dt_from).days + 1.0 return i_days, item_days class MisKpiData(models.AbstractModel): """Abstract class for manually entered KPI values.""" _name = "mis.kpi.data" _description = "MIS Kpi Data Abtract class" name = fields.Char(compute="_compute_name", required=False, readonly=True) kpi_expression_id = fields.Many2one( comodel_name="mis.report.kpi.expression", required=True, ondelete="restrict", string="KPI", ) date_from = fields.Date(required=True, string="From") date_to = fields.Date(required=True, string="To") amount = fields.Float() seq1 = fields.Integer( related="kpi_expression_id.kpi_id.sequence", store=True, readonly=True, string="KPI Sequence", ) seq2 = fields.Integer( related="kpi_expression_id.subkpi_id.sequence", store=True, readonly=True, string="Sub-KPI Sequence", ) @api.depends( "kpi_expression_id.subkpi_id.name", "kpi_expression_id.kpi_id.name", "date_from", "date_to", ) def _compute_name(self): for rec in self: subkpi_name = rec.kpi_expression_id.subkpi_id.name if subkpi_name: subkpi_name = "." + subkpi_name else: subkpi_name = "" rec.name = "{}{}: {} - {}".format( rec.kpi_expression_id.kpi_id.name, subkpi_name, rec.date_from, rec.date_to, ) @api.model def _intersect_days(self, item_dt_from, item_dt_to, dt_from, dt_to): return intersect_days(item_dt_from, item_dt_to, dt_from, dt_to) @api.model def _query_kpi_data(self, date_from, date_to, base_domain): """Query mis.kpi.data over a time period. Returns {mis.report.kpi.expression: amount} """ dt_from = fields.Date.from_string(date_from) dt_to = fields.Date.from_string(date_to) # all data items within or overlapping [date_from, date_to] date_domain = [("date_from", "<=", date_to), ("date_to", ">=", date_from)] domain = expression.AND([date_domain, base_domain]) res = defaultdict(float) res_avg = defaultdict(list) for item in self.search(domain): item_dt_from = fields.Date.from_string(item.date_from) item_dt_to = fields.Date.from_string(item.date_to) i_days, item_days = self._intersect_days( item_dt_from, item_dt_to, dt_from, dt_to ) if item.kpi_expression_id.kpi_id.accumulation_method == ACC_SUM: # accumulate pro-rata overlap between item and reporting period res[item.kpi_expression_id] += item.amount * i_days / item_days elif item.kpi_expression_id.kpi_id.accumulation_method == ACC_AVG: # memorize the amount and number of days overlapping # the reporting period (used as weight in average) res_avg[item.kpi_expression_id].append((i_days, item.amount)) else: raise UserError( _( "Unexpected accumulation method %(method)s for %(name)s.", method=item.kpi_expression_id.kpi_id.accumulation_method, name=item.name, ) ) # compute weighted average for ACC_AVG for kpi_expression, amounts in res_avg.items(): res[kpi_expression] = sum(d * a for d, a in amounts) / sum( d for d, a in amounts ) return res
36.391304
4,185
10,573
py
PYTHON
15.0
# Copyright 2016 Therp BV (<http://therp.nl>) # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2020 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import sys from odoo import _, api, fields, models from odoo.exceptions import ValidationError from .accounting_none import AccountingNone from .data_error import DataError if sys.version_info.major >= 3: unicode = str class PropertyDict(dict): def __getattr__(self, name): return self.get(name) def copy(self): # pylint: disable=copy-wo-api-one,method-required-super return PropertyDict(self) PROPS = [ "color", "background_color", "font_style", "font_weight", "font_size", "indent_level", "prefix", "suffix", "dp", "divider", "hide_empty", "hide_always", ] TYPE_NUM = "num" TYPE_PCT = "pct" TYPE_STR = "str" CMP_DIFF = "diff" CMP_PCT = "pct" CMP_NONE = "none" class MisReportKpiStyle(models.Model): _name = "mis.report.style" _description = "MIS Report Style" @api.constrains("indent_level") def check_positive_val(self): for record in self: if record.indent_level < 0: raise ValidationError( _("Indent level must be greater than " "or equal to 0") ) _font_style_selection = [("normal", "Normal"), ("italic", "Italic")] _font_weight_selection = [("nornal", "Normal"), ("bold", "Bold")] _font_size_selection = [ ("medium", "medium"), ("xx-small", "xx-small"), ("x-small", "x-small"), ("small", "small"), ("large", "large"), ("x-large", "x-large"), ("xx-large", "xx-large"), ] _font_size_to_xlsx_size = { "medium": 11, "xx-small": 5, "x-small": 7, "small": 9, "large": 13, "x-large": 15, "xx-large": 17, } # style name # TODO enforce uniqueness name = fields.Char(string="Style name", required=True) # color color_inherit = fields.Boolean(default=True) color = fields.Char( string="Text color", help="Text color in valid RGB code (from #000000 to #FFFFFF)", default="#000000", ) background_color_inherit = fields.Boolean(default=True) background_color = fields.Char( help="Background color in valid RGB code (from #000000 to #FFFFFF)", default="#FFFFFF", ) # font font_style_inherit = fields.Boolean(default=True) font_style = fields.Selection(selection=_font_style_selection) font_weight_inherit = fields.Boolean(default=True) font_weight = fields.Selection(selection=_font_weight_selection) font_size_inherit = fields.Boolean(default=True) font_size = fields.Selection(selection=_font_size_selection) # indent indent_level_inherit = fields.Boolean(default=True) indent_level = fields.Integer() # number format prefix_inherit = fields.Boolean(default=True) prefix = fields.Char() suffix_inherit = fields.Boolean(default=True) suffix = fields.Char() dp_inherit = fields.Boolean(default=True) dp = fields.Integer(string="Rounding", default=0) divider_inherit = fields.Boolean(default=True) divider = fields.Selection( [ ("1e-6", _("µ")), ("1e-3", _("m")), ("1", _("1")), ("1e3", _("k")), ("1e6", _("M")), ], string="Factor", default="1", ) hide_empty_inherit = fields.Boolean(default=True) hide_empty = fields.Boolean(default=False) hide_always_inherit = fields.Boolean(default=True) hide_always = fields.Boolean(default=False) @api.model def merge(self, styles): """Merge several styles, giving priority to the last. Returns a PropertyDict of style properties. """ r = PropertyDict() for style in styles: if not style: continue if isinstance(style, dict): r.update(style) else: for prop in PROPS: inherit = getattr(style, prop + "_inherit", None) if not inherit: value = getattr(style, prop) r[prop] = value return r @api.model def render(self, lang, style_props, type, value, sign="-"): if type == TYPE_NUM: return self.render_num( lang, value, style_props.divider, style_props.dp, style_props.prefix, style_props.suffix, sign=sign, ) elif type == TYPE_PCT: return self.render_pct(lang, value, style_props.dp, sign=sign) else: return self.render_str(lang, value) @api.model def render_num( self, lang, value, divider=1.0, dp=0, prefix=None, suffix=None, sign="-" ): # format number following user language if value is None or value is AccountingNone: return "" value = round(value / float(divider or 1), dp or 0) or 0 r = lang.format("%%%s.%df" % (sign, dp or 0), value, grouping=True) r = r.replace("-", "\N{NON-BREAKING HYPHEN}") if prefix: r = prefix + "\N{NO-BREAK SPACE}" + r if suffix: r = r + "\N{NO-BREAK SPACE}" + suffix return r @api.model def render_pct(self, lang, value, dp=1, sign="-"): return self.render_num(lang, value, divider=0.01, dp=dp, suffix="%", sign=sign) @api.model def render_str(self, lang, value): if value is None or value is AccountingNone: return "" return unicode(value) @api.model def compare_and_render( self, lang, style_props, type, compare_method, value, base_value, average_value=1, average_base_value=1, ): """ :param lang: res.lang record :param style_props: PropertyDict with style properties :param type: num, pct or str :param compare_method: diff, pct, none :param value: value to compare (value - base_value) :param base_value: value compared with (value - base_value) :param average_value: value = value / average_value :param average_base_value: base_value = base_value / average_base_value :return: tuple with 4 elements - delta = comparison result (Float or AccountingNone) - delta_r = delta rendered in formatted string (String) - delta_style = PropertyDict with style properties - delta_type = Type of the comparison result (num or pct) """ delta = AccountingNone delta_r = "" delta_style = style_props.copy() delta_type = TYPE_NUM if isinstance(value, DataError) or isinstance(base_value, DataError): return AccountingNone, "", delta_style, delta_type if value is None: value = AccountingNone if base_value is None: base_value = AccountingNone if type == TYPE_PCT: delta = value - base_value if delta and round(delta, (style_props.dp or 0) + 2) != 0: delta_style.update(divider=0.01, prefix="", suffix=_("pp")) else: delta = AccountingNone elif type == TYPE_NUM: if value and average_value: # pylint: disable=redefined-variable-type value = value / float(average_value) if base_value and average_base_value: # pylint: disable=redefined-variable-type base_value = base_value / float(average_base_value) if compare_method == CMP_DIFF: delta = value - base_value if delta and round(delta, style_props.dp or 0) != 0: pass else: delta = AccountingNone elif compare_method == CMP_PCT: if base_value and round(base_value, style_props.dp or 0) != 0: delta = (value - base_value) / abs(base_value) if delta and round(delta, 3) != 0: delta_style.update(dp=1) delta_type = TYPE_PCT else: delta = AccountingNone if delta is not AccountingNone: delta_r = self.render(lang, delta_style, delta_type, delta, sign="+") return delta, delta_r, delta_style, delta_type @api.model def to_xlsx_style(self, type, props, no_indent=False): xlsx_attributes = [ ("italic", props.font_style == "italic"), ("bold", props.font_weight == "bold"), ("size", self._font_size_to_xlsx_size.get(props.font_size, 11)), ("font_color", props.color), ("bg_color", props.background_color), ] if type == TYPE_NUM: num_format = "#,##0" if props.dp: num_format += "." num_format += "0" * props.dp if props.prefix: num_format = '"{} "{}'.format(props.prefix, num_format) if props.suffix: num_format = '{}" {}"'.format(num_format, props.suffix) xlsx_attributes.append(("num_format", num_format)) elif type == TYPE_PCT: num_format = "0" if props.dp: num_format += "." num_format += "0" * props.dp num_format += "%" xlsx_attributes.append(("num_format", num_format)) if props.indent_level is not None and not no_indent: xlsx_attributes.append(("indent", props.indent_level)) return dict([a for a in xlsx_attributes if a[1] is not None]) @api.model def to_css_style(self, props, no_indent=False): css_attributes = [ ("font-style", props.font_style), ("font-weight", props.font_weight), ("font-size", props.font_size), ("color", props.color), ("background-color", props.background_color), ] if props.indent_level is not None and not no_indent: css_attributes.append(("text-indent", "{}em".format(props.indent_level))) return ( "; ".join(["%s: %s" % a for a in css_attributes if a[1] is not None]) or None )
33.884615
10,572
19,830
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from collections import OrderedDict, defaultdict from odoo import _ from odoo.exceptions import UserError from .accounting_none import AccountingNone from .mis_kpi_data import ACC_SUM from .mis_safe_eval import DataError, mis_safe_eval from .simple_array import SimpleArray _logger = logging.getLogger(__name__) class KpiMatrixRow(object): # TODO: ultimately, the kpi matrix will become ignorant of KPI's and # accounts and know about rows, columns, sub columns and styles only. # It is already ignorant of period and only knowns about columns. # This will require a correct abstraction for expanding row details. def __init__(self, matrix, kpi, account_id=None, parent_row=None): self._matrix = matrix self.kpi = kpi self.account_id = account_id self.description = "" self.parent_row = parent_row if not self.account_id: self.style_props = self._matrix._style_model.merge( [self.kpi.report_id.style_id, self.kpi.style_id] ) else: self.style_props = self._matrix._style_model.merge( [self.kpi.report_id.style_id, self.kpi.auto_expand_accounts_style_id] ) @property def label(self): if not self.account_id: return self.kpi.description else: return self._matrix.get_account_name(self.account_id) @property def row_id(self): if not self.account_id: return self.kpi.name else: return "{}:{}".format(self.kpi.name, self.account_id) def iter_cell_tuples(self, cols=None): if cols is None: cols = self._matrix.iter_cols() for col in cols: yield col.get_cell_tuple_for_row(self) def iter_cells(self, subcols=None): if subcols is None: subcols = self._matrix.iter_subcols() for subcol in subcols: yield subcol.get_cell_for_row(self) def is_empty(self): for cell in self.iter_cells(): if cell and cell.val not in (AccountingNone, None): return False return True class KpiMatrixCol(object): def __init__(self, key, label, description, locals_dict, subkpis): self.key = key self.label = label self.description = description self.locals_dict = locals_dict self.colspan = subkpis and len(subkpis) or 1 self._subcols = [] self.subkpis = subkpis if not subkpis: subcol = KpiMatrixSubCol(self, "", "", 0) self._subcols.append(subcol) else: for i, subkpi in enumerate(subkpis): subcol = KpiMatrixSubCol(self, subkpi.description, "", i) self._subcols.append(subcol) self._cell_tuples_by_row = {} # {row: (cells tuple)} def _set_cell_tuple(self, row, cell_tuple): self._cell_tuples_by_row[row] = cell_tuple def iter_subcols(self): return self._subcols def iter_cell_tuples(self): return self._cell_tuples_by_row.values() def get_cell_tuple_for_row(self, row): return self._cell_tuples_by_row.get(row) class KpiMatrixSubCol(object): def __init__(self, col, label, description, index=0): self.col = col self.label = label self.description = description self.index = index @property def subkpi(self): if self.col.subkpis: return self.col.subkpis[self.index] def iter_cells(self): for cell_tuple in self.col.iter_cell_tuples(): yield cell_tuple[self.index] def get_cell_for_row(self, row): cell_tuple = self.col.get_cell_tuple_for_row(row) if cell_tuple is None: return None return cell_tuple[self.index] class KpiMatrixCell(object): # noqa: B903 (immutable data class) def __init__( self, row, subcol, val, val_rendered, val_comment, style_props, drilldown_arg, val_type, ): self.row = row self.subcol = subcol self.val = val self.val_rendered = val_rendered self.val_comment = val_comment self.style_props = style_props self.drilldown_arg = drilldown_arg self.val_type = val_type class KpiMatrix(object): def __init__(self, env, multi_company=False, account_model="account.account"): # cache language id for faster rendering lang_model = env["res.lang"] self.lang = lang_model._lang_get(env.user.lang) self._style_model = env["mis.report.style"] self._account_model = env[account_model] # data structures # { kpi: KpiMatrixRow } self._kpi_rows = OrderedDict() # { kpi: {account_id: KpiMatrixRow} } self._detail_rows = {} # { col_key: KpiMatrixCol } self._cols = OrderedDict() # { col_key (left of comparison): [(col_key, base_col_key)] } self._comparison_todo = defaultdict(list) # { col_key (left of sum): (col_key, [(sign, sum_col_key)]) self._sum_todo = {} # { account_id: account_name } self._account_names = {} self._multi_company = multi_company def declare_kpi(self, kpi): """Declare a new kpi (row) in the matrix. Invoke this first for all kpi, in display order. """ self._kpi_rows[kpi] = KpiMatrixRow(self, kpi) self._detail_rows[kpi] = {} def declare_col(self, col_key, label, description, locals_dict, subkpis): """Declare a new column, giving it an identifier (key). Invoke the declare_* methods in display order. """ col = KpiMatrixCol(col_key, label, description, locals_dict, subkpis) self._cols[col_key] = col return col def declare_comparison( self, cmpcol_key, col_key, base_col_key, label, description=None ): """Declare a new comparison column. Invoke the declare_* methods in display order. """ self._comparison_todo[cmpcol_key] = (col_key, base_col_key, label, description) self._cols[cmpcol_key] = None # reserve slot in insertion order def declare_sum( self, sumcol_key, col_to_sum_keys, label, description=None, sum_accdet=False ): """Declare a new summation column. Invoke the declare_* methods in display order. :param col_to_sum_keys: [(sign, col_key)] """ self._sum_todo[sumcol_key] = (col_to_sum_keys, label, description, sum_accdet) self._cols[sumcol_key] = None # reserve slot in insertion order def set_values(self, kpi, col_key, vals, drilldown_args, tooltips=True): """Set values for a kpi and a colum. Invoke this after declaring the kpi and the column. """ self.set_values_detail_account( kpi, col_key, None, vals, drilldown_args, tooltips ) def set_values_detail_account( self, kpi, col_key, account_id, vals, drilldown_args, tooltips=True ): """Set values for a kpi and a column and a detail account. Invoke this after declaring the kpi and the column. """ if not account_id: row = self._kpi_rows[kpi] else: kpi_row = self._kpi_rows[kpi] if account_id in self._detail_rows[kpi]: row = self._detail_rows[kpi][account_id] else: row = KpiMatrixRow(self, kpi, account_id, parent_row=kpi_row) self._detail_rows[kpi][account_id] = row col = self._cols[col_key] cell_tuple = [] assert len(vals) == col.colspan assert len(drilldown_args) == col.colspan for val, drilldown_arg, subcol in zip(vals, drilldown_args, col.iter_subcols()): if isinstance(val, DataError): val_rendered = val.name val_comment = val.msg else: val_rendered = self._style_model.render( self.lang, row.style_props, kpi.type, val ) if row.kpi.multi and subcol.subkpi: val_comment = "{}.{} = {}".format( row.kpi.name, subcol.subkpi.name, row.kpi._get_expression_str_for_subkpi(subcol.subkpi), ) else: val_comment = "{} = {}".format(row.kpi.name, row.kpi.expression) cell_style_props = row.style_props if row.kpi.style_expression: # evaluate style expression try: style_name = mis_safe_eval( row.kpi.style_expression, col.locals_dict ) except Exception: _logger.error( "Error evaluating style expression <%s>", row.kpi.style_expression, exc_info=True, ) if style_name: style = self._style_model.search([("name", "=", style_name)]) if style: cell_style_props = self._style_model.merge( [row.style_props, style[0]] ) else: _logger.error("Style '%s' not found.", style_name) cell = KpiMatrixCell( row, subcol, val, val_rendered, tooltips and val_comment or None, cell_style_props, drilldown_arg, kpi.type, ) cell_tuple.append(cell) assert len(cell_tuple) == col.colspan col._set_cell_tuple(row, cell_tuple) def _common_subkpis(self, cols): if not cols: return set() common_subkpis = set(cols[0].subkpis) for col in cols[1:]: common_subkpis = common_subkpis & set(col.subkpis) return common_subkpis def compute_comparisons(self): """Compute comparisons. Invoke this after setting all values. """ for ( cmpcol_key, (col_key, base_col_key, label, description), ) in self._comparison_todo.items(): col = self._cols[col_key] base_col = self._cols[base_col_key] common_subkpis = self._common_subkpis([col, base_col]) if (col.subkpis or base_col.subkpis) and not common_subkpis: raise UserError( _("Columns {} and {} are not comparable").format( col.description, base_col.description ) ) if not label: label = "{} vs {}".format(col.label, base_col.label) comparison_col = KpiMatrixCol( cmpcol_key, label, description, {}, sorted(common_subkpis, key=lambda s: s.sequence), ) self._cols[cmpcol_key] = comparison_col for row in self.iter_rows(): cell_tuple = col.get_cell_tuple_for_row(row) base_cell_tuple = base_col.get_cell_tuple_for_row(row) if cell_tuple is None and base_cell_tuple is None: continue if cell_tuple is None: vals = [AccountingNone] * (len(common_subkpis) or 1) else: vals = [ cell.val for cell in cell_tuple if not common_subkpis or cell.subcol.subkpi in common_subkpis ] if base_cell_tuple is None: base_vals = [AccountingNone] * (len(common_subkpis) or 1) else: base_vals = [ cell.val for cell in base_cell_tuple if not common_subkpis or cell.subcol.subkpi in common_subkpis ] comparison_cell_tuple = [] for val, base_val, comparison_subcol in zip( vals, base_vals, comparison_col.iter_subcols() ): # TODO FIXME average factors comparison = self._style_model.compare_and_render( self.lang, row.style_props, row.kpi.type, row.kpi.compare_method, val, base_val, 1, 1, ) delta, delta_r, delta_style, delta_type = comparison comparison_cell_tuple.append( KpiMatrixCell( row, comparison_subcol, delta, delta_r, None, delta_style, None, delta_type, ) ) comparison_col._set_cell_tuple(row, comparison_cell_tuple) def compute_sums(self): """Compute comparisons. Invoke this after setting all values. """ for ( sumcol_key, (col_to_sum_keys, label, description, sum_accdet), ) in self._sum_todo.items(): sumcols = [self._cols[k] for (sign, k) in col_to_sum_keys] # TODO check all sumcols are resolved; we need a kind of # recompute queue here so we don't depend on insertion # order common_subkpis = self._common_subkpis(sumcols) if any(c.subkpis for c in sumcols) and not common_subkpis: raise UserError( _( "Sum cannot be computed in column {} " "because the columns to sum have no " "common subkpis" ).format(label) ) sum_col = KpiMatrixCol( sumcol_key, label, description, {}, sorted(common_subkpis, key=lambda s: s.sequence), ) self._cols[sumcol_key] = sum_col for row in self.iter_rows(): acc = SimpleArray([AccountingNone] * (len(common_subkpis) or 1)) if row.kpi.accumulation_method == ACC_SUM and not ( row.account_id and not sum_accdet ): for sign, col_to_sum in col_to_sum_keys: cell_tuple = self._cols[col_to_sum].get_cell_tuple_for_row(row) if cell_tuple is None: vals = [AccountingNone] * (len(common_subkpis) or 1) else: vals = [ cell.val for cell in cell_tuple if not common_subkpis or cell.subcol.subkpi in common_subkpis ] if sign == "+": acc += SimpleArray(vals) else: acc -= SimpleArray(vals) self.set_values_detail_account( row.kpi, sumcol_key, row.account_id, acc, [None] * (len(common_subkpis) or 1), tooltips=False, ) def iter_rows(self): """Iterate rows in display order. yields KpiMatrixRow. """ for kpi_row in self._kpi_rows.values(): yield kpi_row detail_rows = self._detail_rows[kpi_row.kpi].values() detail_rows = sorted(detail_rows, key=lambda r: r.label) for detail_row in detail_rows: yield detail_row def iter_cols(self): """Iterate columns in display order. yields KpiMatrixCol: one for each column or comparison. """ for _col_key, col in self._cols.items(): yield col def iter_subcols(self): """Iterate sub columns in display order. yields KpiMatrixSubCol: one for each subkpi in each column and comparison. """ for col in self.iter_cols(): for subcol in col.iter_subcols(): yield subcol def _load_account_names(self): account_ids = set() for detail_rows in self._detail_rows.values(): account_ids.update(detail_rows.keys()) accounts = self._account_model.search([("id", "in", list(account_ids))]) self._account_names = {a.id: self._get_account_name(a) for a in accounts} def _get_account_name(self, account): result = "{} {}".format(account.code, account.name) if self._multi_company: result = "{} [{}]".format(result, account.company_id.name) return result def get_account_name(self, account_id): if account_id not in self._account_names: self._load_account_names() return self._account_names[account_id] def as_dict(self): header = [{"cols": []}, {"cols": []}] for col in self.iter_cols(): header[0]["cols"].append( { "label": col.label, "description": col.description, "colspan": col.colspan, } ) for subcol in col.iter_subcols(): header[1]["cols"].append( { "label": subcol.label, "description": subcol.description, "colspan": 1, } ) body = [] for row in self.iter_rows(): if ( row.style_props.hide_empty and row.is_empty() ) or row.style_props.hide_always: continue row_data = { "row_id": row.row_id, "parent_row_id": (row.parent_row and row.parent_row.row_id or None), "label": row.label, "description": row.description, "style": self._style_model.to_css_style(row.style_props), "cells": [], } for cell in row.iter_cells(): if cell is None: # TODO use subcol style here row_data["cells"].append({}) else: if cell.val is AccountingNone or isinstance(cell.val, DataError): val = None else: val = cell.val col_data = { "val": val, "val_r": cell.val_rendered, "val_c": cell.val_comment, "style": self._style_model.to_css_style( cell.style_props, no_indent=True ), } if cell.drilldown_arg: col_data["drilldown_arg"] = cell.drilldown_arg row_data["cells"].append(col_data) body.append(row_data) return {"header": header, "body": body}
36.858736
19,830
4,788
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). """ A trivial immutable array that supports basic arithmetic operations. >>> a = SimpleArray((1.0, 2.0, 3.0)) >>> b = SimpleArray((4.0, 5.0, 6.0)) >>> t = (4.0, 5.0, 6.0) >>> +a SimpleArray((1.0, 2.0, 3.0)) >>> -a SimpleArray((-1.0, -2.0, -3.0)) >>> a + b SimpleArray((5.0, 7.0, 9.0)) >>> b + a SimpleArray((5.0, 7.0, 9.0)) >>> a + t SimpleArray((5.0, 7.0, 9.0)) >>> t + a SimpleArray((5.0, 7.0, 9.0)) >>> a - b SimpleArray((-3.0, -3.0, -3.0)) >>> a - t SimpleArray((-3.0, -3.0, -3.0)) >>> t - a SimpleArray((3.0, 3.0, 3.0)) >>> a * b SimpleArray((4.0, 10.0, 18.0)) >>> b * a SimpleArray((4.0, 10.0, 18.0)) >>> a * t SimpleArray((4.0, 10.0, 18.0)) >>> t * a SimpleArray((4.0, 10.0, 18.0)) >>> a / b SimpleArray((0.25, 0.4, 0.5)) >>> b / a SimpleArray((4.0, 2.5, 2.0)) >>> a / t SimpleArray((0.25, 0.4, 0.5)) >>> t / a SimpleArray((4.0, 2.5, 2.0)) >>> b / 2 SimpleArray((2.0, 2.5, 3.0)) >>> 2 * b SimpleArray((8.0, 10.0, 12.0)) >>> 1 - b SimpleArray((-3.0, -4.0, -5.0)) >>> b += 2 ; b SimpleArray((6.0, 7.0, 8.0)) >>> a / ((1.0, 0.0, 1.0)) SimpleArray((1.0, DataError('#DIV/0'), 3.0)) >>> a / 0.0 SimpleArray((DataError('#DIV/0'), DataError('#DIV/0'), DataError('#DIV/0'))) >>> a * ((1.0, 'a', 1.0)) SimpleArray((1.0, DataError('#ERR'), 3.0)) >>> 6.0 / a SimpleArray((6.0, 3.0, 2.0)) >>> Vector = named_simple_array('Vector', ('x', 'y')) >>> p1 = Vector((1, 2)) >>> print(p1.x, p1.y, p1) 1 2 Vector((1, 2)) >>> p2 = Vector((2, 3)) >>> print(p2.x, p2.y, p2) 2 3 Vector((2, 3)) >>> p3 = p1 + p2 >>> print(p3.x, p3.y, p3) 3 5 Vector((3, 5)) >>> p4 = (4, 5) + p2 >>> print(p4.x, p4.y, p4) 6 8 Vector((6, 8)) >>> p1 * 2 Vector((2, 4)) >>> 2 * p1 Vector((2, 4)) >>> p1 - 1 Vector((0, 1)) >>> 1 - p1 Vector((0, -1)) >>> p1 / 2.0 Vector((0.5, 1.0)) >>> v = 2.0 / p1 >>> print(v.x, v.y, v) 2.0 1.0 Vector((2.0, 1.0)) """ import itertools import operator import traceback from .data_error import DataError __all__ = ["SimpleArray", "named_simple_array"] class SimpleArray(tuple): def _op(self, op, other): def _o2(x, y): try: return op(x, y) except ZeroDivisionError: return DataError("#DIV/0", traceback.format_exc()) except Exception: return DataError("#ERR", traceback.format_exc()) if isinstance(other, tuple): if len(other) != len(self): raise TypeError("tuples must have same length for %s" % op) return self.__class__(map(_o2, self, other)) else: return self.__class__(_o2(z, other) for z in self) def _cast(self, other): if isinstance(other, self.__class__): return other elif isinstance(other, tuple): return self.__class__(other) else: # other is a scalar return self.__class__(itertools.repeat(other, len(self))) def __add__(self, other): return self._op(operator.add, other) __radd__ = __add__ def __pos__(self): return self.__class__(map(operator.pos, self)) def __neg__(self): return self.__class__(map(operator.neg, self)) def __sub__(self, other): return self._op(operator.sub, other) def __rsub__(self, other): return self._cast(other)._op(operator.sub, self) def __mul__(self, other): return self._op(operator.mul, other) __rmul__ = __mul__ def __div__(self, other): return self._op(operator.div, other) def __floordiv__(self, other): return self._op(operator.floordiv, other) def __truediv__(self, other): return self._op(operator.truediv, other) def __rdiv__(self, other): return self._cast(other)._op(operator.div, self) def __rfloordiv__(self, other): return self._cast(other)._op(operator.floordiv, self) def __rtruediv__(self, other): return self._cast(other)._op(operator.truediv, self) def __repr__(self): return "{}({})".format(self.__class__.__name__, tuple.__repr__(self)) def named_simple_array(typename, field_names): """Return a subclass of SimpleArray, with named properties. This method is to SimpleArray what namedtuple is to tuple. It's less sophisticated than namedtuple so some namedtuple advanced use cases may not work, but it's good enough for our needs in mis_builder, ie referring to subkpi values by name. """ props = { field_name: property(operator.itemgetter(i)) for i, field_name in enumerate(field_names) } return type(typename, (SimpleArray,), props) if __name__ == "__main__": # pragma: no cover import doctest doctest.testmod()
26.021739
4,788
4,164
py
PYTHON
15.0
# Copyright 2016 Thomas Binsfeld # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). """ Provides the AccountingNone singleton. AccountingNone is a null value that dissolves in basic arithmetic operations, as illustrated in the examples below. In comparisons, AccountingNone behaves the same as zero. >>> 1 + 1 2 >>> 1 + AccountingNone 1 >>> AccountingNone + 1 1 >>> AccountingNone + None AccountingNone >>> None + AccountingNone AccountingNone >>> +AccountingNone AccountingNone >>> -AccountingNone AccountingNone >>> -(AccountingNone) AccountingNone >>> AccountingNone - 1 -1 >>> 1 - AccountingNone 1 >>> abs(AccountingNone) AccountingNone >>> AccountingNone - None AccountingNone >>> None - AccountingNone AccountingNone >>> AccountingNone / 2 0.0 >>> 2 / AccountingNone Traceback (most recent call last): ... ZeroDivisionError >>> AccountingNone / AccountingNone AccountingNone >>> AccountingNone // 2 0.0 >>> 2 // AccountingNone Traceback (most recent call last): ... ZeroDivisionError >>> AccountingNone // AccountingNone AccountingNone >>> AccountingNone * 2 0.0 >>> 2 * AccountingNone 0.0 >>> AccountingNone * AccountingNone AccountingNone >>> AccountingNone * None AccountingNone >>> None * AccountingNone AccountingNone >>> str(AccountingNone) '' >>> bool(AccountingNone) False >>> AccountingNone > 0 False >>> AccountingNone < 0 False >>> AccountingNone < 1 True >>> AccountingNone > 1 False >>> 0 < AccountingNone False >>> 0 > AccountingNone False >>> 1 < AccountingNone False >>> 1 > AccountingNone True >>> AccountingNone == 0 True >>> AccountingNone == 0.0 True >>> AccountingNone == None True >>> AccountingNone >= AccountingNone True >>> AccountingNone <= AccountingNone True >>> round(AccountingNone, 2) 0.0 >>> float(AccountingNone) 0.0 >>> int(AccountingNone) 0 """ __all__ = ["AccountingNone"] class AccountingNoneType(object): def __add__(self, other): if other is None: return AccountingNone return other __radd__ = __add__ def __sub__(self, other): if other is None: return AccountingNone return -other def __rsub__(self, other): if other is None: return AccountingNone return other def __iadd__(self, other): if other is None: return AccountingNone return other def __isub__(self, other): if other is None: return AccountingNone return -other def __abs__(self): return self def __pos__(self): return self def __neg__(self): return self def __div__(self, other): if other is AccountingNone: return AccountingNone return 0.0 def __rdiv__(self, other): raise ZeroDivisionError def __floordiv__(self, other): if other is AccountingNone: return AccountingNone return 0.0 def __rfloordiv__(self, other): raise ZeroDivisionError def __truediv__(self, other): if other is AccountingNone: return AccountingNone return 0.0 def __rtruediv__(self, other): raise ZeroDivisionError def __mul__(self, other): if other is None or other is AccountingNone: return AccountingNone return 0.0 __rmul__ = __mul__ def __repr__(self): return "AccountingNone" def __str__(self): return "" def __nonzero__(self): return False def __bool__(self): return False def __eq__(self, other): return other == 0 or other is None or other is AccountingNone def __lt__(self, other): return other > 0 def __gt__(self, other): return other < 0 def __le__(self, other): return other >= 0 def __ge__(self, other): return other <= 0 def __float__(self): return 0.0 def __int__(self): return 0 def __round__(self, ndigits): return 0.0 AccountingNone = AccountingNoneType() if __name__ == "__main__": # pragma: no cover import doctest doctest.testmod()
19.367442
4,164
37,533
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2020 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import datetime import logging import re import time from collections import defaultdict import dateutil import pytz from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.models import expression as osv_expression from odoo.tools.safe_eval import ( datetime as safe_datetime, dateutil as safe_dateutil, safe_eval, time as safe_time, ) from .accounting_none import AccountingNone from .aep import AccountingExpressionProcessor as AEP from .aggregate import _avg, _max, _min, _sum from .expression_evaluator import ExpressionEvaluator from .kpimatrix import KpiMatrix from .mis_kpi_data import ACC_AVG, ACC_NONE, ACC_SUM from .mis_report_style import CMP_DIFF, CMP_NONE, CMP_PCT, TYPE_NUM, TYPE_PCT, TYPE_STR from .mis_safe_eval import DataError from .simple_array import SimpleArray, named_simple_array _logger = logging.getLogger(__name__) class SubKPITupleLengthError(UserError): pass class SubKPIUnknownTypeError(UserError): pass class AutoStruct(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) def _utc_midnight(d, tz_name, add_day=0): d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day) utc_tz = pytz.timezone("UTC") context_tz = pytz.timezone(tz_name) local_timestamp = context_tz.localize(d, is_dst=False) return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz)) def _python_var(var_str): return re.sub(r"\W|^(?=\d)", "_", var_str).lower() def _is_valid_python_var(name): return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name) class MisReportKpi(models.Model): """A KPI is an element (ie a line) of a MIS report. In addition to a name and description, it has an expression to compute it based on queries defined in the MIS report. It also has various informations defining how to render it (numeric or percentage or a string, a prefix, a suffix, divider) and how to render comparison of two values of the KPI. KPI's have a sequence and are ordered inside the MIS report. """ _name = "mis.report.kpi" _description = "MIS Report KPI" name = fields.Char(required=True) description = fields.Char(required=True, translate=True) multi = fields.Boolean() expression = fields.Char( compute="_compute_expression", inverse="_inverse_expression", ) expression_ids = fields.One2many( comodel_name="mis.report.kpi.expression", inverse_name="kpi_id", copy=True, string="Expressions", ) auto_expand_accounts = fields.Boolean(string="Display details by account") auto_expand_accounts_style_id = fields.Many2one( string="Style for account detail rows", comodel_name="mis.report.style", required=False, ) style_id = fields.Many2one( string="Style", comodel_name="mis.report.style", required=False ) style_expression = fields.Char( help="An expression that returns a style depending on the KPI value. " "Such style is applied on top of the row style.", ) type = fields.Selection( [ (TYPE_NUM, _("Numeric")), (TYPE_PCT, _("Percentage")), (TYPE_STR, _("String")), ], required=True, string="Value type", default=TYPE_NUM, ) compare_method = fields.Selection( [ (CMP_DIFF, _("Difference")), (CMP_PCT, _("Percentage")), (CMP_NONE, _("None")), ], required=True, string="Comparison Method", default=CMP_PCT, ) accumulation_method = fields.Selection( [(ACC_SUM, _("Sum")), (ACC_AVG, _("Average")), (ACC_NONE, _("None"))], required=True, default=ACC_SUM, help="Determines how values of this kpi spanning over a " "time period are transformed to match the reporting period. " "Sum: values of shorter period are added, " "values of longest or partially overlapping periods are " "adjusted pro-rata temporis.\n" "Average: values of included period are averaged " "with a pro-rata temporis weight.", ) sequence = fields.Integer(default=100) report_id = fields.Many2one("mis.report", required=True, ondelete="cascade") _order = "sequence, id" def name_get(self): res = [] for rec in self: name = "{} ({})".format(rec.description, rec.name) res.append((rec.id, name)) return res @api.model def name_search(self, name="", args=None, operator="ilike", limit=100): domain = args or [] domain += ["|", ("name", operator, name), ("description", operator, name)] return self.search(domain, limit=limit).name_get() @api.constrains("name") def _check_name(self): for record in self: if not _is_valid_python_var(record.name): raise ValidationError( _("KPI name ({}) must be a valid python identifier").format( record.name ) ) @api.depends("expression_ids.subkpi_id.name", "expression_ids.name") def _compute_expression(self): for kpi in self: exprs = [] for expression in kpi.expression_ids: if expression.subkpi_id: exprs.append( "{}\xa0=\xa0{}".format( expression.subkpi_id.name, expression.name ) ) else: exprs.append(expression.name or "AccountingNone") kpi.expression = ",\n".join(exprs) def _inverse_expression(self): for kpi in self: if kpi.multi: raise UserError(_("Can not update a multi kpi from " "the kpi line")) if kpi.expression_ids: kpi.expression_ids[0].write({"name": kpi.expression, "subkpi_id": None}) for expression in kpi.expression_ids[1:]: expression.unlink() else: expression = self.env["mis.report.kpi.expression"].new( {"name": kpi.expression} ) kpi.expression_ids += expression @api.onchange("multi") def _onchange_multi(self): for kpi in self: if not kpi.multi: if kpi.expression_ids: kpi.expression = kpi.expression_ids[0].name else: kpi.expression = None else: expressions = [] for subkpi in kpi.report_id.subkpi_ids: expressions.append( (0, 0, {"name": kpi.expression, "subkpi_id": subkpi.id}) ) kpi.expression_ids = expressions @api.onchange("description") def _onchange_description(self): """construct name from description""" if self.description and not self.name: self.name = _python_var(self.description) @api.onchange("type") def _onchange_type(self): if self.type == TYPE_NUM: self.compare_method = CMP_PCT self.accumulation_method = ACC_SUM elif self.type == TYPE_PCT: self.compare_method = CMP_DIFF self.accumulation_method = ACC_AVG elif self.type == TYPE_STR: self.compare_method = CMP_NONE self.accumulation_method = ACC_NONE def _get_expression_str_for_subkpi(self, subkpi): e = self._get_expression_for_subkpi(subkpi) return e and e.name or "" def _get_expression_for_subkpi(self, subkpi): for expression in self.expression_ids: if expression.subkpi_id == subkpi: return expression return None def _get_expressions(self, subkpis): if subkpis and self.multi: return [self._get_expression_for_subkpi(subkpi) for subkpi in subkpis] else: if self.expression_ids: assert len(self.expression_ids) == 1 assert not self.expression_ids[0].subkpi_id return self.expression_ids else: return [None] class MisReportSubkpi(models.Model): _name = "mis.report.subkpi" _description = "MIS Report Sub-KPI" _order = "sequence, id" sequence = fields.Integer(default=1) report_id = fields.Many2one( comodel_name="mis.report", required=True, ondelete="cascade" ) name = fields.Char(required=True) description = fields.Char(required=True, translate=True) expression_ids = fields.One2many("mis.report.kpi.expression", "subkpi_id") @api.constrains("name") def _check_name(self): for record in self: if not _is_valid_python_var(record.name): raise ValidationError( _("Sub-KPI name ({}) must be a valid python identifier").format( record.name ) ) @api.onchange("description") def _onchange_description(self): """construct name from description""" if self.description and not self.name: self.name = _python_var(self.description) class MisReportKpiExpression(models.Model): """A KPI Expression is an expression of a line of a MIS report Kpi. It's used to compute the kpi value. """ _name = "mis.report.kpi.expression" _description = "MIS Report KPI Expression" _order = "sequence, name, id" sequence = fields.Integer(related="subkpi_id.sequence", store=True, readonly=True) name = fields.Char(string="Expression") kpi_id = fields.Many2one("mis.report.kpi", required=True, ondelete="cascade") # TODO FIXME set readonly=True when onchange('subkpi_ids') below works subkpi_id = fields.Many2one("mis.report.subkpi", readonly=False, ondelete="cascade") _sql_constraints = [ ( "subkpi_kpi_unique", "unique(subkpi_id, kpi_id)", "Sub KPI must be used once and only once for each KPI", ) ] def name_get(self): res = [] for rec in self: kpi = rec.kpi_id subkpi = rec.subkpi_id if subkpi: name = "{} / {} ({}.{})".format( kpi.description, subkpi.description, kpi.name, subkpi.name ) else: name = rec.kpi_id.display_name res.append((rec.id, name)) return res @api.model def name_search(self, name="", args=None, operator="ilike", limit=100): # TODO maybe implement negative search operators, although # there is not really a use case for that domain = args or [] splitted_name = name.split(".", 2) name_search_domain = [] if "." in name: kpi_name, subkpi_name = splitted_name[0], splitted_name[1] name_search_domain = osv_expression.AND( [ name_search_domain, [ "|", "|", "&", ("kpi_id.name", "=", kpi_name), ("subkpi_id.name", operator, subkpi_name), ("kpi_id.description", operator, name), ("subkpi_id.description", operator, name), ], ] ) name_search_domain = osv_expression.OR( [ name_search_domain, [ "|", ("kpi_id.name", operator, name), ("kpi_id.description", operator, name), ], ] ) domain = osv_expression.AND([domain, name_search_domain]) return self.search(domain, limit=limit).name_get() class MisReportQuery(models.Model): """A query to fetch arbitrary data for a MIS report. A query works on a model and has a domain and list of fields to fetch. At runtime, the domain is expanded with a "and" on the date/datetime field. """ _name = "mis.report.query" _description = "MIS Report Query" @api.depends("field_ids") def _compute_field_names(self): for record in self: field_names = [field.name for field in record.field_ids] record.field_names = ", ".join(field_names) name = fields.Char(required=True) model_id = fields.Many2one("ir.model", required=True, ondelete="cascade") field_ids = fields.Many2many( "ir.model.fields", required=True, string="Fields to fetch" ) field_names = fields.Char( compute="_compute_field_names", string="Fetched fields name" ) aggregate = fields.Selection( [ ("sum", _("Sum")), ("avg", _("Average")), ("min", _("Min")), ("max", _("Max")), ], ) date_field = fields.Many2one( comodel_name="ir.model.fields", required=True, domain=[("ttype", "in", ("date", "datetime"))], ondelete="cascade", ) domain = fields.Char() report_id = fields.Many2one( comodel_name="mis.report", required=True, ondelete="cascade" ) _order = "name" @api.constrains("name") def _check_name(self): for record in self: if not _is_valid_python_var(record.name): raise ValidationError( _("Query name ({}) must be valid python identifier").format( record.name ) ) class MisReport(models.Model): """A MIS report template (without period information) The MIS report holds: * a list of explicit queries; the result of each query is stored in a variable with same name as a query, containing as list of data structures populated with attributes for each fields to fetch; when queries have an aggregate method and no fields to group, it returns a data structure with the aggregated fields * a list of KPI to be evaluated based on the variables resulting from the accounting data and queries (KPI expressions can references queries and accounting expression - see AccoutingExpressionProcessor) """ _name = "mis.report" _description = "MIS Report Template" def _default_move_lines_source(self): return self.env["ir.model"].sudo().search([("model", "=", "account.move.line")]) name = fields.Char(required=True, translate=True) description = fields.Char(required=False, translate=True) style_id = fields.Many2one(string="Style", comodel_name="mis.report.style") query_ids = fields.One2many( "mis.report.query", "report_id", string="Queries", copy=True ) kpi_ids = fields.One2many("mis.report.kpi", "report_id", string="KPI's", copy=True) subkpi_ids = fields.One2many( "mis.report.subkpi", "report_id", string="Sub KPI", copy=True ) subreport_ids = fields.One2many( "mis.report.subreport", "report_id", string="Sub reports", copy=True ) all_kpi_ids = fields.One2many( comodel_name="mis.report.kpi", compute="_compute_all_kpi_ids", help="KPIs of this report and subreports.", ) move_lines_source = fields.Many2one( comodel_name="ir.model", domain=[ ("field_id.name", "=", "debit"), ("field_id.name", "=", "credit"), ("field_id.name", "=", "account_id"), ("field_id.name", "=", "date"), ("field_id.name", "=", "company_id"), ], default=_default_move_lines_source, required=True, ondelete="cascade", help="A 'move line like' model, ie having at least debit, credit, " "date, account_id and company_id fields. This model is the " "data source for column Actuals.", ) account_model = fields.Char(compute="_compute_account_model") @api.depends("kpi_ids", "subreport_ids") def _compute_all_kpi_ids(self): for rec in self: rec.all_kpi_ids = rec.kpi_ids | rec.subreport_ids.mapped( "subreport_id.kpi_ids" ) @api.depends("move_lines_source") def _compute_account_model(self): for record in self: record.account_model = ( record.move_lines_source.sudo() .field_id.filtered(lambda r: r.name == "account_id") .relation ) @api.onchange("subkpi_ids") def _on_change_subkpi_ids(self): """Update kpi expressions when subkpis change on the report, so the list of kpi expressions is always up-to-date""" for kpi in self.kpi_ids: if not kpi.multi: continue new_subkpis = {subkpi for subkpi in self.subkpi_ids} expressions = [] for expression in kpi.expression_ids: assert expression.subkpi_id # must be true if kpi is multi if expression.subkpi_id not in self.subkpi_ids: expressions.append((2, expression.id, None)) # remove else: new_subkpis.remove(expression.subkpi_id) # no change for subkpi in new_subkpis: # TODO FIXME this does not work, while the remove above works expressions.append( (0, None, {"name": False, "subkpi_id": subkpi.id}) ) # add empty expressions for new subkpis if expressions: kpi.expression_ids = expressions def get_wizard_report_action(self): xmlid = "mis_builder.mis_report_instance_view_action" action = self.env["ir.actions.act_window"]._for_xml_id(xmlid) view = self.env.ref("mis_builder.wizard_mis_report_instance_view_form") action.update( { "view_id": view.id, "views": [(view.id, "form")], "target": "new", "context": { "default_report_id": self.id, "default_name": self.name, "default_temporary": True, }, } ) return action def copy(self, default=None): self.ensure_one() default = dict(default or []) default["name"] = _("%s (copy)") % self.name new = super().copy(default) # after a copy, we have new subkpis, but the expressions # subkpi_id fields still point to the original one, so # we patch them after copying subkpis_by_name = {sk.name: sk for sk in new.subkpi_ids} for subkpi in self.subkpi_ids: # search expressions linked to subkpis of the original report exprs = self.env["mis.report.kpi.expression"].search( [("kpi_id.report_id", "=", new.id), ("subkpi_id", "=", subkpi.id)] ) # and replace them with references to subkpis of the new report exprs.write({"subkpi_id": subkpis_by_name[subkpi.name].id}) return new # TODO: kpi name cannot be start with query name def prepare_kpi_matrix(self, multi_company=False): self.ensure_one() kpi_matrix = KpiMatrix(self.env, multi_company, self.account_model) for kpi in self.kpi_ids: kpi_matrix.declare_kpi(kpi) return kpi_matrix def _prepare_aep(self, companies, currency=None): self.ensure_one() aep = AEP(companies, currency, self.account_model) for kpi in self.all_kpi_ids: for expression in kpi.expression_ids: if expression.name: aep.parse_expr(expression.name) aep.done_parsing() return aep def prepare_locals_dict(self): return { "sum": _sum, "min": _min, "max": _max, "len": len, "avg": _avg, "time": time, "datetime": datetime, "dateutil": dateutil, "AccountingNone": AccountingNone, "SimpleArray": SimpleArray, } def _fetch_queries(self, date_from, date_to, get_additional_query_filter=None): self.ensure_one() res = {} for query in self.query_ids: query_sudo = query.sudo() model = self.env[query_sudo.model_id.model] eval_context = { "env": self.env, "time": safe_time, "datetime": safe_datetime, "dateutil": safe_dateutil, # deprecated "uid": self.env.uid, "context": self.env.context, } domain = query.domain and safe_eval(query.domain, eval_context) or [] if get_additional_query_filter: domain.extend(get_additional_query_filter(query)) if query_sudo.date_field.ttype == "date": domain.extend( [ (query_sudo.date_field.name, ">=", date_from), (query_sudo.date_field.name, "<=", date_to), ] ) else: tz = str(self.env["ir.fields.converter"]._input_tz()) datetime_from = _utc_midnight(date_from, tz) datetime_to = _utc_midnight(date_to, tz, add_day=1) domain.extend( [ (query_sudo.date_field.name, ">=", datetime_from), (query_sudo.date_field.name, "<", datetime_to), ] ) field_names = [f.name for f in query_sudo.field_ids] all_stored = all([model._fields[f].store for f in field_names]) if not query.aggregate: data = model.search_read(domain, field_names) res[query.name] = [AutoStruct(**d) for d in data] elif query.aggregate == "sum" and all_stored: # use read_group to sum stored fields data = model.read_group(domain, field_names, []) s = AutoStruct(count=data[0]["__count"]) for field_name in field_names: try: v = data[0][field_name] except KeyError: _logger.error( "field %s not found in read_group " "for %s; not summable?", field_name, model._name, ) v = AccountingNone setattr(s, field_name, v) res[query.name] = s else: data = model.search_read(domain, field_names) s = AutoStruct(count=len(data)) if query.aggregate == "min": agg = _min elif query.aggregate == "max": agg = _max elif query.aggregate == "avg": agg = _avg elif query.aggregate == "sum": agg = _sum for field_name in field_names: setattr(s, field_name, agg([d[field_name] for d in data])) res[query.name] = s return res def _declare_and_compute_col( # noqa: C901 (TODO simplify this fnction) self, expression_evaluator, kpi_matrix, col_key, col_label, col_description, subkpis_filter, locals_dict, no_auto_expand_accounts=False, ): """This is the main computation loop. It evaluates the kpis and puts the results in the KpiMatrix. Evaluation is done through the expression_evaluator so data sources can provide their own mean of obtaining the data (eg preset kpi values for budget, or alternative move line sources). """ if subkpis_filter: # TODO filter by subkpi names subkpis = [subkpi for subkpi in self.subkpi_ids if subkpi in subkpis_filter] else: subkpis = self.subkpi_ids SimpleArray_cls = named_simple_array( "SimpleArray_{}".format(col_key), [subkpi.name for subkpi in subkpis] ) locals_dict["SimpleArray"] = SimpleArray_cls col = kpi_matrix.declare_col( col_key, col_label, col_description, locals_dict, subkpis ) compute_queue = self.kpi_ids recompute_queue = [] while True: for kpi in compute_queue: # build the list of expressions for this kpi expressions = kpi._get_expressions(subkpis) ( vals, drilldown_args, name_error, ) = expression_evaluator.eval_expressions(expressions, locals_dict) for drilldown_arg in drilldown_args: if not drilldown_arg: continue drilldown_arg["period_id"] = col_key drilldown_arg["kpi_id"] = kpi.id if name_error: recompute_queue.append(kpi) else: # no error, set it in locals_dict so it can be used # in computing other kpis if not subkpis or not kpi.multi: locals_dict[kpi.name] = vals[0] else: locals_dict[kpi.name] = SimpleArray_cls(vals) # even in case of name error we set the result in the matrix # so the name error will be displayed if it cannot be # resolved by recomputing later if subkpis and not kpi.multi: # here we have one expression for this kpi, but # multiple subkpis (so this kpi is most probably # a sum or other operation on multi-valued kpis) if isinstance(vals[0], tuple): vals = vals[0] if len(vals) != col.colspan: raise SubKPITupleLengthError( _( 'KPI "{}" is valued as a tuple of ' "length {} while a tuple of length {} " "is expected." ).format(kpi.description, len(vals), col.colspan) ) elif isinstance(vals[0], DataError): vals = (vals[0],) * col.colspan else: raise SubKPIUnknownTypeError( _( 'KPI "{}" has type {} while a tuple was ' "expected.\n\nThis can be fixed by either:\n\t- " "Changing the KPI value to a tuple of length " "{}\nor\n\t- Changing the " "KPI to `multi` mode and giving an explicit " "value for each sub-KPI." ).format(kpi.description, type(vals[0]), col.colspan) ) if len(drilldown_args) != col.colspan: drilldown_args = [None] * col.colspan kpi_matrix.set_values(kpi, col_key, vals, drilldown_args) if ( name_error or no_auto_expand_accounts or not kpi.auto_expand_accounts ): continue for ( account_id, vals, drilldown_args, _name_error, ) in expression_evaluator.eval_expressions_by_account( expressions, locals_dict ): for drilldown_arg in drilldown_args: if not drilldown_arg: continue drilldown_arg["period_id"] = col_key drilldown_arg["kpi_id"] = kpi.id kpi_matrix.set_values_detail_account( kpi, col_key, account_id, vals, drilldown_args ) if len(recompute_queue) == 0: # nothing to recompute, we are done break if len(recompute_queue) == len(compute_queue): # could not compute anything in this iteration # (ie real Name errors or cyclic dependency) # so we stop trying break # try again compute_queue = recompute_queue recompute_queue = [] def declare_and_compute_period( self, kpi_matrix, col_key, col_label, col_description, aep, date_from, date_to, subkpis_filter=None, get_additional_move_line_filter=None, get_additional_query_filter=None, locals_dict=None, aml_model=None, no_auto_expand_accounts=False, ): _logger.warning( "declare_and_compute_period() is deprecated, " "use _declare_and_compute_period() instead" ) expression_evaluator = ExpressionEvaluator( aep, date_from, date_to, get_additional_move_line_filter() if get_additional_move_line_filter else None, aml_model, ) return self._declare_and_compute_period( expression_evaluator, kpi_matrix, col_key, col_label, col_description, subkpis_filter, get_additional_query_filter, locals_dict, no_auto_expand_accounts, ) def _declare_and_compute_period( self, expression_evaluator, kpi_matrix, col_key, col_label, col_description, subkpis_filter=None, get_additional_query_filter=None, locals_dict=None, no_auto_expand_accounts=False, ): """Evaluate a report for a given period, populating a KpiMatrix. :param expression_evaluator: an ExpressionEvaluator instance :param kpi_matrix: the KpiMatrix object to be populated created with prepare_kpi_matrix() :param col_key: the period key to use when populating the KpiMatrix :param subkpis_filter: a list of subkpis to include in the evaluation (if empty, use all subkpis) :param get_additional_query_filter: a bound method that takes a single query argument and returns a domain compatible with the query underlying model :param locals_dict: personalized locals dictionary used as evaluation context for the KPI expressions :param no_auto_expand_accounts: disable expansion of account details """ self.ensure_one() # prepare the localsdict if locals_dict is None: locals_dict = {} # Evaluate subreports for subreport in self.subreport_ids: subreport_locals_dict = subreport.subreport_id._evaluate( expression_evaluator, subkpis_filter, get_additional_query_filter ) locals_dict[subreport.name] = AutoStruct( **{ srk.name: subreport_locals_dict.get(srk.name, AccountingNone) for srk in subreport.subreport_id.kpi_ids } ) locals_dict.update(self.prepare_locals_dict()) locals_dict["date_from"] = fields.Date.from_string( expression_evaluator.date_from ) locals_dict["date_to"] = fields.Date.from_string(expression_evaluator.date_to) # fetch non-accounting queries locals_dict.update( self._fetch_queries( expression_evaluator.date_from, expression_evaluator.date_to, get_additional_query_filter, ) ) # use AEP to do the accounting queries expression_evaluator.aep_do_queries() self._declare_and_compute_col( expression_evaluator, kpi_matrix, col_key, col_label, col_description, subkpis_filter, locals_dict, no_auto_expand_accounts, ) def get_kpis_by_account_id(self, company): """Return { account_id: set(kpi) }""" aep = self._prepare_aep(company) res = defaultdict(set) for kpi in self.kpi_ids: for expression in kpi.expression_ids: if not expression.name: continue account_ids = aep.get_account_ids_for_expr(expression.name) for account_id in account_ids: res[account_id].add(kpi) return res @api.model def _supports_target_move_filter(self, aml_model_name): return "parent_state" in self.env[aml_model_name]._fields @api.model def _get_target_move_domain(self, target_move, aml_model_name): """ Obtain a domain to apply on a move-line-like model, to get posted entries or return all of them (always excluding cancelled entries). :param: target_move: all|posted :param: aml_model_name: an optional move-line-like model name (defaults to accaount.move.line) """ if not self._supports_target_move_filter(aml_model_name): return [] if target_move == "posted": return [("parent_state", "=", "posted")] elif target_move == "all": # all (in Odoo 13+, there is also the cancel state that we must ignore) return [("parent_state", "in", ("posted", "draft"))] else: raise UserError(_("Unexpected value %s for target_move.") % (target_move,)) def evaluate( self, aep, date_from, date_to, target_move="posted", aml_model=None, subkpis_filter=None, get_additional_move_line_filter=None, get_additional_query_filter=None, ): """Simplified method to evaluate a report over a time period. :param aep: an AccountingExpressionProcessor instance created using _prepare_aep() :param date_from, date_to: the starting and ending date :param target_move: all|posted :param aml_model: the name of a model that is compatible with account.move.line (default: account.move.line) :param subkpis_filter: a list of subkpis to include in the evaluation (if empty, use all subkpis) :param get_additional_move_line_filter: a bound method that takes no arguments and returns a domain compatible with account.move.line :param get_additional_query_filter: a bound method that takes a single query argument and returns a domain compatible with the query underlying model :return: a dictionary where keys are KPI names, and values are the evaluated results; some additional keys might be present: these should be ignored as they might be removed in the future. """ additional_move_line_filter = self._get_target_move_domain( target_move, aml_model or "account.move.line" ) if get_additional_move_line_filter: additional_move_line_filter.extend(get_additional_move_line_filter()) expression_evaluator = ExpressionEvaluator( aep, date_from, date_to, additional_move_line_filter, aml_model, ) return self._evaluate( expression_evaluator, subkpis_filter, get_additional_query_filter ) def _evaluate( self, expression_evaluator, subkpis_filter=None, get_additional_query_filter=None, ): locals_dict = {} kpi_matrix = self.prepare_kpi_matrix() self._declare_and_compute_period( expression_evaluator, kpi_matrix, col_key=1, col_label="", col_description="", subkpis_filter=subkpis_filter, get_additional_query_filter=get_additional_query_filter, locals_dict=locals_dict, no_auto_expand_accounts=True, ) return locals_dict
37.346269
37,533
21,778
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import re from collections import defaultdict from odoo import _, fields from odoo.exceptions import UserError from odoo.models import expression from odoo.tools.float_utils import float_is_zero from odoo.tools.safe_eval import datetime, dateutil, safe_eval, time from .accounting_none import AccountingNone _DOMAIN_START_RE = re.compile(r"\(|(['\"])[!&|]\1") def _is_domain(s): """Test if a string looks like an Odoo domain""" return _DOMAIN_START_RE.match(s) class AccountingExpressionProcessor(object): """Processor for accounting expressions. Expressions of the form <field><mode>[accounts][optional move line domain] are supported, where: * field is bal, crd, deb, pbal (positive balances only), nbal (negative balance only) * mode is i (initial balance), e (ending balance), p (moves over period) * there is also a special u mode (unallocated P&L) which computes the sum from the beginning until the beginning of the fiscal year of the period; it is only meaningful for P&L accounts * accounts is a list of accounts, possibly containing % wildcards, or a domain expression on account.account * an optional domain on move lines allowing filters on eg analytic accounts or journal Examples: * bal[70]: variation of the balance of moves on account 70 over the period (it is the same as balp[70]); * bali[70,60]: balance of accounts 70 and 60 at the start of period; * bale[1%]: balance of accounts starting with 1 at end of period. How to use: * repeatedly invoke parse_expr() for each expression containing accounting variables as described above; this lets the processor group domains and modes and accounts; * when all expressions have been parsed, invoke done_parsing() to notify the processor that it can prepare to query (mainly search all accounts - children, consolidation - that will need to be queried; * for each period, call do_queries(), then call replace_expr() for each expression to replace accounting variables with their resulting value for the given period. How it works: * by accumulating the expressions before hand, it ensures to do the strict minimum number of queries to the database (for each period, one query per domain and mode); * it queries using the orm read_group which reduces to a query with sum on debit and credit and group by on account_id and company_id, (note: it seems the orm then does one query per account to fetch the account name...); * additionally, one query per view/consolidation account is done to discover the children accounts. """ MODE_VARIATION = "p" MODE_INITIAL = "i" MODE_END = "e" MODE_UNALLOCATED = "u" _ACC_RE = re.compile( r"(?P<field>\bbal|\bpbal|\bnbal|\bcrd|\bdeb)" r"(?P<mode>[piseu])?" r"\s*" r"(?P<account_sel>_[a-zA-Z0-9]+|\[.*?\])" r"\s*" r"(?P<ml_domain>\[.*?\])?" ) def __init__(self, companies, currency=None, account_model="account.account"): self.env = companies.env self.companies = companies if not currency: self.currency = companies.mapped("currency_id") if len(self.currency) > 1: raise UserError( _( "If currency_id is not provided, " "all companies must have the same currency." ) ) else: self.currency = currency self.dp = self.currency.decimal_places # before done_parsing: {(ml_domain, mode): set(acc_domain)} # after done_parsing: {(ml_domain, mode): list(account_ids)} self._map_account_ids = defaultdict(set) # {account_domain: set(account_ids)} self._account_ids_by_acc_domain = defaultdict(set) # smart ending balance (returns AccountingNone if there # are no moves in period and 0 initial balance), implies # a first query to get the initial balance and another # to get the variation, so it's a bit slower self.smart_end = True # Account model self._account_model = self.env[account_model].with_context(active_test=False) def _account_codes_to_domain(self, account_codes): """Convert a comma separated list of account codes (possibly with wildcards) to a domain on account.account. """ elems = [] for account_code in account_codes.split(","): account_code = account_code.strip() if "%" in account_code: elems.append([("code", "=like", account_code)]) else: elems.append([("code", "=", account_code)]) return tuple(expression.OR(elems)) def _parse_match_object(self, mo): """Split a match object corresponding to an accounting variable Returns field, mode, account domain, move line domain. """ domain_eval_context = { "ref": self.env.ref, "user": self.env.user, "time": time, "datetime": datetime, "dateutil": dateutil, } field, mode, account_sel, ml_domain = mo.groups() # handle some legacy modes if not mode: mode = self.MODE_VARIATION elif mode == "s": mode = self.MODE_END # convert account selector to account domain if account_sel.startswith("_"): # legacy bal_NNN% acc_domain = self._account_codes_to_domain(account_sel[1:]) else: assert account_sel[0] == "[" and account_sel[-1] == "]" inner_account_sel = account_sel[1:-1].strip() if not inner_account_sel: # empty selector: select all accounts acc_domain = tuple() elif _is_domain(inner_account_sel): # account selector is a domain acc_domain = tuple(safe_eval(account_sel, domain_eval_context)) else: # account selector is a list of account codes acc_domain = self._account_codes_to_domain(inner_account_sel) # move line domain if ml_domain: assert ml_domain[0] == "[" and ml_domain[-1] == "]" ml_domain = tuple(safe_eval(ml_domain, domain_eval_context)) else: ml_domain = tuple() return field, mode, acc_domain, ml_domain def parse_expr(self, expr): """Parse an expression, extracting accounting variables. Move line domains and account selectors are extracted and stored in the map so when all expressions have been parsed, we know which account domains to query for each move line domain and mode. """ for mo in self._ACC_RE.finditer(expr): _, mode, acc_domain, ml_domain = self._parse_match_object(mo) if mode == self.MODE_END and self.smart_end: modes = (self.MODE_INITIAL, self.MODE_VARIATION, self.MODE_END) else: modes = (mode,) for mode in modes: key = (ml_domain, mode) self._map_account_ids[key].add(acc_domain) def done_parsing(self): """Replace account domains by account ids in map""" for key, acc_domains in self._map_account_ids.items(): all_account_ids = set() for acc_domain in acc_domains: acc_domain_with_company = expression.AND( [acc_domain, [("company_id", "in", self.companies.ids)]] ) account_ids = self._account_model.search(acc_domain_with_company).ids self._account_ids_by_acc_domain[acc_domain].update(account_ids) all_account_ids.update(account_ids) self._map_account_ids[key] = list(all_account_ids) @classmethod def has_account_var(cls, expr): """Test if an string contains an accounting variable.""" return bool(cls._ACC_RE.search(expr)) def get_account_ids_for_expr(self, expr): """Get a set of account ids that are involved in an expression. Prerequisite: done_parsing() must have been invoked. """ account_ids = set() for mo in self._ACC_RE.finditer(expr): field, mode, acc_domain, ml_domain = self._parse_match_object(mo) account_ids.update(self._account_ids_by_acc_domain[acc_domain]) return account_ids def get_aml_domain_for_expr(self, expr, date_from, date_to, account_id=None): """Get a domain on account.move.line for an expression. Prerequisite: done_parsing() must have been invoked. Returns a domain that can be used to search on account.move.line. """ aml_domains = [] date_domain_by_mode = {} for mo in self._ACC_RE.finditer(expr): field, mode, acc_domain, ml_domain = self._parse_match_object(mo) aml_domain = list(ml_domain) account_ids = set() account_ids.update(self._account_ids_by_acc_domain[acc_domain]) if not account_id: aml_domain.append(("account_id", "in", tuple(account_ids))) else: # filter on account_id if account_id in account_ids: aml_domain.append(("account_id", "=", account_id)) else: continue if field == "crd": aml_domain.append(("credit", "<>", 0.0)) elif field == "deb": aml_domain.append(("debit", "<>", 0.0)) aml_domains.append(expression.normalize_domain(aml_domain)) if mode not in date_domain_by_mode: date_domain_by_mode[mode] = self.get_aml_domain_for_dates( date_from, date_to, mode ) assert aml_domains # TODO we could do this for more precision: # AND(OR(aml_domains[mode]), date_domain[mode]) for each mode return expression.OR(aml_domains) + expression.OR(date_domain_by_mode.values()) def get_aml_domain_for_dates(self, date_from, date_to, mode): if mode == self.MODE_VARIATION: domain = [("date", ">=", date_from), ("date", "<=", date_to)] elif mode in (self.MODE_INITIAL, self.MODE_END): # for income and expense account, sum from the beginning # of the current fiscal year only, for balance sheet accounts # sum from the beginning of time date_from_date = fields.Date.from_string(date_from) # TODO this takes the fy from the first company # make that user controllable (nice to have)? fy_date_from = self.companies[0].compute_fiscalyear_dates(date_from_date)[ "date_from" ] domain = [ "|", ("date", ">=", fields.Date.to_string(fy_date_from)), ("account_id.user_type_id.include_initial_balance", "=", True), ] if mode == self.MODE_INITIAL: domain.append(("date", "<", date_from)) elif mode == self.MODE_END: domain.append(("date", "<=", date_to)) elif mode == self.MODE_UNALLOCATED: date_from_date = fields.Date.from_string(date_from) # TODO this takes the fy from the first company # make that user controllable (nice to have)? fy_date_from = self.companies[0].compute_fiscalyear_dates(date_from_date)[ "date_from" ] domain = [ ("date", "<", fields.Date.to_string(fy_date_from)), ("account_id.user_type_id.include_initial_balance", "=", False), ] return expression.normalize_domain(domain) def _get_company_rates(self, date): # get exchange rates for each company with its rouding company_rates = {} target_rate = self.currency.with_context(date=date).rate for company in self.companies: if company.currency_id != self.currency: rate = target_rate / company.currency_id.with_context(date=date).rate else: rate = 1.0 company_rates[company.id] = (rate, company.currency_id.decimal_places) return company_rates def do_queries( self, date_from, date_to, additional_move_line_filter=None, aml_model=None, ): """Query sums of debit and credit for all accounts and domains used in expressions. This method must be executed after done_parsing(). """ if not aml_model: aml_model = self.env["account.move.line"] else: aml_model = self.env[aml_model] aml_model = aml_model.with_context(active_test=False) company_rates = self._get_company_rates(date_to) # {(domain, mode): {account_id: (debit, credit)}} self._data = defaultdict(dict) domain_by_mode = {} ends = [] for key in self._map_account_ids: domain, mode = key if mode == self.MODE_END and self.smart_end: # postpone computation of ending balance ends.append((domain, mode)) continue if mode not in domain_by_mode: domain_by_mode[mode] = self.get_aml_domain_for_dates( date_from, date_to, mode ) domain = list(domain) + domain_by_mode[mode] domain.append(("account_id", "in", self._map_account_ids[key])) if additional_move_line_filter: domain.extend(additional_move_line_filter) # fetch sum of debit/credit, grouped by account_id accs = aml_model.read_group( domain, ["debit", "credit", "account_id", "company_id"], ["account_id", "company_id"], lazy=False, ) for acc in accs: rate, dp = company_rates[acc["company_id"][0]] debit = acc["debit"] or 0.0 credit = acc["credit"] or 0.0 if mode in (self.MODE_INITIAL, self.MODE_UNALLOCATED) and float_is_zero( debit - credit, precision_digits=self.dp ): # in initial mode, ignore accounts with 0 balance continue self._data[key][acc["account_id"][0]] = (debit * rate, credit * rate) # compute ending balances by summing initial and variation for key in ends: domain, mode = key initial_data = self._data[(domain, self.MODE_INITIAL)] variation_data = self._data[(domain, self.MODE_VARIATION)] account_ids = set(initial_data.keys()) | set(variation_data.keys()) for account_id in account_ids: di, ci = initial_data.get(account_id, (AccountingNone, AccountingNone)) dv, cv = variation_data.get( account_id, (AccountingNone, AccountingNone) ) self._data[key][account_id] = (di + dv, ci + cv) def replace_expr(self, expr): """Replace accounting variables in an expression by their amount. Returns a new expression string. This method must be executed after do_queries(). """ def f(mo): field, mode, acc_domain, ml_domain = self._parse_match_object(mo) key = (ml_domain, mode) account_ids_data = self._data[key] v = AccountingNone account_ids = self._account_ids_by_acc_domain[acc_domain] for account_id in account_ids: debit, credit = account_ids_data.get( account_id, (AccountingNone, AccountingNone) ) if field == "bal": v += debit - credit elif field == "pbal" and debit >= credit: v += debit - credit elif field == "nbal" and debit < credit: v += debit - credit elif field == "deb": v += debit elif field == "crd": v += credit # in initial balance mode, assume 0 is None # as it does not make sense to distinguish 0 from "no data" if ( v is not AccountingNone and mode in (self.MODE_INITIAL, self.MODE_UNALLOCATED) and float_is_zero(v, precision_digits=self.dp) ): v = AccountingNone return "(" + repr(v) + ")" return self._ACC_RE.sub(f, expr) def replace_exprs_by_account_id(self, exprs): """Replace accounting variables in a list of expression by their amount, iterating by accounts involved in the expression. yields account_id, replaced_expr This method must be executed after do_queries(). """ def f(mo): field, mode, acc_domain, ml_domain = self._parse_match_object(mo) key = (ml_domain, mode) # first check if account_id is involved in # the current expression part if account_id not in self._account_ids_by_acc_domain[acc_domain]: return "(AccountingNone)" # here we know account_id is involved in acc_domain account_ids_data = self._data[key] debit, credit = account_ids_data.get( account_id, (AccountingNone, AccountingNone) ) if field == "bal": v = debit - credit elif field == "pbal": if debit >= credit: v = debit - credit else: v = AccountingNone elif field == "nbal": if debit < credit: v = debit - credit else: v = AccountingNone elif field == "deb": v = debit elif field == "crd": v = credit # in initial balance mode, assume 0 is None # as it does not make sense to distinguish 0 from "no data" if ( v is not AccountingNone and mode in (self.MODE_INITIAL, self.MODE_UNALLOCATED) and float_is_zero(v, precision_digits=self.dp) ): v = AccountingNone return "(" + repr(v) + ")" account_ids = set() for expr in exprs: for mo in self._ACC_RE.finditer(expr): field, mode, acc_domain, ml_domain = self._parse_match_object(mo) key = (ml_domain, mode) account_ids_data = self._data[key] for account_id in self._account_ids_by_acc_domain[acc_domain]: if account_id in account_ids_data: account_ids.add(account_id) for account_id in account_ids: yield account_id, [self._ACC_RE.sub(f, expr) for expr in exprs] @classmethod def _get_balances(cls, mode, companies, date_from, date_to): expr = "deb{mode}[], crd{mode}[]".format(mode=mode) aep = AccountingExpressionProcessor(companies) # disable smart_end to have the data at once, instead # of initial + variation aep.smart_end = False aep.parse_expr(expr) aep.done_parsing() aep.do_queries(date_from, date_to) return aep._data[((), mode)] @classmethod def get_balances_initial(cls, companies, date): """A convenience method to obtain the initial balances of all accounts at a given date. It is the same as get_balances_end(date-1). :param companies: :param date: Returns a dictionary: {account_id, (debit, credit)} """ return cls._get_balances(cls.MODE_INITIAL, companies, date, date) @classmethod def get_balances_end(cls, companies, date): """A convenience method to obtain the ending balances of all accounts at a given date. It is the same as get_balances_initial(date+1). :param companies: :param date: Returns a dictionary: {account_id, (debit, credit)} """ return cls._get_balances(cls.MODE_END, companies, date, date) @classmethod def get_balances_variation(cls, companies, date_from, date_to): """A convenience method to obtain the variation of the balances of all accounts over a period. :param companies: :param date: Returns a dictionary: {account_id, (debit, credit)} """ return cls._get_balances(cls.MODE_VARIATION, companies, date_from, date_to) @classmethod def get_unallocated_pl(cls, companies, date): """A convenience method to obtain the unallocated profit/loss of the previous fiscal years at a given date. :param companies: :param date: Returns a tuple (debit, credit) """ # TODO shoud we include here the accounts of type "unaffected" # or leave that to the caller? bals = cls._get_balances(cls.MODE_UNALLOCATED, companies, date, date) return tuple(map(sum, zip(*bals.values())))
41.246212
21,778
36,285
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2020 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import datetime import logging from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from .aep import AccountingExpressionProcessor as AEP from .expression_evaluator import ExpressionEvaluator _logger = logging.getLogger(__name__) SRC_ACTUALS = "actuals" SRC_ACTUALS_ALT = "actuals_alt" SRC_CMPCOL = "cmpcol" SRC_SUMCOL = "sumcol" MODE_NONE = "none" MODE_FIX = "fix" MODE_REL = "relative" class DateFilterRequired(ValidationError): pass class DateFilterForbidden(ValidationError): pass class MisReportInstancePeriodSum(models.Model): _name = "mis.report.instance.period.sum" _description = "MIS Report Instance Period Sum" period_id = fields.Many2one( comodel_name="mis.report.instance.period", string="Parent column", ondelete="cascade", required=True, ) period_to_sum_id = fields.Many2one( comodel_name="mis.report.instance.period", string="Column", ondelete="restrict", required=True, ) sign = fields.Selection([("+", "+"), ("-", "-")], required=True, default="+") @api.constrains("period_id", "period_to_sum_id") def _check_period_to_sum(self): for rec in self: if rec.period_id == rec.period_to_sum_id: raise ValidationError( _("You cannot sum period %s with itself.") % rec.period_id.name ) class MisReportInstancePeriod(models.Model): """A MIS report instance has the logic to compute a report template for a given date period. Periods have a duration (day, week, fiscal period) and are defined as an offset relative to a pivot date. """ @api.depends( "report_instance_id.pivot_date", "report_instance_id.comparison_mode", "date_range_type_id", "type", "offset", "duration", "mode", "manual_date_from", "manual_date_to", "is_ytd", ) def _compute_dates(self): for record in self: record.date_from = False record.date_to = False record.valid = False report = record.report_instance_id d = fields.Date.from_string(report.pivot_date) if not report.comparison_mode: record.date_from = report.date_from record.date_to = report.date_to record.valid = record.date_from and record.date_to elif record.mode == MODE_NONE: record.date_from = False record.date_to = False record.valid = True elif record.mode == MODE_FIX: record.date_from = record.manual_date_from record.date_to = record.manual_date_to record.valid = record.date_from and record.date_to elif record.mode == MODE_REL and record.type == "d": date_from = d + datetime.timedelta(days=record.offset) date_to = date_from + datetime.timedelta(days=record.duration - 1) record.date_from = fields.Date.to_string(date_from) record.date_to = fields.Date.to_string(date_to) record.valid = True elif record.mode == MODE_REL and record.type == "w": date_from = d - datetime.timedelta(d.weekday()) date_from = date_from + datetime.timedelta(days=record.offset * 7) date_to = date_from + datetime.timedelta(days=(7 * record.duration) - 1) record.date_from = fields.Date.to_string(date_from) record.date_to = fields.Date.to_string(date_to) record.valid = True elif record.mode == MODE_REL and record.type == "m": date_from = d.replace(day=1) date_from = date_from + relativedelta(months=record.offset) date_to = ( date_from + relativedelta(months=record.duration - 1) + relativedelta(day=31) ) record.date_from = fields.Date.to_string(date_from) record.date_to = fields.Date.to_string(date_to) record.valid = True elif record.mode == MODE_REL and record.type == "y": date_from = d.replace(month=1, day=1) date_from = date_from + relativedelta(years=record.offset) date_to = date_from + relativedelta(years=record.duration - 1) date_to = date_to.replace(month=12, day=31) record.date_from = fields.Date.to_string(date_from) record.date_to = fields.Date.to_string(date_to) record.valid = True elif record.mode == MODE_REL and record.type == "date_range": date_range_obj = record.env["date.range"] current_periods = date_range_obj.search( [ ("type_id", "=", record.date_range_type_id.id), ("date_start", "<=", d), ("date_end", ">=", d), "|", ("company_id", "=", False), ( "company_id", "in", record.report_instance_id.query_company_ids.ids, ), ] ) if current_periods: # TODO we take the first date range we found as current # this may be surprising if several companies # have overlapping date ranges with different dates current_period = current_periods[0] all_periods = date_range_obj.search( [ ("type_id", "=", current_period.type_id.id), ("company_id", "=", current_period.company_id.id), ], order="date_start", ) p = all_periods.ids.index(current_period.id) + record.offset if p >= 0 and p + record.duration <= len(all_periods): periods = all_periods[p : p + record.duration] record.date_from = periods[0].date_start record.date_to = periods[-1].date_end record.valid = True if record.mode == MODE_REL and record.valid and record.is_ytd: record.date_from = fields.Date.from_string(record.date_to).replace( day=1, month=1 ) _name = "mis.report.instance.period" _description = "MIS Report Instance Period" name = fields.Char(required=True, string="Label", translate=True) mode = fields.Selection( [ (MODE_FIX, "Fixed dates"), (MODE_REL, "Relative to report base date"), (MODE_NONE, "No date filter"), ], required=True, default=MODE_FIX, ) type = fields.Selection( [ ("d", _("Day")), ("w", _("Week")), ("m", _("Month")), ("y", _("Year")), ("date_range", _("Date Range")), ], string="Period type", ) is_ytd = fields.Boolean( default=False, string="Year to date", help="Forces the start date to Jan 1st of the relevant year", ) date_range_type_id = fields.Many2one( comodel_name="date.range.type", string="Date Range Type", domain=[("allow_overlap", "=", False)], ) offset = fields.Integer(help="Offset from current period", default=-1) duration = fields.Integer(help="Number of periods", default=1) date_from = fields.Date(compute="_compute_dates", string="From (computed)") date_to = fields.Date(compute="_compute_dates", string="To (computed)") manual_date_from = fields.Date(string="From") manual_date_to = fields.Date(string="To") date_range_id = fields.Many2one(comodel_name="date.range", string="Date Range") valid = fields.Boolean(compute="_compute_dates", type="boolean") sequence = fields.Integer(default=100) report_instance_id = fields.Many2one( comodel_name="mis.report.instance", string="Report Instance", required=True, ondelete="cascade", ) report_id = fields.Many2one(related="report_instance_id.report_id") normalize_factor = fields.Integer( string="Factor", help="Factor to use to normalize the period (used in comparison", default=1, ) subkpi_ids = fields.Many2many("mis.report.subkpi", string="Sub KPI Filter") source = fields.Selection( [ (SRC_ACTUALS, "Actuals"), (SRC_ACTUALS_ALT, "Actuals (alternative)"), (SRC_SUMCOL, "Sum columns"), (SRC_CMPCOL, "Compare columns"), ], default=SRC_ACTUALS, required=True, help="Actuals: current data, from accounting and other queries.\n" "Actuals (alternative): current data from an " "alternative source (eg a database view providing look-alike " "account move lines).\n" "Sum columns: summation (+/-) of other columns.\n" "Compare to column: compare to other column.\n", ) source_aml_model_id = fields.Many2one( comodel_name="ir.model", string="Move lines source", domain=[ ("field_id.name", "=", "debit"), ("field_id.name", "=", "credit"), ("field_id.name", "=", "account_id"), ("field_id.name", "=", "date"), ("field_id.name", "=", "company_id"), ("field_id.model_id.model", "!=", "account.move.line"), ], help="A 'move line like' model, ie having at least debit, credit, " "date, account_id and company_id fields.", ) source_aml_model_name = fields.Char( string="Move lines source model name", related="source_aml_model_id.model" ) source_sumcol_ids = fields.One2many( comodel_name="mis.report.instance.period.sum", inverse_name="period_id", string="Columns to sum", ) source_sumcol_accdet = fields.Boolean(string="Sum account details") source_cmpcol_from_id = fields.Many2one( comodel_name="mis.report.instance.period", string="versus" ) source_cmpcol_to_id = fields.Many2one( comodel_name="mis.report.instance.period", string="Compare" ) allowed_cmpcol_ids = fields.Many2many( comodel_name="mis.report.instance.period", compute="_compute_allowed_cmpcol_ids" ) # filters analytic_account_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic Account", help=( "Filter column on journal entries that match this analytic account." "This filter is combined with a AND with the report-level filters " "and cannot be modified in the preview." ), ) analytic_group_id = fields.Many2one( comodel_name="account.analytic.group", string="Analytic Account Group", help=( "Filter column on journal entries that match this analytic account " "group. This filter is combined with a AND with the report-level " "filters and cannot be modified in the preview." ), ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Analytic Tags", help=( "Filter column on journal entries that have all these analytic tags." "This filter is combined with a AND with the report-level filters " "and cannot be modified in the preview." ), ) _order = "sequence, id" _sql_constraints = [ ("duration", "CHECK (duration>0)", "Wrong duration, it must be positive!"), ( "normalize_factor", "CHECK (normalize_factor>0)", "Wrong normalize factor, it must be positive!", ), ( "name_unique", "unique(name, report_instance_id)", "Period name should be unique by report", ), ] @api.depends("report_instance_id") def _compute_allowed_cmpcol_ids(self): """Compute actual records while in NewId context""" for record in self: record.allowed_cmpcol_ids = record.report_instance_id.period_ids - record @api.constrains("source_aml_model_id") def _check_source_aml_model_id(self): for record in self: if record.source_aml_model_id: record_model = record.source_aml_model_id.field_id.filtered( lambda r: r.name == "account_id" ).relation report_account_model = record.report_id.account_model if record_model != report_account_model: raise ValidationError( _( "Actual (alternative) models used in columns must " "have the same account model in the Account field and must " "be the same defined in the " "report template: %s" ) % report_account_model ) @api.onchange("date_range_id") def _onchange_date_range(self): if self.date_range_id: self.manual_date_from = self.date_range_id.date_start self.manual_date_to = self.date_range_id.date_end @api.onchange("manual_date_from", "manual_date_to") def _onchange_dates(self): if self.date_range_id: if ( self.manual_date_from != self.date_range_id.date_start or self.manual_date_to != self.date_range_id.date_end ): self.date_range_id = False @api.onchange("source") def _onchange_source(self): if self.source in (SRC_SUMCOL, SRC_CMPCOL): self.mode = MODE_NONE # Dirty hack to solve bug https://github.com/OCA/mis-builder/issues/393 if self.source and not self.report_instance_id.id: self.report_instance_id = self.report_instance_id._origin.id def _get_aml_model_name(self): self.ensure_one() if self.source == SRC_ACTUALS: return self.report_id.sudo().move_lines_source.model elif self.source == SRC_ACTUALS_ALT: return self.source_aml_model_name return False @api.model def _get_filter_domain_from_context(self): filters = [] mis_report_filters = self.env.context.get("mis_report_filters", {}) for filter_name, domain in mis_report_filters.items(): if domain: value = domain.get("value") operator = domain.get("operator", "=") # Operator = 'all' when coming from JS widget if operator == "all": if not isinstance(value, list): value = [value] for m in value: filters.append((filter_name, "in", [m])) else: filters.append((filter_name, operator, value)) return filters def _get_additional_move_line_filter(self): """Prepare a filter to apply on all move lines This filter is applied with a AND operator on all accounting expression domains. This hook is intended to be inherited, and is useful to implement filtering on analytic dimensions or operational units. The default filter is built from a ``mis_report_filters`` context key, which is a list set by the analytic filtering mechanism of the mis report widget:: [(field_name, {'value': value, 'operator': operator})] Returns an Odoo domain expression (a python list) compatible with account.move.line.""" self.ensure_one() domain = self._get_filter_domain_from_context() aml_model_name = self._get_aml_model_name() if aml_model_name: domain.extend( self.report_id._get_target_move_domain( self.report_instance_id.target_move, aml_model_name ) ) if self.analytic_account_id: domain.append(("analytic_account_id", "=", self.analytic_account_id.id)) if self.analytic_group_id: domain.append( ("analytic_account_id.group_id", "=", self.analytic_group_id.id) ) for tag in self.analytic_tag_ids: domain.append(("analytic_tag_ids", "=", tag.id)) return domain def _get_additional_query_filter(self, query): """Prepare an additional filter to apply on the query This filter is combined to the query domain with a AND operator. This hook is intended to be inherited, and is useful to implement filtering on analytic dimensions or operational units. Returns an Odoo domain expression (a python list) compatible with the model of the query.""" self.ensure_one() return [] @api.constrains("mode", "source") def _check_mode_source(self): for rec in self: if rec.source in (SRC_ACTUALS, SRC_ACTUALS_ALT): if rec.mode == MODE_NONE: raise DateFilterRequired( _("A date filter is mandatory for this source " "in column %s.") % rec.name ) elif rec.source in (SRC_SUMCOL, SRC_CMPCOL): if rec.mode != MODE_NONE: raise DateFilterForbidden( _("No date filter is allowed for this source " "in column %s.") % rec.name ) @api.constrains("source", "source_cmpcol_from_id", "source_cmpcol_to_id") def _check_source_cmpcol(self): for rec in self: if rec.source == SRC_CMPCOL: if not rec.source_cmpcol_from_id or not rec.source_cmpcol_to_id: raise ValidationError( _("Please provide both columns to compare in %s.") % rec.name ) if rec.source_cmpcol_from_id == rec or rec.source_cmpcol_to_id == rec: raise ValidationError( _("Column %s cannot be compared to itrec.") % rec.name ) if ( rec.source_cmpcol_from_id.report_instance_id != rec.report_instance_id or rec.source_cmpcol_to_id.report_instance_id != rec.report_instance_id ): raise ValidationError( _("Columns to compare must belong to the same report " "in %s") % rec.name ) def copy_data(self, default=None): if self.source == SRC_CMPCOL: # While duplicating a MIS report instance, comparison columns are # ignored because they would raise an error, as they keep the old # `source_cmpcol_from_id` and `source_cmpcol_to_id` from the # original record. return [ False, ] return super().copy_data(default=default) class MisReportInstance(models.Model): """The MIS report instance combines everything to compute a MIS report template for a set of periods.""" @api.depends("date") def _compute_pivot_date(self): for record in self: if record.date: record.pivot_date = record.date else: record.pivot_date = fields.Date.context_today(record) _name = "mis.report.instance" _description = "MIS Report Instance" name = fields.Char(required=True, translate=True) description = fields.Char(related="report_id.description", readonly=True) date = fields.Date( string="Base date", help="Report base date " "(leave empty to use current date)" ) pivot_date = fields.Date(compute="_compute_pivot_date") report_id = fields.Many2one("mis.report", required=True, string="Report") period_ids = fields.One2many( comodel_name="mis.report.instance.period", inverse_name="report_instance_id", required=True, string="Periods", copy=True, ) target_move = fields.Selection( [("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", required=True, default="posted", ) company_id = fields.Many2one( comodel_name="res.company", string="Allowed company", default=lambda self: self.env.company, required=False, ) multi_company = fields.Boolean( string="Multiple companies", help="Check if you wish to specify several companies to be searched for data.", default=False, ) company_ids = fields.Many2many( comodel_name="res.company", string="Allowed companies", help="Select companies for which data will be searched.", ) query_company_ids = fields.Many2many( string="Effective companies", comodel_name="res.company", compute="_compute_query_company_ids", help="Companies for which data will be searched.", ) currency_id = fields.Many2one( comodel_name="res.currency", string="Currency", help="Select target currency for the report. " "Required if companies have different currencies.", required=False, ) landscape_pdf = fields.Boolean(string="Landscape PDF") no_auto_expand_accounts = fields.Boolean(string="Disable account details expansion") display_columns_description = fields.Boolean( help="Display the date range details in the column headers." ) comparison_mode = fields.Boolean( compute="_compute_comparison_mode", inverse="_inverse_comparison_mode" ) date_range_id = fields.Many2one(comodel_name="date.range", string="Date Range") date_from = fields.Date(string="From") date_to = fields.Date(string="To") temporary = fields.Boolean(default=False) analytic_account_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic Account" ) analytic_group_id = fields.Many2one( comodel_name="account.analytic.group", string="Analytic Account Group", ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Analytic Tags" ) hide_analytic_filters = fields.Boolean(default=True) @api.onchange("multi_company") def _onchange_company(self): if self.multi_company: self.company_ids |= self.company_id self.company_id = False else: prev = self.company_ids.ids company = False if self.env.company.id in prev or not prev: company = self.env.company else: for c_id in prev: if c_id in self.env.companies.ids: company = self.env["res.company"].browse(c_id) break self.company_id = company self.company_ids = False @api.depends("multi_company", "company_id", "company_ids") @api.depends_context("allowed_company_ids") def _compute_query_company_ids(self): for rec in self: if rec.multi_company: if not rec.company_ids: rec.query_company_ids = self.env.companies else: rec.query_company_ids = rec.company_ids & self.env.companies else: rec.query_company_ids = rec.company_id or self.env.company @api.model def get_filter_descriptions_from_context(self): filters = self.env.context.get("mis_report_filters", {}) analytic_account_id = filters.get("analytic_account_id", {}).get("value") filter_descriptions = [] if analytic_account_id: analytic_account = self.env["account.analytic.account"].browse( analytic_account_id ) filter_descriptions.append( _("Analytic Account: %s") % analytic_account.display_name ) analytic_group_id = filters.get("analytic_account_id.group_id", {}).get("value") if analytic_group_id: analytic_group = self.env["account.analytic.group"].browse( analytic_group_id ) filter_descriptions.append( _("Analytic Account Group: %s") % analytic_group.display_name ) analytic_tag_ids = filters.get("analytic_tag_ids", {}).get("value") if analytic_tag_ids: analytic_tags = self.env["account.analytic.tag"].browse(analytic_tag_ids) filter_descriptions.append( _("Analytic Tags: %s") % ", ".join(analytic_tags.mapped("name")) ) return filter_descriptions def save_report(self): self.ensure_one() self.write({"temporary": False}) xmlid = "mis_builder.mis_report_instance_view_action" action = self.env["ir.actions.act_window"]._for_xml_id(xmlid) view = self.env.ref("mis_builder.mis_report_instance_view_form") action.update({"views": [(view.id, "form")], "res_id": self.id}) return action @api.model def _vacuum_report(self, hours=24): clear_date = fields.Datetime.to_string( datetime.datetime.now() - datetime.timedelta(hours=hours) ) reports = self.search( [("write_date", "<", clear_date), ("temporary", "=", True)] ) _logger.debug("Vacuum %s Temporary MIS Builder Report", len(reports)) return reports.unlink() def copy(self, default=None): self.ensure_one() default = dict(default or {}) default["name"] = _("%s (copy)") % self.name return super().copy(default) def _format_date(self, date): # format date following user language lang_model = self.env["res.lang"] lang = lang_model._lang_get(self.env.user.lang) date_format = lang.date_format return datetime.datetime.strftime(fields.Date.from_string(date), date_format) @api.depends("date_from") def _compute_comparison_mode(self): for instance in self: instance.comparison_mode = bool(instance.period_ids) and not bool( instance.date_from ) def _inverse_comparison_mode(self): for record in self: if not record.comparison_mode: if not record.date_from: record.date_from = fields.Date.context_today(self) if not record.date_to: record.date_to = fields.Date.context_today(self) record.period_ids.unlink() record.write({"period_ids": [(0, 0, {"name": "Default"})]}) else: record.date_from = None record.date_to = None @api.onchange("date_range_id") def _onchange_date_range(self): if self.date_range_id: self.date_from = self.date_range_id.date_start self.date_to = self.date_range_id.date_end @api.onchange("date_from", "date_to") def _onchange_dates(self): if self.date_range_id: if ( self.date_from != self.date_range_id.date_start or self.date_to != self.date_range_id.date_end ): self.date_range_id = False def _add_analytic_filters_to_context(self, context): self.ensure_one() if self.analytic_account_id: context["mis_report_filters"]["analytic_account_id"] = { "value": self.analytic_account_id.id, "operator": "=", } if self.analytic_group_id: context["mis_report_filters"]["analytic_account_id.group_id"] = { "value": self.analytic_group_id.id, "operator": "=", } if self.analytic_tag_ids: context["mis_report_filters"]["analytic_tag_ids"] = { "value": self.analytic_tag_ids.ids, "operator": "all", } def _context_with_filters(self): self.ensure_one() if "mis_report_filters" in self.env.context: # analytic filters are already in context, do nothing return self.env.context context = dict(self.env.context, mis_report_filters={}) self._add_analytic_filters_to_context(context) return context def preview(self): self.ensure_one() view_id = self.env.ref("mis_builder." "mis_report_instance_result_view_form") return { "type": "ir.actions.act_window", "res_model": "mis.report.instance", "res_id": self.id, "view_mode": "form", "view_id": view_id.id, "target": "current", "context": self._context_with_filters(), } def print_pdf(self): self.ensure_one() context = dict(self._context_with_filters(), landscape=self.landscape_pdf) return ( self.env.ref("mis_builder.qweb_pdf_export") .with_context(**context) .report_action(self, data=dict(dummy=True)) # required to propagate context ) def export_xls(self): self.ensure_one() context = dict(self._context_with_filters()) return ( self.env.ref("mis_builder.xls_export") .with_context(**context) .report_action(self, data=dict(dummy=True)) # required to propagate context ) def display_settings(self): assert len(self.ids) <= 1 view_id = self.env.ref("mis_builder.mis_report_instance_view_form") return { "type": "ir.actions.act_window", "res_model": "mis.report.instance", "res_id": self.id if self.id else False, "view_mode": "form", "views": [(view_id.id, "form")], "view_id": view_id.id, "target": "current", } def _add_column_move_lines(self, aep, kpi_matrix, period, label, description): if not period.date_from or not period.date_to: raise UserError( _("Column %s with move lines source must have from/to dates.") % (period.name,) ) expression_evaluator = ExpressionEvaluator( aep, period.date_from, period.date_to, period._get_additional_move_line_filter(), period._get_aml_model_name(), ) self.report_id._declare_and_compute_period( expression_evaluator, kpi_matrix, period.id, label, description, period.subkpi_ids, period._get_additional_query_filter, no_auto_expand_accounts=self.no_auto_expand_accounts, ) def _add_column_sumcol(self, aep, kpi_matrix, period, label, description): kpi_matrix.declare_sum( period.id, [(c.sign, c.period_to_sum_id.id) for c in period.source_sumcol_ids], label, description, period.source_sumcol_accdet, ) def _add_column_cmpcol(self, aep, kpi_matrix, period, label, description): kpi_matrix.declare_comparison( period.id, period.source_cmpcol_to_id.id, period.source_cmpcol_from_id.id, label, description, ) def _add_column(self, aep, kpi_matrix, period, label, description): if period.source == SRC_ACTUALS: return self._add_column_move_lines( aep, kpi_matrix, period, label, description ) elif period.source == SRC_ACTUALS_ALT: return self._add_column_move_lines( aep, kpi_matrix, period, label, description ) elif period.source == SRC_SUMCOL: return self._add_column_sumcol(aep, kpi_matrix, period, label, description) elif period.source == SRC_CMPCOL: return self._add_column_cmpcol(aep, kpi_matrix, period, label, description) def _compute_matrix(self): """Compute a report and return a KpiMatrix. The key attribute of the matrix columns (KpiMatrixCol) is guaranteed to be the id of the mis.report.instance.period. """ self.ensure_one() aep = self.report_id._prepare_aep(self.query_company_ids, self.currency_id) kpi_matrix = self.report_id.prepare_kpi_matrix(self.multi_company) for period in self.period_ids: description = None if period.mode == MODE_NONE: pass elif not self.display_columns_description: pass elif period.date_from == period.date_to and period.date_from: description = self._format_date(period.date_from) elif period.date_from and period.date_to: date_from = self._format_date(period.date_from) date_to = self._format_date(period.date_to) description = _( "from %(date_from)s to %(date_to)s", date_from=date_from, date_to=date_to, ) self._add_column(aep, kpi_matrix, period, period.name, description) kpi_matrix.compute_comparisons() kpi_matrix.compute_sums() return kpi_matrix def compute(self): self.ensure_one() kpi_matrix = self._compute_matrix() return kpi_matrix.as_dict() def drilldown(self, arg): self.ensure_one() period_id = arg.get("period_id") expr = arg.get("expr") account_id = arg.get("account_id") if period_id and expr and AEP.has_account_var(expr): period = self.env["mis.report.instance.period"].browse(period_id) aep = AEP( self.query_company_ids, self.currency_id, self.report_id.account_model ) aep.parse_expr(expr) aep.done_parsing() domain = aep.get_aml_domain_for_expr( expr, period.date_from, period.date_to, account_id, ) domain.extend(period._get_additional_move_line_filter()) return { "name": self._get_drilldown_action_name(arg), "domain": domain, "type": "ir.actions.act_window", "res_model": period._get_aml_model_name(), "views": [[False, "list"], [False, "form"]], "view_mode": "list", "target": "current", "context": {"active_test": False}, } else: return False def _get_drilldown_action_name(self, arg): kpi_id = arg.get("kpi_id") kpi = self.env["mis.report.kpi"].browse(kpi_id) period_id = arg.get("period_id") period = self.env["mis.report.instance.period"].browse(period_id) account_id = arg.get("account_id") if account_id: account = self.env[self.report_id.account_model].browse(account_id) return "{kpi} - {account} - {period}".format( kpi=kpi.description, account=account.display_name, period=period.display_name, ) else: return "{kpi} - {period}".format( kpi=kpi.description, period=period.display_name, )
39.269481
36,285
3,607
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.fields import Date from .mis_kpi_data import intersect_days class ProRataReadGroupMixin(models.AbstractModel): _name = "prorata.read_group.mixin" _description = "Adapt model with date_from/date_to for pro-rata temporis read_group" date_from = fields.Date(required=True) date_to = fields.Date(required=True) date = fields.Date( compute=lambda self: None, search="_search_date", help=( "Dummy field that adapts searches on date " "to searches on date_from/date_to." ), ) def _search_date(self, operator, value): if operator in (">=", ">"): return [("date_to", operator, value)] elif operator in ("<=", "<"): return [("date_from", operator, value)] raise UserError( _("Unsupported operator %s for searching on date") % (operator,) ) @api.model def _intersect_days(self, item_dt_from, item_dt_to, dt_from, dt_to): return intersect_days(item_dt_from, item_dt_to, dt_from, dt_to) @api.model def read_group( self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True ): """Override read_group to perform pro-rata temporis adjustments. When read_group is invoked with a domain that filters on a time period (date >= from and date <= to, or date_from <= to and date_to >= from), adjust the accumulated values pro-rata temporis. """ date_from = None date_to = None assert isinstance(domain, list) for domain_item in domain: if isinstance(domain_item, (list, tuple)): field, op, value = domain_item if field == "date" and op == ">=": date_from = value elif field == "date_to" and op == ">=": date_from = value elif field == "date" and op == "<=": date_to = value elif field == "date_from" and op == "<=": date_to = value if ( date_from is not None and date_to is not None and not any(":" in f for f in fields) ): dt_from = Date.from_string(date_from) dt_to = Date.from_string(date_to) res = {} sum_fields = set(fields) - set(groupby) read_fields = set(fields + ["date_from", "date_to"]) for item in self.search(domain).read(read_fields): key = tuple(item[k] for k in groupby) if key not in res: res[key] = {k: item[k] for k in groupby} res[key].update({k: 0.0 for k in sum_fields}) res_item = res[key] for sum_field in sum_fields: item_dt_from = Date.from_string(item["date_from"]) item_dt_to = Date.from_string(item["date_to"]) i_days, item_days = self._intersect_days( item_dt_from, item_dt_to, dt_from, dt_to ) res_item[sum_field] += item[sum_field] * i_days / item_days return res.values() return super().read_group( domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy, )
37.572917
3,607
1,061
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import traceback from odoo.tools.safe_eval import _BUILTINS, _SAFE_OPCODES, test_expr from .data_error import DataError, NameDataError __all__ = ["mis_safe_eval"] def mis_safe_eval(expr, locals_dict): """Evaluate an expression using safe_eval Returns the evaluated value or DataError. Raises NameError if the evaluation depends on a variable that is not present in local_dict. """ try: c = test_expr(expr, _SAFE_OPCODES, mode="eval") globals_dict = {"__builtins__": _BUILTINS} # pylint: disable=eval-used,eval-referenced val = eval(c, globals_dict, locals_dict) except NameError: val = NameDataError("#NAME", traceback.format_exc()) except ZeroDivisionError: # pylint: disable=redefined-variable-type val = DataError("#DIV/0", traceback.format_exc()) except Exception: val = DataError("#ERR", traceback.format_exc()) return val
32.151515
1,061
6,512
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging import numbers from collections import defaultdict from datetime import datetime from odoo import _, fields, models from ..models.accounting_none import AccountingNone from ..models.data_error import DataError from ..models.mis_report_style import TYPE_STR _logger = logging.getLogger(__name__) ROW_HEIGHT = 15 # xlsxwriter units COL_WIDTH = 0.9 # xlsxwriter units MIN_COL_WIDTH = 10 # characters MAX_COL_WIDTH = 50 # characters class MisBuilderXlsx(models.AbstractModel): _name = "report.mis_builder.mis_report_instance_xlsx" _description = "MIS Builder XLSX report" _inherit = "report.report_xlsx.abstract" def generate_xlsx_report(self, workbook, data, objects): # get the computed result of the report matrix = objects._compute_matrix() style_obj = self.env["mis.report.style"] # create worksheet report_name = "{} - {}".format( objects[0].name, ", ".join([a.name for a in objects[0].query_company_ids]) ) sheet = workbook.add_worksheet(report_name[:31]) row_pos = 0 col_pos = 0 # width of the labels column label_col_width = MIN_COL_WIDTH # {col_pos: max width in characters} col_width = defaultdict(lambda: MIN_COL_WIDTH) # document title bold = workbook.add_format({"bold": True}) header_format = workbook.add_format( {"bold": True, "align": "center", "bg_color": "#F0EEEE"} ) sheet.write(row_pos, 0, report_name, bold) row_pos += 2 # filters if not objects.hide_analytic_filters: for filter_description in objects.get_filter_descriptions_from_context(): sheet.write(row_pos, 0, filter_description) row_pos += 1 row_pos += 1 # column headers sheet.write(row_pos, 0, "", header_format) col_pos = 1 for col in matrix.iter_cols(): label = col.label if col.description: label += "\n" + col.description sheet.set_row(row_pos, ROW_HEIGHT * 2) if col.colspan > 1: sheet.merge_range( row_pos, col_pos, row_pos, col_pos + col.colspan - 1, label, header_format, ) else: sheet.write(row_pos, col_pos, label, header_format) col_width[col_pos] = max( col_width[col_pos], len(col.label or ""), len(col.description or "") ) col_pos += col.colspan row_pos += 1 # sub column headers sheet.write(row_pos, 0, "", header_format) col_pos = 1 for subcol in matrix.iter_subcols(): label = subcol.label if subcol.description: label += "\n" + subcol.description sheet.set_row(row_pos, ROW_HEIGHT * 2) sheet.write(row_pos, col_pos, label, header_format) col_width[col_pos] = max( col_width[col_pos], len(subcol.label or ""), len(subcol.description or ""), ) col_pos += 1 row_pos += 1 # rows for row in matrix.iter_rows(): if ( row.style_props.hide_empty and row.is_empty() ) or row.style_props.hide_always: continue row_xlsx_style = style_obj.to_xlsx_style(TYPE_STR, row.style_props) row_format = workbook.add_format(row_xlsx_style) col_pos = 0 label = row.label if row.description: label += "\n" + row.description sheet.set_row(row_pos, ROW_HEIGHT * 2) sheet.write(row_pos, col_pos, label, row_format) label_col_width = max( label_col_width, len(row.label or ""), len(row.description or "") ) for cell in row.iter_cells(): col_pos += 1 if not cell or cell.val is AccountingNone: # TODO col/subcol format sheet.write(row_pos, col_pos, "", row_format) continue cell_xlsx_style = style_obj.to_xlsx_style( cell.val_type, cell.style_props, no_indent=True ) cell_xlsx_style["align"] = "right" cell_format = workbook.add_format(cell_xlsx_style) if isinstance(cell.val, DataError): val = cell.val.name # TODO display cell.val.msg as Excel comment? elif cell.val is None or cell.val is AccountingNone: val = "" else: divider = float(cell.style_props.get("divider", 1)) if ( divider != 1 and isinstance(cell.val, numbers.Number) and not cell.val_type == "pct" ): val = cell.val / divider else: val = cell.val sheet.write(row_pos, col_pos, val, cell_format) col_width[col_pos] = max( col_width[col_pos], len(cell.val_rendered or "") ) row_pos += 1 # Add date/time footer row_pos += 1 footer_format = workbook.add_format( {"italic": True, "font_color": "#202020", "size": 9} ) lang_model = self.env["res.lang"] lang = lang_model._lang_get(self.env.user.lang) now_tz = fields.Datetime.context_timestamp( self.env["res.users"], datetime.now() ) create_date = _("Generated on {} at {}").format( now_tz.strftime(lang.date_format), now_tz.strftime(lang.time_format) ) sheet.write(row_pos, 0, create_date, footer_format) # adjust col widths sheet.set_column(0, 0, min(label_col_width, MAX_COL_WIDTH) * COL_WIDTH) data_col_width = min(MAX_COL_WIDTH, max(col_width.values())) min_col_pos = min(col_width.keys()) max_col_pos = max(col_width.keys()) sheet.set_column(min_col_pos, max_col_pos, data_col_width * COL_WIDTH)
37.425287
6,512
1,020
py
PYTHON
15.0
# Copyright 2014 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from odoo import models _logger = logging.getLogger(__name__) class Report(models.Model): _inherit = "ir.actions.report" def _render_qweb_pdf(self, res_ids=None, data=None): if self.report_name == "mis_builder.report_mis_report_instance": if not res_ids: res_ids = self.env.context.get("active_ids") mis_report_instance = self.env["mis.report.instance"].browse(res_ids)[0] context = dict( mis_report_instance._context_with_filters(), landscape=mis_report_instance.landscape_pdf, ) # data=None, because it was there only to force Odoo # to propagate context return super(Report, self.with_context(**context))._render_qweb_pdf( res_ids, data=None ) return super()._render_qweb_pdf(res_ids, data)
36.428571
1,020
1,444
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Hotel Management", "version": "15.0.1.0.0", "author": "Odoo Community Association (OCA), Serpent Consulting \ Services Pvt. Ltd., OpenERP SA", "category": "Hotel Management", "website": "https://github.com/OCA/vertical-hotel", "depends": ["sale_stock", "account"], "license": "LGPL-3", "summary": "Hotel Management to Manage Folio and Hotel Configuration", "demo": ["demo/hotel_data.xml"], "data": [ "security/hotel_security.xml", "security/ir.model.access.csv", "data/hotel_sequence.xml", "report/report_view.xml", "report/hotel_folio_report_template.xml", "views/hotel_folio.xml", "views/hotel_room.xml", "views/hotel_room_amenities.xml", "views/hotel_room_type.xml", "views/hotel_service_type.xml", "views/hotel_services.xml", "views/product_product.xml", "views/res_company.xml", "views/actions.xml", "views/menus.xml", "wizard/hotel_wizard.xml", ], "assets": { "web.assets_backend": ["hotel/static/src/css/room_kanban.css"], }, "external_dependencies": {"python": ["python-dateutil"]}, "images": ["static/description/Hotel.png"], "application": True, }
37.025641
1,444
1,811
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo.tests import common class TestHotel(common.TransactionCase): def setUp(self): super(TestHotel, self).setUp() self.hotel_folio_obj = self.env["hotel.folio"] self.hotel_folio_line = self.env["hotel.folio.line"] self.warehouse = self.env.ref("stock.warehouse0") self.partner = self.env.ref("base.res_partner_2") self.price_list = self.env.ref("product.list0") self.room = self.env.ref("hotel.hotel_room_0") cur_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.hotel_folio = self.hotel_folio_obj.create( { "name": "Folio/00001", "date_order": cur_date, "warehouse_id": self.warehouse.id, "invoice_status": "no", "pricelist_id": self.price_list.id, "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "state": "draft", } ) def test_confirm_sale(self): self.hotel_folio.action_confirm() self.assertEqual(self.hotel_folio.state == "sale", True) def test_folio_cancel(self): self.hotel_folio.action_cancel() self.assertEqual(self.hotel_folio.state == "cancel", True) def test_folio_set_to_draft(self): self.hotel_folio.action_cancel_draft() self.assertEqual(self.hotel_folio.state == "draft", True) def test_set_done(self): self.hotel_folio.action_done() self.assertEqual(self.hotel_folio.state == "done", True)
36.959184
1,811
747
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class FolioReportWizard(models.TransientModel): _name = "folio.report.wizard" _rec_name = "date_start" _description = "Allow print folio report by date" date_start = fields.Datetime("Start Date") date_end = fields.Datetime("End Date") def print_report(self): data = { "ids": self.ids, "model": "hotel.folio", "form": self.read(["date_start", "date_end"])[0], } return self.env.ref("hotel.report_hotel_management").report_action( self, data=data )
32.478261
747
1,458
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" advance_payment_method = fields.Selection( [ ("delivered", "Regular invoice"), ("percentage", "Down payment (percentage)"), ("fixed", "Down payment (fixed amount)"), ], string="Create Invoice", default="delivered", required=True, help="""A standard invoice is issued with all the order lines ready for invoicing, according to their invoicing policy (based on ordered or delivered quantity).""", ) def create_invoices(self): ctx = self.env.context.copy() if self._context.get("active_model") == "hotel.folio": HotelFolio = self.env["hotel.folio"] folio = HotelFolio.browse(self._context.get("active_ids", [])) folio.room_line_ids.mapped("product_id").write({"isroom": True}) ctx.update( { "active_ids": folio.order_id.ids, "active_id": folio.order_id.id, "folio_id": folio.id, } ) res = super(SaleAdvancePaymentInv, self.with_context(**ctx)).create_invoices() return res
36.45
1,458
574
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class AccountMove(models.Model): _inherit = "account.move" @api.model def create(self, vals): res = super(AccountMove, self).create(vals) if self._context.get("folio_id"): folio = self.env["hotel.folio"].browse(self._context["folio_id"]) folio.write({"hotel_invoice_id": res.id, "invoice_status": "invoiced"}) return res
33.764706
574
11,673
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.osv import expression class HotelFloor(models.Model): _name = "hotel.floor" _description = "Floor" _order = "sequence" name = fields.Char("Floor Name", required=True, index=True) sequence = fields.Integer("sequence", default=10) class HotelRoom(models.Model): _name = "hotel.room" _description = "Hotel Room" product_id = fields.Many2one( "product.product", "Product_id", required=True, delegate=True, ondelete="cascade", ) floor_id = fields.Many2one( "hotel.floor", "Floor No", help="At which floor the room is located.", ondelete="restrict", ) max_adult = fields.Integer() max_child = fields.Integer() room_categ_id = fields.Many2one( "hotel.room.type", "Room Category", required=True, ondelete="restrict" ) room_amenities_ids = fields.Many2many( "hotel.room.amenities", string="Room Amenities", help="List of room amenities." ) status = fields.Selection( [("available", "Available"), ("occupied", "Occupied")], default="available", ) capacity = fields.Integer(required=True) room_line_ids = fields.One2many( "folio.room.line", "room_id", string="Room Reservation Line" ) product_manager = fields.Many2one("res.users") @api.model def create(self, vals): if "room_categ_id" in vals: room_categ = self.env["hotel.room.type"].browse(vals.get("room_categ_id")) vals.update({"categ_id": room_categ.product_categ_id.id}) return super(HotelRoom, self).create(vals) @api.constrains("capacity") def _check_capacity(self): for room in self: if room.capacity <= 0: raise ValidationError(_("Room capacity must be more than 0")) @api.onchange("isroom") def _isroom_change(self): """ Based on isroom, status will be updated. ---------------------------------------- @param self: object pointer """ self.status = "available" if self.status else "occupied" def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. """ if "room_categ_id" in vals: room_categ = self.env["hotel.room.type"].browse(vals.get("room_categ_id")) vals.update({"categ_id": room_categ.product_categ_id.id}) if "isroom" in vals and vals["isroom"] is False: vals.update({"color": 2, "status": "occupied"}) if "isroom" in vals and vals["isroom"] is True: vals.update({"color": 5, "status": "available"}) return super(HotelRoom, self).write(vals) def set_room_status_occupied(self): """ This method is used to change the state to occupied of the hotel room. --------------------------------------- @param self: object pointer """ return self.write({"isroom": False, "color": 2}) def set_room_status_available(self): """ This method is used to change the state to available of the hotel room. --------------------------------------- @param self: object pointer """ return self.write({"isroom": True, "color": 5}) class HotelRoomType(models.Model): _name = "hotel.room.type" _description = "Room Type" categ_id = fields.Many2one("hotel.room.type", "Category") child_ids = fields.One2many("hotel.room.type", "categ_id", "Room Child Categories") product_categ_id = fields.Many2one( "product.category", "Product Category", delegate=True, required=True, copy=False, ondelete="restrict", ) @api.model def create(self, vals): if "categ_id" in vals: room_categ = self.env["hotel.room.type"].browse(vals.get("categ_id")) vals.update({"parent_id": room_categ.product_categ_id.id}) return super(HotelRoomType, self).create(vals) def write(self, vals): if "categ_id" in vals: room_categ = self.env["hotel.room.type"].browse(vals.get("categ_id")) vals.update({"parent_id": room_categ.product_categ_id.id}) return super(HotelRoomType, self).write(vals) def name_get(self): def get_names(cat): """Return the list [cat.name, cat.categ_id.name, ...]""" res = [] while cat: res.append(cat.name) cat = cat.categ_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self] @api.model def name_search(self, name, args=None, operator="ilike", limit=100): if not args: args = [] if name: # Be sure name_search is symmetric to name_get category_names = name.split(" / ") parents = list(category_names) child = parents.pop() domain = [("name", operator, child)] if parents: names_ids = self.name_search( " / ".join(parents), args=args, operator="ilike", limit=limit, ) category_ids = [name_id[0] for name_id in names_ids] if operator in expression.NEGATIVE_TERM_OPERATORS: categories = self.search([("id", "not in", category_ids)]) domain = expression.OR( [[("categ_id", "in", categories.ids)], domain] ) else: domain = expression.AND( [[("categ_id", "in", category_ids)], domain] ) for i in range(1, len(category_names)): domain = [ [ ( "name", operator, " / ".join(category_names[-1 - i :]), ) ], domain, ] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = expression.AND(domain) else: domain = expression.OR(domain) categories = self.search(expression.AND([domain, args]), limit=limit) else: categories = self.search(args, limit=limit) return categories.name_get() class HotelRoomAmenitiesType(models.Model): _name = "hotel.room.amenities.type" _description = "amenities Type" amenity_id = fields.Many2one("hotel.room.amenities.type", "Category") child_ids = fields.One2many( "hotel.room.amenities.type", "amenity_id", "Amenities Child Categories" ) product_categ_id = fields.Many2one( "product.category", "Product Category", delegate=True, required=True, copy=False, ondelete="restrict", ) @api.model def create(self, vals): if "amenity_id" in vals: amenity_categ = self.env["hotel.room.amenities.type"].browse( vals.get("amenity_id") ) vals.update({"parent_id": amenity_categ.product_categ_id.id}) return super(HotelRoomAmenitiesType, self).create(vals) def write(self, vals): if "amenity_id" in vals: amenity_categ = self.env["hotel.room.amenities.type"].browse( vals.get("amenity_id") ) vals.update({"parent_id": amenity_categ.product_categ_id.id}) return super(HotelRoomAmenitiesType, self).write(vals) def name_get(self): def get_names(cat): """Return the list [cat.name, cat.amenity_id.name, ...]""" res = [] while cat: res.append(cat.name) cat = cat.amenity_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self] @api.model def name_search(self, name, args=None, operator="ilike", limit=100): if not args: args = [] if name: # Be sure name_search is symetric to name_get category_names = name.split(" / ") parents = list(category_names) child = parents.pop() domain = [("name", operator, child)] if parents: names_ids = self.name_search( " / ".join(parents), args=args, operator="ilike", limit=limit, ) category_ids = [name_id[0] for name_id in names_ids] if operator in expression.NEGATIVE_TERM_OPERATORS: categories = self.search([("id", "not in", category_ids)]) domain = expression.OR( [[("amenity_id", "in", categories.ids)], domain] ) else: domain = expression.AND( [[("amenity_id", "in", category_ids)], domain] ) for i in range(1, len(category_names)): domain = [ [ ( "name", operator, " / ".join(category_names[-1 - i :]), ) ], domain, ] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = expression.AND(domain) else: domain = expression.OR(domain) categories = self.search(expression.AND([domain, args]), limit=limit) else: categories = self.search(args, limit=limit) return categories.name_get() class HotelRoomAmenities(models.Model): _name = "hotel.room.amenities" _description = "Room amenities" product_id = fields.Many2one( "product.product", "Room Amenities Product", required=True, delegate=True, ondelete="cascade", ) amenities_categ_id = fields.Many2one( "hotel.room.amenities.type", "Amenities Category", required=True, ondelete="restrict", ) product_manager = fields.Many2one("res.users") @api.model def create(self, vals): if "amenities_categ_id" in vals: amenities_categ = self.env["hotel.room.amenities.type"].browse( vals.get("amenities_categ_id") ) vals.update({"categ_id": amenities_categ.product_categ_id.id}) return super(HotelRoomAmenities, self).create(vals) def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. """ if "amenities_categ_id" in vals: amenities_categ = self.env["hotel.room.amenities.type"].browse( vals.get("amenities_categ_id") ) vals.update({"categ_id": amenities_categ.product_categ_id.id}) return super(HotelRoomAmenities, self).write(vals)
35.054054
11,673
32,808
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from datetime import timedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT from odoo.tools.misc import get_lang class FolioRoomLine(models.Model): _name = "folio.room.line" _description = "Hotel Room Reservation" _rec_name = "room_id" room_id = fields.Many2one("hotel.room", ondelete="restrict", index=True) check_in = fields.Datetime("Check In Date", required=True) check_out = fields.Datetime("Check Out Date", required=True) folio_id = fields.Many2one("hotel.folio", "Folio Number", ondelete="cascade") status = fields.Selection(related="folio_id.state", string="state") class HotelFolio(models.Model): _name = "hotel.folio" _description = "hotel folio" _rec_name = "order_id" def name_get(self): res = [] fname = "" for rec in self: if rec.order_id: fname = str(rec.name) res.append((rec.id, fname)) return res @api.model def name_search(self, name="", args=None, operator="ilike", limit=100): if args is None: args = [] args += [("name", operator, name)] folio = self.search(args, limit=100) return folio.name_get() @api.model def _get_checkin_date(self): self._context.get("tz") or self.env.user.partner_id.tz or "UTC" checkin_date = fields.Datetime.context_timestamp(self, fields.Datetime.now()) return fields.Datetime.to_string(checkin_date) @api.model def _get_checkout_date(self): self._context.get("tz") or self.env.user.partner_id.tz or "UTC" checkout_date = fields.Datetime.context_timestamp( self, fields.Datetime.now() + timedelta(days=1) ) return fields.Datetime.to_string(checkout_date) name = fields.Char("Folio Number", readonly=True, index=True, default="New") order_id = fields.Many2one( "sale.order", "Order", delegate=True, required=True, ondelete="cascade" ) checkin_date = fields.Datetime( "Check In", required=True, readonly=True, states={"draft": [("readonly", False)]}, default=_get_checkin_date, ) checkout_date = fields.Datetime( "Check Out", required=True, readonly=True, states={"draft": [("readonly", False)]}, default=_get_checkout_date, ) room_line_ids = fields.One2many( "hotel.folio.line", "folio_id", readonly=True, states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, help="Hotel room reservation detail.", ) service_line_ids = fields.One2many( "hotel.service.line", "folio_id", readonly=True, states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, help="Hotel services details provided to" "Customer and it will included in " "the main Invoice.", ) hotel_policy = fields.Selection( [ ("prepaid", "On Booking"), ("manual", "On Check In"), ("picking", "On Checkout"), ], default="manual", help="Hotel policy for payment that " "either the guest has to payment at " "booking time or check-in " "check-out time.", ) duration = fields.Float( "Duration in Days", help="Number of days which will automatically " "count from the check-in and check-out date. ", ) hotel_invoice_id = fields.Many2one("account.move", "Invoice", copy=False) duration_dummy = fields.Float() @api.constrains("room_line_ids") def _check_duplicate_folio_room_line(self): """ This method is used to validate the room_lines. ------------------------------------------------ @param self: object pointer @return: raise warning depending on the validation """ for rec in self: for product in rec.room_line_ids.mapped("product_id"): for line in rec.room_line_ids.filtered( lambda l: l.product_id == product ): record = rec.room_line_ids.search( [ ("product_id", "=", product.id), ("folio_id", "=", rec.id), ("id", "!=", line.id), ("checkin_date", ">=", line.checkin_date), ("checkout_date", "<=", line.checkout_date), ] ) if record: raise ValidationError( _( """Room Duplicate Exceeded!, """ """You Cannot Take Same %s Room Twice!""" ) % (product.name) ) def _update_folio_line(self, folio_id): folio_room_line_obj = self.env["folio.room.line"] hotel_room_obj = self.env["hotel.room"] for rec in folio_id: for room_rec in rec.room_line_ids: room = hotel_room_obj.search( [("product_id", "=", room_rec.product_id.id)] ) room.write({"isroom": False}) vals = { "room_id": room.id, "check_in": rec.checkin_date, "check_out": rec.checkout_date, "folio_id": rec.id, } folio_room_line_obj.create(vals) @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. @return: new record set for hotel folio. """ if not "service_line_ids" and "folio_id" in vals: tmp_room_lines = vals.get("room_line_ids", []) vals["order_policy"] = vals.get("hotel_policy", "manual") vals.update({"room_line_ids": []}) folio_id = super(HotelFolio, self).create(vals) for line in tmp_room_lines: line[2].update({"folio_id": folio_id.id}) vals.update({"room_line_ids": tmp_room_lines}) folio_id.write(vals) else: if not vals: vals = {} vals["name"] = self.env["ir.sequence"].next_by_code("hotel.folio") vals["duration"] = vals.get("duration", 0.0) or vals.get("duration", 0.0) folio_id = super(HotelFolio, self).create(vals) self._update_folio_line(folio_id) return folio_id def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. """ product_obj = self.env["product.product"] hotel_room_obj = self.env["hotel.room"] folio_room_line_obj = self.env["folio.room.line"] for rec in self: rooms_list = [res.product_id.id for res in rec.room_line_ids] if vals and vals.get("duration", False): vals["duration"] = vals.get("duration", 0.0) else: vals["duration"] = rec.duration room_lst = [folio_rec.product_id.id for folio_rec in rec.room_line_ids] new_rooms = set(room_lst).difference(set(rooms_list)) if len(list(new_rooms)) != 0: room_list = product_obj.browse(list(new_rooms)) for rm in room_list: room_obj = hotel_room_obj.search([("product_id", "=", rm.id)]) room_obj.write({"isroom": False}) vals = { "room_id": room_obj.id, "check_in": rec.checkin_date, "check_out": rec.checkout_date, "folio_id": rec.id, } folio_room_line_obj.create(vals) if not len(list(new_rooms)): room_list_obj = product_obj.browse(rooms_list) for room in room_list_obj: room_obj = hotel_room_obj.search([("product_id", "=", room.id)]) room_obj.write({"isroom": False}) room_vals = { "room_id": room_obj.id, "check_in": rec.checkin_date, "check_out": rec.checkout_date, "folio_id": rec.id, } folio_romline_rec = folio_room_line_obj.search( [("folio_id", "=", rec.id)] ) folio_romline_rec.write(room_vals) return super(HotelFolio, self).write(vals) @api.onchange("partner_id") def _onchange_partner_id(self): """ When you change partner_id it will update the partner_invoice_id, partner_shipping_id and pricelist_id of the hotel folio as well --------------------------------------------------------------- @param self: object pointer """ if self.partner_id: self.update( { "partner_invoice_id": self.partner_id.id, "partner_shipping_id": self.partner_id.id, "pricelist_id": self.partner_id.property_product_pricelist.id, } ) def action_done(self): self.write({"state": "done"}) def action_cancel(self): """ @param self: object pointer """ for rec in self: if not rec.order_id: raise UserError(_("Order id is not available")) for product in rec.room_line_ids.filtered( lambda l: l.order_line_id.product_id == product ): rooms = self.env["hotel.room"].search([("product_id", "=", product.id)]) rooms.write({"isroom": True, "status": "available"}) rec.invoice_ids.button_cancel() return rec.order_id.action_cancel() def action_confirm(self): for order in self.order_id: order.state = "sale" if not order.analytic_account_id: if order.order_line.filtered( lambda line: line.product_id.invoice_policy == "cost" ): order._create_analytic_account() config_parameter_obj = self.env["ir.config_parameter"] if config_parameter_obj.sudo().get_param("sale.auto_done_setting"): self.order_id.action_done() def action_cancel_draft(self): """ @param self: object pointer """ order_line_recs = self.env["sale.order.line"].search( [("order_id", "in", self.ids), ("state", "=", "cancel")] ) self.write({"state": "draft", "invoice_ids": []}) order_line_recs.write( { "invoiced": False, "state": "draft", "invoice_lines": [(6, 0, [])], } ) class HotelFolioLine(models.Model): _name = "hotel.folio.line" _description = "Hotel Folio Line" order_line_id = fields.Many2one( "sale.order.line", "Order Line", required=True, delegate=True, ondelete="cascade", ) folio_id = fields.Many2one("hotel.folio", "Folio", ondelete="cascade") checkin_date = fields.Datetime("Check In", required=True) checkout_date = fields.Datetime("Check Out", required=True) is_reserved = fields.Boolean(help="True when folio line created from Reservation") @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. @return: new record set for hotel folio line. """ if "folio_id" in vals: folio = self.env["hotel.folio"].browse(vals["folio_id"]) vals.update({"order_id": folio.order_id.id}) return super(HotelFolioLine, self).create(vals) @api.constrains("checkin_date", "checkout_date") def _check_dates(self): """ This method is used to validate the checkin_date and checkout_date. ------------------------------------------------------------------- @param self: object pointer @return: raise warning depending on the validation """ if self.checkin_date >= self.checkout_date: raise ValidationError( _( """Room line Check In Date Should be """ """less than the Check Out Date!""" ) ) if self.folio_id.date_order and self.checkin_date: if self.checkin_date.date() < self.folio_id.date_order.date(): raise ValidationError( _( """Room line check in date should be """ """greater than the current date.""" ) ) def unlink(self): """ Overrides orm unlink method. @param self: The object pointer @return: True/False. """ for line in self: if line.order_line_id: rooms = self.env["hotel.room"].search( [("product_id", "=", line.order_line_id.product_id.id)] ) folio_room_lines = self.env["folio.room.line"].search( [ ("folio_id", "=", line.folio_id.id), ("room_id", "in", rooms.ids), ] ) folio_room_lines.unlink() rooms.write({"isroom": True, "status": "available"}) line.order_line_id.unlink() return super(HotelFolioLine, self).unlink() def _get_real_price_currency(self, product, rule_id, qty, uom, pricelist_id): """Retrieve the price before applying the pricelist :param obj product: object of current product record :parem float qty: total quentity of product :param tuple price_and_rule: tuple(price, suitable_rule) coming from pricelist computation :param obj uom: unit of measure of current order line :param integer pricelist_id: pricelist id of sale order""" PricelistItem = self.env["product.pricelist.item"] field_name = "lst_price" currency_id = None product_currency = None if rule_id: pricelist_item = PricelistItem.browse(rule_id) if pricelist_item.pricelist_id.discount_policy == "without_discount": while ( pricelist_item.base == "pricelist" and pricelist_item.base_pricelist_id and pricelist_item.base_pricelist_id.discount_policy == "without_discount" ): price, rule_id = pricelist_item.base_pricelist_id.with_context( uom=uom.id ).get_product_price_rule(product, qty, self.folio_id.partner_id) pricelist_item = PricelistItem.browse(rule_id) if pricelist_item.base == "standard_price": field_name = "standard_price" if pricelist_item.base == "pricelist" and pricelist_item.base_pricelist_id: field_name = "price" product = product.with_context( pricelist=pricelist_item.base_pricelist_id.id ) product_currency = pricelist_item.base_pricelist_id.currency_id currency_id = pricelist_item.pricelist_id.currency_id product_currency = ( product_currency or (product.company_id and product.company_id.currency_id) or self.env.user.company_id.currency_id ) if not currency_id: currency_id = product_currency cur_factor = 1.0 else: if currency_id.id == product_currency.id: cur_factor = 1.0 else: cur_factor = currency_id._get_conversion_rate( product_currency, currency_id ) product_uom = self.env.context.get("uom") or product.uom_id.id if uom and uom.id != product_uom: # the unit price is in a different uom uom_factor = uom._compute_price(1.0, product.uom_id) else: uom_factor = 1.0 return product[field_name] * uom_factor * cur_factor, currency_id.id def _get_display_price(self, product): # TO DO: move me in master/saas-16 on sale.order if self.folio_id.pricelist_id.discount_policy == "with_discount": return product.with_context(pricelist=self.folio_id.pricelist_id.id).price product_context = dict( self.env.context, partner_id=self.folio_id.partner_id.id, date=self.folio_id.date_order, uom=self.product_uom.id, ) final_price, rule_id = self.folio_id.pricelist_id.with_context( **product_context ).get_product_price_rule( self.product_id, self.product_uom_qty or 1.0, self.folio_id.partner_id, ) base_price, currency_id = self.with_context( **product_context )._get_real_price_currency( product, rule_id, self.product_uom_qty, self.product_uom, self.folio_id.pricelist_id.id, ) if currency_id != self.folio_id.pricelist_id.currency_id.id: base_price = ( self.env["res.currency"] .browse(currency_id) .with_context(**product_context) .compute(base_price, self.folio_id.pricelist_id.currency_id) ) # negative discounts (= surcharge) are included in the display price return max(base_price, final_price) def _compute_tax_id(self): for line in self: line = line.with_company(line.company_id) fpos = ( line.order_id.fiscal_position_id or line.order_id.fiscal_position_id.get_fiscal_position( line.order_partner_id.id ) ) # If company_id is set, always filter taxes by the company taxes = line.product_id.taxes_id.filtered( lambda t: t.company_id == line.env.company ) line.tax_id = fpos.map_tax(taxes) @api.onchange("product_id") def _onchange_product_id(self): if not self.product_id: return product_tmpl = self.product_id.product_tmpl_id attribute_lines = product_tmpl.valid_product_template_attribute_line_ids valid_values = attribute_lines.product_template_value_ids # remove the is_custom values that don't belong to this template for pacv in self.product_custom_attribute_value_ids: if pacv.custom_product_template_attribute_value_id not in valid_values: self.product_custom_attribute_value_ids -= pacv # remove the no_variant attributes that don't belong to this template for ptav in self.product_no_variant_attribute_value_ids: if ptav._origin not in valid_values: self.product_no_variant_attribute_value_ids -= ptav vals = {} if not self.product_uom or (self.product_id.uom_id.id != self.product_uom.id): vals["product_uom"] = self.product_id.uom_id vals["product_uom_qty"] = self.product_uom_qty or 1.0 product = self.product_id.with_context( lang=get_lang(self.env, self.order_id.partner_id.lang).code, partner=self.order_id.partner_id, quantity=vals.get("product_uom_qty") or self.product_uom_qty, date=self.order_id.date_order, pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id, ) vals.update( name=self.order_line_id.get_sale_order_line_multiline_description_sale( product ) ) self._compute_tax_id() if self.folio_id.pricelist_id and self.folio_id.partner_id: vals["price_unit"] = self.env[ "account.tax" ]._fix_tax_included_price_company( self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id, ) self.update(vals) title = False message = False result = {} warning = {} if product.sale_line_warn != "no-message": title = _("Warning for %s", product.name) message = product.sale_line_warn_msg warning["title"] = title warning["message"] = message result = {"warning": warning} if product.sale_line_warn == "block": self.product_id = False return result @api.onchange("checkin_date", "checkout_date") def _onchange_checkin_checkout_dates(self): """ When you change checkin_date or checkout_date it will checked it and update the qty of hotel folio line ----------------------------------------------------------------- @param self: object pointer """ configured_addition_hours = ( self.folio_id.warehouse_id.company_id.additional_hours ) myduration = 0 if self.checkin_date and self.checkout_date: dur = self.checkout_date - self.checkin_date sec_dur = dur.seconds if (not dur.days and not sec_dur) or (dur.days and not sec_dur): myduration = dur.days else: myduration = dur.days + 1 # To calculate additional hours in hotel room as per minutes if configured_addition_hours > 0: additional_hours = abs((dur.seconds / 60) / 60) if additional_hours >= configured_addition_hours: myduration += 1 self.product_uom_qty = myduration def copy_data(self, default=None): """ @param self: object pointer @param default: dict of default values to be set """ sale_line_obj = self.order_line_id return sale_line_obj.copy_data(default=default) class HotelServiceLine(models.Model): _name = "hotel.service.line" _description = "hotel Service line" @api.returns("self", lambda value: value.id) def copy(self, default=None): """ @param self: object pointer @param default: dict of default values to be set """ return super(HotelServiceLine, self).copy(default=default) service_line_id = fields.Many2one( "sale.order.line", "Service Line", required=True, delegate=True, ondelete="cascade", ) folio_id = fields.Many2one("hotel.folio", "Folio", ondelete="cascade") ser_checkin_date = fields.Datetime("From Date") ser_checkout_date = fields.Datetime("To Date") @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. @return: new record set for hotel service line. """ if "folio_id" in vals: folio = self.env["hotel.folio"].browse(vals["folio_id"]) vals.update({"order_id": folio.order_id.id}) return super(HotelServiceLine, self).create(vals) def unlink(self): """ Overrides orm unlink method. @param self: The object pointer @return: True/False. """ self.mapped("service_line_id").unlink() return super().unlink() def _compute_tax_id(self): for line in self: fpos = ( line.folio_id.fiscal_position_id or line.folio_id.partner_id.property_account_position_id ) # If company_id is set, always filter taxes by the company taxes = line.product_id.taxes_id.filtered( lambda r: not line.company_id or r.company_id == line.company_id ) line.tax_id = ( fpos.map_tax(taxes, line.product_id, line.folio_id.partner_shipping_id) if fpos else taxes ) def _get_real_price_currency(self, product, rule_id, qty, uom, pricelist_id): """Retrieve the price before applying the pricelist :param obj product: object of current product record :parem float qty: total quentity of product :param tuple price_and_rule: tuple(price, suitable_rule) coming from pricelist computation :param obj uom: unit of measure of current order line :param integer pricelist_id: pricelist id of sale order""" PricelistItem = self.env["product.pricelist.item"] field_name = "lst_price" currency_id = None product_currency = None if rule_id: pricelist_item = PricelistItem.browse(rule_id) if pricelist_item.pricelist_id.discount_policy == "without_discount": while ( pricelist_item.base == "pricelist" and pricelist_item.base_pricelist_id and pricelist_item.base_pricelist_id.discount_policy == "without_discount" ): price, rule_id = pricelist_item.base_pricelist_id.with_context( uom=uom.id ).get_product_price_rule(product, qty, self.folio_id.partner_id) pricelist_item = PricelistItem.browse(rule_id) if pricelist_item.base == "standard_price": field_name = "standard_price" if pricelist_item.base == "pricelist" and pricelist_item.base_pricelist_id: field_name = "price" product = product.with_context( pricelist=pricelist_item.base_pricelist_id.id ) product_currency = pricelist_item.base_pricelist_id.currency_id currency_id = pricelist_item.pricelist_id.currency_id product_currency = ( product_currency or (product.company_id and product.company_id.currency_id) or self.env.user.company_id.currency_id ) if not currency_id: currency_id = product_currency cur_factor = 1.0 else: if currency_id.id == product_currency.id: cur_factor = 1.0 else: cur_factor = currency_id._get_conversion_rate( product_currency, currency_id ) product_uom = self.env.context.get("uom") or product.uom_id.id if uom and uom.id != product_uom: # the unit price is in a different uom uom_factor = uom._compute_price(1.0, product.uom_id) else: uom_factor = 1.0 return product[field_name] * uom_factor * cur_factor, currency_id.id def _get_display_price(self, product): # TO DO: move me in master/saas-16 on sale.order if self.folio_id.pricelist_id.discount_policy == "with_discount": return product.with_context(pricelist=self.folio_id.pricelist_id.id).price product_context = dict( self.env.context, partner_id=self.folio_id.partner_id.id, date=self.folio_id.date_order, uom=self.product_uom.id, ) final_price, rule_id = self.folio_id.pricelist_id.with_context( **product_context ).get_product_price_rule( self.product_id, self.product_uom_qty or 1.0, self.folio_id.partner_id, ) base_price, currency_id = self.with_context( **product_context )._get_real_price_currency( product, rule_id, self.product_uom_qty, self.product_uom, self.folio_id.pricelist_id.id, ) if currency_id != self.folio_id.pricelist_id.currency_id.id: base_price = ( self.env["res.currency"] .browse(currency_id) .with_context(**product_context) .compute(base_price, self.folio_id.pricelist_id.currency_id) ) # negative discounts (= surcharge) are included in the display price return max(base_price, final_price) @api.onchange("product_id") def _onchange_product_id(self): if not self.product_id: return product_tmpl = self.product_id.product_tmpl_id attribute_lines = product_tmpl.valid_product_template_attribute_line_ids valid_values = attribute_lines.product_template_value_ids # remove the is_custom values that don't belong to this template for pacv in self.product_custom_attribute_value_ids: if pacv.custom_product_template_attribute_value_id not in valid_values: self.product_custom_attribute_value_ids -= pacv # remove the no_variant attributes that don't belong to this template for ptav in self.product_no_variant_attribute_value_ids: if ptav._origin not in valid_values: self.product_no_variant_attribute_value_ids -= ptav vals = {} if not self.product_uom or (self.product_id.uom_id.id != self.product_uom.id): vals["product_uom"] = self.product_id.uom_id vals["product_uom_qty"] = self.product_uom_qty or 1.0 product = self.product_id.with_context( lang=get_lang(self.env, self.order_id.partner_id.lang).code, partner=self.order_id.partner_id, quantity=vals.get("product_uom_qty") or self.product_uom_qty, date=self.order_id.date_order, pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id, ) vals.update( name=self.service_line_id.get_sale_order_line_multiline_description_sale( product ) ) self._compute_tax_id() if self.folio_id.pricelist_id and self.folio_id.partner_id: vals["price_unit"] = self.env[ "account.tax" ]._fix_tax_included_price_company( self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id, ) self.update(vals) title = False message = False result = {} warning = {} if product.sale_line_warn != "no-message": title = _("Warning for %s", product.name) message = product.sale_line_warn_msg warning["title"] = title warning["message"] = message result = {"warning": warning} if product.sale_line_warn == "block": self.product_id = False return result @api.onchange("ser_checkin_date", "ser_checkout_date") def _on_change_checkin_checkout_dates(self): """ When you change checkin_date or checkout_date it will checked it and update the qty of hotel service line ----------------------------------------------------------------- @param self: object pointer """ if not self.ser_checkin_date: time_a = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) self.ser_checkin_date = time_a if not self.ser_checkout_date: self.ser_checkout_date = time_a if self.ser_checkout_date < self.ser_checkin_date: raise ValidationError(_("Checkout must be greater or equal checkin date")) if self.ser_checkin_date and self.ser_checkout_date: diffDate = self.ser_checkout_date - self.ser_checkin_date qty = diffDate.days + 1 self.product_uom_qty = qty def copy_data(self, default=None): """ @param self: object pointer @param default: dict of default values to be set """ return self.service_line_id.copy_data(default=default)
39.244019
32,808
2,227
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models, tools class ProductProduct(models.Model): _inherit = "product.product" isroom = fields.Boolean("Is Room") iscategid = fields.Boolean("Is Categ") isservice = fields.Boolean("Is Service") @api.model def _search( self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None, ): args = args or [] context = self._context or {} checkin_date = context.get("checkin_date") checkout_date = context.get("checkout_date") if isinstance(checkin_date, str): checkin_date = fields.datetime.strptime( context.get("checkin_date"), tools.DEFAULT_SERVER_DATETIME_FORMAT ) if isinstance(checkout_date, str): checkout_date = fields.datetime.strptime( context.get("checkout_date"), tools.DEFAULT_SERVER_DATETIME_FORMAT ) if checkin_date and checkout_date: hotel_room_obj = self.env["hotel.room"] avail_prod_ids = [] for room in hotel_room_obj.search([]): assigned = False for rm_line in room.room_line_ids: if rm_line.status != "cancel": if (checkin_date <= rm_line.check_in <= checkout_date) or ( checkin_date <= rm_line.check_out <= checkout_date ): assigned = True elif ( rm_line.check_in <= checkin_date <= rm_line.check_out ) or (rm_line.check_in <= checkout_date <= rm_line.check_out): assigned = True if not assigned: avail_prod_ids.append(room.product_id.id) args.append(("id", "in", avail_prod_ids)) return super(ProductProduct, self)._search( args, offset, limit, order, count=count, access_rights_uid=access_rights_uid )
39.070175
2,227
581
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" additional_hours = fields.Integer( help="Provide the min hours value for \ check in, checkout days, whatever the \ hours will be provided here based on \ that extra days will be calculated.", )
36.3125
581
4,937
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class HotelServices(models.Model): _name = "hotel.services" _description = "Hotel Services and its charges" product_id = fields.Many2one( "product.product", "Service_id", required=True, ondelete="cascade", delegate=True, ) service_categ_id = fields.Many2one( "hotel.service.type", "Service Category", required=True, ondelete="restrict", ) product_manager = fields.Many2one("res.users") @api.model def create(self, vals): if "service_categ_id" in vals: service_categ = self.env["hotel.service.type"].browse( vals.get("service_categ_id") ) vals.update({"categ_id": service_categ.product_categ_id.id}) return super(HotelServices, self).create(vals) def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. """ if "service_categ_id" in vals: service_categ_id = self.env["hotel.service.type"].browse( vals.get("service_categ_id") ) vals.update({"categ_id": service_categ_id.product_categ_id.id}) return super(HotelServices, self).write(vals) class HotelServiceType(models.Model): _name = "hotel.service.type" _description = "Service Type" service_id = fields.Many2one("hotel.service.type", "Service Category") child_ids = fields.One2many( "hotel.service.type", "service_id", "Service Child Categories" ) product_categ_id = fields.Many2one( "product.category", "Product Category", delegate=True, required=True, copy=False, ondelete="restrict", ) @api.model def create(self, vals): if "service_id" in vals: service_categ = self.env["hotel.service.type"].browse( vals.get("service_id") ) vals.update({"parent_id": service_categ.product_categ_id.id}) return super(HotelServiceType, self).create(vals) def write(self, vals): if "service_id" in vals: service_categ = self.env["hotel.service.type"].browse( vals.get("service_id") ) vals.update({"parent_id": service_categ.product_categ_id.id}) return super(HotelServiceType, self).write(vals) def name_get(self): def get_names(cat): """Return the list [cat.name, cat.service_id.name, ...]""" res = [] while cat: res.append(cat.name) cat = cat.service_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self] @api.model def name_search(self, name, args=None, operator="ilike", limit=100): if not args: args = [] if name: # Be sure name_search is symetric to name_get category_names = name.split(" / ") parents = list(category_names) child = parents.pop() domain = [("name", operator, child)] if parents: names_ids = self.name_search( " / ".join(parents), args=args, operator="ilike", limit=limit, ) category_ids = [name_id[0] for name_id in names_ids] if operator in expression.NEGATIVE_TERM_OPERATORS: categories = self.search([("id", "not in", category_ids)]) domain = expression.OR( [[("service_id", "in", categories.ids)], domain] ) else: domain = expression.AND( [[("service_id", "in", category_ids)], domain] ) for i in range(1, len(category_names)): domain = [ [ ( "name", operator, " / ".join(category_names[-1 - i :]), ) ], domain, ] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = expression.AND(domain) else: domain = expression.OR(domain) categories = self.search(expression.AND([domain, args]), limit=limit) else: categories = self.search(args, limit=limit) return categories.name_get()
34.767606
4,937
2,264
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import api, fields, models class FolioReport(models.AbstractModel): _name = "report.hotel.report_hotel_folio" _description = "Auxiliar to get the report" def _get_folio_data(self, date_start, date_end): total_amount = 0.0 data_folio = [] folio_obj = self.env["hotel.folio"] act_domain = [ ("checkin_date", ">=", date_start), ("checkout_date", "<=", date_end), ] tids = folio_obj.search(act_domain) for data in tids: checkin = fields.Datetime.to_string( fields.Datetime.context_timestamp(self, data.checkin_date) ) checkout = fields.Datetime.to_string( fields.Datetime.context_timestamp(self, data.checkout_date) ) data_folio.append( { "name": data.name, "partner": data.partner_id.name, "checkin": checkin, "checkout": checkout, "amount": data.amount_total, } ) total_amount += data.amount_total data_folio.append({"total_amount": total_amount}) return data_folio @api.model def _get_report_values(self, docids, data): model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.folio"].browse(docids) date_start = data["form"].get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=+1, day=1, days=-1))[:10], ) return { "doc_ids": docids, "doc_model": model, "data": data["form"], "docs": folio_profile, "time": time, "folio_data": self._get_folio_data(date_start, date_end), }
34.830769
2,264
675
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Hotel Reservation Management - Reporting", "version": "15.0.1.0.0", "author": "Odoo Community Association (OCA), Serpent Consulting\ Services Pvt. Ltd., Odoo S.A.", "website": "https://github.com/OCA/vertical-hotel", "depends": ["hotel_reservation"], "license": "AGPL-3", "category": "Generic Modules/Hotel Reservation", "data": [ "security/ir.model.access.csv", "views/report_hotel_reservation_view.xml", ], "installable": True, }
37.5
675
1,246
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ReportHotelReservationStatus(models.Model): _name = "report.hotel.reservation.status" _description = "Reservation By State" _auto = False reservation_no = fields.Char(readonly=True) no_of_reservation = fields.Integer("Reservation", readonly=True) state = fields.Selection( [("draft", "Draft"), ("confirm", "Confirm"), ("done", "Done")], readonly=True, ) def init(self): """ This method is for initialization for report hotel reservation status Module. @param self: The object pointer @param cr: database cursor """ self.env.cr.execute( """ create or replace view report_hotel_reservation_status as ( select min(c.id) as id, c.reservation_no, c.state, count(*) as no_of_reservation from hotel_reservation c group by c.state,c.reservation_no )""" )
31.948718
1,246
832
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Restaurant Management - Reporting", "version": "15.0.1.0.0", "author": "Odoo Community Association (OCA), Serpent Consulting\ Services Pvt. Ltd., Odoo S.A.", "maintainer": "Serpent Consulting Services Pvt. Ltd.,\ Rajan-SerpentCS,\ vimalpatelserpentcs", "website": "https://github.com/OCA/vertical-hotel", "depends": ["hotel_restaurant", "report_hotel_reservation"], "category": "Generic Modules/Hotel Restaurant", "license": "AGPL-3", "data": [ "security/ir.model.access.csv", "views/report_hotel_restaurant_view.xml", ], "installable": True, }
39.619048
832
1,291
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ReportHotelRestaurantStatus(models.Model): _name = "report.hotel.restaurant.status" _description = "Reservation By State" _auto = False reservation_id = fields.Char("Reservation No", readonly=True) no_of_reservation_order = fields.Integer("Reservation Order No", readonly=True) state = fields.Selection( [("draft", "Draft"), ("confirm", "Confirm"), ("done", "Done")], readonly=True, ) def init(self): """ This method is for initialization for report hotel restaurant status Module. @param self: The object pointer @param cr: database cursor """ self.env.cr.execute( """ create or replace view report_hotel_restaurant_status as ( select min(c.id) as id, c.reservation_id, c.state, count(*) as no_of_reservation_order from hotel_restaurant_reservation c group by c.state,c.reservation_id )""" )
33.973684
1,291
906
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Hotel Housekeeping Management", "version": "15.0.1.0.0", "author": "Odoo Community Association (OCA), Serpent Consulting \ Services Pvt. Ltd., Odoo S.A.", "website": "https://github.com/OCA/vertical-hotel", "license": "AGPL-3", "summary": "Manages Housekeeping Activities and its Process", "category": "Generic Modules/Hotel Housekeeping", "depends": ["hotel"], "demo": ["demo/hotel_housekeeping_data.xml"], "data": [ "security/ir.model.access.csv", "views/report_hotel_housekeeping.xml", "views/hotel_housekeeping_view.xml", "report/hotel_housekeeping_report.xml", "wizard/hotel_housekeeping_wizard.xml", ], "installable": True, }
39.391304
906
3,691
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from datetime import datetime from odoo.tests import common class TestHousekeeping(common.TransactionCase): def setUp(self): super(TestHousekeeping, self).setUp() self.env = self.env(context=dict(self.env.context, tracking_disable=True)) self.housekeeping_obj = self.env["hotel.housekeeping"] self.hotel_act_obj = self.env["hotel.housekeeping.activities"] self.hotel_act_type_obj = self.env["hotel.housekeeping.activity.type"] self.housekeeper_id = self.env.ref("base.user_root") self.inspector_id = self.env.ref("base.user_demo") self.act_type = self.env.ref( "hotel_housekeeping.hotel_housekeeping_activity_type_1" ) self.room = self.env.ref("hotel.hotel_room_0") self.activity = self.env.ref("hotel_housekeeping.hotel_room_activities_1") self.activity_type = self.env["hotel.housekeeping.activity.type"] cur_date = datetime.now().strftime("%Y-%m-21 %H:%M:%S") cur_date1 = datetime.now().strftime("%Y-%m-23 %H:%M:%S") self.housekeeping = self.housekeeping_obj.create( { "current_date": time.strftime("%Y-%m-%d"), "room_id": self.room.id, "clean_type": "daily", "inspector_id": self.inspector_id.id, "state": "dirty", "quality": "excellent", "inspect_date_time": cur_date, } ) self.hotel_act_type = self.hotel_act_type_obj.create( {"name": "Test Room Activity", "activity_id": self.act_type.id} ) self.hotel_activity = self.hotel_act_obj.create( { "housekeeping_id": self.housekeeping.id, "today_date": time.strftime("%Y-%m-%d"), "activity_id": self.activity.id, "housekeeper_id": self.housekeeper_id.id, "clean_start_time": cur_date, "clean_end_time": cur_date1, } ) self.hotel_act_type.name_get() hotel_activity_type = self.hotel_act_type_obj.name_search("Test Room Activity") self.assertEqual( len(hotel_activity_type), 1, "Incorrect search number result for name_search", ) def test_name_search(self): self.activity_type = self.env["hotel.housekeeping.activity.type"].create( { "name": "Test", } ) self.env["hotel.housekeeping.activity.type"].name_search( "All Activities / Test Room Activity", [], "not like", None ) def test_activity_check_clean_start_time(self): self.hotel_activity._check_clean_start_time() def test_activity_default_get(self): fields = ["room_id", "today_date"] self.hotel_activity.default_get(fields) def test_action_set_to_dirty(self): self.housekeeping.action_set_to_dirty() def test_room_cancel(self): self.housekeeping.room_cancel() self.assertEqual(self.housekeeping.state == "cancel", True) def test_room_done(self): self.housekeeping.room_done() self.assertEqual(self.housekeeping.state == "done", True) def test_room_inspect(self): self.housekeeping.room_inspect() self.assertEqual(self.housekeeping.state == "inspect", True) def test_room_clean(self): self.housekeeping.room_clean() self.assertEqual(self.housekeeping.state == "clean", True)
37.663265
3,691
874
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class HotelHousekeepingWizard(models.TransientModel): _name = "hotel.housekeeping.wizard" _description = "Hotel Housekeeping Wizard" date_start = fields.Datetime("Activity Start Date", required=True) date_end = fields.Datetime("Activity End Date", required=True) room_id = fields.Many2one("hotel.room", "Room No", required=True) def print_report(self): data = { "ids": self.ids, "model": "hotel.housekeeping", "form": self.read(["date_start", "date_end", "room_id"])[0], } return self.env.ref( "hotel_housekeeping.report_hotel_housekeeping" ).report_action(self, data=data)
38
874
2,774
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class HotelHousekeepingActivityType(models.Model): _name = "hotel.housekeeping.activity.type" _description = "Activity Type" name = fields.Char(required=True) activity_id = fields.Many2one("hotel.housekeeping.activity.type", "Activity Type") def name_get(self): def get_names(cat): """Return the list [cat.name, cat.activity_id.name, ...]""" res = [] while cat: res.append(cat.name) cat = cat.activity_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self] @api.model def name_search(self, name, args=None, operator="ilike", limit=100): if not args: args = [] if name: # Be sure name_search is symmetric to name_get category_names = name.split(" / ") parents = list(category_names) child = parents.pop() domain = [("name", operator, child)] if parents: names_ids = self.name_search( " / ".join(parents), args=args, operator="ilike", limit=limit, ) category_ids = [name_id[0] for name_id in names_ids] if operator in expression.NEGATIVE_TERM_OPERATORS: categories = self.search([("id", "not in", category_ids)]) domain = expression.OR( [[("activity_id", "in", categories.ids)], domain] ) else: domain = expression.AND( [[("activity_id", "in", category_ids)], domain] ) for num in range(1, len(category_names)): domain = [ [ ( "name", operator, " / ".join(category_names[-1 - num :]), ) ], domain, ] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = expression.AND(domain) else: domain = expression.OR(domain) categories = self.search(expression.AND([domain, args]), limit=limit) else: categories = self.search(args, limit=limit) return categories.name_get()
38.527778
2,774
3,858
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models from odoo.exceptions import ValidationError class HotelHousekeeping(models.Model): _name = "hotel.housekeeping" _description = "Hotel Housekeeping" _rec_name = "room_id" current_date = fields.Date( "Today's Date", required=True, index=True, states={"done": [("readonly", True)]}, default=fields.Date.today, ) clean_type = fields.Selection( [ ("daily", "Daily"), ("checkin", "Check-In"), ("checkout", "Check-Out"), ], required=True, states={"done": [("readonly", True)]}, ) room_id = fields.Many2one( "hotel.room", "Room No", required=True, states={"done": [("readonly", True)]}, index=True, ) activity_line_ids = fields.One2many( "hotel.housekeeping.activities", "housekeeping_id", "Activities", states={"done": [("readonly", True)]}, help="Detail of housekeeping activities", ) inspector_id = fields.Many2one( "res.users", "Inspector", required=True, states={"done": [("readonly", True)]}, ) inspect_date_time = fields.Datetime( required=True, states={"done": [("readonly", True)]}, ) quality = fields.Selection( [ ("excellent", "Excellent"), ("good", "Good"), ("average", "Average"), ("bad", "Bad"), ("ok", "Ok"), ], states={"done": [("readonly", True)]}, help="Inspector inspect the room and mark" "as Excellent, Average, Bad, Good or Ok. ", ) state = fields.Selection( [ ("inspect", "Inspect"), ("dirty", "Dirty"), ("clean", "Clean"), ("done", "Done"), ("cancel", "Cancelled"), ], states={"done": [("readonly", True)]}, required=True, readonly=True, default="inspect", ) def action_set_to_dirty(self): """ This method is used to change the state to dirty of the hotel housekeeping --------------------------------------- @param self: object pointer """ self.write({"state": "dirty", "quality": False}) self.activity_line_ids.write({"is_clean": False, "is_dirty": True}) def room_cancel(self): """ This method is used to change the state to cancel of the hotel housekeeping --------------------------------------- @param self: object pointer """ self.write({"state": "cancel", "quality": False}) def room_done(self): """ This method is used to change the state to done of the hotel housekeeping --------------------------------------- @param self: object pointer """ if not self.quality: raise ValidationError(_("Please update quality of work!")) self.write({"state": "done"}) def room_inspect(self): """ This method is used to change the state to inspect of the hotel housekeeping --------------------------------------- @param self: object pointer """ self.write({"state": "inspect", "quality": False}) def room_clean(self): """ This method is used to change the state to clean of the hotel housekeeping --------------------------------------- @param self: object pointer """ self.write({"state": "clean", "quality": False}) self.activity_line_ids.write({"is_clean": True, "is_dirty": False})
30.377953
3,858
569
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class HotelActivity(models.Model): _name = "hotel.activity" _description = "Housekeeping Activity" product_id = fields.Many2one( "product.product", "Hotel Activity", required=True, delegate=True, ondelete="cascade", index=True, ) categ_id = fields.Many2one("hotel.housekeeping.activity.type", "Category")
28.45
569
2,151
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class HotelHousekeepingActivities(models.Model): _name = "hotel.housekeeping.activities" _description = "Housekeeping Activities" housekeeping_id = fields.Many2one("hotel.housekeeping", "Reservation") today_date = fields.Date() activity_id = fields.Many2one("hotel.activity", "Housekeeping Activity") housekeeper_id = fields.Many2one("res.users", "Housekeeper", required=True) clean_start_time = fields.Datetime(required=True) clean_end_time = fields.Datetime(required=True) is_dirty = fields.Boolean( "Dirty", help="Checked if the housekeeping activity" "results as Dirty.", ) is_clean = fields.Boolean( "Clean", help="Checked if the housekeeping" "activity results as Clean.", ) @api.constrains("clean_start_time", "clean_end_time") def _check_clean_start_time(self): """ This method is used to validate the clean_start_time and clean_end_time. --------------------------------------------------------- @param self: object pointer @return: raise warning depending on the validation """ for activity in self: if activity.clean_start_time >= activity.clean_end_time: raise ValidationError(_("Start Date Should be less than the End Date!")) @api.model def default_get(self, fields): """ To get default values for the object. @param self: The object pointer. @param fields: List of fields for which we want default values @return: A dictionary which of fields with values. """ res = super().default_get(fields) if self._context.get("room_id", False): res.update({"room_id": self._context["room_id"]}) if self._context.get("today_date", False): res.update({"today_date": self._context["today_date"]}) return res
39.833333
2,151
2,359
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import api, fields, models class ActivityReport(models.AbstractModel): _name = "report.hotel_housekeeping.housekeeping_report" _description = "Hotel Housekeeping Report" def get_room_activity_detail(self, date_start, date_end, room_id): activity_detail = [] house_keep_act_obj = self.env["hotel.housekeeping.activities"] activity_line_ids = house_keep_act_obj.search( [ ("clean_start_time", ">=", date_start), ("clean_end_time", "<=", date_end), ("housekeeping_id.room_id", "=", room_id), ] ) for activity in activity_line_ids: activity_detail.append( { "current_date": activity.today_date, "activity": (activity.activity_id.name or ""), "login": (activity.housekeeper_id.name or ""), "clean_start_time": activity.clean_start_time, "clean_end_time": activity.clean_end_time, "duration": activity.clean_end_time - activity.clean_start_time, } ) return activity_detail @api.model def _get_report_values(self, docids, data=None): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") activity_doc = self.env["hotel.housekeeping.activities"].browse(docids) date_start = data["form"].get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=+1, day=1, days=-1))[:10], ) room_id = data["form"].get("room_id")[0] return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": activity_doc, "time": time, "activity_detail": self.get_room_activity_detail( date_start, date_end, room_id ), }
36.292308
2,359
749
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-vertical-hotel", description="Meta package for oca-vertical-hotel Odoo addons", version=version, install_requires=[ 'odoo-addon-hotel>=15.0dev,<15.1dev', 'odoo-addon-hotel_housekeeping>=15.0dev,<15.1dev', 'odoo-addon-hotel_reservation>=15.0dev,<15.1dev', 'odoo-addon-hotel_restaurant>=15.0dev,<15.1dev', 'odoo-addon-report_hotel_reservation>=15.0dev,<15.1dev', 'odoo-addon-report_hotel_restaurant>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
32.565217
749
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
1,040
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Hotel Restaurant Management", "version": "15.0.1.0.0", "author": "Odoo Community Association (OCA), Serpent Consulting\ Services Pvt. Ltd., Odoo S.A.", "category": "Generic Modules/Hotel Restaurant", "website": "https://github.com/OCA/vertical-hotel", "depends": ["hotel", "point_of_sale"], "license": "AGPL-3", "summary": "Table booking facilities and Managing customers orders", "demo": ["demo/hotel_restaurant_data.xml"], "data": [ "security/ir.model.access.csv", "report/hotel_restaurant_report.xml", "views/res_table.xml", "views/kot.xml", "views/bill.xml", "views/folio_order_report.xml", "views/hotel_restaurant_sequence.xml", "views/hotel_restaurant_view.xml", "wizard/hotel_restaurant_wizard.xml", ], "installable": True, }
38.518519
1,040
5,111
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo.tests import common class TestRestaurant(common.TransactionCase): def setUp(self): super(TestRestaurant, self).setUp() self.menucard_type_obj = self.env["hotel.menucard.type"] self.hotel_rest_reserv_obj = self.env["hotel.restaurant.reservation"] self.hotel_kot_obj = self.env["hotel.restaurant.kitchen.order.tickets"] self.rest_order_obj = self.env["hotel.restaurant.order.list"] self.hotel_rest_order_obj = self.env["hotel.restaurant.order"] self.hotel_reserv_order_obj = self.env["hotel.reservation.order"] self.fooditem = self.env.ref("hotel_restaurant.hotel_fooditem_5") self.fooditem_type = self.env.ref("hotel_restaurant.hotel_menucard_type_1") self.rest_res = self.env.ref("hotel_restaurant.hotel_restaurant_reservation_1") self.tablelist = self.env.ref("hotel_restaurant.hotel_reservation_order_line_0") self.table1 = self.env.ref("hotel_restaurant.hotel_restaurant_tables_table1") self.table0 = self.env.ref("hotel_restaurant.hotel_restaurant_tables_table0") self.room1 = self.env.ref("point_of_sale.desk_organizer") self.partner = self.env.ref("base.res_partner_4") self.waiter = self.env.ref("base.res_partner_3") self.menucard_type_1 = self.env["hotel.menucard.type"] cur_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.menucard_type = self.menucard_type_obj.create( {"name": "Punjabi", "menu_id": self.fooditem_type.id} ) self.menucard_type.name_get() hotel_menucard_type = self.menucard_type.name_search("Punjabi") self.assertEqual( len(hotel_menucard_type), 2, "Incorrect search number result for name_search", ) self.hotel_rest_order = self.hotel_rest_order_obj.create( { "customer_id": self.partner.id, "room_id": self.room1.id, "amount_subtotal": 500.00, "amount_total": 500.00, "waiter_id": self.waiter.id, "table_nos_ids": [(6, 0, [self.table1.id, self.table0.id])], "kitchen": 1, "state": "draft", "order_list_ids": [(6, 0, [self.tablelist.id])], } ) self.rest_order = self.rest_order_obj.create( { "menucard_id": self.fooditem.id, "price_subtotal": 500.00, "item_qty": 2, "item_rate": 1000.00, } ) self.hotel_reserv_order = self.hotel_reserv_order_obj.create( { "order_number": "0RR/00001", "reservation_id": self.rest_res.id, "order_date": cur_date, "waitername": self.waiter.id, "amount_subtotal": 500.00, "amount_total": 500.00, "rests_ids": [(6, 0, [self.tablelist.id])], "table_nos_ids": [(6, 0, [self.table1.id, self.table0.id])], "kitchen": 1, "state": "draft", "order_list_ids": [(6, 0, [self.tablelist.id])], } ) def test_name_search(self): self.menucard_type_1 = self.env["hotel.menucard.type"].create( { "name": "Test", } ) self.env["hotel.menucard.type"].name_search( "All FoodItems / Punjabi", [], "not like", None ) def test_compute_price_subtotal(self): self.rest_order._compute_price_subtotal() def test_on_change_item_name(self): self.rest_order._onchange_item_name() def test_compute_amount_all_total_reserv(self): self.hotel_reserv_order._compute_amount_all_total() def test_reservation_generate_kot(self): self.hotel_reserv_order.reservation_generate_kot() self.assertEqual(self.hotel_reserv_order.state == "order", True) def test_done_kot(self): self.hotel_reserv_order.done_kot() self.assertEqual(self.hotel_reserv_order.state == "done", True) def test_compute_amount_all_total_rest(self): self.hotel_rest_order._compute_amount_all_total() def test_done_cancel(self): self.hotel_rest_order.done_cancel() self.assertEqual(self.hotel_rest_order.state == "cancel", True) def test_set_to_draft(self): self.hotel_rest_order.set_to_draft() self.assertEqual(self.hotel_rest_order.state == "draft", True) def test_generate_kot(self): self.assertEqual(len(self.tablelist.ids), 1, "Please Give an Order") self.hotel_rest_order.generate_kot() self.assertEqual(self.hotel_rest_order.state == "order", True) def test_done_order_kot(self): self.hotel_rest_order.done_order_kot() self.assertEqual(self.hotel_rest_order.state == "done", True)
40.563492
5,111
1,717
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class WizardHotelRestaurant(models.TransientModel): _name = "wizard.hotel.restaurant" _description = "wizard.hotel.restaurant" date_start = fields.Datetime("Start Date", required=True) date_end = fields.Datetime("End Date", required=True) def print_report(self): data = { "ids": self.ids, "model": "hotel.restaurant.reservation", "form": self.read(["date_start", "date_end"])[0], } return self.env.ref("hotel_restaurant.report_hotel_table_res").report_action( self, data=data ) class FolioRestReservation(models.TransientModel): _name = "folio.rest.reservation" _description = "folio.rest.reservation" _rec_name = "date_start" date_start = fields.Datetime("Start Date") date_end = fields.Datetime("End Date") check = fields.Boolean("With Details") def print_rest_report(self): data = { "ids": self.ids, "model": "hotel.folio", "form": self.read(["date_start", "date_end", "check"])[0], } return self.env.ref("hotel_restaurant.report_hotel_res_folio").report_action( self, data=data ) def print_reserv_report(self): data = { "ids": self.ids, "model": "hotel.folio", "form": self.read(["date_start", "date_end", "check"])[0], } return self.env.ref("hotel_restaurant.report_hotel_res_folio1").report_action( self, data=data )
32.396226
1,717
25,936
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class HotelRestaurantTables(models.Model): _name = "hotel.restaurant.tables" _description = "Includes Hotel Restaurant Table" name = fields.Char("Table Number", required=True) capacity = fields.Integer() class HotelRestaurantReservation(models.Model): _name = "hotel.restaurant.reservation" _description = "Includes Hotel Restaurant Reservation" _rec_name = "reservation_id" def create_order(self): """ This method is for create a new order for hotel restaurant reservation .when table is booked and create order button is clicked then this method is called and order is created.you can see this created order in "Orders" ------------------------------------------------------------ @param self: The object pointer @return: new record set for hotel restaurant reservation. """ reservation_order = self.env["hotel.reservation.order"] for record in self: table_ids = record.table_nos_ids.ids values = { "reservation_id": record.id, "order_date": record.start_date, "folio_id": record.folio_id.id, "table_nos_ids": [(6, 0, table_ids)], "is_folio": record.is_folio, } reservation_order.create(values) self.write({"state": "order"}) return True @api.onchange("customer_id") def _onchange_partner_id(self): """ When Customer name is changed respective adress will display in Adress field @param self: object pointer """ if not self.customer_id: self.partner_address_id = False else: addr = self.customer_id.address_get(["default"]) self.partner_address_id = addr["default"] @api.onchange("folio_id") def _onchange_folio_id(self): """ When you change folio_id, based on that it will update the customer_id and room_number as well --------------------------------------------------------- @param self: object pointer """ for rec in self: if rec.folio_id: rec.customer_id = rec.folio_id.partner_id.id rec.room_id = rec.folio_id.room_line_ids[0].product_id.id def action_set_to_draft(self): """ This method is used to change the state to draft of the hotel restaurant reservation -------------------------------------------- @param self: object pointer """ self.write({"state": "draft"}) def table_reserved(self): """ when CONFIRM BUTTON is clicked this method is called for table reservation @param self: The object pointer @return: change a state depending on the condition """ for reservation in self: if not reservation.table_nos_ids: raise ValidationError(_("Please Select Tables For Reservation")) reservation._cr.execute( "select count(*) from " "hotel_restaurant_reservation as hrr " "inner join reservation_table as rt on \ rt.reservation_table_id = hrr.id " "where (start_date,end_date)overlaps\ ( timestamp %s , timestamp %s ) " "and hrr.id<> %s and state != 'done'" "and rt.name in (select rt.name from \ hotel_restaurant_reservation as hrr " "inner join reservation_table as rt on \ rt.reservation_table_id = hrr.id " "where hrr.id= %s) ", ( reservation.start_date, reservation.end_date, reservation.id, reservation.id, ), ) res = self._cr.fetchone() roomcount = res and res[0] or 0.0 if roomcount: raise ValidationError( _( """You tried to confirm reservation """ """with table those already reserved """ """in this reservation period""" ) ) reservation.state = "confirm" return True def table_cancel(self): """ This method is used to change the state to cancel of the hotel restaurant reservation -------------------------------------------- @param self: object pointer """ self.write({"state": "cancel"}) def table_done(self): """ This method is used to change the state to done of the hotel restaurant reservation -------------------------------------------- @param self: object pointer """ self.write({"state": "done"}) reservation_id = fields.Char("Reservation No", readonly=True, index=True) room_id = fields.Many2one("product.product", "Room No") folio_id = fields.Many2one("hotel.folio", "Folio No") start_date = fields.Datetime( "Start Time", required=True, default=lambda self: fields.Datetime.now() ) end_date = fields.Datetime("End Time", required=True) customer_id = fields.Many2one("res.partner", "Customer Name", required=True) partner_address_id = fields.Many2one("res.partner", "Address") table_nos_ids = fields.Many2many( "hotel.restaurant.tables", "reservation_table", "reservation_table_id", "name", string="Table Number", help="Table reservation detail.", ) state = fields.Selection( [ ("draft", "Draft"), ("confirm", "Confirmed"), ("done", "Done"), ("cancel", "Cancelled"), ("order", "Order Created"), ], "state", required=True, readonly=True, copy=False, default="draft", ) is_folio = fields.Boolean("Is a Hotel Guest??") @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. """ seq_obj = self.env["ir.sequence"] reserve = seq_obj.next_by_code("hotel.restaurant.reservation") or "New" vals["reservation_id"] = reserve return super(HotelRestaurantReservation, self).create(vals) @api.constrains("start_date", "end_date") def _check_start_dates(self): """ This method is used to validate the start_date and end_date. ------------------------------------------------------------- @param self: object pointer @return: raise a warning depending on the validation """ if self.start_date >= self.end_date: raise ValidationError(_("Start Date Should be less than the End Date!")) if self.is_folio: for line in self.folio_id.room_line_ids: if self.start_date < line.checkin_date: raise ValidationError( _( """Start Date Should be greater """ """than the Folio Check-in Date!""" ) ) if self.end_date > line.checkout_date: raise ValidationError( _("End Date Should be less than the Folio Check-out Date!") ) class HotelRestaurantKitchenOrderTickets(models.Model): _name = "hotel.restaurant.kitchen.order.tickets" _description = "Includes Hotel Restaurant Order" _rec_name = "order_number" order_number = fields.Char(readonly=True) reservation_number = fields.Char() kot_date = fields.Datetime("Date") room_no = fields.Char(readonly=True) waiter_name = fields.Char(readonly=True) table_nos_ids = fields.Many2many( "hotel.restaurant.tables", "restaurant_kitchen_order_rel", "table_no", "name", "Table Number", help="Table reservation detail.", ) kot_list_ids = fields.One2many( "hotel.restaurant.order.list", "kot_order_id", "Order List", help="Kitchen order list", ) class HotelRestaurantOrder(models.Model): _name = "hotel.restaurant.order" _description = "Includes Hotel Restaurant Order" _rec_name = "order_no" @api.depends("order_list_ids") def _compute_amount_all_total(self): """ amount_subtotal and amount_total will display on change of order_list_ids --------------------------------------------------------------------- @param self: object pointer """ for sale in self: sale.amount_subtotal = sum( line.price_subtotal for line in sale.order_list_ids ) sale.amount_total = 0.0 if sale.amount_subtotal: sale.amount_total = ( sale.amount_subtotal + (sale.amount_subtotal * sale.tax) / 100 ) def done_cancel(self): """ This method is used to change the state to cancel of the hotel restaurant order ---------------------------------------- @param self: object pointer """ self.write({"state": "cancel"}) def set_to_draft(self): """ This method is used to change the state to draft of the hotel restaurant order ---------------------------------------- @param self: object pointer """ self.write({"state": "draft"}) def generate_kot(self): """ This method create new record for hotel restaurant order list. @param self: The object pointer @return: new record set for hotel restaurant order list. """ res = [] order_tickets_obj = self.env["hotel.restaurant.kitchen.order.tickets"] restaurant_order_list_obj = self.env["hotel.restaurant.order.list"] for order in self: if not order.order_list_ids: raise ValidationError(_("Please Give an Order")) if not order.table_nos_ids: raise ValidationError(_("Please Assign a Table")) table_ids = order.table_nos_ids.ids kot_data = order_tickets_obj.create( { "order_number": order.order_no, "kot_date": order.o_date, "room_no": order.room_id.name, "waiter_name": order.waiter_id.name, "table_nos_ids": [(6, 0, table_ids)], } ) for order_line in order.order_list_ids: o_line = { "kot_order_id": kot_data.id, "menucard_id": order_line.menucard_id.id, "item_qty": order_line.item_qty, "item_rate": order_line.item_rate, } restaurant_order_list_obj.create(o_line) res.append(order_line.id) order.update( { "kitchen": kot_data.id, "rest_item_id": [(6, 0, res)], "state": "order", } ) return True order_no = fields.Char("Order Number", readonly=True) o_date = fields.Datetime( "Order Date", required=True, default=lambda self: fields.Datetime.now() ) room_id = fields.Many2one("product.product", "Room No") folio_id = fields.Many2one("hotel.folio", "Folio No") waiter_id = fields.Many2one("res.partner", "Waiter") table_nos_ids = fields.Many2many( "hotel.restaurant.tables", "restaurant_table_order_rel", "table_no", "name", "Table Number", ) order_list_ids = fields.One2many( "hotel.restaurant.order.list", "restaurant_order_id", "Order List" ) tax = fields.Float("Tax (%) ") amount_subtotal = fields.Float( compute="_compute_amount_all_total", string="Subtotal" ) amount_total = fields.Float(compute="_compute_amount_all_total", string="Total") state = fields.Selection( [ ("draft", "Draft"), ("order", "Order Created"), ("done", "Done"), ("cancel", "Cancelled"), ], required=True, readonly=True, copy=False, default="draft", ) is_folio = fields.Boolean( "Is a Hotel Guest??", help="is customer reside in hotel or not" ) customer_id = fields.Many2one("res.partner", "Customer Name", required=True) kitchen = fields.Integer() rest_item_id = fields.Many2many( "hotel.restaurant.order.list", "restaurant_kitchen_rel", "restau_id", "kit_id", "Rest", ) @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. """ seq_obj = self.env["ir.sequence"] rest_order = seq_obj.next_by_code("hotel.restaurant.order") or "New" vals["order_no"] = rest_order return super(HotelRestaurantOrder, self).create(vals) @api.onchange("folio_id") def _onchange_folio_id(self): """ When you change folio_id, based on that it will update the customer_id and room_number as well --------------------------------------------------------- @param self: object pointer """ if self.folio_id: self.update( { "customer_id": self.folio_id.partner_id.id, "room_id": self.folio_id.room_line_ids[0].product_id.id, } ) def generate_kot_update(self): """ This method update record for hotel restaurant order list. ---------------------------------------------------------- @param self: The object pointer @return: update record set for hotel restaurant order list. """ order_tickets_obj = self.env["hotel.restaurant.kitchen.order.tickets"] rest_order_list_obj = self.env["hotel.restaurant.order.list"] for order in self: line_data = { "order_number": order.order_no, "kot_date": fields.Datetime.to_string(fields.datetime.now()), "room_no": order.room_id.name, "waiter_name": order.waiter_id.name, "table_nos_ids": [(6, 0, order.table_nos_ids.ids)], } kot_id = order_tickets_obj.browse(self.kitchen) kot_id.write(line_data) for order_line in order.order_list_ids: if order_line.id not in order.rest_item_id.ids: kot_data = order_tickets_obj.create(line_data) order.kitchen = kot_data.id o_line = { "kot_order_id": kot_data.id, "menucard_id": order_line.menucard_id.id, "item_qty": order_line.item_qty, "item_rate": order_line.item_rate, } order.rest_item_id = [(4, order_line.id)] rest_order_list_obj.create(o_line) return True def done_order_kot(self): """ This method is used to change the state to done of the hotel restaurant order ---------------------------------------- @param self: object pointer """ hsl_obj = self.env["hotel.service.line"] so_line_obj = self.env["sale.order.line"] for order_obj in self: for order in order_obj.order_list_ids: if order_obj.folio_id: values = { "order_id": order_obj.folio_id.order_id.id, "name": order.menucard_id.name, "product_id": order.menucard_id.product_id.id, "product_uom": order.menucard_id.uom_id.id, "product_uom_qty": order.item_qty, "price_unit": order.item_rate, "price_subtotal": order.price_subtotal, } sol_rec = so_line_obj.create(values) hsl_obj.create( { "folio_id": order_obj.folio_id.id, "service_line_id": sol_rec.id, } ) order_obj.folio_id.write( {"hotel_restaurant_orders_ids": [(4, order_obj.id)]} ) self.write({"state": "done"}) return True class HotelReservationOrder(models.Model): _name = "hotel.reservation.order" _description = "Reservation Order" _rec_name = "order_number" @api.depends("order_list_ids") def _compute_amount_all_total(self): """ amount_subtotal and amount_total will display on change of order_list_ids --------------------------------------------------------------------- @param self: object pointer """ for sale in self: sale.amount_subtotal = sum( line.price_subtotal for line in sale.order_list_ids ) sale.amount_total = ( sale.amount_subtotal + (sale.amount_subtotal * sale.tax) / 100 ) def reservation_generate_kot(self): """ This method create new record for hotel restaurant order list. -------------------------------------------------------------- @param self: The object pointer @return: new record set for hotel restaurant order list. """ res = [] order_tickets_obj = self.env["hotel.restaurant.kitchen.order.tickets"] rest_order_list_obj = self.env["hotel.restaurant.order.list"] for order in self: if not order.order_list_ids: raise ValidationError(_("Please Give an Order")) table_ids = order.table_nos_ids.ids line_data = { "order_number": order.order_number, "reservation_number": order.reservation_id.reservation_id, "kot_date": order.order_date, "waiter_name": order.waitername.name, "table_nos_ids": [(6, 0, table_ids)], } kot_data = order_tickets_obj.create(line_data) for order_line in order.order_list_ids: o_line = { "kot_order_id": kot_data.id, "menucard_id": order_line.menucard_id.id, "item_qty": order_line.item_qty, "item_rate": order_line.item_rate, } rest_order_list_obj.create(o_line) res.append(order_line.id) order.update( { "kitchen": kot_data.id, "rests_ids": [(6, 0, res)], "state": "order", } ) return res def reservation_update_kot(self): """ This method update record for hotel restaurant order list. ---------------------------------------------------------- @param self: The object pointer @return: update record set for hotel restaurant order list. """ order_tickets_obj = self.env["hotel.restaurant.kitchen.order.tickets"] rest_order_list_obj = self.env["hotel.restaurant.order.list"] for order in self: table_ids = order.table_nos_ids.ids line_data = { "order_number": order.order_number, "reservation_number": order.reservation_id.reservation_id, "kot_date": fields.Datetime.to_string(fields.datetime.now()), "waiter_name": order.waitername.name, "table_nos_ids": [(6, 0, table_ids)], } kot_id = order_tickets_obj.browse(self.kitchen) kot_id.write(line_data) for order_line in order.order_list_ids: if order_line not in order.rests_ids.ids: kot_data = order_tickets_obj.create(line_data) o_line = { "kot_order_id": kot_data.id, "menucard_id": order_line.menucard_id.id, "item_qty": order_line.item_qty, "item_rate": order_line.item_rate, } order.update( { "kitchen": kot_data.id, "rests_ids": [(4, order_line.id)], } ) rest_order_list_obj.create(o_line) return True def done_kot(self): """ This method is used to change the state to done of the hotel reservation order ---------------------------------------- @param self: object pointer """ hsl_obj = self.env["hotel.service.line"] so_line_obj = self.env["sale.order.line"] for res_order in self: for order in res_order.order_list_ids: if res_order.folio_id: values = { "order_id": res_order.folio_id.order_id.id, "name": order.menucard_id.name, "product_id": order.menucard_id.product_id.id, "product_uom_qty": order.item_qty, "price_unit": order.item_rate, "price_subtotal": order.price_subtotal, } sol_rec = so_line_obj.create(values) hsl_obj.create( { "folio_id": res_order.folio_id.id, "service_line_id": sol_rec.id, } ) res_order.folio_id.write( {"hotel_reservation_orders_ids": [(4, res_order.id)]} ) res_order.reservation_id.write({"state": "done"}) self.write({"state": "done"}) return True order_number = fields.Char("Order No", readonly=True) reservation_id = fields.Many2one("hotel.restaurant.reservation", "Reservation No") order_date = fields.Datetime( "Date", required=True, default=lambda self: fields.Datetime.now() ) waitername = fields.Many2one("res.partner", "Waiter Name") table_nos_ids = fields.Many2many( "hotel.restaurant.tables", "temp_table4", "table_no", "name", "Table Number", ) order_list_ids = fields.One2many( "hotel.restaurant.order.list", "reservation_order_id", "Order List" ) tax = fields.Float("Tax (%) ") amount_subtotal = fields.Float( compute="_compute_amount_all_total", string="Subtotal" ) amount_total = fields.Float(compute="_compute_amount_all_total", string="Total") kitchen = fields.Integer("Kitchen Id") rests_ids = fields.Many2many( "hotel.restaurant.order.list", "reserv_id", "kitchen_id", "res_kit_ids", "Rest", ) state = fields.Selection( [("draft", "Draft"), ("order", "Order Created"), ("done", "Done")], required=True, readonly=True, default="draft", ) folio_id = fields.Many2one("hotel.folio", "Folio No") is_folio = fields.Boolean( "Is a Hotel Guest??", help="is customer reside in hotel or not" ) @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. """ seq_obj = self.env["ir.sequence"] res_oder = seq_obj.next_by_code("hotel.reservation.order") or "New" vals["order_number"] = res_oder return super(HotelReservationOrder, self).create(vals) class HotelRestaurantOrderList(models.Model): _name = "hotel.restaurant.order.list" _description = "Includes Hotel Restaurant Order" @api.depends("item_qty", "item_rate") def _compute_price_subtotal(self): """ price_subtotal will display on change of item_rate -------------------------------------------------- @param self: object pointer """ for line in self: line.price_subtotal = line.item_rate * int(line.item_qty) @api.onchange("menucard_id") def _onchange_item_name(self): """ item rate will display on change of item name --------------------------------------------- @param self: object pointer """ self.item_rate = self.menucard_id.list_price restaurant_order_id = fields.Many2one("hotel.restaurant.order", "Restaurant Order") reservation_order_id = fields.Many2one( "hotel.reservation.order", "Reservation Order" ) kot_order_id = fields.Many2one( "hotel.restaurant.kitchen.order.tickets", "Kitchen Order Tickets" ) menucard_id = fields.Many2one("hotel.menucard", "Item Name", required=True) item_qty = fields.Integer("Qty", required=True, default=1) item_rate = fields.Float("Rate") price_subtotal = fields.Float(compute="_compute_price_subtotal", string="Subtotal")
37.697674
25,936
3,249
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class HotelMenucardType(models.Model): _name = "hotel.menucard.type" # need to recheck for v15 _description = "Food Item Type" name = fields.Char(required=True) menu_id = fields.Many2one("hotel.menucard.type", "Food Item Type") child_ids = fields.One2many("hotel.menucard.type", "menu_id", "Child Categories") def name_get(self): def get_names(cat): """Return the list [cat.name, cat.menu_id.name, ...]""" res = [] while cat: res.append(cat.name) cat = cat.menu_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self] @api.model def name_search(self, name, args=None, operator="ilike", limit=100): if not args: args = [] if name: # Be sure name_search is symetric to name_get category_names = name.split(" / ") parents = list(category_names) child = parents.pop() domain = [("name", operator, child)] if parents: names_ids = self.name_search( " / ".join(parents), args=args, operator="ilike", limit=limit, ) category_ids = [name_id[0] for name_id in names_ids] if operator in expression.NEGATIVE_TERM_OPERATORS: categories = self.search([("id", "not in", category_ids)]) domain = expression.OR( [[("menu_id", "in", categories.ids)], domain] ) else: domain = expression.AND([[("menu_id", "in", category_ids)], domain]) for i in range(1, len(category_names)): domain = [ [ ( "name", operator, " / ".join(category_names[-1 - i :]), ) ], domain, ] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = expression.AND(domain) else: domain = expression.OR(domain) categories = self.search(expression.AND([domain, args]), limit=limit) else: categories = self.search(args, limit=limit) return categories.name_get() class HotelMenucard(models.Model): _name = "hotel.menucard" _description = "Hotel Menucard" product_id = fields.Many2one( "product.product", "Hotel Menucard", required=True, delegate=True, ondelete="cascade", index=True, ) categ_id = fields.Many2one( "hotel.menucard.type", "Food Item Category", required=True ) product_manager_id = fields.Many2one("res.users", "Product Manager")
36.1
3,249
643
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class HotelFolio(models.Model): _inherit = "hotel.folio" hotel_reservation_orders_ids = fields.Many2many( "hotel.reservation.order", "hotel_res_rel", "hotel_folio_id", "reste_id", "Reservation Orders", ) hotel_restaurant_orders_ids = fields.Many2many( "hotel.restaurant.order", "hotel_res_resv", "hfolio_id", "reserves_id", "Restaurant Orders", )
26.791667
643
9,813
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import api, fields, models class HotelRestaurantReport(models.AbstractModel): _name = "report.hotel_restaurant.report_res_table" _description = "report.hotel_restaurant.report_res_table" def get_res_data(self, date_start, date_end): data = [] tids = self.env["hotel.restaurant.reservation"].search( [("start_date", ">=", date_start), ("end_date", "<=", date_end)] ) for record in tids: data.append( { "reservation": record.reservation_id, "name": record.customer_id.name, "start_date": fields.Datetime.to_string(record.start_date), "end_date": fields.Datetime.to_string(record.end_date), } ) return data @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.restaurant.tables"].browse(docids) date_start = data.get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=1, day=1, days=1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) reservation_res = rm_act.get_res_data(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "Reservations": reservation_res, } class ReportKot(models.AbstractModel): _name = "report.hotel_restaurant.report_hotel_order_kot" _description = "report.hotel_restaurant.report_hotel_order_kot" @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.restaurant.order"].browse(docids) return { "doc_ids": docids, "doc_model": active_model, "docs": folio_profile, "data": data, } class FolioRestReport(models.AbstractModel): _name = "report.hotel_restaurant.report_rest_order" _description = "Folio Rest Report" def get_data(self, date_start, date_end): data = [] tids = self.env["hotel.folio"].search( [ ("checkin_date", ">=", date_start), ("checkout_date", "<=", date_end), ] ) total = 0.0 for record in tids: if record.hotel_reservation_orders_ids: total_amount = sum( order.amount_total for order in record.hotel_reservation_orders_ids ) total_order = len(record.hotel_reservation_orders_ids.ids) data.append( { "folio_name": record.name, "customer_name": record.partner_id.name, "checkin_date": fields.Datetime.to_string(record.checkin_date), "checkout_date": fields.Datetime.to_string( record.checkout_date ), "total_amount": total_amount, "total_order": total_order, } ) data.append({"total": total}) return data def get_rest(self, date_start, date_end): data = [] tids = self.env["hotel.folio"].search( [ ("checkin_date", ">=", date_start), ("checkout_date", "<=", date_end), ] ) for record in tids: if record.hotel_reservation_orders_ids: order_data = [] for order in record.hotel_reservation_orders_ids: order_data.append( { "order_no": order.order_number, "order_date": fields.Datetime.to_string(order.order_date), "state": order.state, "table_nos_ids": len(order.table_nos_ids), "order_len": len(order.order_list_ids), "amount_total": order.amount_total, } ) data.append( { "folio_name": record.name, "customer_name": record.partner_id.name, "order_data": order_data, } ) return data @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.reservation.order"].browse(docids) date_start = data["form"].get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=1, day=1, days=1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) get_data_res = rm_act.get_data(date_start, date_end) get_rest_res = rm_act.get_rest(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "GetData": get_data_res, "GetRest": get_rest_res, } class FolioReservReport(models.AbstractModel): _name = "report.hotel_restaurant.report_reserv_order" _description = "report.hotel_restaurant.report_reserv_order" def get_data(self, date_start, date_end): data = [] tids = self.env["hotel.folio"].search( [ ("checkin_date", ">=", date_start), ("checkout_date", "<=", date_end), ] ) total = 0.0 for record in tids: if record.hotel_restaurant_orders_ids: total_amount = sum( order.amount_total for order in record.hotel_restaurant_orders_ids ) total_order = len(record.hotel_restaurant_orders_ids.ids) data.append( { "folio_name": record.name, "customer_name": record.partner_id.name, "checkin_date": fields.Datetime.to_string(record.checkin_date), "checkout_date": fields.Datetime.to_string( record.checkout_date ), "total_amount": total_amount, "total_order": total_order, } ) data.append({"total": total}) return data def get_reserv(self, date_start, date_end): data = [] tids = self.env["hotel.folio"].search( [ ("checkin_date", ">=", date_start), ("checkout_date", "<=", date_end), ] ) for record in tids: if record.hotel_restaurant_orders_ids: order_data = [] for order in record.hotel_restaurant_orders_ids: order_date = order.o_date # order_date = (fields.Datetime.to_string(record.order_date),) order_data.append( { "order_no": order.order_no, "order_date": order_date, "state": order.state, "room_id": order.room_id.name, "table_nos_ids": len(order.table_nos_ids), "amount_total": order.amount_total, } ) data.append( { "folio_name": record.name, "customer_name": record.partner_id.name, "order_data": order_data, } ) return data @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.restaurant.order"].browse(docids) date_start = data.get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=1, day=1, days=1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) get_data_res = rm_act.get_data(date_start, date_end) get_reserv_res = rm_act.get_reserv(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "GetData": get_data_res, "GetReserv": get_reserv_res, }
37.742308
9,813
1,553
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Hotel Reservation Management", "version": "15.0.1.0.0", "author": "Odoo Community Association (OCA), Serpent Consulting \ Services Pvt. Ltd., Odoo S.A.", "category": "Generic Modules/Hotel Reservation", "license": "AGPL-3", "summary": "Manages Guest Reservation & displays Reservation Summary", "website": "https://github.com/OCA/vertical-hotel", "depends": ["hotel", "stock", "mail"], "demo": ["data/hotel_reservation_data.xml"], "data": [ "security/ir.model.access.csv", "data/hotel_scheduler.xml", "data/hotel_reservation_sequence.xml", "data/email_template_view.xml", "views/hotel_reservation_view.xml", "report/checkin_report_template.xml", "report/checkout_report_template.xml", "report/room_max_report_template.xml", "report/hotel_reservation_report_template.xml", "report/report_view.xml", "wizards/hotel_reservation_wizard.xml", ], "assets": { "web.assets_qweb": [ "hotel_reservation/static/src/xml/hotel_room_summary.xml", ], "web.assets_backend": [ "hotel_reservation/static/src/css/room_summary.css", "hotel_reservation/static/src/js/hotel_room_summary.js", ], }, "external_dependencies": {"python": ["dateutil"]}, "installable": True, }
39.820513
1,553
7,293
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime, timedelta from odoo.exceptions import ValidationError from odoo.tests import common class TestReservation(common.TransactionCase): def setUp(self): super(TestReservation, self).setUp() self.hotel_reserv_line_obj = self.env["hotel.reservation.line"] self.hotel_reserv_obj = self.env["hotel.reservation"] self.hotel_room_obj = self.env["hotel.room"] self.hotel_room_reserv_obj = self.env["hotel.room.reservation.line"] self.reserv_summary_obj = self.env["room.reservation.summary"] self.quick_room_reserv_obj = self.env["quick.room.reservation"] self.hotel_folio_obj = self.env["hotel.folio"] self.reserv_line = self.env.ref("hotel_reservation.hotel_reservation_0") self.room_type = self.env.ref("hotel.hotel_room_type_1") self.room = self.env.ref("hotel.hotel_room_0") self.company = self.env.ref("base.main_company") self.partner = self.env.ref("base.res_partner_2") self.pricelist = self.env.ref("product.list0") self.floor = self.env.ref("hotel.hotel_floor_ground0") self.manager = self.env.ref("base.user_root") self.warehouse = self.env.ref("stock.warehouse0") self.price_list = self.env.ref("product.list0") cur_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.hotel_reserv_line = self.hotel_reserv_line_obj.create( { "name": "R/00001", "line_id": self.reserv_line.id, "reserve": [(6, 0, [self.room.id])], "categ_id": self.room_type.id, } ) self.hotel_reserv = self.hotel_reserv_obj.create( { "reservation_no": "R/00002", "date_order": cur_date, "company_id": self.company.id, "partner_id": self.partner.id, "pricelist_id": self.pricelist.id, "checkin": cur_date, "checkout": cur_date, "adults": 1, "state": "draft", "children": 1, "partner_invoice_id": self.partner.id, "partner_order_id": self.partner.id, "partner_shipping_id": self.partner.id, "reservation_line": [(6, 0, [self.room.id])], } ) self.reserv_summary = self.reserv_summary_obj.create( { "name": "Room Reservation Summary", "date_from": cur_date, "date_to": cur_date, } ) self.quick_room_reserv = self.quick_room_reserv_obj.create( { "partner_id": self.partner.id, "check_in": cur_date, "check_out": cur_date, "room_id": self.room.id, "company_id": self.company.id, "pricelist_id": self.pricelist.id, "partner_invoice_id": self.partner.id, "partner_order_id": self.partner.id, "partner_shipping_id": self.partner.id, "adults": 1, } ) self.hotel_room_reserv = self.hotel_room_reserv_obj.create( { "room_id": self.room.id, "check_in": cur_date, "check_out": cur_date, } ) self.hotel_room = self.hotel_room_obj.create( { "product_id": self.room.product_id.id, "floor_id": self.floor.id, "max_adult": 2, "max_child": 1, "capacity": 4, "room_categ_id": self.room_type.categ_id.id, "status": "available", "product_manager": self.manager.id, "room_reservation_line_ids": [(6, 0, [self.hotel_room_reserv.id])], } ) self.hotel_folio = self.hotel_folio_obj.create( { "name": "Folio/00003", "date_order": cur_date, "warehouse_id": self.warehouse.id, "invoice_status": "no", "pricelist_id": self.price_list.id, "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "state": "draft", } ) def test_hotel_room_unlink(self): self.hotel_room.unlink() def test_cron_room_line(self): self.hotel_room.cron_room_line() def test_quick_room_reserv_on_change_check_out(self): self.quick_room_reserv._on_change_check_out() def test_quick_room_reserv_onchange_partner_id_res(self): self.quick_room_reserv._onchange_partner_id_res() def test_quick_room_reserv_default_get(self): fields = ["date_from", "room_id"] self.quick_room_reserv.default_get(fields) def test_default_get(self): fields = ["date_from", "date_to"] self.reserv_summary.default_get(fields) def test_room_reservation(self): self.reserv_summary.room_reservation() def test_get_room_summary(self): self.reserv_summary.get_room_summary() def test_check_reservation_rooms(self): for rec in self.hotel_reserv.reservation_line: self.assertEqual(len(rec.reserve), 1, "Please Select Rooms For Reservation") self.hotel_reserv._check_reservation_rooms() def test_unlink_reserv(self): self.assertEqual(self.hotel_reserv.state != "draft", False) self.hotel_reserv.unlink() def test_copy(self): self.hotel_reserv.copy() def test_reserv_check_in_out_dates(self): self.hotel_reserv.check_in_out_dates() def test_reserv_check_overlap(self): date1 = datetime.now() date2 = datetime.now() + timedelta(days=1) self.hotel_reserv.check_overlap(date1, date2) def test_onchange_partner_id(self): self.hotel_reserv._onchange_partner_id() def test_set_to_draft_reservation(self): self.hotel_reserv.set_to_draft_reservation() self.assertEqual(self.hotel_reserv.state == "draft", True) def test_send_reservation_maill(self): self.hotel_reserv.action_send_reservation_mail() def test_reservation_reminder_24hrs(self): self.hotel_reserv.reservation_reminder_24hrs() def test_create_folio(self): with self.assertRaises(ValidationError): self.hotel_reserv.create_folio() def test_onchange_check_dates(self): self.hotel_reserv._onchange_check_dates() def test_confirmed_reservation(self): self.hotel_reserv.confirmed_reservation() def test_cancel_reservation(self): self.hotel_reserv.cancel_reservation() self.assertEqual(self.hotel_reserv.state == "cancel", True) def test_write(self): self.hotel_folio.write({"reservation_id": self.hotel_reserv.id}) def test_on_change_categ(self): self.hotel_reserv_line.on_change_categ() def test_unlink(self): self.hotel_reserv_line.unlink()
36.465
7,293
4,715
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class QuickRoomReservation(models.TransientModel): _name = "quick.room.reservation" _description = "Quick Room Reservation" partner_id = fields.Many2one("res.partner", "Customer", required=True) check_in = fields.Datetime(required=True) check_out = fields.Datetime(required=True) room_id = fields.Many2one("hotel.room", required=True) company_id = fields.Many2one("res.company", "Hotel", required=True) pricelist_id = fields.Many2one("product.pricelist", "pricelist") partner_invoice_id = fields.Many2one( "res.partner", "Invoice Address", required=True ) partner_order_id = fields.Many2one("res.partner", "Ordering Contact", required=True) partner_shipping_id = fields.Many2one( "res.partner", "Delivery Address", required=True ) adults = fields.Integer() @api.onchange("check_out", "check_in") def _on_change_check_out(self): """ When you change checkout or checkin it will check whether Checkout date should be greater than Checkin date and update dummy field ----------------------------------------------------------- @param self: object pointer @return: raise warning depending on the validation """ if (self.check_out and self.check_in) and (self.check_out < self.check_in): raise ValidationError( _("Checkout date should be greater than Checkin date.") ) @api.onchange("partner_id") def _onchange_partner_id_res(self): """ When you change partner_id it will update the partner_invoice_id, partner_shipping_id and pricelist_id of the hotel reservation as well --------------------------------------------------------------------- @param self: object pointer """ if not self.partner_id: self.update( { "partner_invoice_id": False, "partner_shipping_id": False, "partner_order_id": False, } ) else: addr = self.partner_id.address_get(["delivery", "invoice", "contact"]) self.update( { "partner_invoice_id": addr["invoice"], "partner_shipping_id": addr["delivery"], "partner_order_id": addr["contact"], "pricelist_id": self.partner_id.property_product_pricelist.id, } ) @api.model def default_get(self, fields): """ To get default values for the object. @param self: The object pointer. @param fields: List of fields for which we want default values @return: A dictionary which of fields with values. """ res = super(QuickRoomReservation, self).default_get(fields) keys = self._context.keys() if "date" in keys: res.update({"check_in": self._context["date"]}) if "room_id" in keys: roomid = self._context["room_id"] res.update({"room_id": int(roomid)}) return res def room_reserve(self): """ This method create a new record for hotel.reservation ----------------------------------------------------- @param self: The object pointer @return: new record set for hotel reservation. """ hotel_res_obj = self.env["hotel.reservation"] for res in self: rec = hotel_res_obj.create( { "partner_id": res.partner_id.id, "partner_invoice_id": res.partner_invoice_id.id, "partner_order_id": res.partner_order_id.id, "partner_shipping_id": res.partner_shipping_id.id, "checkin": res.check_in, "checkout": res.check_out, "company_id": res.company_id.id, "pricelist_id": res.pricelist_id.id, "adults": res.adults, "reservation_line": [ ( 0, 0, { "reserve": [(6, 0, res.room_id.ids)], "name": res.room_id.name or " ", }, ) ], } ) return rec
39.957627
4,715
13,012
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT as dt _logger = logging.getLogger(__name__) try: import pytz except (ImportError, IOError) as err: _logger.debug(err) class HotelRoom(models.Model): _inherit = "hotel.room" _description = "Hotel Room" room_reservation_line_ids = fields.One2many( "hotel.room.reservation.line", "room_id", string="Room Reserve Line" ) def unlink(self): """ Overrides orm unlink method. @param self: The object pointer @return: True/False. """ for room in self: for reserv_line in room.room_reservation_line_ids: if reserv_line.status == "confirm": raise ValidationError( _( """User is not able to delete the """ """room after the room in %s state """ """in reservation""" ) % (reserv_line.status) ) return super(HotelRoom, self).unlink() @api.model def cron_room_line(self): """ This method is for scheduler every 1min scheduler will call this method and check Status of room is occupied or available -------------------------------------------------------------- @param self: The object pointer @return: update status of hotel room reservation line """ reservation_line_obj = self.env["hotel.room.reservation.line"] folio_room_line_obj = self.env["folio.room.line"] curr_date = fields.Datetime.now().strftime(dt) for room in self.search([]): reserv_line_ids = room.room_reservation_line_ids.ids reservation_line_ids = reservation_line_obj.search( [ ("id", "in", reserv_line_ids), ("check_in", "<=", curr_date), ("check_out", ">=", curr_date), ] ) rooms_ids = room.room_line_ids.ids room_line_ids = folio_room_line_obj.search( [ ("id", "in", rooms_ids), ("check_in", "<=", curr_date), ("check_out", ">=", curr_date), ] ) status = {"isroom": True, "color": 5} if reservation_line_ids: status = {"isroom": False, "color": 2} room.write(status) if room_line_ids: status = {"isroom": False, "color": 2} room.write(status) if reservation_line_ids and room_line_ids: raise ValidationError( _( "Please Check Rooms Status for %(room_name)s.", room_name=room.name, ) ) return True class RoomReservationSummary(models.Model): _name = "room.reservation.summary" _description = "Room reservation summary" name = fields.Char("Reservation Summary", default="Reservations Summary") date_from = fields.Datetime(default=lambda self: fields.Date.today()) date_to = fields.Datetime( default=lambda self: fields.Date.today() + relativedelta(days=30), ) summary_header = fields.Text() room_summary = fields.Text() def room_reservation(self): """ @param self: object pointer """ resource_id = self.env.ref("hotel_reservation.view_hotel_reservation_form").id return { "name": _("Reconcile Write-Off"), "context": self._context, "view_type": "form", "view_mode": "form", "res_model": "hotel.reservation", "views": [(resource_id, "form")], "type": "ir.actions.act_window", "target": "new", } @api.onchange("date_from", "date_to") # noqa C901 (function is too complex) def get_room_summary(self): # noqa C901 (function is too complex) """ @param self: object pointer """ res = {} all_detail = [] room_obj = self.env["hotel.room"] reservation_line_obj = self.env["hotel.room.reservation.line"] folio_room_line_obj = self.env["folio.room.line"] user_obj = self.env["res.users"] date_range_list = [] main_header = [] summary_header_list = ["Rooms"] if self.date_from and self.date_to: if self.date_from > self.date_to: raise UserError(_("Checkout date should be greater than Checkin date.")) if self._context.get("tz", False): timezone = pytz.timezone(self._context.get("tz", False)) else: timezone = pytz.timezone("UTC") d_frm_obj = ( (self.date_from) .replace(tzinfo=pytz.timezone("UTC")) .astimezone(timezone) ) d_to_obj = ( (self.date_to).replace(tzinfo=pytz.timezone("UTC")).astimezone(timezone) ) temp_date = d_frm_obj while temp_date <= d_to_obj: val = "" val = ( str(temp_date.strftime("%a")) + " " + str(temp_date.strftime("%b")) + " " + str(temp_date.strftime("%d")) ) summary_header_list.append(val) date_range_list.append(temp_date.strftime(dt)) temp_date = temp_date + timedelta(days=1) all_detail.append(summary_header_list) room_ids = room_obj.search([]) all_room_detail = [] for room in room_ids: room_detail = {} room_list_stats = [] room_detail.update({"name": room.name or ""}) if not room.room_reservation_line_ids and not room.room_line_ids: for chk_date in date_range_list: room_list_stats.append( { "state": "Free", "date": chk_date, "room_id": room.id, } ) else: for chk_date in date_range_list: ch_dt = chk_date[:10] + " 23:59:59" ttime = datetime.strptime(ch_dt, dt) c = ttime.replace(tzinfo=timezone).astimezone( pytz.timezone("UTC") ) chk_date = c.strftime(dt) reserline_ids = room.room_reservation_line_ids.ids reservline_ids = reservation_line_obj.search( [ ("id", "in", reserline_ids), ("check_in", "<=", chk_date), ("check_out", ">=", chk_date), ("state", "=", "assigned"), ] ) if not reservline_ids: sdt = dt chk_date = datetime.strptime(chk_date, sdt) chk_date = datetime.strftime( chk_date - timedelta(days=1), sdt ) reservline_ids = reservation_line_obj.search( [ ("id", "in", reserline_ids), ("check_in", "<=", chk_date), ("check_out", ">=", chk_date), ("state", "=", "assigned"), ] ) for res_room in reservline_ids: cid = res_room.check_in cod = res_room.check_out dur = cod - cid if room_list_stats: count = 0 for rlist in room_list_stats: cidst = datetime.strftime(cid, dt) codst = datetime.strftime(cod, dt) rm_id = res_room.room_id.id ci = rlist.get("date") >= cidst co = rlist.get("date") <= codst rm = rlist.get("room_id") == rm_id st = rlist.get("state") == "Reserved" if ci and co and rm and st: count += 1 if count - dur.days == 0: c_id1 = user_obj.browse(self._uid) c_id = c_id1.company_id con_add = 0 amin = 0.0 # When configured_addition_hours is # greater than zero then we calculate # additional minutes if c_id: con_add = c_id.additional_hours if con_add > 0: amin = abs(con_add * 60) hr_dur = abs(dur.seconds / 60) if amin > 0: # When additional minutes is greater # than zero then check duration with # extra minutes and give the room # reservation status is reserved # -------------------------- if hr_dur >= amin: reservline_ids = True else: reservline_ids = False else: if hr_dur > 0: reservline_ids = True else: reservline_ids = False else: reservline_ids = False fol_room_line_ids = room.room_line_ids.ids chk_state = ["draft", "cancel"] folio_resrv_ids = folio_room_line_obj.search( [ ("id", "in", fol_room_line_ids), ("check_in", "<=", chk_date), ("check_out", ">=", chk_date), ("status", "not in", chk_state), ] ) if reservline_ids or folio_resrv_ids: room_list_stats.append( { "state": "Reserved", "date": chk_date, "room_id": room.id, "is_draft": "No", "data_model": "", "data_id": 0, } ) else: room_list_stats.append( { "state": "Free", "date": chk_date, "room_id": room.id, } ) room_detail.update({"value": room_list_stats}) all_room_detail.append(room_detail) main_header.append({"header": summary_header_list}) self.summary_header = str(main_header) self.room_summary = str(all_room_detail) return res
44.258503
13,012
4,111
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class HotelFolio(models.Model): _inherit = "hotel.folio" _order = "reservation_id desc" reservation_id = fields.Many2one( "hotel.reservation", "Reservation", ondelete="restrict" ) def write(self, vals): res = super(HotelFolio, self).write(vals) reservation_line_obj = self.env["hotel.room.reservation.line"] for folio in self: reservations = reservation_line_obj.search( [("reservation_id", "=", folio.reservation_id.id)] ) if len(reservations) == 1: for line in folio.reservation_id.reservation_line: for room in line.reserve: vals = { "room_id": room.id, "check_in": folio.checkin_date, "check_out": folio.checkout_date, "state": "assigned", "reservation_id": folio.reservation_id.id, } reservations.write(vals) return res class HotelFolioLine(models.Model): _inherit = "hotel.folio.line" @api.onchange("checkin_date", "checkout_date") def _onchange_checkin_checkout_dates(self): res = super(HotelFolioLine, self)._onchange_checkin_checkout_dates() avail_prod_ids = [] for room in self.env["hotel.room"].search([]): assigned = False for line in room.room_reservation_line_ids.filtered( lambda l: l.status != "cancel" ): if self.checkin_date and line.check_in and self.checkout_date: if (self.checkin_date <= line.check_in <= self.checkout_date) or ( self.checkin_date <= line.check_out <= self.checkout_date ): assigned = True elif (line.check_in <= self.checkin_date <= line.check_out) or ( line.check_in <= self.checkout_date <= line.check_out ): assigned = True if not assigned: avail_prod_ids.append(room.product_id.id) return res def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. Update Hotel Room Reservation line history""" reservation_line_obj = self.env["hotel.room.reservation.line"] room_obj = self.env["hotel.room"] prod_id = vals.get("product_id") or self.product_id.id checkin = vals.get("checkin_date") or self.checkin_date checkout = vals.get("checkout_date") or self.checkout_date is_reserved = self.is_reserved if prod_id and is_reserved: prod_room = room_obj.search([("product_id", "=", prod_id)], limit=1) if self.product_id and self.checkin_date and self.checkout_date: old_prod_room = room_obj.search( [("product_id", "=", self.product_id.id)], limit=1 ) if prod_room and old_prod_room: # Check for existing room lines. rm_lines = reservation_line_obj.search( [ ("room_id", "=", old_prod_room.id), ("check_in", "=", self.checkin_date), ("check_out", "=", self.checkout_date), ] ) if rm_lines: rm_line_vals = { "room_id": prod_room.id, "check_in": checkin, "check_out": checkout, } rm_lines.write(rm_line_vals) return super(HotelFolioLine, self).write(vals)
41.94898
4,111
23,901
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import timedelta from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import ValidationError class HotelReservation(models.Model): _name = "hotel.reservation" _rec_name = "reservation_no" _description = "Reservation" _order = "reservation_no desc" _inherit = ["mail.thread"] def _compute_folio_count(self): for res in self: res.update({"no_of_folio": len(res.folio_id.ids)}) reservation_no = fields.Char(readonly=True, copy=False) date_order = fields.Datetime( "Date Ordered", readonly=True, required=True, index=True, default=lambda self: fields.Datetime.now(), ) company_id = fields.Many2one( "res.company", "Hotel", readonly=True, index=True, required=True, default=1, states={"draft": [("readonly", False)]}, ) partner_id = fields.Many2one( "res.partner", "Guest Name", readonly=True, index=True, required=True, states={"draft": [("readonly", False)]}, ) pricelist_id = fields.Many2one( "product.pricelist", "Scheme", required=True, readonly=True, states={"draft": [("readonly", False)]}, help="Pricelist for current reservation.", ) partner_invoice_id = fields.Many2one( "res.partner", "Invoice Address", readonly=True, states={"draft": [("readonly", False)]}, help="Invoice address for " "current reservation.", ) partner_order_id = fields.Many2one( "res.partner", "Ordering Contact", readonly=True, states={"draft": [("readonly", False)]}, help="The name and address of the " "contact that requested the order " "or quotation.", ) partner_shipping_id = fields.Many2one( "res.partner", "Delivery Address", readonly=True, states={"draft": [("readonly", False)]}, help="Delivery address" "for current reservation. ", ) checkin = fields.Datetime( "Expected-Date-Arrival", required=True, readonly=True, states={"draft": [("readonly", False)]}, ) checkout = fields.Datetime( "Expected-Date-Departure", required=True, readonly=True, states={"draft": [("readonly", False)]}, ) adults = fields.Integer( readonly=True, states={"draft": [("readonly", False)]}, help="List of adults there in guest list. ", ) children = fields.Integer( readonly=True, states={"draft": [("readonly", False)]}, help="Number of children there in guest list.", ) reservation_line = fields.One2many( "hotel.reservation.line", "line_id", help="Hotel room reservation details.", readonly=True, states={"draft": [("readonly", False)]}, ) state = fields.Selection( [ ("draft", "Draft"), ("confirm", "Confirm"), ("cancel", "Cancel"), ("done", "Done"), ], readonly=True, default="draft", ) folio_id = fields.Many2many( "hotel.folio", "hotel_folio_reservation_rel", "order_id", "invoice_id", string="Folio", ) no_of_folio = fields.Integer("No. Folio", compute="_compute_folio_count") def unlink(self): """ Overrides orm unlink method. @param self: The object pointer @return: True/False. """ lines_of_moves_to_post = self.filtered( lambda reserv_rec: reserv_rec.state != "draft" ) if lines_of_moves_to_post: raise ValidationError( _("Sorry, you can only delete the reservation when it's draft!") ) return super(HotelReservation, self).unlink() def copy(self): ctx = dict(self._context) or {} ctx.update({"duplicate": True}) return super(HotelReservation, self.with_context(**ctx)).copy() @api.constrains("reservation_line", "adults", "children") def _check_reservation_rooms(self): """ This method is used to validate the reservation_line. ----------------------------------------------------- @param self: object pointer @return: raise a warning depending on the validation """ ctx = dict(self._context) or {} for reservation in self: cap = 0 for rec in reservation.reservation_line: if len(rec.reserve) == 0: raise ValidationError(_("Please Select Rooms For Reservation.")) cap = sum(room.capacity for room in rec.reserve) if not ctx.get("duplicate"): if (reservation.adults + reservation.children) > cap: raise ValidationError( _( "Room Capacity Exceeded \n" " Please Select Rooms According to" " Members Accomodation." ) ) if reservation.adults <= 0: raise ValidationError(_("Adults must be more than 0")) @api.constrains("checkin", "checkout") def check_in_out_dates(self): """ When date_order is less then check-in date or Checkout date should be greater than the check-in date. """ if self.checkout and self.checkin: if self.checkin < self.date_order: raise ValidationError( _( """Check-in date should be greater than """ """the current date.""" ) ) if self.checkout < self.checkin: raise ValidationError( _("""Check-out date should be greater """ """than Check-in date.""") ) @api.onchange("partner_id") def _onchange_partner_id(self): """ When you change partner_id it will update the partner_invoice_id, partner_shipping_id and pricelist_id of the hotel reservation as well --------------------------------------------------------------------- @param self: object pointer """ if not self.partner_id: self.update( { "partner_invoice_id": False, "partner_shipping_id": False, "partner_order_id": False, } ) else: addr = self.partner_id.address_get(["delivery", "invoice", "contact"]) self.update( { "partner_invoice_id": addr["invoice"], "partner_shipping_id": addr["delivery"], "partner_order_id": addr["contact"], "pricelist_id": self.partner_id.property_product_pricelist.id, } ) @api.model def create(self, vals): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. """ vals["reservation_no"] = ( self.env["ir.sequence"].next_by_code("hotel.reservation") or "New" ) return super(HotelReservation, self).create(vals) def check_overlap(self, date1, date2): delta = date2 - date1 return {date1 + timedelta(days=i) for i in range(delta.days + 1)} def confirmed_reservation(self): """ This method create a new record set for hotel room reservation line ------------------------------------------------------------------- @param self: The object pointer @return: new record set for hotel room reservation line. """ reservation_line_obj = self.env["hotel.room.reservation.line"] vals = {} for reservation in self: reserv_checkin = reservation.checkin reserv_checkout = reservation.checkout room_bool = False for line_id in reservation.reservation_line: for room in line_id.reserve: if room.room_reservation_line_ids: for reserv in room.room_reservation_line_ids.search( [ ("status", "in", ("confirm", "done")), ("room_id", "=", room.id), ] ): check_in = reserv.check_in check_out = reserv.check_out if check_in <= reserv_checkin <= check_out: room_bool = True if check_in <= reserv_checkout <= check_out: room_bool = True if ( reserv_checkin <= check_in and reserv_checkout >= check_out ): room_bool = True r_checkin = (reservation.checkin).date() r_checkout = (reservation.checkout).date() check_intm = (reserv.check_in).date() check_outtm = (reserv.check_out).date() range1 = [r_checkin, r_checkout] range2 = [check_intm, check_outtm] overlap_dates = self.check_overlap( *range1 ) & self.check_overlap(*range2) if room_bool: raise ValidationError( _( "You tried to Confirm " "Reservation with room" " those already " "reserved in this " "Reservation Period. " "Overlap Dates are " "%s" ) % overlap_dates ) else: self.state = "confirm" vals = { "room_id": room.id, "check_in": reservation.checkin, "check_out": reservation.checkout, "state": "assigned", "reservation_id": reservation.id, } room.write({"isroom": False, "status": "occupied"}) else: self.state = "confirm" vals = { "room_id": room.id, "check_in": reservation.checkin, "check_out": reservation.checkout, "state": "assigned", "reservation_id": reservation.id, } room.write({"isroom": False, "status": "occupied"}) else: self.state = "confirm" vals = { "room_id": room.id, "check_in": reservation.checkin, "check_out": reservation.checkout, "state": "assigned", "reservation_id": reservation.id, } room.write({"isroom": False, "status": "occupied"}) reservation_line_obj.create(vals) return True def cancel_reservation(self): """ This method cancel record set for hotel room reservation line ------------------------------------------------------------------ @param self: The object pointer @return: cancel record set for hotel room reservation line. """ room_res_line_obj = self.env["hotel.room.reservation.line"] hotel_res_line_obj = self.env["hotel.reservation.line"] self.state = "cancel" room_reservation_line = room_res_line_obj.search( [("reservation_id", "in", self.ids)] ) room_reservation_line.write({"state": "unassigned"}) room_reservation_line.unlink() reservation_lines = hotel_res_line_obj.search([("line_id", "in", self.ids)]) for reservation_line in reservation_lines: reservation_line.reserve.write({"isroom": True, "status": "available"}) return True def set_to_draft_reservation(self): self.update({"state": "draft"}) def action_send_reservation_mail(self): """ This function opens a window to compose an email, template message loaded by default. @param self: object pointer """ self.ensure_one(), "This is for a single id at a time." template_id = self.env.ref( "hotel_reservation.email_template_hotel_reservation" ).id compose_form_id = self.env.ref("mail.email_compose_message_wizard_form").id ctx = { "default_model": "hotel.reservation", "default_res_id": self.id, "default_use_template": bool(template_id), "default_template_id": template_id, "default_composition_mode": "comment", "force_send": True, "mark_so_as_sent": True, } return { "type": "ir.actions.act_window", "view_mode": "form", "res_model": "mail.compose.message", "views": [(compose_form_id, "form")], "view_id": compose_form_id, "target": "new", "context": ctx, "force_send": True, } @api.model def reservation_reminder_24hrs(self): """ This method is for scheduler every 1day scheduler will call this method to find all tomorrow's reservations. ---------------------------------------------- @param self: The object pointer @return: send a mail """ now_date = fields.Date.today() template_id = self.env.ref( "hotel_reservation.mail_template_reservation_reminder_24hrs" ) for reserv_rec in self: checkin_date = reserv_rec.checkin difference = relativedelta(now_date, checkin_date) if ( difference.days == -1 and reserv_rec.partner_id.email and reserv_rec.state == "confirm" ): template_id.send_mail(reserv_rec.id, force_send=True) return True def create_folio(self): """ This method is for create new hotel folio. ----------------------------------------- @param self: The object pointer @return: new record set for hotel folio. """ hotel_folio_obj = self.env["hotel.folio"] for reservation in self: folio_lines = [] checkin_date = reservation["checkin"] checkout_date = reservation["checkout"] duration_vals = self._onchange_check_dates( checkin_date=checkin_date, checkout_date=checkout_date, duration=False, ) duration = duration_vals.get("duration") or 0.0 folio_vals = { "date_order": reservation.date_order, "company_id": reservation.company_id.id, "partner_id": reservation.partner_id.id, "pricelist_id": reservation.pricelist_id.id, "partner_invoice_id": reservation.partner_invoice_id.id, "partner_shipping_id": reservation.partner_shipping_id.id, "checkin_date": reservation.checkin, "checkout_date": reservation.checkout, "duration": duration, "reservation_id": reservation.id, } for line in reservation.reservation_line: for r in line.reserve: folio_lines.append( ( 0, 0, { "checkin_date": checkin_date, "checkout_date": checkout_date, "product_id": r.product_id and r.product_id.id, "name": reservation["reservation_no"], "price_unit": r.list_price, "product_uom_qty": duration, "is_reserved": True, }, ) ) r.write({"status": "occupied", "isroom": False}) folio_vals.update({"room_line_ids": folio_lines}) folio = hotel_folio_obj.create(folio_vals) for rm_line in folio.room_line_ids: rm_line._onchange_product_id() self.write({"folio_id": [(6, 0, folio.ids)], "state": "done"}) return True def _onchange_check_dates( self, checkin_date=False, checkout_date=False, duration=False ): """ This method gives the duration between check in checkout if customer will leave only for some hour it would be considers as a whole day. If customer will checkin checkout for more or equal hours, which configured in company as additional hours than it would be consider as full days -------------------------------------------------------------------- @param self: object pointer @return: Duration and checkout_date """ value = {} configured_addition_hours = self.company_id.additional_hours duration = 0 if checkin_date and checkout_date: dur = checkout_date - checkin_date duration = dur.days + 1 if configured_addition_hours > 0: additional_hours = abs(dur.seconds / 60) if additional_hours <= abs(configured_addition_hours * 60): duration -= 1 value.update({"duration": duration}) return value def open_folio_view(self): folios = self.mapped("folio_id") action = self.env.ref("hotel.open_hotel_folio1_form_tree_all").read()[0] if len(folios) > 1: action["domain"] = [("id", "in", folios.ids)] elif len(folios) == 1: action["views"] = [(self.env.ref("hotel.view_hotel_folio_form").id, "form")] action["res_id"] = folios.id else: action = {"type": "ir.actions.act_window_close"} return action class HotelReservationLine(models.Model): _name = "hotel.reservation.line" _description = "Reservation Line" name = fields.Char() line_id = fields.Many2one("hotel.reservation") reserve = fields.Many2many( "hotel.room", "hotel_reservation_line_room_rel", "hotel_reservation_line_id", "room_id", domain="[('isroom','=',True),\ ('categ_id','=',categ_id)]", ) categ_id = fields.Many2one("hotel.room.type", "Room Type") @api.onchange("categ_id") def on_change_categ(self): """ When you change categ_id it check checkin and checkout are filled or not if not then raise warning ----------------------------------------------------------- @param self: object pointer """ if not self.line_id.checkin: raise ValidationError( _( """Before choosing a room,\n You have to """ """select a Check in date or a Check out """ """ date in the reservation form.""" ) ) hotel_room_ids = self.env["hotel.room"].search( [("room_categ_id", "=", self.categ_id.id)] ) room_ids = [] for room in hotel_room_ids: assigned = False for line in room.room_reservation_line_ids.filtered( lambda l: l.status != "cancel" ): if self.line_id.checkin and line.check_in and self.line_id.checkout: if ( self.line_id.checkin <= line.check_in <= self.line_id.checkout ) or ( self.line_id.checkin <= line.check_out <= self.line_id.checkout ): assigned = True elif (line.check_in <= self.line_id.checkin <= line.check_out) or ( line.check_in <= self.line_id.checkout <= line.check_out ): assigned = True for rm_line in room.room_line_ids.filtered(lambda l: l.status != "cancel"): if self.line_id.checkin and rm_line.check_in and self.line_id.checkout: if ( self.line_id.checkin <= rm_line.check_in <= self.line_id.checkout ) or ( self.line_id.checkin <= rm_line.check_out <= self.line_id.checkout ): assigned = True elif ( rm_line.check_in <= self.line_id.checkin <= rm_line.check_out ) or ( rm_line.check_in <= self.line_id.checkout <= rm_line.check_out ): assigned = True if not assigned: room_ids.append(room.id) domain = {"reserve": [("id", "in", room_ids)]} return {"domain": domain} def unlink(self): """ Overrides orm unlink method. @param self: The object pointer @return: True/False. """ hotel_room_reserv_line_obj = self.env["hotel.room.reservation.line"] for reserv_rec in self: for rec in reserv_rec.reserve: myobj = hotel_room_reserv_line_obj.search( [ ("room_id", "=", rec.id), ("reservation_id", "=", reserv_rec.line_id.id), ] ) if myobj: rec.write({"isroom": True, "status": "available"}) myobj.unlink() return super(HotelReservationLine, self).unlink() class HotelRoomReservationLine(models.Model): _name = "hotel.room.reservation.line" _description = "Hotel Room Reservation" _rec_name = "room_id" room_id = fields.Many2one("hotel.room") check_in = fields.Datetime("Check In Date", required=True) check_out = fields.Datetime("Check Out Date", required=True) state = fields.Selection( [("assigned", "Assigned"), ("unassigned", "Unassigned")], "Room Status" ) reservation_id = fields.Many2one("hotel.reservation", "Reservation") status = fields.Selection(string="state", related="reservation_id.state")
39.246305
23,901
9,341
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import api, fields, models from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class ReportTestCheckin(models.AbstractModel): _name = "report.hotel_reservation.report_checkin_qweb" _description = "Auxiliar to get the check in report" def _get_room_type(self, date_start, date_end): reservations = self.env["hotel.reservation"].search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) return reservations def _get_room_nos(self, date_start, date_end): reservations = self.env["hotel.reservation"].search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) return reservations def get_checkin(self, date_start, date_end): reservations = self.env["hotel.reservation"].search( [("checkin", ">=", date_start), ("checkin", "<=", date_end)] ) return reservations @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.reservation"].browse(docids) date_start = data.get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=+1, day=1, days=-1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) _get_room_type = rm_act._get_room_type(date_start, date_end) _get_room_nos = rm_act._get_room_nos(date_start, date_end) get_checkin = rm_act.get_checkin(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "get_room_type": _get_room_type, "get_room_nos": _get_room_nos, "get_checkin": get_checkin, } class ReportTestCheckout(models.AbstractModel): _name = "report.hotel_reservation.report_checkout_qweb" _description = "Auxiliar to get the check out report" def _get_room_type(self, date_start, date_end): reservations = self.env["hotel.reservation"].search( [("checkout", ">=", date_start), ("checkout", "<=", date_end)] ) return reservations def _get_room_nos(self, date_start, date_end): reservations = self.env["hotel.reservation"].search( [("checkout", ">=", date_start), ("checkout", "<=", date_end)] ) return reservations def _get_checkout(self, date_start, date_end): reservations = self.env["hotel.reservation"].search( [("checkout", ">=", date_start), ("checkout", "<=", date_end)] ) return reservations @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.reservation"].browse(docids) date_start = data.get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=+1, day=1, days=-1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) _get_room_type = rm_act._get_room_type(date_start, date_end) _get_room_nos = rm_act._get_room_nos(date_start, date_end) _get_checkout = rm_act._get_checkout(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "get_room_type": _get_room_type, "get_room_nos": _get_room_nos, "get_checkout": _get_checkout, } class ReportTestMaxroom(models.AbstractModel): _name = "report.hotel_reservation.report_maxroom_qweb" _description = "Auxiliar to get the room report" def _get_room_type(self, date_start, date_end): res = self.env["hotel.reservation"].search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) return res def _get_room_nos(self, date_start, date_end): res = self.env["hotel.reservation"].search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) return res def _get_data(self, date_start, date_end): res = self.env["hotel.reservation"].search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) return res def _get_room_used_detail(self, date_start, date_end): room_used_details = [] hotel_room_obj = self.env["hotel.room"] for room in hotel_room_obj.search([]): counter = 0 details = {} if room.room_reservation_line_ids: end_date = datetime.strptime(date_end, DEFAULT_SERVER_DATETIME_FORMAT) start_date = datetime.strptime( date_start, DEFAULT_SERVER_DATETIME_FORMAT ) counter = len( room.room_reservation_line_ids.filtered( lambda l: start_date <= l.check_in <= end_date ) ) if counter >= 1: details.update({"name": room.name or "", "no_of_times_used": counter}) room_used_details.append(details) return room_used_details @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.reservation"].browse(docids) date_start = data["form"].get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=+1, day=1, days=-1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) _get_room_type = rm_act._get_room_type(date_start, date_end) _get_room_nos = rm_act._get_room_nos(date_start, date_end) _get_data = rm_act._get_data(date_start, date_end) _get_room_used_detail = rm_act._get_room_used_detail(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "get_room_type": _get_room_type, "get_room_nos": _get_room_nos, "get_data": _get_data, "get_room_used_detail": _get_room_used_detail, } class ReportRoomReservation(models.AbstractModel): _name = "report.hotel_reservation.report_room_reservation_qweb" _description = "Auxiliar to get the room report" def _get_room_type(self, date_start, date_end): reservation_obj = self.env["hotel.reservation"] tids = reservation_obj.search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) res = reservation_obj.browse(tids) return res def _get_room_nos(self, date_start, date_end): reservation_obj = self.env["hotel.reservation"] tids = reservation_obj.search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) res = reservation_obj.browse(tids) return res def _get_data(self, date_start, date_end): reservation_obj = self.env["hotel.reservation"] res = reservation_obj.search( [("checkin", ">=", date_start), ("checkout", "<=", date_end)] ) return res @api.model def _get_report_values(self, docids, data): active_model = self.env.context.get("active_model") if data is None: data = {} if not docids: docids = data["form"].get("docids") folio_profile = self.env["hotel.reservation"].browse(docids) date_start = data.get("date_start", fields.Date.today()) date_end = data["form"].get( "date_end", str(datetime.now() + relativedelta(months=+1, day=1, days=-1))[:10], ) rm_act = self.with_context(**data["form"].get("used_context", {})) _get_room_type = rm_act._get_room_type(date_start, date_end) _get_room_nos = rm_act._get_room_nos(date_start, date_end) _get_data = rm_act._get_data(date_start, date_end) return { "doc_ids": docids, "doc_model": active_model, "data": data["form"], "docs": folio_profile, "time": time, "get_room_type": _get_room_type, "get_room_nos": _get_room_nos, "get_data": _get_data, }
38.599174
9,341
2,524
py
PYTHON
15.0
# Copyright (C) 2022-TODAY Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class HotelReservationWizard(models.TransientModel): _name = "hotel.reservation.wizard" _description = "Allow to generate a reservation" date_start = fields.Datetime("Start Date", required=True) date_end = fields.Datetime("End Date", required=True) def report_reservation_detail(self): data = { "ids": self.ids, "model": "hotel.reservation", "form": self.read(["date_start", "date_end"])[0], } return self.env.ref("hotel_reservation.hotel_roomres_details").report_action( self, data=data ) def report_checkin_detail(self): data = { "ids": self.ids, "model": "hotel.reservation", "form": self.read(["date_start", "date_end"])[0], } return self.env.ref("hotel_reservation.hotel_checkin_details").report_action( self, data=data ) def report_checkout_detail(self): data = { "ids": self.ids, "model": "hotel.reservation", "form": self.read(["date_start", "date_end"])[0], } return self.env.ref("hotel_reservation.hotel_checkout_details").report_action( self, data=data ) def report_maxroom_detail(self): data = { "ids": self.ids, "model": "hotel.reservation", "form": self.read(["date_start", "date_end"])[0], } return self.env.ref("hotel_reservation.hotel_maxroom_details").report_action( self, data=data ) class MakeFolioWizard(models.TransientModel): _name = "wizard.make.folio" _description = "Allow to generate the folio" grouped = fields.Boolean("Group the Folios") def make_folios(self): reservation_obj = self.env["hotel.reservation"] newinv = [ order.id for order in reservation_obj.browse( self.env.context.get("active_ids", []) ).mapped("folio_id") ] return { "domain": "[('id','in', [" + ",".join(map(str, newinv)) + "])]", "name": "Folios", "view_type": "form", "view_mode": "tree,form", "res_model": "hotel.folio", "view_id": False, "type": "ir.actions.act_window", }
32.779221
2,524
879
py
PYTHON
15.0
# Copyright (C) 2019 - TODAY, Patrick Wilson # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Field Service - Project", "summary": "Create field service orders from a project or project task", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "Pavlov Media, Odoo Community Association (OCA)", "category": "Project", "website": "https://github.com/OCA/field-service", "depends": ["fieldservice", "project"], "data": [ "views/project_views.xml", "views/project_task_views.xml", "views/fsm_location_views.xml", "views/fsm_order_views.xml", "security/ir.model.access.csv", "views/fsm_team.xml", ], "assets": { "web.assets_backend": [ "/fieldservice_project/static/src/scss/project_column.scss", ] }, "installable": True, }
33.807692
879
706
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from .common import Common class TestProjectTask(Common): def test_action_create_order(self): project = self.project task = self.env["project.task"].create( {"name": "task test", "project_id": project.id} ) action = task.action_create_order() self.assertDictEqual( action.get("context"), { "default_project_id": project.id, "default_project_task_id": task.id, "default_location_id": project.fsm_location_id.id, "default_origin": task.name, }, )
32.090909
706
547
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class Common(TransactionCase): @classmethod def setUpClass(cls): super(Common, cls).setUpClass() cls.partner = cls.env["res.partner"].create({"name": "partner test"}) cls.location = cls.env["fsm.location"].create( {"name": "location test", "owner_id": cls.partner.id} ) cls.project = cls.env["project.project"].create({"name": "project test"})
36.466667
547
965
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from .common import Common class TestFsmLocation(Common): def test_project_count(self): location = self.location project = self.project self.assertEqual(location.project_count, 0) project.write({"fsm_location_id": location.id}) location.invalidate_cache() self.assertEqual(location.project_count, 1) def test_action_view_project(self): location = self.location project = self.project action = location.action_view_project() action_domain = action.get("domain") res_id = action.get("res_id") self.assertEqual(action_domain, [("id", "in", [])]) self.assertFalse(res_id) project.write({"fsm_location_id": location.id}) action = location.action_view_project() res_id = action.get("res_id") self.assertEqual(res_id, project.id)
35.740741
965
538
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from .common import Common class TestProject(Common): def test_action_create_order(self): project = self.project action = project.action_create_order() self.assertDictEqual( action.get("context"), { "default_project_id": project.id, "default_location_id": project.fsm_location_id.id, "default_origin": project.name, }, )
29.888889
538
960
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import Form from .common import Common class TestFsmOrder(Common): @classmethod def setUpClass(cls): super(TestFsmOrder, cls).setUpClass() cls.FsmOrder = cls.env["fsm.order"] def test_action_view_order(self): order = self.FsmOrder.create({"location_id": self.location.id}) action = order.action_view_order() res_id = action.get("res_id") self.assertEqual(res_id, order.id) def test_onchange_team_id(self): project = self.project team_with_project = self.env["fsm.team"].create( {"name": "test team", "project_id": project.id} ) fsm_order_form = Form(self.FsmOrder) self.assertFalse(fsm_order_form.project_id) fsm_order_form.team_id = team_with_project self.assertEqual(fsm_order_form.project_id, project)
33.103448
960
1,178
py
PYTHON
15.0
# Copyright (C) 2019 - TODAY, Patrick Wilson # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class FSMLocation(models.Model): _inherit = "fsm.location" project_count = fields.Integer( compute="_compute_project_count", string="# Projects" ) def _compute_project_count(self): for location in self: location.project_count = self.env["project.project"].search_count( [("fsm_location_id", "=", location.id)] ) def action_view_project(self): for location in self: project_ids = self.env["project.project"].search( [("fsm_location_id", "=", location.id)] ) action = self.env.ref( "fieldservice_project.action_fsm_location_project" ).read()[0] action["context"] = {} if len(project_ids) == 1: action["views"] = [(self.env.ref("project.edit_project").id, "form")] action["res_id"] = project_ids.ids[0] else: action["domain"] = [("id", "in", project_ids.ids)] return action
34.647059
1,178
1,044
py
PYTHON
15.0
# Copyright (C) 2019 - TODAY, Patrick Wilson # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) class FSMOrder(models.Model): _inherit = "fsm.order" project_id = fields.Many2one("project.project", string="Project", tracking=True) project_task_id = fields.Many2one( "project.task", string="Project Task", tracking=True ) def action_view_order(self): """ This function returns an action that displays a full FSM Order form when viewing an FSM Order from a project. """ action = self.env.ref("fieldservice.action_fsm_operation_order").read()[0] order = self.env["fsm.order"].search([("id", "=", self.id)]) action["views"] = [(self.env.ref("fieldservice.fsm_order_form").id, "form")] action["res_id"] = order.id return action @api.onchange("team_id") def onchange_team_id(self): self.project_id = self.team_id.project_id
32.625
1,044
1,079
py
PYTHON
15.0
# Copyright (C) 2019 - TODAY, Patrick Wilson # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProjectTask(models.Model): _inherit = "project.task" fsm_order_ids = fields.One2many( "fsm.order", "project_task_id", string="Service Orders" ) def action_create_order(self): """ This function returns an action that displays a full FSM Order form when creating an FSM Order from a project. """ action = self.env.ref("fieldservice.action_fsm_operation_order") result = action.read()[0] # override the context to get rid of the default filtering result["context"] = { "default_project_id": self.project_id.id, "default_project_task_id": self.id, "default_location_id": self.project_id.fsm_location_id.id, "default_origin": self.name, } res = self.env.ref("fieldservice.fsm_order_form", False) result["views"] = [(res and res.id or False, "form")] return result
35.966667
1,079
271
py
PYTHON
15.0
# Copyright (C) 2020, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class FSMTeam(models.Model): _inherit = "fsm.team" project_id = fields.Many2one("project.project", string="Project")
27.1
271
1,133
py
PYTHON
15.0
# Copyright (C) 2019 - TODAY, Patrick Wilson # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class Project(models.Model): _inherit = "project.project" fsm_order_ids = fields.One2many("fsm.order", "project_id", string="Service Orders") fsm_location_id = fields.Many2one("fsm.location", string="FSM Location") def action_create_order(self): """ This function returns an action that displays a full FSM Order form when creating an FSM Order from a project. """ action = self.env.ref( "fieldservice.action_fsm_operation_order", raise_if_not_found=False ) result = action.read()[0] # override the context to get rid of the default filtering result["context"] = { "default_project_id": self.id, "default_location_id": self.fsm_location_id.id, "default_origin": self.name, } res = self.env.ref("fieldservice.fsm_order_form", raise_if_not_found=False) result["views"] = [(res and res.id or False, "form")] return result
37.766667
1,133
963
py
PYTHON
15.0
# Copyright (C) 2018 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Field Service - ISP Accounting", "summary": """Invoice Field Service orders based on employee time or contractor costs""", "version": "15.0.1.0.0", "category": "Field Service", "author": "Open Source Integrators, Odoo Community Association (OCA)", "website": "https://github.com/OCA/field-service", "depends": [ "fieldservice_account_analytic", "fieldservice_project", "hr_timesheet", ], "data": [ "security/fsm_order_cost.xml", "security/ir.model.access.csv", "data/time_products.xml", "views/account.xml", "views/fsm_order.xml", "views/fsm_person.xml", "views/hr_timesheet.xml", ], "license": "AGPL-3", "development_status": "Beta", "maintainers": ["osimallen", "brian10048", "bodedra"], }
33.206897
963
9,463
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 from odoo.exceptions import ValidationError from odoo.tests import TransactionCase class FSMISPAccountCase(TransactionCase): @classmethod def setUpClass(cls): super(FSMISPAccountCase, cls).setUpClass() cls.AccountMoveLine = cls.env["account.move.line"] cls.test_person = cls.env["fsm.person"].create({"name": "Worker-1"}) cls.test_person2 = cls.env["fsm.person"].create( {"name": "Worker-1", "supplier_rank": 1} ) cls.test_analytic = cls.env.ref("analytic.analytic_administratif") cls.account_id = cls.env["account.account"].create( { "code": "NC1110", "name": "Test Payable Account", "user_type_id": cls.env.ref("account.data_account_type_payable").id, "reconcile": True, } ) # create a Res Partner to be converted to FSM Location/Person cls.test_loc_partner = cls.env["res.partner"].create( {"name": "Test Loc Partner", "phone": "ABC", "email": "[email protected]"} ) # create expected FSM Location to compare to converted FSM Location cls.test_location = cls.env["fsm.location"].create( { "name": "Test Location", "phone": "123", "email": "[email protected]", "partner_id": cls.test_loc_partner.id, "owner_id": cls.test_loc_partner.id, "customer_id": cls.test_loc_partner.id, } ) def _create_workorder(self, bill_to, contractors, timesheets): # Create a new work order timesheets = self.env["account.analytic.line"].create(timesheets) order = self.env["fsm.order"].create( { "location_id": self.test_location.id, "bill_to": bill_to, "person_id": self.test_person.id, "employee_timesheet_ids": [(6, 0, timesheets.ids)], } ) order2 = self.env["fsm.order"].create( { "location_id": self.test_location.id, "bill_to": bill_to, "person_id": self.test_person.id, } ) order3 = self.env["fsm.order"].create( { "location_id": self.test_location.id, "bill_to": bill_to, "person_id": self.test_person2.id, } ) order._compute_employee() self.test_person._compute_vendor_bills() self.test_person.action_view_bills() with self.assertRaises(ValidationError): order2.action_complete() with self.assertRaises(ValidationError): order3.action_complete() for contractor in contractors: contractor.update({"fsm_order_id": order.id}) contractors = self.env["fsm.order.cost"].create(contractors) contractors.onchange_product_id() order.write({"contractor_cost_ids": [(6, 0, contractors.ids)]}) order.person_ids += self.test_person order.account_no_invoice() return order def _process_order_to_invoices(self, order): # Change states order.date_start = fields.Datetime.today() order.date_end = fields.Datetime.today() order.resolution = "Done something!" order.action_complete() order3 = self.env["fsm.order"].create( { "location_id": self.test_location.id, "bill_to": "contact", "person_id": self.test_person2.id, "customer_id": self.test_loc_partner.id, } ) self.assertEqual(order.account_stage, "review") # Create vendor bill # Vendor bill created from order's contractor if not order.person_id.partner_id.supplier_rank: with self.assertRaises(ValidationError): order.account_confirm() order.person_id.partner_id.supplier_rank = True order.account_confirm() self.assertEqual(order.account_stage, "confirmed") bill = self.AccountMoveLine.search( [("fsm_order_ids", "in", order.id)] ).move_id.filtered(lambda i: i.move_type == "in_invoice") self.test_person.action_view_bills() self.assertEqual(len(bill), 1) self.assertEqual(len(order.contractor_cost_ids), len(bill.invoice_line_ids)) order3.account_create_invoice() order.account_create_invoice() self.assertEqual(order.account_stage, "invoiced") invoice = self.AccountMoveLine.search( [("fsm_order_ids", "in", order.id)] ).move_id.filtered(lambda i: i.move_type == "out_invoice") self.assertEqual(len(invoice), 1) self.assertEqual( len(order.contractor_cost_ids) + len(order.employee_timesheet_ids), len(invoice.invoice_line_ids), ) return (bill, invoice) def test_fsm_order_exception(self): """Create a new work order, error raised when - If person_is is not set, but user try to add new contractor_cost_ids - If analytic account is not set in location, and user create contractor_cost_ids (account.move.line) """ # Test if the person_id is not selected, error when add contractor line # Setup required data self.test_location.analytic_account_id = self.test_analytic # Create a new work order with contract = 500 and timesheet = 300 self.env.ref("hr.employee_qdp").timesheet_cost = 20.0 order = self.env["fsm.order"].create( {"location_id": self.test_location.id, "person_id": self.test_person.id} ) order.person_id = self.test_person order.person_ids += self.test_person order.date_start = fields.Datetime.today() order.date_end = fields.Datetime.today() order.resolution = "Done something!" with self.assertRaises(ValidationError): order.action_complete() def test_fsm_order_bill_to_location(self): """Bill To Location, invoice created is based on this order's location's partner """ # Setup required data self.test_location.analytic_account_id = self.test_analytic contractors = [ { "product_id": self.env.ref("product.expense_hotel").id, "quantity": 2, "price_unit": 200, }, ] self.env.ref("hr.employee_qdp").timesheet_cost = 100 timesheets = [ { "name": "timesheet_line_1", "employee_id": self.env.ref("hr.employee_qdp").id, "account_id": self.test_analytic.id, "product_id": self.env.ref("product.expense_hotel").id, "unit_amount": 6, }, { "name": "timesheet_line_2", "employee_id": self.env.ref("hr.employee_qdp").id, "account_id": self.test_analytic.id, "product_id": self.env.ref("product.expense_hotel").id, "unit_amount": 4, }, ] order = self._create_workorder( bill_to="location", contractors=contractors, timesheets=timesheets ) order._compute_contractor_cost() order._compute_employee_hours() order._compute_total_cost() self.assertEqual(order.contractor_total, 800.0) self.assertEqual(order.employee_time_total, 10) # Hrs self.assertEqual(order.total_cost, 1800.0) bill, invoice = self._process_order_to_invoices(order) self.assertEqual(bill.partner_id, order.person_id.partner_id) self.assertEqual(invoice.partner_id, order.location_id.customer_id) def test_fsm_order_bill_to_contact(self): """Bill To Contact, invoice created is based on this order's contact """ # Setup required data self.test_location.analytic_account_id = self.test_analytic # Create a new work order with contract = 500 and timesheet = 300 contractors = [ { "product_id": self.env.ref("product.expense_hotel").id, "quantity": 2, "price_unit": 100, }, { "product_id": self.env.ref("product.expense_hotel").id, "quantity": 1, "price_unit": 300, }, ] self.env.ref("hr.employee_qdp").timesheet_cost = 20.0 timesheets = [ { "name": "timesheet_line_3", "employee_id": self.env.ref("hr.employee_qdp").id, "account_id": self.test_analytic.id, "product_id": self.env.ref("product.expense_hotel").id, "unit_amount": 10, }, ] order = self._create_workorder( bill_to="contact", contractors=contractors, timesheets=timesheets ) order._compute_contractor_cost() order._compute_employee_hours() order._compute_total_cost() self.assertEqual(order.contractor_total, 1200.0) self.assertEqual(order.employee_time_total, 10) # Hrs self.assertEqual(order.total_cost, 1400.0)
41.143478
9,463
1,034
py
PYTHON
15.0
# Copyright (C) 2018 - TODAY, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class FSMPerson(models.Model): _inherit = "fsm.person" bill_count = fields.Integer(string="Vendor Bills", compute="_compute_vendor_bills") def _compute_vendor_bills(self): self.bill_count = self.env["account.move"].search_count( [("partner_id", "=", self.partner_id.id)] ) def action_view_bills(self): for bill in self: action = self.env.ref("account.action_move_out_invoice_type").read()[0] vendor_bills = self.env["account.move"].search( [("partner_id", "=", bill.partner_id.id)] ) if len(vendor_bills) == 1: action["views"] = [(self.env.ref("account.view_move_form").id, "form")] action["res_id"] = vendor_bills.id else: action["domain"] = [("id", "in", vendor_bills.ids)] return action
36.928571
1,034
9,284
py
PYTHON
15.0
# Copyright (C) 2018 - TODAY, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError ACCOUNT_STAGES = [ ("draft", "Draft"), ("review", "Needs Review"), ("confirmed", "Confirmed"), ("invoiced", "Fully Invoiced"), ("no", "Nothing Invoiced"), ] class FSMOrder(models.Model): _inherit = "fsm.order" contractor_cost_ids = fields.One2many( "fsm.order.cost", "fsm_order_id", string="Contractor Costs" ) employee_timesheet_ids = fields.One2many( "account.analytic.line", "fsm_order_id", string="Employee Timesheets" ) employee = fields.Boolean(compute="_compute_employee") contractor_total = fields.Float( compute="_compute_contractor_cost", string="Contractor Cost Estimate" ) employee_time_total = fields.Float( compute="_compute_employee_hours", string="Total Employee Hours" ) account_stage = fields.Selection( ACCOUNT_STAGES, string="Accounting Stage", default="draft" ) def _compute_employee(self): user = self.env["res.users"].browse(self.env.uid) for order in self: order.employee = True if user.employee_ids else False @api.depends("employee_timesheet_ids", "contractor_cost_ids") def _compute_total_cost(self): res = super()._compute_total_cost() for order in self: order.total_cost = 0.0 rate = 0 for line in order.employee_timesheet_ids: rate = line.employee_id.timesheet_cost order.total_cost += line.unit_amount * rate for cost in order.contractor_cost_ids: order.total_cost += cost.price_unit * cost.quantity return res @api.depends("employee_timesheet_ids") def _compute_employee_hours(self): for order in self: order.employee_time_total = 0.0 for line in order.employee_timesheet_ids: order.employee_time_total += line.unit_amount @api.depends("contractor_cost_ids") def _compute_contractor_cost(self): for order in self: order.contractor_total = 0.0 for cost in order.contractor_cost_ids: order.contractor_total += cost.price_unit * cost.quantity def action_complete(self): for order in self: order.account_stage = "review" if self.person_id.supplier_rank and not self.contractor_cost_ids: raise ValidationError( _("Cannot move to Complete " + "until 'Contractor Costs' is filled in") ) if not self.person_id.supplier_rank and not self.employee_timesheet_ids: raise ValidationError( _( "Cannot move to Complete until " + "'Employee Timesheets' is filled in" ) ) return super(FSMOrder, self).action_complete() def create_bills(self): jrnl = self.env["account.journal"].search( [ ("company_id", "=", self.env.company.id), ("type", "=", "purchase"), ("active", "=", True), ], limit=1, ) fpos = self.person_id.partner_id.property_account_position_id invoice_line_vals = [] for cost in self.contractor_cost_ids: template = cost.product_id.product_tmpl_id accounts = template.get_product_accounts() account = accounts["expense"] taxes = template.supplier_taxes_id tax_ids = fpos.map_tax(taxes) invoice_line_vals.append( ( 0, 0, { "analytic_account_id": self.location_id.analytic_account_id.id, "product_id": cost.product_id.id, "quantity": cost.quantity, "name": cost.product_id.display_name, "price_unit": cost.price_unit, "account_id": account.id, "fsm_order_ids": [(4, self.id)], "tax_ids": [(6, 0, tax_ids.ids)], }, ) ) vals = { "partner_id": self.person_id.partner_id.id, "move_type": "in_invoice", "journal_id": jrnl.id or False, "fiscal_position_id": fpos.id or False, "fsm_order_ids": [(4, self.id)], "company_id": self.env.company.id, "invoice_line_ids": invoice_line_vals, } bill = self.env["account.move"].sudo().create(vals) bill._recompute_tax_lines() def account_confirm(self): for order in self: if order.contractor_cost_ids: if order.person_id.partner_id.supplier_rank: order.create_bills() order.account_stage = "confirmed" else: raise ValidationError( _("The worker assigned to this order" " is not a supplier") ) if order.employee_timesheet_ids: order.account_stage = "confirmed" def account_create_invoice(self): jrnl = self.env["account.journal"].search( [ ("company_id", "=", self.env.company.id), ("type", "=", "sale"), ("active", "=", True), ], limit=1, ) if self.bill_to == "contact" and self.customer_id: fpos = self.customer_id.property_account_position_id invoice_vals = { "partner_id": self.customer_id.id, "move_type": "out_invoice", "journal_id": jrnl.id or False, "fiscal_position_id": fpos.id or False, "fsm_order_ids": [(4, self.id)], } price_list = self.customer_id.property_product_pricelist else: fpos = self.location_id.customer_id.property_account_position_id invoice_vals = { "partner_id": self.location_id.customer_id.id, "move_type": "out_invoice", "journal_id": jrnl.id or False, "fiscal_position_id": fpos.id or False, "fsm_order_ids": [(4, self.id)], "company_id": self.env.company.id, } price_list = self.location_id.customer_id.property_product_pricelist invoice_line_vals = [] for cost in self.contractor_cost_ids: price = price_list.get_product_price( product=cost.product_id, quantity=cost.quantity, partner=invoice_vals.get("partner_id"), date=False, uom_id=False, ) template = cost.product_id.product_tmpl_id accounts = template.get_product_accounts() account = accounts["income"] taxes = template.taxes_id tax_ids = fpos.map_tax(taxes) invoice_line_vals.append( ( 0, 0, { "product_id": cost.product_id.id, "analytic_account_id": self.location_id.analytic_account_id.id, "quantity": cost.quantity, "name": cost.product_id.display_name, "price_unit": price, "account_id": account.id, "fsm_order_ids": [(4, self.id)], "tax_ids": [(6, 0, tax_ids.ids)], }, ) ) for line in self.employee_timesheet_ids: price = price_list.get_product_price( product=line.product_id, quantity=line.unit_amount, partner=invoice_vals.get("partner_id"), date=False, uom_id=False, ) accounts = line.product_id.product_tmpl_id.get_product_accounts() account = accounts["income"] taxes = line.product_id.product_tmpl_id.taxes_id tax_ids = fpos.map_tax(taxes) invoice_line_vals.append( ( 0, 0, { "product_id": line.product_id.id, "analytic_account_id": line.account_id.id, "quantity": line.unit_amount, "name": line.name, "price_unit": price, "account_id": account.id, "fsm_order_ids": [(4, self.id)], "tax_ids": [(6, 0, tax_ids.ids)], }, ) ) invoice_vals.update({"invoice_line_ids": invoice_line_vals}) invoice = self.env["account.move"].sudo().create(invoice_vals) invoice._recompute_tax_lines() self.account_stage = "invoiced" return invoice def account_no_invoice(self): self.account_stage = "no"
38.845188
9,284
758
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class FsmOrderCost(models.Model): _name = "fsm.order.cost" _description = "Fsm Order Cost" fsm_order_id = fields.Many2one( "fsm.order", required=True, ) price_unit = fields.Float( string="Unit Price", required=True, ) quantity = fields.Float( required=True, default=1, ) product_id = fields.Many2one( "product.product", string="Product", required=True, ) @api.onchange("product_id") def onchange_product_id(self): for cost in self: cost.price_unit = cost.product_id.standard_price
22.969697
758
683
py
PYTHON
15.0
# Copyright (C) 2019 Brian McMaster # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Field Service - Sale Stock", "version": "15.0.1.0.0", "summary": "Sell stockable items linked to field service orders.", "category": "Field Service", "author": "Brian McMaster, Odoo Community Association (OCA)", "website": "https://github.com/OCA/field-service", "depends": [ "fieldservice_sale", "fieldservice_stock", ], "license": "AGPL-3", "development_status": "Beta", "maintainers": [ "wolfhall", "max3903", "brian10048", ], "installable": True, "auto_install": True, }
28.458333
683
17,612
py
PYTHON
15.0
# Copyright (C) 2019 Brian McMaster <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields from odoo.addons.fieldservice_sale.tests.test_fsm_sale_common import TestFSMSale class TestFSMSaleOrder(TestFSMSale): @classmethod def setUpClass(cls): super(TestFSMSaleOrder, cls).setUpClass() cls.test_location = cls.env.ref("fieldservice.test_location") # Setup products that when sold will create some FSM orders cls.setUpFSMProducts() cls.partner_customer_usd = cls.env["res.partner"].create( { "name": "partner_a", "company_id": False, } ) cls.pricelist_usd = cls.env["product.pricelist"].search( [("currency_id.name", "=", "USD")], limit=1 ) cls.fsm_per_order_1 = cls.env["product.product"].create( { "name": "FSM Order per Sale Order #1", "categ_id": cls.env.ref("product.product_category_3").id, "standard_price": 85.0, "list_price": 90.0, "type": "product", "uom_id": cls.env.ref("uom.product_uom_unit").id, "uom_po_id": cls.env.ref("uom.product_uom_unit").id, "invoice_policy": "order", "field_service_tracking": "sale", "fsm_order_template_id": cls.fsm_template_1.id, } ) # Create some sale orders that will use the above products SaleOrder = cls.env["sale.order"].with_context(tracking_disable=True) # create a generic Sale Order with one product # set to create FSM service per sale order cls.sale_order_1 = SaleOrder.create( { "partner_id": cls.partner_customer_usd.id, "fsm_location_id": cls.test_location.id, "pricelist_id": cls.pricelist_usd.id, } ) cls.sol_service_per_order_1 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_order_1.name, "product_id": cls.fsm_per_order_1.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_order_1.uom_id.id, "price_unit": cls.fsm_per_order_1.list_price, "order_id": cls.sale_order_1.id, "tax_id": False, } ) # create a generic Sale Order with one product # set to create FSM service per sale order line cls.sale_order_2 = SaleOrder.create( { "partner_id": cls.partner_customer_usd.id, "fsm_location_id": cls.test_location.id, "pricelist_id": cls.pricelist_usd.id, } ) cls.sol_service_per_line_1 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_line_1.name, "product_id": cls.fsm_per_line_1.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_line_1.uom_id.id, "price_unit": cls.fsm_per_line_1.list_price, "order_id": cls.sale_order_2.id, "tax_id": False, } ) # create a generic Sale Order with multiple products # set to create FSM service per sale order line cls.sale_order_3 = SaleOrder.create( { "partner_id": cls.partner_customer_usd.id, "fsm_location_id": cls.test_location.id, "pricelist_id": cls.pricelist_usd.id, } ) cls.sol_service_per_line_2 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_line_1.name, "product_id": cls.fsm_per_line_1.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_line_1.uom_id.id, "price_unit": cls.fsm_per_line_1.list_price, "order_id": cls.sale_order_3.id, "tax_id": False, } ) cls.sol_service_per_line_3 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_line_2.name, "product_id": cls.fsm_per_line_2.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_line_2.uom_id.id, "price_unit": cls.fsm_per_line_2.list_price, "order_id": cls.sale_order_3.id, "tax_id": False, } ) # create a generic Sale Order with mixed products # 2 lines based on service per sale order line # 2 lines based on service per sale order cls.sale_order_4 = SaleOrder.create( { "partner_id": cls.partner_customer_usd.id, "fsm_location_id": cls.test_location.id, "pricelist_id": cls.pricelist_usd.id, } ) cls.sol_service_per_line_4 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_line_1.name, "product_id": cls.fsm_per_line_1.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_line_1.uom_id.id, "price_unit": cls.fsm_per_line_1.list_price, "order_id": cls.sale_order_4.id, "tax_id": False, } ) cls.sol_service_per_line_5 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_line_2.name, "product_id": cls.fsm_per_line_2.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_line_2.uom_id.id, "price_unit": cls.fsm_per_line_2.list_price, "order_id": cls.sale_order_4.id, "tax_id": False, } ) cls.sol_service_per_order_2 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_order_1.name, "product_id": cls.fsm_per_order_1.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_order_1.uom_id.id, "price_unit": cls.fsm_per_order_1.list_price, "order_id": cls.sale_order_4.id, "tax_id": False, } ) cls.sol_service_per_order_3 = cls.env["sale.order.line"].create( { "name": cls.fsm_per_order_2.name, "product_id": cls.fsm_per_order_2.id, "product_uom_qty": 1, "product_uom": cls.fsm_per_order_2.uom_id.id, "price_unit": cls.fsm_per_order_2.list_price, "order_id": cls.sale_order_4.id, "tax_id": False, } ) def _isp_account_installed(self): """Checks if module is installed which will require more logic for the tests. :return Boolean indicating the installed status of the module """ result = False isp_account_module = self.env["ir.module.module"].search( [("name", "=", "fieldservice_isp_account")] ) if isp_account_module and isp_account_module.state == "installed": result = True return result def _fulfill_order(self, order): """Extra logic required to fulfill FSM order status and prevent validation error when attempting to complete the FSM order :return FSM Order with additional fields set """ analytic_account = self.env.ref("analytic.analytic_administratif") self.test_location.analytic_account_id = analytic_account.id timesheet = self.env["account.analytic.line"].create( { "name": "timesheet_line", "unit_amount": 1, "account_id": analytic_account.id, "user_id": self.env.ref("base.partner_admin").id, "product_id": self.env.ref( "fieldservice_isp_account.field_service_regular_time" ).id, } ) order.write( { "employee_timesheet_ids": [(6, 0, timesheet.ids)], } ) return order def test_sale_order_1(self): """Test the sales order 1 flow from sale to invoice. - One FSM order linked to the Sale Order should be created. - One Invoice linked to the FSM Order should be created. """ # Confirm the sale order self.sale_order_1.action_confirm() # 1 FSM order created self.assertEqual( len(self.sale_order_1.fsm_order_ids.ids), 1, "FSM Sale: Sale Order 1 should create 1 FSM Order", ) FSM_Order = self.env["fsm.order"] fsm_order = FSM_Order.search( [("id", "=", self.sale_order_1.fsm_order_ids[0].id)] ) # Sale Order linked to FSM order self.assertEqual( len(fsm_order.ids), 1, "FSM Sale: Sale Order not linked to FSM Order" ) # Complete the FSM order if self._isp_account_installed(): fsm_order = self._fulfill_order(fsm_order) fsm_order.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order.action_complete() # Invoice the order invoice = self.sale_order_1._create_invoices() # 1 invoices created self.assertEqual( len(invoice.ids), 1, "FSM Sale: Sale Order 1 should create 1 invoice" ) self.assertTrue( fsm_order in invoice.fsm_order_ids, "FSM Sale: Invoice should be linked to FSM Order", ) def test_sale_order_2(self): """Test the sales order 2 flow from sale to invoice. - One FSM order linked to the Sale Order Line should be created. - The FSM Order should update qty_delivered when completed. - One Invoice linked to the FSM Order should be created. """ sol = self.sol_service_per_line_1 # Confirm the sale order self.sale_order_2.action_confirm() # 1 order created self.assertEqual( len(self.sale_order_2.fsm_order_ids.ids), 1, "FSM Sale: Sale Order 2 should create 1 FSM Order", ) FSM_Order = self.env["fsm.order"] fsm_order = FSM_Order.search([("id", "=", sol.fsm_order_id.id)]) # SOL linked to FSM order self.assertTrue( sol.fsm_order_id.id == fsm_order.id, "FSM Sale: Sale Order 2 Line not linked to FSM Order", ) # Complete the FSM order if self._isp_account_installed(): fsm_order = self._fulfill_order(fsm_order) fsm_order.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order.action_complete() # qty delivered should be updated self.assertTrue( sol.qty_delivered == sol.product_uom_qty, "FSM Sale: Sale Order Line qty delivered not equal to qty ordered", ) # Invoice the order invoice = self.sale_order_2._create_invoices() # 1 invoice created self.assertEqual( len(invoice.ids), 1, "FSM Sale: Sale Order 2 should create 1 invoice" ) self.assertTrue( fsm_order in invoice.fsm_order_ids, "FSM Sale: Invoice should be linked to FSM Order", ) def test_sale_order_3(self): """Test sale order 3 flow from sale to invoice. - An FSM order should be created for each Sale Order Line. - The FSM Order should update qty_delivered when completed. - An Invoice linked to each FSM Order should be created. """ sol1 = self.sol_service_per_line_2 sol2 = self.sol_service_per_line_3 # Confirm the sale order self.sale_order_3.action_confirm() # 2 orders created and SOLs linked to FSM orders self.assertEqual( len(self.sale_order_3.fsm_order_ids.ids), 2, "FSM Sale: Sale Order 3 should create 2 FSM Orders", ) FSM_Order = self.env["fsm.order"] fsm_order_1 = FSM_Order.search([("id", "=", sol1.fsm_order_id.id)]) self.assertTrue( sol1.fsm_order_id.id == fsm_order_1.id, "FSM Sale: Sale Order Line 2 not linked to FSM Order", ) fsm_order_2 = FSM_Order.search([("id", "=", sol2.fsm_order_id.id)]) self.assertTrue( sol2.fsm_order_id.id == fsm_order_2.id, "FSM Sale: Sale Order Line 3 not linked to FSM Order", ) # Complete the FSM orders if self._isp_account_installed(): fsm_order_1 = self._fulfill_order(fsm_order_1) fsm_order_1.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order_1.action_complete() self.assertTrue( sol1.qty_delivered == sol1.product_uom_qty, "FSM Sale: Sale Order Line qty delivered not equal to qty ordered", ) if self._isp_account_installed(): fsm_order_2 = self._fulfill_order(fsm_order_2) fsm_order_2.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order_2.action_complete() self.assertTrue( sol2.qty_delivered == sol2.product_uom_qty, "FSM Sale: Sale Order Line qty delivered not equal to qty ordered", ) # Invoice the sale order invoices = self.sale_order_3._create_invoices() # 2 invoices created self.assertEqual( len(invoices.ids), 1, "FSM Sale: Sale Order 3 should create 1 invoices" ) inv_fsm_orders = FSM_Order for inv in invoices: inv_fsm_orders |= inv.fsm_order_ids self.assertTrue( fsm_order_1 in inv_fsm_orders, "FSM Sale: FSM Order 1 should be linked to invoice", ) self.assertTrue( fsm_order_2 in inv_fsm_orders, "FSM Sale: FSM Order 2 should be linked to invoice", ) def test_sale_order_4(self): """Test sale order 4 flow from sale to invoice. - Two FSM orders linked to the Sale Order Lines should be created. - One FSM order linked to the Sale Order should be created. - One Invoices should be created (One for each FSM Order). """ sol1 = self.sol_service_per_line_4 sol2 = self.sol_service_per_line_5 # sol3 = self.sol_service_per_order_2 # sol4 = self.sol_service_per_order_3 # Confirm the sale order self.sale_order_4.action_confirm() # 3 orders created self.assertEqual( len(self.sale_order_4.fsm_order_ids.ids), 3, "FSM Sale: Sale Order 4 should create 3 FSM Orders", ) FSM_Order = self.env["fsm.order"] fsm_order_1 = FSM_Order.search([("id", "=", sol1.fsm_order_id.id)]) self.assertTrue( sol1.fsm_order_id.id == fsm_order_1.id, "FSM Sale: Sale Order Line not linked to FSM Order", ) fsm_order_2 = FSM_Order.search([("id", "=", sol2.fsm_order_id.id)]) self.assertTrue( sol2.fsm_order_id.id == fsm_order_2.id, "FSM Sale: Sale Order Line not linked to FSM Order", ) fsm_order_3 = FSM_Order.search( [ ("id", "in", self.sale_order_4.fsm_order_ids.ids), ("sale_line_id", "=", False), ] ) self.assertEqual( len(fsm_order_3.ids), 1, "FSM Sale: FSM Order not linked to Sale Order" ) # Complete the FSM order if self._isp_account_installed(): fsm_order_1 = self._fulfill_order(fsm_order_1) fsm_order_1.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order_1.action_complete() self.assertTrue( sol1.qty_delivered == sol1.product_uom_qty, "FSM Sale: Sale Order Line qty delivered not equal to qty ordered", ) if self._isp_account_installed(): fsm_order_2 = self._fulfill_order(fsm_order_2) fsm_order_2.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order_2.action_complete() self.assertTrue( sol2.qty_delivered == sol2.product_uom_qty, "FSM Sale: Sale Order Line qty delivered not equal to qty ordered", ) if self._isp_account_installed(): fsm_order_3 = self._fulfill_order(fsm_order_3) fsm_order_3.write( { "date_end": fields.Datetime.today(), "resolution": "Work completed", } ) fsm_order_3.action_complete() # qty_delivered does not update for FSM orders linked only to the sale # Invoice the sale order invoices = self.sale_order_4._create_invoices() # 3 invoices created self.assertEqual( len(invoices.ids), 1, "FSM Sale: Sale Order 4 should create 1 invoice" )
38.454148
17,612
1,418
py
PYTHON
15.0
# Copyright (C) 2019 Brian McMaster # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class SaleOrder(models.Model): _inherit = "sale.order" def prepare_fsm_values_for_stock_move(self, fsm_order): return { "fsm_order_id": fsm_order.id, } def prepare_fsm_values_for_stock_picking(self, fsm_order): return { "fsm_order_id": fsm_order.id, } def _link_pickings_to_fsm(self): for rec in self: # TODO: We may want to split the picking to have one picking # per FSM order fsm_order = self.env["fsm.order"].search( [ ("sale_id", "=", rec.id), ("sale_line_id", "=", False), ] ) if rec.procurement_group_id: rec.procurement_group_id.fsm_order_id = fsm_order.id or False for picking in rec.picking_ids: picking.write(rec.prepare_fsm_values_for_stock_picking(fsm_order)) for move in picking.move_lines: move.write(rec.prepare_fsm_values_for_stock_move(fsm_order)) def _action_confirm(self): """On SO confirmation, link the fsm order on the pickings created by the sale order""" res = super()._action_confirm() self._link_pickings_to_fsm() return res
34.585366
1,418
735
py
PYTHON
15.0
# Copyright (C) 2019 Open Source Integrators # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Field Service Activity", "summary": """Field Service Activities are a set of actions that need to be performed on a service order""", "version": "15.0.1.0.0", "category": "Field Service", "license": "AGPL-3", "author": "Open Source Integrators, Odoo Community Association (OCA)", "website": "https://github.com/OCA/field-service", "depends": ["fieldservice"], "data": [ "views/fsm_order.xml", "views/fsm_template.xml", "security/ir.model.access.csv", ], "development_status": "Beta", "maintainers": ["max3903", "osi-scampbell"], }
35
735
5,128
py
PYTHON
15.0
# Copyright (C) 2019, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import datetime from odoo.exceptions import ValidationError from odoo.tests.common import Form, TransactionCase class TestFSMActivity(TransactionCase): def setUp(self): super().setUp() self.Order = self.env["fsm.order"] self.test_location = self.env.ref("fieldservice.test_location") self.Activity = self.env["fsm.activity"] self.template_obj = self.env["fsm.template"] self.activty_type = self.env["mail.activity.type"].create( {"name": "Meeting", "category": "phonecall"} ) self.user_employee = self.env["res.users"].create( { "name": "Ernest Employee", "login": "emp", "email": "[email protected]", "signature": "--\nErnest", "notification_type": "inbox", "groups_id": [ ( 6, 0, [ self.env.ref("base.group_user").id, self.env.ref("base.group_partner_manager").id, ], ) ], } ) def test_fsm_activity(self): """Test creating new activites, and moving them along thier stages, - Don't move FSM Order to complete if Required Activity in 'To Do' - Check completed_by is saved - Check completed_on is saved """ # Create an Orders view_id = "fieldservice.fsm_order_form" with Form(self.Order, view=view_id) as f: f.location_id = self.test_location order = f.save() order2 = self.Order.create( { "location_id": self.test_location.id, } ) order_id = order.id activity_id = self.env["mail.activity"].create( { "summary": "Meeting with partner", "activity_type_id": self.activty_type.id, "res_model_id": self.env["ir.model"]._get("fsm.order").id, "res_id": order2.id, "user_id": self.env.user.id, } ) order2.activity_ids = [(6, False, activity_id.ids)] self.Activity.create( self.get_activity_vals("Activity Test", False, "Ref 1", order2.id) ) self.Activity.create( self.get_activity_vals("Activity 1", False, "Ref 1", order_id) ) self.Activity.create( self.get_activity_vals("Activity 2", False, "Ref 2", order_id) ) self.Activity.create( self.get_activity_vals("Activity 3", True, "Ref 3", order_id) ) order2.order_activity_ids.action_done() order2.action_complete() # Test action_done() order.order_activity_ids[0].action_done() self.assertEqual( order.order_activity_ids[0].completed_on.replace(microsecond=0), datetime.now().replace(microsecond=0), ) self.assertEqual(order.order_activity_ids[0].completed_by, self.env.user) self.assertEqual(order.order_activity_ids[0].state, "done") # Test action_cancel() order.order_activity_ids[1].action_cancel() self.assertEqual(order.order_activity_ids[1].state, "cancel") # As per FSM order needs, end date may not be set # stop tracking validation error if not order.date_end: order.date_end = datetime.now() # Test required Activity with self.assertRaises(ValidationError): order.action_complete() order.order_activity_ids[2].action_done() order.action_complete() self.assertEqual( order.stage_id.id, self.env.ref("fieldservice.fsm_stage_completed").id ) def get_activity_vals(self, name, required, ref, order_id): return { "name": name, "required": required, "ref": ref, "fsm_order_id": order_id, } def test_onchange_template_id(self): # Create a Template self.template = self.template_obj.create( { "name": "Demo template", "temp_activity_ids": [ ( 0, 0, { "name": "Activity new", "required": True, "ref": "Ref new", "state": "todo", }, ) ], } ) # Create an Order self.fso = self.Order.create( {"location_id": self.test_location.id, "template_id": self.template.id} ) # Test _onchange_template_id() self.fso._onchange_template_id() self.assertNotEqual( self.fso.order_activity_ids.ids, self.fso.template_id.temp_activity_ids.ids )
36.112676
5,128
297
py
PYTHON
15.0
# Copyright (C) 2019, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class FSMTemplate(models.Model): _inherit = "fsm.template" temp_activity_ids = fields.One2many("fsm.activity", "fsm_template_id", "Activites")
29.7
297
2,047
py
PYTHON
15.0
# Copyright (C) 2019, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class FSMOrder(models.Model): _inherit = "fsm.order" order_activity_ids = fields.One2many("fsm.activity", "fsm_order_id", "Activites") @api.onchange("template_id") def _onchange_template_id(self): res = super()._onchange_template_id() for rec in self: # Clear existing activities rec.order_activity_ids = [(5, 0, 0)] if rec.template_id: activity_list = [] for temp_activity in rec.template_id.temp_activity_ids: activity_list.append( ( 0, 0, { "name": temp_activity.name, "required": temp_activity.required, "ref": temp_activity.ref, "state": temp_activity.state, }, ) ) rec.order_activity_ids = activity_list return res @api.model def create(self, vals): """Update Activities for FSM orders that are generate from SO""" order = super(FSMOrder, self).create(vals) order._onchange_template_id() return order def action_complete(self): res = super().action_complete() for activity_id in self.order_activity_ids: if activity_id.required and activity_id.state == "todo": raise ValidationError( _( "You must complete activity '%s' before \ completing this order." ) % activity_id.name ) for activity_id in self.activity_ids: activity_id._action_done() return res
35.912281
2,047
1,328
py
PYTHON
15.0
# Copyright (C) 2019 Open Source Integrators # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from datetime import datetime from odoo import fields, models class FSMActivity(models.Model): _name = "fsm.activity" _description = "Field Service Activity" name = fields.Char( required=True, readonly=True, states={"todo": [("readonly", False)]} ) required = fields.Boolean( default=False, readonly=True, states={"todo": [("readonly", False)]}, ) sequence = fields.Integer() completed = fields.Boolean() completed_on = fields.Datetime(readonly=True) completed_by = fields.Many2one("res.users", readonly=True) ref = fields.Char( "Reference", readonly=True, states={"todo": [("readonly", False)]} ) fsm_order_id = fields.Many2one("fsm.order", "FSM Order") fsm_template_id = fields.Many2one("fsm.template", "FSM Template") state = fields.Selection( [("todo", "To Do"), ("done", "Completed"), ("cancel", "Cancelled")], readonly=True, default="todo", ) def action_done(self): self.completed = True self.completed_on = datetime.now() self.completed_by = self.env.user self.state = "done" def action_cancel(self): self.state = "cancel"
30.883721
1,328
737
py
PYTHON
15.0
# Copyright (C) 2019 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Field Service Location Builder", "summary": "Adds a tool to help build out Location Hierarchies", "version": "15.0.1.0.0", "category": "Field Service", "author": "Open Source Integrators, Odoo Community Association (OCA)", "website": "https://github.com/OCA/field-service", "depends": ["fieldservice"], "data": [ "security/ir.model.access.csv", "wizard/fsm_location_builder_wizard.xml", "wizard/fsm_location_level.xml", ], "license": "AGPL-3", "development_status": "Beta", "maintainers": [ "osi-scampbell", "max3903", ], }
32.043478
737
1,687
py
PYTHON
15.0
# Copyright (C) 2022 - TODAY, Open Source Integrators # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo.tests.common import TransactionCase class FSMLocationBuilderWizardCase(TransactionCase): def setUp(self): super(FSMLocationBuilderWizardCase, self).setUp() self.fsm_order = self.env["fsm.order"] self.Wizard = self.env["fsm.location.builder.wizard"] self.test_location = self.env.ref("fieldservice.test_location") self.level = self.env["fsm.location.level"] self.fr = self.env.ref("base.fr") self.state_fr = self.env["res.country.state"].create( dict(name="State", code="ST", country_id=self.fr.id) ) def test_location_wiz(self): tag = self.env.ref("base.res_partner_category_8") self.test_location.write( { "state_id": self.state_fr.id, "country_id": self.fr.id, "tz": "Pacific/Honolulu", } ) level_1 = self.level.create( { "name": "Floor", "start_number": 2, "end_number": 2, "spacer": "Test", "tag_ids": [(6, 0, tag.ids)], } ) level_2 = self.level.create( { "name": "Room", "start_number": 1, "end_number": 2, } ) level_1._compute_total_number() level_2._compute_total_number() wiz = self.Wizard.create({"level_ids": [(6, 0, [level_2.id, level_1.id])]}) wiz.with_context(active_id=self.test_location.id).create_sub_locations()
35.145833
1,687