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
3,227
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo.addons.point_of_sale.tests.common import TestPointOfSaleCommon from odoo.tests.common import Form @odoo.tests.tagged('post_install', '-at_install') class TestPosMrp(TestPointOfSaleCommon): def test_bom_kit_order_total_cost(self): #create a product category that use fifo category = self.env['product.category'].create({ 'name': 'Category for kit', 'property_cost_method': 'fifo', }) self.kit = self.env['product.product'].create({ 'name': 'Kit Product', 'available_in_pos': True, 'type': 'product', 'lst_price': 10.0, 'categ_id': category.id, }) self.component_a = self.env['product.product'].create({ 'name': 'Comp A', 'type': 'product', 'available_in_pos': True, 'lst_price': 10.0, 'standard_price': 5.0, }) self.component_b = self.env['product.product'].create({ 'name': 'Comp B', 'type': 'product', 'available_in_pos': True, 'lst_price': 10.0, 'standard_price': 10.0, }) bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.kit bom_product_form.product_tmpl_id = self.kit.product_tmpl_id bom_product_form.product_qty = 1.0 bom_product_form.type = 'phantom' with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.component_a bom_line.product_qty = 1.0 with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.component_b bom_line.product_qty = 1.0 self.bom_a = bom_product_form.save() self.pos_config.open_session_cb() order = self.env['pos.order'].create({ 'session_id': self.pos_config.current_session_id.id, 'lines': [(0, 0, { 'name': self.kit.name, 'product_id': self.kit.id, 'price_unit': self.kit.lst_price, 'qty': 1, 'tax_ids': [[6, False, []]], 'price_subtotal': self.kit.lst_price, 'price_subtotal_incl': self.kit.lst_price, })], 'pricelist_id': self.pos_config.pricelist_id.id, 'amount_paid': self.kit.lst_price, 'amount_total': self.kit.lst_price, 'amount_tax': 0.0, 'amount_return': 0.0, 'to_invoice': False, }) payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() self.pos_config.current_session_id.action_pos_session_closing_control() pos_order = self.env['pos.order'].search([], order='id desc', limit=1) self.assertEqual(pos_order.lines[0].total_cost, 15.0)
38.879518
3,227
711
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class PosOrderLine(models.Model): _inherit = "pos.order.line" def _get_stock_moves_to_consider(self, stock_moves, product): bom = product.env['mrp.bom']._bom_find(product, company_id=stock_moves.company_id.id, bom_type='phantom')[product] if not bom: return super()._get_stock_moves_to_consider(stock_moves, product) ml_product_to_consider = (product.bom_ids and bom.bom_line_ids.mapped('product_id').mapped('id')) or [product.id] return stock_moves.filtered(lambda ml: ml.product_id.id in ml_product_to_consider and ml.bom_line_id)
50.785714
711
541
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Project Accounting', 'version': '1.0', 'category': 'Services/account', 'summary': 'Project accounting', 'description': 'Bridge created to remove the profitability setting if the account module is installed', 'depends': ['project', 'account'], 'data': [ 'views/project_project_templates.xml', ], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
28.473684
541
748
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Time Off in Payslips', 'version': '1.0', 'category': 'Human Resources/Payroll', 'sequence': 95, 'summary': 'Manage Time Off in Payslips', 'description': """ Manage Time Off in Payslips ============================ This application allows you to integrate time off in payslips. """, 'depends': ['hr_holidays', 'hr_work_entry_contract'], 'data': [ 'views/hr_leave_views.xml', ], 'demo': ['data/hr_payroll_holidays_demo.xml'], 'installable': True, 'application': False, 'auto_install': True, 'post_init_hook': '_validate_existing_work_entry', 'license': 'LGPL-3', }
27.703704
748
8,528
py
PYTHON
15.0
# # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo.addons.hr_work_entry_holidays.tests.common import TestWorkEntryHolidaysBase @tagged('work_entry_multi_contract') class TestWorkEntryHolidaysMultiContract(TestWorkEntryHolidaysBase): def setUp(self): super().setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Legal Leaves', 'time_type': 'leave', 'requires_allocation': 'no', 'work_entry_type_id': self.work_entry_type_leave.id }) def create_leave(self, start, end): work_days_data = self.jules_emp._get_work_days_data_batch(start, end) return self.env['hr.leave'].create({ 'name': 'Doctor Appointment', 'employee_id': self.jules_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': start, 'date_to': end, 'number_of_days': work_days_data[self.jules_emp.id]['days'], }) def test_multi_contract_holiday(self): # Leave during second contract leave = self.create_leave(datetime(2015, 11, 17, 7, 0), datetime(2015, 11, 20, 18, 0)) leave.action_approve() start = datetime.strptime('2015-11-01', '%Y-%m-%d') end_generate = datetime(2015, 11, 30, 23, 59, 59) work_entries = self.jules_emp.contract_ids._generate_work_entries(start, end_generate) work_entries.action_validate() work_entries = work_entries.filtered(lambda we: we.contract_id == self.contract_cdi) work = work_entries.filtered(lambda line: line.work_entry_type_id == self.env.ref('hr_work_entry.work_entry_type_attendance')) leave = work_entries.filtered(lambda line: line.work_entry_type_id == self.work_entry_type_leave) self.assertEqual(sum(work.mapped('duration')), 49, "It should be 49 hours of work this month for this contract") self.assertEqual(sum(leave.mapped('duration')), 28, "It should be 28 hours of leave this month for this contract") def test_move_contract_in_leave(self): # test move contract dates such that a leave is across two contracts start = datetime.strptime('2015-11-05 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-12-15 18:00:00', '%Y-%m-%d %H:%M:%S') self.contract_cdi.write({'date_start': datetime.strptime('2015-12-30', '%Y-%m-%d').date()}) # begins during contract, ends after contract leave = self.create_leave(start, end) leave.action_approve() # move contract in the middle of the leave with self.assertRaises(ValidationError): self.contract_cdi.date_start = datetime.strptime('2015-11-17', '%Y-%m-%d').date() def test_create_contract_in_leave(self): # test create contract such that a leave is across two contracts start = datetime.strptime('2015-11-05 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-12-15 18:00:00', '%Y-%m-%d %H:%M:%S') self.contract_cdi.date_start = datetime.strptime('2015-12-30', '%Y-%m-%d').date() # remove this contract to be able to create the leave # begins during contract, ends after contract leave = self.create_leave(start, end) leave.action_approve() # move contract in the middle of the leave with self.assertRaises(ValidationError): self.env['hr.contract'].create({ 'date_start': datetime.strptime('2015-11-30', '%Y-%m-%d').date(), 'name': 'Contract for Richard', 'resource_calendar_id': self.calendar_40h.id, 'wage': 5000.0, 'employee_id': self.jules_emp.id, 'state': 'open', 'date_generated_from': datetime.strptime('2015-11-30', '%Y-%m-%d'), 'date_generated_to': datetime.strptime('2015-11-30', '%Y-%m-%d'), }) def test_leave_outside_contract(self): # Leave outside contract => should not raise start = datetime.strptime('2014-10-18 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2014-10-20 09:00:00', '%Y-%m-%d %H:%M:%S') self.create_leave(start, end) # begins before contract, ends during contract => should not raise start = datetime.strptime('2014-10-25 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-01-15 18:00:00', '%Y-%m-%d %H:%M:%S') self.create_leave(start, end) # begins during contract, ends after contract => should not raise self.contract_cdi.date_end = datetime.strptime('2015-11-30', '%Y-%m-%d').date() start = datetime.strptime('2015-11-25 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-12-5 18:00:00', '%Y-%m-%d %H:%M:%S') self.create_leave(start, end) def test_no_leave_overlapping_contracts(self): with self.assertRaises(ValidationError): # Overlap two contracts start = datetime.strptime('2015-11-12 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-11-17 18:00:00', '%Y-%m-%d %H:%M:%S') self.create_leave(start, end) # Leave inside fixed term contract => should not raise start = datetime.strptime('2015-11-04 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-11-07 09:00:00', '%Y-%m-%d %H:%M:%S') self.create_leave(start, end) # Leave inside contract (no end) => should not raise start = datetime.strptime('2015-11-18 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-11-20 09:00:00', '%Y-%m-%d %H:%M:%S') self.create_leave(start, end) def test_leave_request_next_contracts(self): start = datetime.strptime('2015-11-23 07:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2015-11-24 18:00:00', '%Y-%m-%d %H:%M:%S') leave = self.create_leave(start, end) leave._compute_number_of_hours_display() self.assertEqual(leave.number_of_hours_display, 14, "It should count hours according to the future contract.") def test_leave_multi_contracts_same_schedule(self): # Allow leaves overlapping multiple contracts if same # resource calendar leave = self.create_leave(datetime(2022, 6, 1, 7, 0, 0), datetime(2022, 6, 30, 18, 0, 0)) leave.action_approve() self.contract_cdi.date_end = date(2022, 6, 15) new_contract_cdi = self.env['hr.contract'].create({ 'date_start': date(2022, 6, 16), 'name': 'New Contract for Jules', 'resource_calendar_id': self.calendar_35h.id, 'wage': 5000.0, 'employee_id': self.jules_emp.id, 'state': 'draft', 'kanban_state': 'normal', }) new_contract_cdi.state = 'open' def test_leave_multi_contracts_split(self): # Check that setting a contract as running correctly # splits the existing time off for this employee that # are ovelapping with another contract with another # working schedule leave = self.create_leave(datetime(2022, 6, 1, 5, 0, 0), datetime(2022, 6, 30, 20, 0, 0)) leave.action_approve() self.assertEqual(leave.number_of_days, 22) self.assertEqual(leave.state, 'validate') self.contract_cdi.date_end = date(2022, 6, 15) new_contract_cdi = self.env['hr.contract'].create({ 'date_start': date(2022, 6, 16), 'name': 'New Contract for Jules', 'resource_calendar_id': self.calendar_40h.id, 'wage': 5000.0, 'employee_id': self.jules_emp.id, 'state': 'draft', 'kanban_state': 'normal', }) new_contract_cdi.state = 'open' leaves = self.env['hr.leave'].search([('employee_id', '=', self.jules_emp.id)]) self.assertEqual(len(leaves), 3) self.assertEqual(leave.state, 'refuse') first_leave = leaves.filtered(lambda l: l.date_from.day == 1 and l.date_to.day == 15) self.assertEqual(first_leave.state, 'validate') self.assertEqual(first_leave.number_of_days, 11) second_leave = leaves.filtered(lambda l: l.date_from.day == 16 and l.date_to.day == 30) self.assertEqual(second_leave.state, 'validate') self.assertEqual(second_leave.number_of_days, 11)
49.871345
8,528
10,491
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date from dateutil.relativedelta import relativedelta from odoo.addons.hr_work_entry_holidays.tests.common import TestWorkEntryHolidaysBase from odoo.tests import tagged @tagged('test_leave') class TestWorkEntryLeave(TestWorkEntryHolidaysBase): def test_resource_leave_has_work_entry_type(self): leave = self.create_leave() resource_leave = leave._create_resource_leave() self.assertEqual(resource_leave.work_entry_type_id, self.leave_type.work_entry_type_id, "it should have the corresponding work_entry type") def test_resource_leave_in_contract_calendar(self): other_calendar = self.env['resource.calendar'].create({'name': 'New calendar'}) contract = self.richard_emp.contract_ids[0] contract.resource_calendar_id = other_calendar contract.state = 'open' # this set richard's calendar to New calendar leave = self.create_leave() resource_leave = leave._create_resource_leave() self.assertEqual(len(resource_leave), 1, "it should have created only one resource leave") self.assertEqual(resource_leave.work_entry_type_id, self.leave_type.work_entry_type_id, "it should have the corresponding work_entry type") def test_resource_leave_different_calendars(self): other_calendar = self.env['resource.calendar'].create({'name': 'New calendar'}) contract = self.richard_emp.contract_ids[0] contract.resource_calendar_id = other_calendar contract.state = 'open' # this set richard's calendar to New calendar # set another calendar self.richard_emp.resource_calendar_id = self.env['resource.calendar'].create({'name': 'Other calendar'}) leave = self.create_leave() resource_leave = leave._create_resource_leave() self.assertEqual(len(resource_leave), 2, "it should have created one resource leave per calendar") self.assertEqual(resource_leave.mapped('work_entry_type_id'), self.leave_type.work_entry_type_id, "they should have the corresponding work_entry type") def test_create_mark_conflicting_work_entries(self): work_entry = self.create_work_entry(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 12, 0)) self.assertNotEqual(work_entry.state, 'conflict', "It should not be conflicting") leave = self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 18, 0)) self.assertEqual(work_entry.state, 'conflict', "It should be conflicting") self.assertEqual(work_entry.leave_id, leave, "It should be linked to conflicting leave") def test_write_mark_conflicting_work_entries(self): leave = self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 12, 0)) work_entry = self.create_work_entry(datetime(2019, 10, 9, 9, 0), datetime(2019, 10, 10, 9, 0)) # the day before self.assertNotEqual(work_entry.state, 'conflict', "It should not be conflicting") leave.date_from = datetime(2019, 10, 9, 9, 0) # now it conflicts self.assertEqual(work_entry.state, 'conflict', "It should be conflicting") self.assertEqual(work_entry.leave_id, leave, "It should be linked to conflicting leave") def test_validate_leave_with_overlap(self): contract = self.richard_emp.contract_ids[:1] contract.state = 'open' contract.date_generated_from = datetime(2019, 10, 10, 9, 0) contract.date_generated_to = datetime(2019, 10, 10, 9, 0) leave = self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 12, 18, 0)) work_entry_1 = self.create_work_entry(datetime(2019, 10, 8, 9, 0), datetime(2019, 10, 11, 9, 0)) # overlaps work_entry_2 = self.create_work_entry(datetime(2019, 10, 11, 9, 0), datetime(2019, 10, 11, 10, 0)) # included adjacent_work_entry = self.create_work_entry(datetime(2019, 10, 12, 18, 0), datetime(2019, 10, 13, 18, 0)) # after and don't overlap leave.action_validate() self.assertNotEqual(adjacent_work_entry.state, 'conflict', "It should not conflict") self.assertFalse(work_entry_2.active, "It should have been archived") self.assertEqual(work_entry_1.state, 'conflict', "It should conflict") self.assertFalse(work_entry_1.leave_id, "It should not be linked to the leave") leave_work_entry = self.env['hr.work.entry'].search([('leave_id', '=', leave.id)]) - work_entry_1 self.assertTrue(leave_work_entry.work_entry_type_id.is_leave, "It should have created a leave work entry") self.assertEqual(leave_work_entry[:1].state, 'conflict', "The leave work entry should conflict") def test_conflict_move_work_entry(self): leave = self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 12, 18, 0)) work_entry = self.create_work_entry(datetime(2019, 10, 8, 9, 0), datetime(2019, 10, 11, 9, 0)) # overlaps self.assertEqual(work_entry.state, 'conflict', "It should be conflicting") self.assertEqual(work_entry.leave_id, leave, "It should be linked to conflicting leave") work_entry.date_stop = datetime(2019, 10, 9, 9, 0) # no longer overlaps self.assertNotEqual(work_entry.state, 'conflict', "It should not be conflicting") self.assertFalse(work_entry.leave_id, "It should not be linked to any leave") def test_validate_leave_without_overlap(self): contract = self.richard_emp.contract_ids[:1] contract.state = 'open' contract.date_generated_from = datetime(2019, 10, 10, 9, 0) contract.date_generated_to = datetime(2019, 10, 10, 9, 0) leave = self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 12, 18, 0)) work_entry = self.create_work_entry(datetime(2019, 10, 11, 9, 0), datetime(2019, 10, 11, 10, 0)) # included leave.action_validate() self.assertFalse(work_entry[:1].active, "It should have been archived") leave_work_entry = self.env['hr.work.entry'].search([('leave_id', '=', leave.id)]) self.assertTrue(leave_work_entry.work_entry_type_id.is_leave, "It should have created a leave work entry") self.assertNotEqual(leave_work_entry[:1].state, 'conflict', "The leave work entry should not conflict") def test_refuse_leave(self): leave = self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 18, 0)) work_entries = self.richard_emp.contract_id._generate_work_entries(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 18, 0)) adjacent_work_entry = self.create_work_entry(datetime(2019, 10, 7, 9, 0), datetime(2019, 10, 10, 9, 0)) self.assertTrue(all(work_entries.mapped(lambda w: w.state == 'conflict')), "Attendance work entries should all conflict with the leave") self.assertNotEqual(adjacent_work_entry.state, 'conflict', "Non overlapping work entry should not conflict") leave.action_refuse() self.assertTrue(all(work_entries.mapped(lambda w: w.state != 'conflict')), "Attendance work entries should no longer conflict") self.assertNotEqual(adjacent_work_entry.state, 'conflict', "Non overlapping work entry should not conflict") def test_refuse_approved_leave(self): start = datetime(2019, 10, 10, 6, 0) end = datetime(2019, 10, 10, 18, 0) # Setup contract generation state contract = self.richard_emp.contract_ids[:1] contract.state = 'open' contract.date_generated_from = start - relativedelta(hours=1) contract.date_generated_to = start - relativedelta(hours=1) leave = self.create_leave(start, end) leave.action_validate() work_entries = self.env['hr.work.entry'].search([('employee_id', '=', self.richard_emp.id), ('date_start', '<=', end), ('date_stop', '>=', start)]) leave_work_entry = self.richard_emp.contract_ids._generate_work_entries(start, end) self.assertEqual(leave_work_entry[:1].leave_id, leave) leave.action_refuse() work_entries = self.env['hr.work.entry'].search([('employee_id', '=', self.richard_emp.id), ('date_start', '>=', start), ('date_stop', '<=', end)]) self.assertFalse(leave_work_entry[:1].filtered('leave_id').active) self.assertEqual(len(work_entries), 2, "Attendance work entries should have been re-created (morning and afternoon)") self.assertTrue(all(work_entries.mapped(lambda w: w.state != 'conflict')), "Attendance work entries should not conflict") def test_archived_work_entry_conflict(self): self.create_leave(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 18, 0)) work_entry = self.create_work_entry(datetime(2019, 10, 10, 9, 0), datetime(2019, 10, 10, 18, 0)) self.assertTrue(work_entry.active) self.assertEqual(work_entry.state, 'conflict', "Attendance work entries should conflict with the leave") work_entry.toggle_active() self.assertEqual(work_entry.state, 'cancelled', "Attendance work entries should be cancelled and not conflict") self.assertFalse(work_entry.active) def test_work_entry_generation_company_time_off(self): existing_leaves = self.env['hr.leave'].search([]) existing_leaves.action_refuse() existing_leaves.action_draft() existing_leaves.unlink() start = date(2022, 8, 1) end = date(2022, 8, 31) self.contract_cdi._generate_work_entries(start, end) work_entries = self.env['hr.work.entry'].search([ ('employee_id', '=', self.jules_emp.id), ('date_start', '>=', start), ('date_stop', '<=', end), ]) self.assertEqual(len(work_entries.work_entry_type_id), 1) leave = self.env['hr.leave'].create({ 'name': 'Holiday !!!', 'holiday_type': 'company', 'mode_company_id': self.env.company.id, 'holiday_status_id': self.leave_type.id, 'date_from': datetime(2022, 8, 8, 9, 0), 'date_to': datetime(2022, 8, 8, 18, 0), 'number_of_days': 1, }) leave.action_validate() work_entries = self.env['hr.work.entry'].search([ ('employee_id', '=', self.jules_emp.id), ('date_start', '>=', start), ('date_stop', '<=', end), ]) self.assertEqual(len(work_entries.work_entry_type_id), 2)
61.711765
10,491
1,618
py
PYTHON
15.0
# # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date from odoo.addons.hr_work_entry_holidays.tests.common import TestWorkEntryHolidaysBase class TestPayslipHolidaysComputation(TestWorkEntryHolidaysBase): def setUp(self): super().setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Legal Leaves', 'time_type': 'leave', 'requires_allocation': 'no', 'work_entry_type_id': self.work_entry_type_leave.id }) def test_work_data(self): start = datetime(2015, 11, 8, 8, 0) end = datetime(2015, 11, 10, 22, 0) work_days_data = self.jules_emp._get_work_days_data_batch(start, end) leave = self.env['hr.leave'].create({ 'name': 'Doctor Appointment', 'employee_id': self.jules_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': start, 'date_to': end, 'number_of_days': work_days_data[self.jules_emp.id]['days'], }) leave.action_approve() work_entries = self.jules_emp.contract_ids._generate_work_entries(date(2015, 11, 10), date(2015, 11, 21)) work_entries.action_validate() work_entries = work_entries.filtered(lambda we: we.work_entry_type_id in self.env.ref('hr_work_entry.work_entry_type_attendance')) sum_hours = sum(work_entries.mapped('duration')) self.assertEqual(sum_hours, 59, 'It should count 59 attendance hours') # 24h first contract + 35h second contract
41.487179
1,618
9,949
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date from dateutil.relativedelta import relativedelta import pytz from odoo.tests.common import tagged from odoo.fields import Date, Datetime from odoo.addons.hr_work_entry_holidays.tests.common import TestWorkEntryHolidaysBase @tagged('work_entry') class TestWorkeEntryHolidaysWorkEntry(TestWorkEntryHolidaysBase): def setUp(self): super(TestWorkeEntryHolidaysWorkEntry, self).setUp() self.tz = pytz.timezone(self.richard_emp.tz) self.start = datetime(2015, 11, 1, 1, 0, 0) self.end = datetime(2015, 11, 30, 23, 59, 59) self.resource_calendar_id = self.env['resource.calendar'].create({'name': 'Zboub'}) contract = self.env['hr.contract'].create({ 'date_start': self.start.date() - relativedelta(days=5), 'name': 'dodo', 'resource_calendar_id': self.resource_calendar_id.id, 'wage': 1000, 'employee_id': self.richard_emp.id, 'state': 'open', 'date_generated_from': self.end.date() + relativedelta(days=5), }) self.richard_emp.resource_calendar_id = self.resource_calendar_id self.richard_emp.contract_id = contract def test_validate_non_approved_leave_work_entry(self): work_entry1 = self.env['hr.work.entry'].create({ 'name': '1', 'employee_id': self.richard_emp.id, 'work_entry_type_id': self.work_entry_type_leave.id, 'contract_id': self.richard_emp.contract_id.id, 'date_start': self.start, 'date_stop': self.end, }) self.env['hr.leave'].create({ 'name': 'Doctor Appointment', 'employee_id': self.richard_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': self.start - relativedelta(days=1), 'date_to': self.start + relativedelta(days=1), 'number_of_days': 2, }) self.assertFalse(work_entry1.action_validate(), "It should not validate work_entries conflicting with non approved leaves") self.assertEqual(work_entry1.state, 'conflict') def test_refuse_leave_work_entry(self): start = datetime(2015, 11, 1, 9, 0, 0) end = datetime(2015, 11, 3, 13, 0, 0) leave = self.env['hr.leave'].create({ 'name': 'Doctor Appointment', 'employee_id': self.richard_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': start, 'date_to': start + relativedelta(days=1), 'number_of_days': 2, }) work_entry = self.env['hr.work.entry'].create({ 'name': '1', 'employee_id': self.richard_emp.id, 'contract_id': self.richard_emp.contract_id.id, 'work_entry_type_id': self.work_entry_type.id, 'date_start': start, 'date_stop': end, 'leave_id': leave.id }) work_entry.action_validate() self.assertEqual(work_entry.state, 'conflict', "It should have an error (conflicting leave to approve") leave.action_refuse() self.assertNotEqual(work_entry.state, 'conflict', "It should not have an error") def test_time_week_leave_work_entry(self): # /!\ this is a week day => it exists an calendar attendance at this time start = datetime(2015, 11, 2, 10, 0, 0) end = datetime(2015, 11, 2, 17, 0, 0) work_days_data = self.jules_emp._get_work_days_data_batch(start, end) leave = self.env['hr.leave'].create({ 'name': '1leave', 'employee_id': self.richard_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': start, 'date_to': end, 'number_of_days': work_days_data[self.jules_emp.id]['days'], }) leave.action_validate() work_entries = self.richard_emp.contract_id._generate_work_entries(self.start, self.end) work_entries.action_validate() leave_work_entry = work_entries.filtered(lambda we: we.work_entry_type_id in self.work_entry_type_leave) sum_hours = sum(leave_work_entry.mapped('duration')) self.assertEqual(sum_hours, 5.0, "It should equal the number of hours richard should have worked") def test_contract_on_another_company(self): """ Test that the work entry generation still work if the contract is not on the same company than the employee (Internal Use Case) So when generating the work entries in Belgium, there is an issue when accessing to the time off in Hong Kong. """ company = self.env['res.company'].create({'name': 'Another Company'}) employee = self.env['hr.employee'].create({ 'name': 'New Employee', 'company_id': company.id, }) self.env['hr.contract'].create({ 'name': 'Employee Contract', 'employee_id': employee.id, 'date_start': Date.from_string('2015-01-01'), 'state': 'open', 'company_id': self.env.ref('base.main_company').id, 'wage': 4000, }) leave_type = self.env['hr.leave.type'].create({ 'name': 'Sick', 'request_unit': 'hour', 'leave_validation_type': 'both', 'requires_allocation': 'no', 'company_id': company.id, }) leave1 = self.env['hr.leave'].create({ 'name': 'Sick 1 week during christmas snif', 'employee_id': employee.id, 'holiday_status_id': leave_type.id, 'date_from': Datetime.from_string('2019-12-23 06:00:00'), 'date_to': Datetime.from_string('2019-12-27 20:00:00'), 'number_of_days': 5, }) leave1.action_approve() leave1.action_validate() # The work entries generation shouldn't raise an error user = self.env['res.users'].create({ 'name': 'Classic User', 'login': 'Classic User', 'company_id': self.env.ref('base.main_company').id, 'company_ids': self.env.ref('base.main_company').ids, 'groups_id': [(6, 0, [self.env.ref('hr_contract.group_hr_contract_manager').id, self.env.ref('base.group_user').id])], }) self.env['hr.employee'].with_user(user).generate_work_entries('2019-12-01', '2019-12-31') def test_work_entries_generation_if_parent_leave_zero_hours(self): # Test case: The employee has a parental leave at 0 hours per week # The employee has a leave during that period employee = self.env['hr.employee'].create({'name': 'My employee'}) calendar = self.env['resource.calendar'].create({ 'name': 'Parental 0h', 'attendance_ids': False, }) employee.resource_calendar_id = calendar contract = self.env['hr.contract'].create({ 'date_start': self.start.date() - relativedelta(years=1), 'name': 'Contract - Parental 0h', 'resource_calendar_id': calendar.id, 'wage': 1000, 'employee_id': employee.id, 'state': 'open', }) leave_type = self.env['hr.leave.type'].create({ 'name': 'Sick', 'request_unit': 'hour', 'leave_validation_type': 'both', 'requires_allocation': 'no', }) leave = self.env['hr.leave'].create({ 'name': "Sick 1 that doesn't make sense, but it's the prod so YOLO", 'employee_id': employee.id, 'holiday_status_id': leave_type.id, 'request_date_from': date(2020, 9, 4), 'request_date_to': date(2020, 9, 4), 'number_of_days': 1, }) leave.action_approve() leave.action_validate() work_entries = contract._generate_work_entries(date(2020, 7, 1), date(2020, 9, 30)) self.assertEqual(len(work_entries), 0) def test_work_entries_leave_if_leave_conflict_with_public_holiday(self): date_from = datetime(2023, 2, 1, 0, 0, 0) date_to = datetime(2023, 2, 28, 23, 59, 59) work_entry_type_holiday = self.env['hr.work.entry.type'].create({ 'name': 'Public Holiday', 'is_leave': True, 'code': 'LEAVETEST500' }) self.env['resource.calendar.leaves'].create({ 'name': 'Public Holiday', 'date_from': datetime(2023, 2, 6, 0, 0, 0), 'date_to': datetime(2023, 2, 7, 23, 59, 59), 'calendar_id': self.richard_emp.resource_calendar_id.id, 'work_entry_type_id': work_entry_type_holiday.id, }) leave = self.env['hr.leave'].create({ 'name': 'AL', 'employee_id': self.richard_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': date(2023, 2, 3), 'date_to': date(2023, 2, 9), 'number_of_days': 3, }) leave.action_validate() self.richard_emp.generate_work_entries(date_from, date_to, True) work_entries = self.env['hr.work.entry'].search([ ('employee_id', '=', self.richard_emp.id), ('date_stop', '>=', date_from), ('date_start', '<=', date_to), ('state', '!=', 'validated')]) leave_work_entry = work_entries.filtered(lambda we: we.work_entry_type_id in self.work_entry_type_leave) self.assertEqual(leave_work_entry.leave_id.id, leave.id, "Leave work entry should have leave_id value") public_holiday_work_entry = work_entries.filtered(lambda we: we.work_entry_type_id == work_entry_type_holiday) self.assertEqual(len(public_holiday_work_entry.leave_id), 0, "Public holiday work entry should not have leave_id")
43.445415
9,949
4,600
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime from odoo.addons.hr_work_entry_holidays.tests.common import TestWorkEntryHolidaysBase from odoo.tests.common import users, warmup, tagged @tagged('work_entry_perf') class TestWorkEntryHolidaysPerformance(TestWorkEntryHolidaysBase): @classmethod def setUpClass(cls): super(TestWorkEntryHolidaysPerformance, cls).setUpClass() cls.jack = cls.env['hr.employee'].create({'name': 'Jack'}) cls.employees = cls.richard_emp | cls.jack cls.env['hr.contract'].create([{ 'date_start': date(2018, 1, 1), 'date_end': date(2018, 2, 1), 'name': 'Contract for %s' % employee.name, 'wage': 5000.0, 'state': 'open', 'employee_id': employee.id, 'date_generated_from': datetime(2018, 1, 1, 0, 0), 'date_generated_to': datetime(2018, 1, 1, 0, 0), } for employee in cls.employees]) @users('__system__', 'admin') @warmup def test_performance_leave_validate(self): self.richard_emp.generate_work_entries(date(2018, 1, 1), date(2018, 1, 2)) leave = self.create_leave(datetime(2018, 1, 1, 7, 0), datetime(2018, 1, 1, 18, 0)) with self.assertQueryCount(__system__=94, admin=95): leave.action_validate() leave.action_refuse() @users('__system__', 'admin') @warmup def test_performance_leave_write(self): leave = self.create_leave(datetime(2018, 1, 1, 7, 0), datetime(2018, 1, 1, 18, 0)) with self.assertQueryCount(__system__=21, admin=30): leave.date_to = datetime(2018, 1, 1, 19, 0) leave.action_refuse() @users('__system__', 'admin') @warmup def test_performance_leave_create(self): with self.assertQueryCount(__system__=30, admin=31): leave = self.create_leave(datetime(2018, 1, 1, 7, 0), datetime(2018, 1, 1, 18, 0)) leave.action_refuse() @users('__system__', 'admin') @warmup def test_performance_leave_confirm(self): leave = self.create_leave(datetime(2018, 1, 1, 7, 0), datetime(2018, 1, 1, 18, 0)) leave.action_draft() with self.assertQueryCount(__system__=27, admin=28): leave.action_confirm() leave.state = 'refuse' @tagged('work_entry_perf') class TestWorkEntryHolidaysPerformancesBigData(TestWorkEntryHolidaysBase): @classmethod def setUpClass(cls): super(TestWorkEntryHolidaysPerformancesBigData, cls).setUpClass() cls.company = cls.env['res.company'].create({'name': 'A company'}) cls.paid_time_off = cls.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'request_unit': 'day', 'leave_validation_type': 'both', 'company_id': cls.company.id, 'requires_allocation': 'no', }) cls.employees = cls.env['hr.employee'].create([{ 'name': 'Employee %s' % i, 'company_id': cls.company.id } for i in range(100)]) cls.contracts = cls.env['hr.contract'].create([{ 'date_start': date(2018, 1, 1), 'date_end': False, 'name': 'Contract for %s' % employee.name, 'wage': 5000.0, 'state': 'open', 'employee_id': employee.id, 'date_generated_from': datetime(2018, 1, 1, 0, 0), 'date_generated_to': datetime(2018, 1, 1, 0, 0), } for employee in cls.employees]) cls.leaves = cls.env['hr.leave'].create([{ 'name': 'Holiday - %s' % employee.name, 'employee_id': employee.id, 'holiday_status_id': cls.paid_time_off.id, 'request_date_from': date(2020, 8, 3), 'request_date_to': date(2020, 8, 7), 'number_of_days': 5, } for employee in cls.employees]) cls.leaves._compute_date_from_to() cls.leaves.action_approve() cls.leaves.action_validate() def test_work_entries_generation_perf(self): # Test Case 7: Try to generate work entries for # a hundred employees over a month with self.assertQueryCount(__system__=11420, admin=11522): work_entries = self.contracts._generate_work_entries(date(2020, 7, 1), date(2020, 8, 31)) # Original work entries to generate when we don't adapt date_generated_from and # date_generated_to when they are equal for old contracts: 138300 self.assertEqual(len(work_entries), 8800)
38.983051
4,600
4,368
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo.fields import Datetime from odoo.addons.hr_work_entry_contract.tests.common import TestWorkEntryBase class TestWorkEntryHolidaysBase(TestWorkEntryBase): @classmethod def setUpClass(cls): super(TestWorkEntryHolidaysBase, cls).setUpClass() cls.leave_type = cls.env['hr.leave.type'].create({ 'name': 'Legal Leaves', 'time_type': 'leave', 'requires_allocation': 'no', 'work_entry_type_id': cls.work_entry_type_leave.id }) # I create a new employee "Jules" cls.jules_emp = cls.env['hr.employee'].create({ 'name': 'Jules', 'gender': 'male', 'birthday': '1984-05-01', 'country_id': cls.env.ref('base.be').id, 'department_id': cls.dep_rd.id, }) cls.calendar_35h = cls.env['resource.calendar'].create({ 'name': '35h calendar', 'attendance_ids': [ (0, 0, {'name': 'Monday Morning', 'dayofweek': '0', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Monday Evening', 'dayofweek': '0', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}), (0, 0, {'name': 'Tuesday Morning', 'dayofweek': '1', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Tuesday Evening', 'dayofweek': '1', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}), (0, 0, {'name': 'Wednesday Morning', 'dayofweek': '2', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Wednesday Evening', 'dayofweek': '2', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}), (0, 0, {'name': 'Thursday Morning', 'dayofweek': '3', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Thursday Evening', 'dayofweek': '3', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}), (0, 0, {'name': 'Friday Morning', 'dayofweek': '4', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Friday Evening', 'dayofweek': '4', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}) ] }) cls.calendar_35h._onchange_hours_per_day() # update hours/day cls.calendar_40h = cls.env['resource.calendar'].create({'name': 'Default calendar'}) # This contract ends at the 15th of the month cls.contract_cdd = cls.env['hr.contract'].create({ # Fixed term contract 'date_end': datetime.strptime('2015-11-15', '%Y-%m-%d'), 'date_start': datetime.strptime('2015-01-01', '%Y-%m-%d'), 'name': 'First CDD Contract for Jules', 'resource_calendar_id': cls.calendar_40h.id, 'wage': 5000.0, 'employee_id': cls.jules_emp.id, 'state': 'open', 'kanban_state': 'blocked', 'date_generated_from': datetime.strptime('2015-11-16', '%Y-%m-%d'), 'date_generated_to': datetime.strptime('2015-11-16', '%Y-%m-%d'), }) # This contract starts the next day cls.contract_cdi = cls.env['hr.contract'].create({ 'date_start': datetime.strptime('2015-11-16', '%Y-%m-%d'), 'name': 'Contract for Jules', 'resource_calendar_id': cls.calendar_35h.id, 'wage': 5000.0, 'employee_id': cls.jules_emp.id, 'state': 'open', 'kanban_state': 'normal', 'date_generated_from': datetime.strptime('2015-11-15', '%Y-%m-%d'), 'date_generated_to': datetime.strptime('2015-11-15', '%Y-%m-%d'), }) @classmethod def create_leave(cls, date_from=None, date_to=None): date_from = date_from or Datetime.today() date_to = date_to or Datetime.today() + relativedelta(days=1) return cls.env['hr.leave'].create({ 'name': 'Holiday !!!', 'employee_id': cls.richard_emp.id, 'holiday_status_id': cls.leave_type.id, 'date_to': date_to, 'date_from': date_from, 'number_of_days': 1, })
49.636364
4,368
12,439
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from datetime import datetime, date from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.osv.expression import AND from odoo.tools import format_date class HrLeaveType(models.Model): _inherit = 'hr.leave.type' work_entry_type_id = fields.Many2one('hr.work.entry.type', string='Work Entry Type') class HrLeave(models.Model): _inherit = 'hr.leave' def _create_resource_leave(self): """ Add a resource leave in calendars of contracts running at the same period. This is needed in order to compute the correct number of hours/days of the leave according to the contract's calender. """ resource_leaves = super(HrLeave, self)._create_resource_leave() for resource_leave in resource_leaves: resource_leave.work_entry_type_id = resource_leave.holiday_id.holiday_status_id.work_entry_type_id.id resource_leave_values = [] for leave in self.filtered(lambda l: l.employee_id): contracts = leave.employee_id.sudo()._get_contracts(leave.date_from, leave.date_to, states=['open']) for contract in contracts: if contract and contract.resource_calendar_id != leave.employee_id.resource_calendar_id: resource_leave_values += [{ 'name': _("%s: Time Off", leave.employee_id.name), 'holiday_id': leave.id, 'resource_id': leave.employee_id.resource_id.id, 'work_entry_type_id': leave.holiday_status_id.work_entry_type_id.id, 'time_type': leave.holiday_status_id.time_type, 'date_from': max(leave.date_from, datetime.combine(contract.date_start, datetime.min.time())), 'date_to': min(leave.date_to, datetime.combine(contract.date_end or date.max, datetime.max.time())), 'calendar_id': contract.resource_calendar_id.id, }] return resource_leaves | self.env['resource.calendar.leaves'].create(resource_leave_values) def _get_overlapping_contracts(self, contract_states=None): self.ensure_one() if contract_states is None: contract_states = [ '|', ('state', 'not in', ['draft', 'cancel']), '&', ('state', '=', 'draft'), ('kanban_state', '=', 'done') ] domain = AND([contract_states, [ ('employee_id', '=', self.employee_id.id), ('date_start', '<=', self.date_to), '|', ('date_end', '>=', self.date_from), '&', ('date_end', '=', False), ('state', '!=', 'close') ]]) return self.env['hr.contract'].sudo().search(domain) @api.constrains('date_from', 'date_to') def _check_contracts(self): """ A leave cannot be set across multiple contracts. Note: a leave can be across multiple contracts despite this constraint. It happens if a leave is correctly created (not across multiple contracts) but contracts are later modifed/created in the middle of the leave. """ for holiday in self.filtered('employee_id'): contracts = holiday._get_overlapping_contracts() if len(contracts.resource_calendar_id) > 1: state_labels = {e[0]: e[1] for e in contracts._fields['state']._description_selection(self.env)} raise ValidationError( _("""A leave cannot be set across multiple contracts with different working schedules. Please create one time off for each contract. Time off: %s Contracts: %s""", holiday.display_name, '\n'.join(_( "Contract %s from %s to %s, status: %s", contract.name, format_date(self.env, contract.date_start), format_date(self.env, contract.date_start) if contract.date_end else _("undefined"), state_labels[contract.state] ) for contract in contracts))) def _cancel_work_entry_conflict(self): """ Creates a leave work entry for each hr.leave in self. Check overlapping work entries with self. Work entries completely included in a leave are archived. e.g.: |----- work entry ----|---- work entry ----| |------------------- hr.leave ---------------| || vv |----* work entry ****| |************ work entry leave --------------| """ if not self: return # 1. Create a work entry for each leave work_entries_vals_list = [] for leave in self: contracts = leave.employee_id.sudo()._get_contracts(leave.date_from, leave.date_to, states=['open', 'close']) for contract in contracts: # Generate only if it has aleady been generated if leave.date_to >= contract.date_generated_from and leave.date_from <= contract.date_generated_to: work_entries_vals_list += contracts._get_work_entries_values(leave.date_from, leave.date_to) new_leave_work_entries = self.env['hr.work.entry'].create(work_entries_vals_list) if new_leave_work_entries: # 2. Fetch overlapping work entries, grouped by employees start = min(self.mapped('date_from'), default=False) stop = max(self.mapped('date_to'), default=False) work_entry_groups = self.env['hr.work.entry'].read_group([ ('date_start', '<', stop), ('date_stop', '>', start), ('employee_id', 'in', self.employee_id.ids), ], ['work_entry_ids:array_agg(id)', 'employee_id'], ['employee_id', 'date_start', 'date_stop'], lazy=False) work_entries_by_employee = defaultdict(lambda: self.env['hr.work.entry']) for group in work_entry_groups: employee_id = group.get('employee_id')[0] work_entries_by_employee[employee_id] |= self.env['hr.work.entry'].browse(group.get('work_entry_ids')) # 3. Archive work entries included in leaves included = self.env['hr.work.entry'] overlappping = self.env['hr.work.entry'] for work_entries in work_entries_by_employee.values(): # Work entries for this employee new_employee_work_entries = work_entries & new_leave_work_entries previous_employee_work_entries = work_entries - new_leave_work_entries # Build intervals from work entries leave_intervals = new_employee_work_entries._to_intervals() conflicts_intervals = previous_employee_work_entries._to_intervals() # Compute intervals completely outside any leave # Intervals are outside, but associated records are overlapping. outside_intervals = conflicts_intervals - leave_intervals overlappping |= self.env['hr.work.entry']._from_intervals(outside_intervals) included |= previous_employee_work_entries - overlappping overlappping.write({'leave_id': False}) included.write({'active': False}) def write(self, vals): if not self: return True skip_check = not bool({'employee_id', 'state', 'date_from', 'date_to'} & vals.keys()) start = min(self.mapped('date_from') + [fields.Datetime.from_string(vals.get('date_from', False)) or datetime.max]) stop = max(self.mapped('date_to') + [fields.Datetime.from_string(vals.get('date_to', False)) or datetime.min]) with self.env['hr.work.entry']._error_checking(start=start, stop=stop, skip=skip_check): return super().write(vals) @api.model_create_multi def create(self, vals_list): start_dates = [v.get('date_from') for v in vals_list if v.get('date_from')] stop_dates = [v.get('date_to') for v in vals_list if v.get('date_to')] if any(vals.get('holiday_type', 'employee') == 'employee' and not vals.get('multi_employee', False) and not vals.get('employee_id', False) for vals in vals_list): raise ValidationError(_("There is no employee set on the time off. Please make sure you're logged in the correct company.")) with self.env['hr.work.entry']._error_checking(start=min(start_dates, default=False), stop=max(stop_dates, default=False)): return super().create(vals_list) def action_confirm(self): start = min(self.mapped('date_from'), default=False) stop = max(self.mapped('date_to'), default=False) with self.env['hr.work.entry']._error_checking(start=start, stop=stop): return super().action_confirm() def _get_leaves_on_public_holiday(self): return super()._get_leaves_on_public_holiday().filtered( lambda l: l.holiday_status_id.work_entry_type_id.code not in ['LEAVE110', 'LEAVE280']) def _validate_leave_request(self): super(HrLeave, self)._validate_leave_request() self.sudo()._cancel_work_entry_conflict() # delete preexisting conflicting work_entries return True def action_refuse(self): """ Override to archive linked work entries and recreate attendance work entries where the refused leave was. """ res = super(HrLeave, self).action_refuse() work_entries = self.env['hr.work.entry'].sudo().search([('leave_id', 'in', self.ids)]) work_entries.write({'active': False}) # Re-create attendance work entries vals_list = [] for work_entry in work_entries: vals_list += work_entry.contract_id._get_work_entries_values(work_entry.date_start, work_entry.date_stop) self.env['hr.work.entry'].create(vals_list) return res def _get_number_of_days(self, date_from, date_to, employee_id): """ If an employee is currently working full time but asks for time off next month where he has a new contract working only 3 days/week. This should be taken into account when computing the number of days for the leave (2 weeks leave = 6 days). Override this method to get number of days according to the contract's calendar at the time of the leave. """ days = super(HrLeave, self)._get_number_of_days(date_from, date_to, employee_id) if employee_id: employee = self.env['hr.employee'].browse(employee_id) # Use sudo otherwise base users can't compute number of days contracts = employee.sudo()._get_contracts(date_from, date_to, states=['open']) contracts |= employee.sudo()._get_incoming_contracts(date_from, date_to) calendar = contracts[:1].resource_calendar_id if contracts else None # Note: if len(contracts)>1, the leave creation will crash because of unicity constaint # We force the company in the domain as we are more than likely in a compute_sudo domain = [('company_id', 'in', self.env.company.ids + self.env.context.get('allowed_company_ids', []))] result = employee._get_work_days_data_batch(date_from, date_to, calendar=calendar, domain=domain)[employee.id] if self.request_unit_half and result['hours'] > 0: result['days'] = 0.5 return result return days def _get_calendar(self): self.ensure_one() if self.date_from and self.date_to: contracts = self.employee_id.sudo()._get_contracts(self.date_from, self.date_to, states=['open']) contracts |= self.employee_id.sudo()._get_incoming_contracts(self.date_from, self.date_to) contract_calendar = contracts[:1].resource_calendar_id if contracts else None return contract_calendar or self.employee_id.resource_calendar_id or self.env.company.resource_calendar_id return super()._get_calendar()
50.771429
12,439
7,231
py
PYTHON
15.0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import pytz from datetime import date, datetime from odoo import api, models class HrContract(models.Model): _inherit = 'hr.contract' _description = 'Employee Contract' @api.constrains('date_start', 'date_end', 'state') def _check_contracts(self): self._get_leaves()._check_contracts() def _get_leaves(self): return self.env['hr.leave'].search([ ('state', '!=', 'refuse'), ('employee_id', 'in', self.mapped('employee_id.id')), ('date_from', '<=', max([end or date.max for end in self.mapped('date_end')])), ('date_to', '>=', min(self.mapped('date_start'))), ]) # override to add work_entry_type from leave def _get_leave_work_entry_type(self, leave): if leave.holiday_id: return leave.holiday_id.holiday_status_id.work_entry_type_id else: return leave.work_entry_type_id # YTI TODO: Master remove the method (deprecated) def _get_more_vals_leave(self, leave): return [('leave_id', leave.holiday_id and leave.holiday_id.id)] def _get_more_vals_leave_interval(self, interval, leaves): result = super()._get_more_vals_leave_interval(interval, leaves) for leave in leaves: if interval[0] >= leave[0] and interval[1] <= leave[1]: result.append(('leave_id', leave[2].holiday_id.id)) return result def _get_interval_leave_work_entry_type(self, interval, leaves, bypassing_codes): # returns the work entry time related to the leave that # includes the whole interval. # Overriden in hr_work_entry_contract_holiday to select the # global time off first (eg: Public Holiday > Home Working) self.ensure_one() if interval[2].work_entry_type_id.code in bypassing_codes: return interval[2].work_entry_type_id interval_start = interval[0].astimezone(pytz.utc).replace(tzinfo=None) interval_stop = interval[1].astimezone(pytz.utc).replace(tzinfo=None) including_rcleaves = [l[2] for l in leaves if l[2] and interval_start >= l[2].date_from and interval_stop <= l[2].date_to] including_global_rcleaves = [l for l in including_rcleaves if not l.holiday_id] including_holiday_rcleaves = [l for l in including_rcleaves if l.holiday_id] rc_leave = False # Example: In CP200: Long term sick > Public Holidays (which is global) if bypassing_codes: bypassing_rc_leave = [l for l in including_holiday_rcleaves if l.holiday_id.holiday_status_id.work_entry_type_id.code in bypassing_codes] else: bypassing_rc_leave = [] if bypassing_rc_leave: rc_leave = bypassing_rc_leave[0] elif including_global_rcleaves: rc_leave = including_global_rcleaves[0] elif including_holiday_rcleaves: rc_leave = including_holiday_rcleaves[0] if rc_leave: return self._get_leave_work_entry_type_dates(rc_leave, interval_start, interval_stop, self.employee_id) return self.env.ref('hr_work_entry_contract.work_entry_type_leave') def _get_leave_domain(self, start_dt, end_dt): self.ensure_one() # Complete override, compare over holiday_id.employee_id instead of calendar_id return [ ('time_type', '=', 'leave'), '|', ('calendar_id', 'in', [False, self.resource_calendar_id.id]), ('holiday_id.employee_id', '=', self.employee_id.id), # see https://github.com/odoo/enterprise/pull/15091 ('resource_id', 'in', [False, self.employee_id.resource_id.id]), ('date_from', '<=', end_dt), ('date_to', '>=', start_dt), ('company_id', 'in', [False, self.company_id.id]), ] def write(self, vals): # Special case when setting a contract as running: # If there is already a validated time off over another contract # with a different schedule, split the time off, before the # _check_contracts raises an issue. if 'state' not in vals or vals['state'] != 'open': return super().write(vals) specific_contracts = self.env['hr.contract'] all_new_leave_origin = [] all_new_leave_vals = [] leaves_state = {} for contract in self: leaves = contract._get_leaves() for leave in leaves: overlapping_contracts = leave._get_overlapping_contracts(contract_states=[('state', '!=', 'cancel')]) if len(overlapping_contracts.resource_calendar_id) <= 1: continue if leave.id not in leaves_state: leaves_state[leave.id] = leave.state if leave.state != 'refuse': leave.action_refuse() super(HrContract, contract).write(vals) specific_contracts += contract for overlapping_contract in overlapping_contracts: # Exclude other draft contracts that are not set to running on this # transaction if overlapping_contract.state == 'draft' and overlapping_contract not in self: continue new_date_from = max(leave.date_from, datetime.combine(overlapping_contract.date_start, datetime.min.time())) new_date_to = min(leave.date_to, datetime.combine(overlapping_contract.date_end or date.max, datetime.max.time())) new_leave_vals = leave.copy_data({ 'date_from': new_date_from, 'date_to': new_date_to, 'state': leaves_state[leave.id], })[0] new_leave = self.env['hr.leave'].new(new_leave_vals) new_leave._compute_date_from_to() new_leave._compute_number_of_days() # Could happen for part-time contract, that time off is not necessary # anymore. if new_leave.date_from < new_leave.date_to: all_new_leave_origin.append(leave) all_new_leave_vals.append(new_leave._convert_to_write(new_leave._cache)) if all_new_leave_vals: new_leaves = self.env['hr.leave'].with_context( tracking_disable=True, mail_activity_automation_skip=True, leave_fast_create=True, leave_skip_state_check=True ).create(all_new_leave_vals) new_leaves.filtered(lambda l: l.state in 'validate')._validate_leave_request() for index, new_leave in enumerate(new_leaves): subtype_note = self.env.ref('mail.mt_note') new_leave.message_post_with_view( 'mail.message_origin_link', values={'self': new_leave, 'origin': all_new_leave_origin[index]}, subtype_id=subtype_note.id) return super(HrContract, self - specific_contracts).write(vals)
49.190476
7,231
3,548
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class HrWorkEntry(models.Model): _inherit = 'hr.work.entry' leave_id = fields.Many2one('hr.leave', string='Time Off') leave_state = fields.Selection(related='leave_id.state') def _get_duration(self, date_start, date_stop): if not date_start or not date_stop: return 0 if not self.work_entry_type_id and self.leave_id: calendar = self.contract_id.resource_calendar_id employee = self.contract_id.employee_id contract_data = employee._get_work_days_data_batch( date_start, date_stop, compute_leaves=False, calendar=calendar)[employee.id] return contract_data.get('hours', 0) return super()._get_duration(date_start, date_stop) def write(self, vals): if 'state' in vals and vals['state'] == 'cancelled': self.mapped('leave_id').filtered(lambda l: l.state != 'refuse').action_refuse() return super().write(vals) def _reset_conflicting_state(self): super()._reset_conflicting_state() attendances = self.filtered(lambda w: w.work_entry_type_id and not w.work_entry_type_id.is_leave) attendances.write({'leave_id': False}) def _check_if_error(self): res = super()._check_if_error() conflict_with_leaves = self._compute_conflicts_leaves_to_approve() return res or conflict_with_leaves def _compute_conflicts_leaves_to_approve(self): if not self: return False self.flush(['date_start', 'date_stop', 'employee_id']) self.env['hr.leave'].flush(['date_from', 'date_to', 'state', 'employee_id']) query = """ SELECT b.id AS work_entry_id, l.id AS leave_id FROM hr_work_entry b INNER JOIN hr_leave l ON b.employee_id = l.employee_id WHERE b.active = TRUE AND b.id IN %s AND l.date_from < b.date_stop AND l.date_to > b.date_start AND l.state IN ('confirm', 'validate1'); """ self.env.cr.execute(query, [tuple(self.ids)]) conflicts = self.env.cr.dictfetchall() for res in conflicts: self.browse(res.get('work_entry_id')).write({ 'state': 'conflict', 'leave_id': res.get('leave_id') }) return bool(conflicts) def action_approve_leave(self): self.ensure_one() if self.leave_id: # Already confirmed once if self.leave_id.state == 'validate1': self.leave_id.action_validate() # Still in confirmed state else: self.leave_id.action_approve() # If double validation, still have to validate it again if self.leave_id.validation_type == 'both': self.leave_id.action_validate() def action_refuse_leave(self): self.ensure_one() leave_sudo = self.leave_id.sudo() if leave_sudo: leave_sudo.action_refuse() class HrWorkEntryType(models.Model): _inherit = 'hr.work.entry.type' _description = 'HR Work Entry Type' leave_type_ids = fields.One2many( 'hr.leave.type', 'work_entry_type_id', string='Time Off Type', help="Every new time off type in this list will be reported as select work entry in payslip.")
37.744681
3,548
1,432
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) Quartile Limited { 'name': 'Japan - Accounting', 'version': '2.2', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Overview: --------- * Chart of Accounts and Taxes template for companies in Japan. * This probably does not cover all the necessary accounts for a company. \ You are expected to add/delete/modify accounts based on this template. Note: ----- * Fiscal positions '内税' and '外税' have been added to handle special \ requirements which might arise from POS implementation. [1] Under normal \ circumstances, you might not need to use those at all. [1] See https://github.com/odoo/odoo/pull/6470 for detail. """, 'author': 'Quartile Limited', 'website': 'https://www.quartile.co/', 'depends': ['account'], 'data': [ 'data/l10n_jp_chart_data.xml', 'data/account.account.template.csv', 'data/account.tax.group.csv', 'data/account_tax_report_data.xml', 'data/account_tax_template_data.xml', 'data/account_chart_template_data.xml', 'data/account.fiscal.position.template.csv', 'data/account.fiscal.position.tax.template.csv', 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
30.297872
1,424
1,140
py
PYTHON
15.0
#-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2012 Michael Telahun Makonnen <[email protected]>. { 'name': 'Ethiopia - Accounting', 'version': '2.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Base Module for Ethiopian Localization ====================================== This is the latest Ethiopian Odoo localization and consists of: - Chart of Accounts - VAT tax structure - Withholding tax structure - Regional State listings """, 'author':'Michael Telahun Makonnen <[email protected]>', 'website':'http://miketelahun.wordpress.com', 'depends': [ 'account', ], 'data': [ 'data/l10n_et_chart_data.xml', 'data/account.account.template.csv', 'data/account_chart_template_data.xml', 'data/account.tax.group.csv', 'data/account_tax_report_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
30
1,140
534
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Gulf Cooperation Council WMS Accounting", 'version': '1.0', 'description': """ Arabic/English for GCC + lot/SN numbers """, 'author': "Odoo S.A.", 'website': "https://www.odoo.com", 'category': 'Accounting/Localizations', 'depends': ['l10n_gcc_invoice', 'stock_account'], 'data': [ 'views/report_invoice.xml', ], 'auto_install': True, 'license': 'LGPL-3', }
26.7
534
909
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Transifex integration', 'version': '1.0', 'summary': 'Add a link to edit a translation in Transifex', 'category': 'Hidden/Tools', 'description': """ Transifex integration ===================== This module will add a link to the Transifex project in the translation view. The purpose of this module is to speed up translations of the main modules. To work, Odoo uses Transifex configuration files `.tx/config` to detec the project source. Custom modules will not be translated (as not published on the main Transifex project). The language the user tries to translate must be activated on the Transifex project. """, 'data': [ 'data/transifex_data.xml', 'data/ir_translation_view.xml', ], 'depends': ['base'], 'license': 'LGPL-3', }
31.344828
909
3,910
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from configparser import ConfigParser from os.path import join as opj import os import werkzeug.urls import odoo from odoo import models, fields class IrTranslation(models.Model): _inherit = 'ir.translation' transifex_url = fields.Char("Transifex URL", compute='_get_transifex_url', help="Propose a modification in the official version of Odoo") def _get_transifex_url(self): """ Construct transifex URL based on the module on configuration """ # e.g. 'https://www.transifex.com/odoo/' base_url = self.env['ir.config_parameter'].sudo().get_param('transifex.project_url') tx_config_file = ConfigParser() tx_sections = [] for addon_path in odoo.addons.__path__: tx_path = opj(addon_path, '.tx', 'config') if os.path.isfile(tx_path): tx_config_file.read(tx_path) # first section is [main], after [odoo-11.sale] tx_sections.extend(tx_config_file.sections()[1:]) # parent directory ad .tx/config is root directory in odoo/odoo tx_path = opj(addon_path, os.pardir, '.tx', 'config') if os.path.isfile(tx_path): tx_config_file.read(tx_path) tx_sections.extend(tx_config_file.sections()[1:]) if not base_url or not tx_sections: self.update({'transifex_url': False}) else: base_url = base_url.rstrip('/') # will probably be the same for all terms, avoid multiple searches translation_languages = list(set(self.mapped('lang'))) languages = self.env['res.lang'].with_context(active_test=False).search( [('code', 'in', translation_languages)]) language_codes = dict((l.code, l.iso_code) for l in languages) # .tx/config files contains the project reference # using ini files translation_modules = set(self.mapped('module')) project_modules = {} for module in translation_modules: for section in tx_sections: if len(section.split(':')) != 6: # old format ['main', 'odoo-16.base', ...] tx_project, tx_mod = section.split(".") else: # tx_config_file.sections(): ['main', 'o:odoo:p:odoo-16:r:base', ...] _, _, _, tx_project, _, tx_mod = section.split(':') if tx_mod == module: project_modules[module] = tx_project for translation in self: if not translation.module or not translation.src or translation.lang == 'en_US': # custom or source term translation.transifex_url = False continue lang_code = language_codes.get(translation.lang) if not lang_code: translation.transifex_url = False continue project = project_modules.get(translation.module) if not project: translation.transifex_url = False continue # e.g. https://www.transifex.com/odoo/odoo-10/translate/#fr/sale/42?q=text:'Sale+Order' src = werkzeug.urls.url_quote_plus(translation.src[:50].replace("\n", "").replace("'", "\\'")) src = f"'{src}'" if "+" in src else src translation.transifex_url = "%(url)s/%(project)s/translate/#%(lang)s/%(module)s/42?q=%(src)s" % { 'url': base_url, 'project': project, 'lang': lang_code, 'module': translation.module, 'src': f"text%3A{src}", }
42.967033
3,910
588
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Buckaroo Payment Acquirer', 'version': '2.0', 'category': 'Accounting/Payment Acquirers', 'sequence': 355, 'summary': 'Payment Acquirer: Buckaroo Implementation', 'description': """Buckaroo Payment Acquirer""", 'depends': ['payment'], 'data': [ 'views/payment_views.xml', 'views/payment_buckaroo_templates.xml', 'data/payment_acquirer_data.xml', ], 'application': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
30.947368
588
428
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # Mapping of transaction states to Buckaroo status codes. # See https://www.pronamic.nl/wp-content/uploads/2013/04/BPE-3.0-Gateway-HTML.1.02.pdf for the # exhaustive list of status codes. STATUS_CODES_MAPPING = { 'pending': (790, 791, 792, 793), 'done': (190,), 'cancel': (890, 891), 'refused': (690,), 'error': (490, 491, 492,), }
35.666667
428
595
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.payment.tests.common import PaymentCommon class BuckarooCommon(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.buckaroo = cls._prepare_acquirer('buckaroo', update_values={ 'buckaroo_website_key': 'dummy', 'buckaroo_secret_key': 'test_key_123', }) # Override defaults cls.acquirer = cls.buckaroo cls.currency = cls.currency_euro
31.315789
595
5,182
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo.tools import mute_logger from .common import BuckarooCommon from ..controllers.main import BuckarooController @tagged('post_install', '-at_install') class BuckarooTest(BuckarooCommon): def test_redirect_form_values(self): self.patch(self, 'base_url', 'http://localhost:8069') self.patch(type(self.env['base']), 'get_base_url', lambda _: 'http://localhost:8069') return_url = self._build_url(BuckarooController._return_url) expected_values = { 'Brq_websitekey': self.buckaroo.buckaroo_website_key, 'Brq_amount': str(self.amount), 'Brq_currency': self.currency.name, 'Brq_invoicenumber': self.reference, 'Brq_signature': '669d4f64ea9cbb58cfefba9b802389667e4eef39', 'Brq_return': return_url, 'Brq_returncancel': return_url, 'Brq_returnerror': return_url, 'Brq_returnreject': return_url, 'Brq_culture': 'en-US', } tx_sudo = self.create_transaction(flow='redirect') with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx_sudo._get_processing_values() form_info = self._extract_values_from_html_form(processing_values['redirect_form_html']) self.assertEqual(form_info['action'], "https://testcheckout.buckaroo.nl/html/") self.assertDictEqual(expected_values, form_info['inputs'], "Buckaroo: invalid inputs specified in the redirect form.") def test_feedback_processing(self): self.amount = 2240.0 self.reference = 'SO004' # typical data posted by buckaroo after client has successfully paid buckaroo_post_data = { 'BRQ_RETURNDATA': u'', 'BRQ_AMOUNT': str(self.amount), 'BRQ_CURRENCY': self.currency.name, 'BRQ_CUSTOMER_NAME': u'Jan de Tester', 'BRQ_INVOICENUMBER': self.reference, 'brq_payment': u'573311D081B04069BD6336001611DBD4', 'BRQ_PAYMENT_METHOD': u'paypal', 'BRQ_SERVICE_PAYPAL_PAYERCOUNTRY': u'NL', 'BRQ_SERVICE_PAYPAL_PAYEREMAIL': u'[email protected]', 'BRQ_SERVICE_PAYPAL_PAYERFIRSTNAME': u'Jan', 'BRQ_SERVICE_PAYPAL_PAYERLASTNAME': u'Tester', 'BRQ_SERVICE_PAYPAL_PAYERMIDDLENAME': u'de', 'BRQ_SERVICE_PAYPAL_PAYERSTATUS': u'verified', 'Brq_signature': u'e67e32ee1be1030a86c7764adfcc01856e00f9a7', 'BRQ_STATUSCODE': u'190', 'BRQ_STATUSCODE_DETAIL': u'S001', 'BRQ_STATUSMESSAGE': u'Transaction successfully processed', 'BRQ_TIMESTAMP': u'2014-05-08 12:41:21', 'BRQ_TRANSACTIONS': u'D6106678E1D54EEB8093F5B3AC42EA7B', 'BRQ_WEBSITEKEY': u'5xTGyGyPyl', } with self.assertRaises(ValidationError): # unknown transaction self.env['payment.transaction']._handle_feedback_data('buckaroo', buckaroo_post_data) tx = self.create_transaction(flow='redirect') # validate it tx._handle_feedback_data('buckaroo', buckaroo_post_data) self.assertEqual(tx.state, 'done', 'Buckaroo: validation did not put tx into done state') self.assertEqual(tx.acquirer_reference, buckaroo_post_data.get('BRQ_TRANSACTIONS'), 'Buckaroo: validation did not update tx payid') # New reference for new tx self.reference = 'SO004-2' tx = self.create_transaction(flow='redirect') buckaroo_post_data['BRQ_INVOICENUMBER'] = self.reference # now buckaroo post is ok: try to modify the SHASIGN buckaroo_post_data['Brq_signature'] = '54d928810e343acf5fb0c3ee75fd747ff159ef7a' with self.assertRaises(ValidationError): self.env['payment.transaction']._handle_feedback_data('buckaroo', buckaroo_post_data) # simulate an error buckaroo_post_data['BRQ_STATUSCODE'] = '2' buckaroo_post_data['Brq_signature'] = '3e67da5181b1a895d322987303e42bab2a376eec' # Avoid warning log bc of unknown status code with mute_logger('odoo.addons.payment_buckaroo.models.payment_transaction'): self.env['payment.transaction']._handle_feedback_data('buckaroo', buckaroo_post_data) self.assertEqual(tx.state, 'error', 'Buckaroo: unexpected status code should put tx in error state') def test_signature_is_computed_based_on_lower_case_data_keys(self): """ Test that lower case keys are used to execute the case-insensitive sort. """ computed_signature = self.acquirer._buckaroo_generate_digital_sign({ 'brq_a': '1', 'brq_b': '2', 'brq_c_first': '3', 'brq_csecond': '4', 'brq_D': '5', }, incoming=False) self.assertEqual( computed_signature, '937cca8f486b75e93df1e9811a5ebf43357fc3f2', msg="The signing string items should be ordered based on a lower-case copy of the keys", )
45.45614
5,182
6,137
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from werkzeug import urls from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.addons.payment_buckaroo.const import STATUS_CODES_MAPPING from odoo.addons.payment_buckaroo.controllers.main import BuckarooController _logger = logging.getLogger(__name__) def _normalize_dataset(data): """ Set all keys of a dictionary to uppercase. As Buckaroo parameters names are case insensitive, we can convert everything to upper case to easily detected the presence of a parameter by checking the uppercase key only. :param dict data: The dictionary whose keys must be set to uppercase :return: A copy of the original data with all keys set to uppercase :rtype: dict """ return {key.upper(): val for key, val in data.items()} class PaymentTransaction(models.Model): _inherit = 'payment.transaction' def _get_specific_rendering_values(self, processing_values): """ Override of payment to return Buckaroo-specific rendering values. Note: self.ensure_one() from `_get_processing_values` :param dict processing_values: The generic and specific processing values of the transaction :return: The dict of acquirer-specific processing values :rtype: dict """ res = super()._get_specific_rendering_values(processing_values) if self.provider != 'buckaroo': return res return_url = urls.url_join(self.acquirer_id.get_base_url(), BuckarooController._return_url) rendering_values = { 'api_url': self.acquirer_id._buckaroo_get_api_url(), 'Brq_websitekey': self.acquirer_id.buckaroo_website_key, 'Brq_amount': self.amount, 'Brq_currency': self.currency_id.name, 'Brq_invoicenumber': self.reference, # Include all 4 URL keys despite they share the same value as they are part of the sig. 'Brq_return': return_url, 'Brq_returncancel': return_url, 'Brq_returnerror': return_url, 'Brq_returnreject': return_url, } if self.partner_lang: rendering_values['Brq_culture'] = self.partner_lang.replace('_', '-') rendering_values['Brq_signature'] = self.acquirer_id._buckaroo_generate_digital_sign( rendering_values, incoming=False ) return rendering_values @api.model def _get_tx_from_feedback_data(self, provider, data): """ Override of payment to find the transaction based on Buckaroo data. :param str provider: The provider of the acquirer that handled the transaction :param dict data: The feedback data sent by the provider :return: The transaction if found :rtype: recordset of `payment.transaction` :raise: ValidationError if inconsistent data were received :raise: ValidationError if the data match no transaction :raise: ValidationError if the signature can not be verified """ tx = super()._get_tx_from_feedback_data(provider, data) if provider != 'buckaroo': return tx normalized_data = _normalize_dataset(data) reference = normalized_data.get('BRQ_INVOICENUMBER') shasign = normalized_data.get('BRQ_SIGNATURE') if not reference or not shasign: raise ValidationError( "Buckaroo: " + _( "Received data with missing reference (%(ref)s) or shasign (%(sign)s)", ref=reference, sign=shasign ) ) tx = self.search([('reference', '=', reference), ('provider', '=', 'buckaroo')]) if not tx: raise ValidationError( "Buckaroo: " + _("No transaction found matching reference %s.", reference) ) # Verify signature shasign_check = tx.acquirer_id._buckaroo_generate_digital_sign(data, incoming=True) if shasign_check != shasign: raise ValidationError( "Buckaroo: " + _( "Invalid shasign: received %(sign)s, computed %(check)s", sign=shasign, check=shasign_check ) ) return tx def _process_feedback_data(self, data): """ Override of payment to process the transaction based on Buckaroo data. Note: self.ensure_one() :param dict data: The feedback data sent by the provider :return: None :raise: ValidationError if inconsistent data were received """ super()._process_feedback_data(data) if self.provider != 'buckaroo': return normalized_data = _normalize_dataset(data) transaction_keys = normalized_data.get('BRQ_TRANSACTIONS') if not transaction_keys: raise ValidationError("Buckaroo: " + _("Received data with missing transaction keys")) # BRQ_TRANSACTIONS can hold multiple, comma-separated, tx keys. In practice, it holds only # one reference. So we split for semantic correctness and keep the first transaction key. self.acquirer_reference = transaction_keys.split(',')[0] status_code = int(normalized_data.get('BRQ_STATUSCODE') or 0) if status_code in STATUS_CODES_MAPPING['pending']: self._set_pending() elif status_code in STATUS_CODES_MAPPING['done']: self._set_done() elif status_code in STATUS_CODES_MAPPING['cancel']: self._set_canceled() elif status_code in STATUS_CODES_MAPPING['refused']: self._set_error(_("Your payment was refused (code %s). Please try again.", status_code)) elif status_code in STATUS_CODES_MAPPING['error']: self._set_error(_("An error occurred during processing of your payment (code %s). Please try again.", status_code)) else: _logger.warning("Buckaroo: received unknown status code: %s", status_code) self._set_error("Buckaroo: " + _("Unknown status code: %s", status_code))
42.618056
6,137
431
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class AccountPaymentMethod(models.Model): _inherit = 'account.payment.method' @api.model def _get_payment_method_information(self): res = super()._get_payment_method_information() res['buckaroo'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]} return res
30.785714
431
3,048
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from hashlib import sha1 from werkzeug import urls from odoo import fields, models class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection( selection_add=[('buckaroo', "Buckaroo")], ondelete={'buckaroo': 'set default'}) buckaroo_website_key = fields.Char( string="Website Key", help="The key solely used to identify the website with Buckaroo", required_if_provider='buckaroo') buckaroo_secret_key = fields.Char( string="Buckaroo Secret Key", required_if_provider='buckaroo', groups='base.group_system') def _buckaroo_get_api_url(self): """ Return the API URL according to the state. Note: self.ensure_one() :return: The API URL :rtype: str """ self.ensure_one() if self.state == 'enabled': return 'https://checkout.buckaroo.nl/html/' else: return 'https://testcheckout.buckaroo.nl/html/' def _buckaroo_generate_digital_sign(self, values, incoming=True): """ Generate the shasign for incoming or outgoing communications. :param dict values: The values used to generate the signature :param bool incoming: Whether the signature must be generate for an incoming (Buckaroo to Odoo) or outgoing (Odoo to Buckaroo) communication. :return: The shasign :rtype: str """ if incoming: # Remove the signature from the values used to check the signature for key in values.keys(): if key.upper() == 'BRQ_SIGNATURE': # Keys are case-insensitive del values[key] break # Incoming communication values must be URL-decoded before checking the signature items = [(k, urls.url_unquote_plus(v)) for k, v in values.items()] else: # Only use items whose key starts with 'add_', 'brq_', or 'cust_' (case insensitive) items = [ (k, v) for k, v in values.items() if any(k.upper().startswith(key_prefix) for key_prefix in ('ADD_', 'BRQ_', 'CUST_')) ] # Sort parameters by lower-cased key. Not upper- because ord('A') < ord('_') < ord('a'). sorted_items = sorted(items, key=lambda pair: pair[0].lower()) # Build the signing string by concatenating all parameters sign_string = ''.join(f'{k}={v or ""}' for k, v in sorted_items) # Append the pre-shared secret key to the signing string sign_string += self.buckaroo_secret_key # Calculate the SHA-1 hash over the signing string return sha1(sign_string.encode('utf-8')).hexdigest() def _get_default_payment_method_id(self): self.ensure_one() if self.provider != 'buckaroo': return super()._get_default_payment_method_id() return self.env.ref('payment_buckaroo.payment_method_buckaroo').id
42.929577
3,048
1,493
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint from odoo import http from odoo.http import request _logger = logging.getLogger(__name__) class BuckarooController(http.Controller): _return_url = '/payment/buckaroo/return' @http.route( _return_url, type='http', auth='public', methods=['POST'], csrf=False, save_session=False ) def buckaroo_return_from_redirect(self, **data): """ Process the data returned by Buckaroo after redirection. The route is flagged with `save_session=False` to prevent Odoo from assigning a new session to the user if they are redirected to this route with a POST request. Indeed, as the session cookie is created without a `SameSite` attribute, some browsers that don't implement the recommended default `SameSite=Lax` behavior will not include the cookie in the redirection request from the payment provider to Odoo. As the redirection to the '/payment/status' page will satisfy any specification of the `SameSite` attribute, the session of the user will be retrieved and with it the transaction which will be immediately post-processed. :param dict data: The feedback data """ _logger.info("received notification data:\n%s", pprint.pformat(data)) request.env['payment.transaction'].sudo()._handle_feedback_data('buckaroo', data) return request.redirect('/payment/status')
45.242424
1,493
823
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'CRM Mail Plugin', 'version': '1.0', 'category': 'Sales/CRM', 'sequence': 5, 'summary': 'Turn emails received in your mailbox into leads and log their content as internal notes.', 'description': "Turn emails received in your mailbox into leads and log their content as internal notes.", 'website': 'https://www.odoo.com/app/crm', 'depends': [ 'crm', 'mail_plugin', ], 'data': [ 'views/crm_mail_plugin_lead.xml', 'views/crm_lead_views.xml' ], 'web.assets_backend': [ 'crm_mail_plugin/static/src/to_translate/**/*', ], 'installable': True, 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
30.481481
823
4,200
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from odoo.addons.mail_plugin.tests.common import TestMailPluginControllerCommon, mock_auth_method_outlook class TestCrmMailPlugin(TestMailPluginControllerCommon): @mock_auth_method_outlook('employee') def test_get_contact_data(self): """Check that the leads section is not visible if the user has not access to crm.lead.""" partner, partner_2 = self.env["res.partner"].create([ {"name": "Partner 1"}, {"name": "Partner 2"}, ]) result = self._make_rpc_call("/mail_plugin/partner/get", {"partner_id": partner.id}) self.assertNotIn("leads", result, msg="The user has no access to crm.lead, the leads section should not be visible") self.user_test.groups_id |= self.env.ref("sales_team.group_sale_salesman_all_leads") lead_1, lead_2 = self.env["crm.lead"].create([ {"name": "Lead Partner 1", "partner_id": partner.id}, {"name": "Lead Partner 2", "partner_id": partner_2.id}, ]) result = self._make_rpc_call("/mail_plugin/partner/get", {"partner_id": partner.id}) self.assertIn( "leads", result, msg="The user has access to crm.lead, the leads section should be visible", ) self.assertTrue([lead for lead in result["leads"] if lead["lead_id"] == lead_1.id], msg="The first lead belongs to the first partner, it should be returned") self.assertFalse([lead for lead in result["leads"] if lead["lead_id"] == lead_2.id], msg="The second lead does not belong to the first partner, it should not be returned") @mock_auth_method_outlook('employee') def test_crm_lead_create_multi_company(self): """ Test that creating a record using the mail plugin for a contact belonging to a different company than the default company of the user does not result in any issues. """ company_a, company_b = self.env['res.company'].create([ {'name': 'Company_A'}, {'name': 'Company_B'}, ]) # create contact belonging to Company_B contact = self.env['res.partner'].create({ 'name': 'John Doe', 'email': '[email protected]', 'company_id': company_b.id, }) # set default company to Company_A self.env.user.company_id = company_a.id self.user_test.groups_id |= self.env.ref('sales_team.group_sale_salesman_all_leads') # Add company_B to user_test to have access to records related to company_B self.user_test.write({'company_ids': [(4, company_b.id)]}) params = { 'partner_id': contact.id, 'email_body': 'test body', 'email_subject': 'test subject', } result = self._make_rpc_call('/mail_plugin/lead/create', params) # Check that the created lead record has the correct company and return the lead_id self.assertIn( 'lead_id', result, msg='The lead_id should be returned in the response', ) created_lead = self.env['crm.lead'].browse(result['lead_id']) self.assertEqual( created_lead.company_id, company_b, msg='The created record should belong to company_B', ) def _make_rpc_call(self, url, params): """ Makes an RPC call to the specified URL with the given parameters, and returns the 'result' key from the response. :param params (dict): A dictionary containing the parameters to send in the RPC call. :param url (str): The URL to send the RPC call to. :return (dict): The 'result' key from the response. """ data = { 'id': 0, 'jsonrpc': '2.0', 'method': 'call', 'params': params, } response = self.url_open( url, data=json.dumps(data).encode(), headers={'Content-Type': 'application/json'} ).json() return response['result']
37.168142
4,200
677
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class Lead(models.Model): _inherit = 'crm.lead' @api.model def _form_view_auto_fill(self): """ deprecated as of saas-14.3, not needed for newer versions of the mail plugin but necessary for supporting older versions """ return { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'crm.lead', 'context': { 'default_partner_id': self.env.context.get('params', {}).get('partner_id'), } }
29.434783
677
3,339
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo.http import request from odoo.tools.misc import formatLang from odoo.addons.mail_plugin.controllers import mail_plugin _logger = logging.getLogger(__name__) class MailPluginController(mail_plugin.MailPluginController): def _fetch_partner_leads(self, partner, limit=5, offset=0): """ Returns an array containing partner leads, each lead will have the following structure : { id: the lead's id, name: the lead's name, expected_revenue: the expected revenue field value probability: the value of the probability field, recurring_revenue: the value of the recurring_revenue field if the lead has a recurring revenue recurring_plan: the value of the recurring plan field if the lead has a recurring revenue } """ partner_leads = request.env['crm.lead'].search( [('partner_id', '=', partner.id)], offset=offset, limit=limit) recurring_revenues = request.env.user.has_group('crm.group_use_recurring_revenues') leads = [] for lead in partner_leads: lead_values = { 'lead_id': lead.id, 'name': lead.name, 'expected_revenue': formatLang(request.env, lead.expected_revenue, monetary=True, currency_obj=lead.company_currency), 'probability': lead.probability, } if recurring_revenues: lead_values.update({ 'recurring_revenue': formatLang(request.env, lead.recurring_revenue, monetary=True, currency_obj=lead.company_currency), 'recurring_plan': lead.recurring_plan.name, }) leads.append(lead_values) return leads def _get_contact_data(self, partner): """ Return the leads key only if the current user can create leads. So, if he can not create leads, the section won't be visible on the addin side (like if the CRM module was not installed on the database). """ contact_values = super(MailPluginController, self)._get_contact_data(partner) if not request.env['crm.lead'].check_access_rights('create', raise_exception=False): return contact_values if not partner: contact_values['leads'] = [] else: contact_values['leads'] = self._fetch_partner_leads(partner) return contact_values def _mail_content_logging_models_whitelist(self): models_whitelist = super(MailPluginController, self)._mail_content_logging_models_whitelist() if not request.env['crm.lead'].check_access_rights('create', raise_exception=False): return models_whitelist return models_whitelist + ['crm.lead'] def _translation_modules_whitelist(self): modules_whitelist = super(MailPluginController, self)._translation_modules_whitelist() if not request.env['crm.lead'].check_access_rights('create', raise_exception=False): return modules_whitelist return modules_whitelist + ['crm_mail_plugin']
41.222222
3,339
2,858
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request from odoo.tools import html2plaintext from .mail_plugin import MailPluginController class CrmClient(MailPluginController): @http.route(route='/mail_client_extension/log_single_mail_content', type="json", auth="outlook", cors="*") def log_single_mail_content(self, lead, message, **kw): """ deprecated as of saas-14.3, not needed for newer versions of the mail plugin but necessary for supporting older versions """ crm_lead = request.env['crm.lead'].browse(lead) crm_lead.message_post(body=message) @http.route('/mail_client_extension/lead/get_by_partner_id', type="json", auth="outlook", cors="*") def crm_lead_get_by_partner_id(self, partner, limit=5, offset=0, **kwargs): """ deprecated as of saas-14.3, not needed for newer versions of the mail plugin but necessary for supporting older versions """ partner_instance = request.env['res.partner'].browse(partner) return {'leads': self._fetch_partner_leads(partner_instance, limit, offset)} @http.route('/mail_client_extension/lead/create_from_partner', type='http', auth='user', methods=['GET']) def crm_lead_redirect_create_form_view(self, partner_id): """ deprecated as of saas-14.3, not needed for newer versions of the mail plugin but necessary for supporting older versions """ server_action = http.request.env.ref("crm_mail_plugin.lead_creation_prefilled_action") return request.redirect( '/web#action=%s&model=crm.lead&partner_id=%s' % (server_action.id, int(partner_id))) @http.route('/mail_plugin/lead/create', type='json', auth='outlook', cors="*") def crm_lead_create(self, partner_id, email_body, email_subject): partner = request.env['res.partner'].browse(partner_id).exists() if not partner: return {'error': 'partner_not_found'} record = request.env['crm.lead'].with_company(partner.company_id).create({ 'name': html2plaintext(email_subject), 'partner_id': partner_id, 'description': email_body, }) return {'lead_id': record.id} @http.route('/mail_client_extension/lead/open', type='http', auth='user') def crm_lead_open(self, lead_id): """ deprecated as of saas-14.3, not needed for newer versions of the mail plugin but necessary for supporting older versions """ action = http.request.env.ref("crm.crm_lead_view_form") url = '/web#id=%s&action=%s&model=crm.lead&edit=1&model=crm.lead' % (lead_id, action.id) return request.redirect(url)
44.65625
2,858
530
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Mass mailing on sale orders', 'category': 'Hidden', 'version': '1.0', 'summary': 'Add sale order UTM info on mass mailing', 'description': """UTM and mass mailing on sale orders""", 'depends': ['sale', 'mass_mailing'], 'data': [ 'views/mailing_mailing_views.xml', ], 'demo': [ 'data/mass_mailing_demo.xml', ], 'auto_install': True, 'license': 'LGPL-3', }
27.894737
530
392
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class SaleOrder(models.Model): _inherit = 'sale.order' _mailing_enabled = True def _mailing_get_default_domain(self, mailing): """ Exclude by default canceled orders when performing a mass mailing. """ return [('state', '!=', 'cancel')]
30.153846
392
366
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class UtmCampaign(models.Model): _inherit = 'utm.campaign' ab_testing_winner_selection = fields.Selection(selection_add=[ ('sale_quotation_count', 'Quotations'), ('sale_invoiced_amount', 'Revenues'), ])
28.153846
366
3,796
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _, tools from odoo.osv import expression class MassMailing(models.Model): _name = 'mailing.mailing' _inherit = 'mailing.mailing' sale_quotation_count = fields.Integer('Quotation Count', groups='sales_team.group_sale_salesman', compute='_compute_sale_quotation_count') sale_invoiced_amount = fields.Integer('Invoiced Amount', groups='sales_team.group_sale_salesman', compute='_compute_sale_invoiced_amount') @api.depends('mailing_domain') def _compute_sale_quotation_count(self): has_so_access = self.env['sale.order'].check_access_rights('read', raise_exception=False) if not has_so_access: self.sale_quotation_count = 0 return for mass_mailing in self: mass_mailing.sale_quotation_count = self.env['sale.order'].search_count(mass_mailing._get_sale_utm_domain()) @api.depends('mailing_domain') def _compute_sale_invoiced_amount(self): if not self.user_has_groups('sales_team.group_sale_salesman') or not self.user_has_groups('account.group_account_invoice'): self.sale_invoiced_amount = 0 return for mass_mailing in self: domain = expression.AND([ mass_mailing._get_sale_utm_domain(), [('state', 'not in', ['draft', 'cancel'])] ]) moves = self.env['account.move'].search_read(domain, ['amount_untaxed_signed']) mass_mailing.sale_invoiced_amount = sum(i['amount_untaxed_signed'] for i in moves) def action_redirect_to_quotations(self): action = self.env["ir.actions.actions"]._for_xml_id("sale.action_quotations_with_onboarding") action['domain'] = self._get_sale_utm_domain() action['context'] = {'create': False} return action def action_redirect_to_invoiced(self): action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_out_invoice_type") moves = self.env['account.move'].search(self._get_sale_utm_domain()) action['context'] = { 'create': False, 'edit': False, 'view_no_maturity': True } action['domain'] = [ ('id', 'in', moves.ids), ('move_type', 'in', ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt')), ('state', 'not in', ['draft', 'cancel']) ] action['context'] = {'create': False} return action def _get_sale_utm_domain(self): res = [] if self.campaign_id: res.append(('campaign_id', '=', self.campaign_id.id)) if self.source_id: res.append(('source_id', '=', self.source_id.id)) if self.medium_id: res.append(('medium_id', '=', self.medium_id.id)) if not res: res.append((0, '=', 1)) return res def _prepare_statistics_email_values(self): self.ensure_one() values = super(MassMailing, self)._prepare_statistics_email_values() if not self.user_id: return values self_with_company = self.with_company(self.user_id.company_id) currency = self.user_id.company_id.currency_id formated_amount = tools.format_decimalized_amount(self_with_company.sale_invoiced_amount, currency) values['kpi_data'][1]['kpi_col2'] = { 'value': self.sale_quotation_count, 'col_subtitle': _('QUOTATIONS'), } values['kpi_data'][1]['kpi_col3'] = { 'value': formated_amount, 'col_subtitle': _('INVOICED'), } values['kpi_data'][1]['kpi_name'] = 'sale' return values
41.714286
3,796
1,968
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # List of contributors: # Jordi Esteve <[email protected]> # Ignacio Ibeas <[email protected]> # Dpto. Consultoría Grupo Opentia <[email protected]> # Pedro M. Baeza <[email protected]> # Carlos Liébana <[email protected]> # Hugo Santos <[email protected]> # Albert Cabedo <[email protected]> # Olivier Colson <[email protected]> # Roberto Lizana <[email protected]> { "name" : "Spain - Accounting (PGCE 2008)", "version" : "5.2", "author" : "Spanish Localization Team", 'category': 'Accounting/Localizations/Account Charts', "description": """ Spanish charts of accounts (PGCE 2008). ======================================== * Defines the following chart of account templates: * Spanish general chart of accounts 2008 * Spanish general chart of accounts 2008 for small and medium companies * Spanish general chart of accounts 2008 for associations * Defines templates for sale and purchase VAT * Defines tax templates * Defines fiscal positions for spanish fiscal legislation * Defines tax reports mod 111, 115 and 303 """, "depends" : [ "account", "base_iban", "base_vat", ], "data" : [ 'data/account_chart_template_data.xml', 'data/account_group.xml', 'data/account.account.template-common.csv', 'data/account.account.template-pymes.csv', 'data/account.account.template-assoc.csv', 'data/account.account.template-full.csv', 'data/account_chart_template_account_account_link.xml', 'data/account_tax_group_data.xml', 'data/account_tax_data.xml', 'data/account_fiscal_position_template_data.xml', 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
35.745455
1,966
263
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.models.chart_template import update_taxes_from_templates def migrate(cr, version): update_taxes_from_templates(cr, 'l10n_es.account_chart_template_common')
37.571429
263
3,297
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, SUPERUSER_ID def migrate(cr, version): # For taxes coming from tax templates, replace grid 61 by the right tag. # For the other ones, we can't guess what to use, and the user will have to change his # config manually, possibly creating a ticket to ask to fix his accounting history. def get_taxes_from_templates(templates): cr.execute(f""" SELECT array_agg(tax.id) FROM account_tax tax JOIN ir_model_data data ON data.model = 'account.tax' AND data.res_id = tax.id AND data.module = 'l10n_es' AND data.name ~ '^[0-9]*_({'|'.join(templates)})\\Z' """) return cr.fetchone()[0] env = api.Environment(cr, SUPERUSER_ID, {}) templates_mapping = { 'mod_303_120': ['account_tax_template_s_iva_ns', 'account_tax_template_s_iva_ns_b'], 'mod_303_122': ['account_tax_template_s_iva_e', 'account_tax_template_s_iva0_isp'], } # To run in a server action to fix issues on dbs with custom taxes, # replace the content of this dict. taxes_mapping = {} for tag_name, template_names in templates_mapping.items(): taxes_from_templates = get_taxes_from_templates(template_names) if taxes_from_templates: taxes_mapping[tag_name] = taxes_from_templates old_tag = env.ref('l10n_es.mod_303_61') for tag_name, tax_ids in taxes_mapping.items(): # Grid 61 is only for base repartition. # If it was used for taxes repartition, we don't touch it (and it'll require manual check, # as the BOE file probably won't pass government checks). new_tag = env.ref(f'l10n_es.{tag_name}') # Change tax config cr.execute(""" UPDATE account_account_tag_account_tax_repartition_line_rel tax_rep_tag SET account_account_tag_id = %s FROM account_account_tag new_tag, account_tax_repartition_line repln WHERE tax_rep_tag.account_account_tag_id = %s AND repln.id = tax_rep_tag.account_tax_repartition_line_id AND COALESCE(repln.invoice_tax_id, repln.refund_tax_id) IN %s """, [new_tag.id, old_tag.id, tuple(tax_ids)]) # Change amls in history, starting at Q3 2021 (date of introduction for the new tags) # Set tags cr.execute(""" UPDATE account_account_tag_account_move_line_rel aml_tag SET account_account_tag_id = %s FROM account_move_line aml, account_move_line_account_tax_rel aml_tax WHERE aml_tag.account_move_line_id = aml.id AND aml_tax.account_move_line_id = aml.id AND aml.date >= '2021-07-01' AND aml_tax.account_tax_id IN %s AND aml_tag.account_account_tag_id = %s """, [new_tag.id, tuple(tax_ids), old_tag.id]) # Fix tax audit string cr.execute(""" UPDATE account_move_line aml SET tax_audit = REPLACE(tax_audit, %s, %s) FROM account_account_tag_account_move_line_rel aml_tag WHERE aml_tag.account_move_line_id = aml.id AND aml_tag.account_account_tag_id = %s """, [old_tag.name, f"{new_tag.name}:", new_tag.id])
42.818182
3,297
263
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.models.chart_template import update_taxes_from_templates def migrate(cr, version): update_taxes_from_templates(cr, 'l10n_es.account_chart_template_common')
37.571429
263
473
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'OdooBot for livechat', 'version': '1.0', 'category': 'Productivity/Discuss', 'summary': 'Add livechat support for OdooBot', 'description': "", 'website': 'https://www.odoo.com/app/discuss', 'depends': ['mail_bot', 'im_livechat'], 'installable': True, 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
29.5625
473
391
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class Users(models.Model): _inherit = 'res.users' odoobot_state = fields.Selection(selection_add=[ ('onboarding_canned', 'Onboarding canned'), ], ondelete={'onboarding_canned': lambda users: users.write({'odoobot_state': 'disabled'})})
32.583333
391
1,505
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class MailBot(models.AbstractModel): _inherit = 'mail.bot' def _get_answer(self, record, body, values, command): odoobot_state = self.env.user.odoobot_state if self._is_bot_in_private_channel(record): if odoobot_state == "onboarding_attachement" and values.get("attachment_ids"): self.env.user.odoobot_failed = False self.env.user.odoobot_state = "onboarding_canned" return _("That's me! 🎉<br/>Try typing <span class=\"o_odoobot_command\">:</span> to use canned responses.") elif odoobot_state == "onboarding_canned" and values.get("canned_response_ids"): self.env.user.odoobot_failed = False self.env.user.odoobot_state = "idle" return _("Good, you can customize canned responses in the live chat application.<br/><br/><b>It's the end of this overview</b>, enjoy discovering Odoo!") # repeat question if needed elif odoobot_state == 'onboarding_canned' and not self._is_help_requested(body): self.env.user.odoobot_failed = True return _("Not sure what you are doing. Please, type <span class=\"o_odoobot_command\">:</span> and wait for the propositions. Select one of them and press enter.") return super(MailBot, self)._get_answer(record, body, values, command)
60.08
1,502
980
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Collaborative Pads', 'version': '2.0', 'category': 'Hidden/Tools', 'description': """ Adds enhanced support for (Ether)Pad attachments in the web client. =================================================================== Lets the company customize which Pad installation should be used to link to new pads (by default, http://etherpad.com/). """, 'depends': ['web', 'base_setup'], 'data': [ 'views/res_config_settings_views.xml', ], 'demo': ['data/pad_demo.xml'], 'web': True, 'assets': { 'web.assets_backend': [ 'pad/static/src/css/etherpad.css', 'pad/static/src/js/pad.js', ], 'web.qunit_suite_tests': [ 'pad/static/tests/**/*', ], 'web.assets_qweb': [ 'pad/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
28.823529
980
6,034
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import random import re import string import requests from markupsafe import Markup from odoo import api, models, _ from odoo.exceptions import UserError from ..py_etherpad import EtherpadLiteClient _logger = logging.getLogger(__name__) class PadCommon(models.AbstractModel): _name = 'pad.common' _description = 'Pad Common' def _valid_field_parameter(self, field, name): return name == 'pad_content_field' or super()._valid_field_parameter(field, name) @api.model def pad_is_configured(self): return bool(self.env['ir.config_parameter'].sudo().get_param('pad.pad_server')) @api.model def pad_generate_url(self): pad = { "server": self.env['ir.config_parameter'].sudo().get_param('pad.pad_server'), "key": self.env['ir.config_parameter'].sudo().get_param('pad.pad_key'), } # make sure pad server in the form of http://hostname if not pad["server"]: return pad if not pad["server"].startswith('http'): pad["server"] = 'http://' + pad["server"] pad["server"] = pad["server"].rstrip('/') # generate a salt s = string.ascii_uppercase + string.digits salt = ''.join([s[random.SystemRandom().randint(0, len(s) - 1)] for i in range(10)]) # path # etherpad hardcodes pad id length limit to 50 path = '-%s-%s' % (self._name, salt) path = '%s%s' % (self.env.cr.dbname.replace('_', '-')[0:50 - len(path)], path) # contruct the url url = '%s/p/%s' % (pad["server"], path) # if create with content if self.env.context.get('field_name') and self.env.context.get('model'): myPad = EtherpadLiteClient(pad["key"], pad["server"] + '/api') try: myPad.createPad(path) except IOError: raise UserError(_("Pad creation failed, either there is a problem with your pad server URL or with your connection.")) # get attr on the field model model = self.env[self.env.context["model"]] field = model._fields[self.env.context['field_name']] real_field = field.pad_content_field res_id = self.env.context.get("object_id") record = model.browse(res_id) # get content of the real field real_field_value = record[real_field] or self.env.context.get('record', {}).get(real_field, '') if real_field_value: myPad.setHtmlFallbackText(path, real_field_value) return { "server": pad["server"], "path": path, "url": url, } @api.model def pad_get_content(self, url): pad = { "server": self.env['ir.config_parameter'].sudo().get_param('pad.pad_server'), "key": self.env['ir.config_parameter'].sudo().get_param('pad.pad_key'), } myPad = EtherpadLiteClient(pad['key'], (pad['server'] or '') + '/api') content = '' if url: split_url = url.split('/p/') path = len(split_url) == 2 and split_url[1] try: content = myPad.getHtml(path).get('html', '') except IOError: _logger.warning('Http Error: the credentials might be absent for url: "%s". Falling back.' % url) try: r = requests.get('%s/export/html' % url) r.raise_for_status() except Exception: _logger.warning("No pad found with url '%s'.", url) else: mo = re.search('<body>(.*)</body>', r.content.decode(), re.DOTALL) if mo: content = mo.group(1) return Markup(content) # TODO # reverse engineer protocol to be setHtml without using the api key def write(self, vals): self._set_field_to_pad(vals) self._set_pad_to_field(vals) return super(PadCommon, self).write(vals) @api.model def create(self, vals): # Case of a regular creation: we receive the pad url, so we need to update the # corresponding field self._set_pad_to_field(vals) pad = super(PadCommon, self).create(vals) # Case of a programmatical creation (e.g. copy): we receive the field content, so we need # to create the corresponding pad if self.env.context.get('pad_no_create', False): return pad for k, field in self._fields.items(): if hasattr(field, 'pad_content_field') and k not in vals: ctx = { 'model': self._name, 'field_name': k, 'object_id': pad.id, } pad_info = self.with_context(**ctx).pad_generate_url() pad[k] = pad_info.get('url') return pad def _set_field_to_pad(self, vals): # Update the pad if the `pad_content_field` is modified for k, field in self._fields.items(): if hasattr(field, 'pad_content_field') and vals.get(field.pad_content_field) and self[k]: pad = { "server": self.env['ir.config_parameter'].sudo().get_param('pad.pad_server'), "key": self.env['ir.config_parameter'].sudo().get_param('pad.pad_key'), } myPad = EtherpadLiteClient(pad['key'], (pad['server'] or '') + '/api') path = self[k].split('/p/')[1] myPad.setHtmlFallbackText(path, vals[field.pad_content_field]) def _set_pad_to_field(self, vals): # Update the `pad_content_field` if the pad is modified for k, v in list(vals.items()): field = self._fields.get(k) if hasattr(field, 'pad_content_field'): vals[field.pad_content_field] = self.pad_get_content(v)
39.181818
6,034
385
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' pad_server = fields.Char(config_parameter='pad.pad_server', string="Pad Server") pad_key = fields.Char(config_parameter='pad.pad_key', string="Pad API Key")
35
385
906
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Kenya - Accounting', 'version': '1.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This provides a base chart of accounts and taxes template for use in Odoo. """, 'author': 'Odoo S.A.', 'depends': [ 'account', ], 'data': [ 'data/account_chart_template_data.xml', 'data/account.account.template.csv', 'data/l10n_ke_chart_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_template_data.xml', 'data/account_fiscal_position_template.xml', 'data/account_chart_template_configure_data.xml', 'data/menu_item_data.xml', ], 'demo': [ 'demo/demo_company.xml' ], 'license': 'LGPL-3', }
30.2
906
290
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Germany - Stock', 'category': 'Accounting/Localizations', 'depends': [ 'l10n_de', 'stock', ], 'auto_install': True, 'license': 'LGPL-3', }
22.307692
290
1,144
py
PYTHON
15.0
from odoo import models, fields, _ from odoo.tools import format_date class StockPicking(models.Model): _inherit = 'stock.picking' l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data') l10n_de_addresses = fields.Binary(compute='_compute_l10n_de_addresses') def _compute_l10n_de_template_data(self): self.l10n_de_template_data = [] def _compute_l10n_de_addresses(self): for record in self: record.l10n_de_addresses = data = [] if record.partner_id: if record.picking_type_id.code == 'incoming': data.append((_('Vendor Address:'), record.partner_id)) if record.picking_type_id.code == 'internal': data.append((_('Warehouse Address:'), record.partner_id)) if record.picking_type_id.code == 'outgoing' and record.move_ids_without_package and record.move_ids_without_package[0].partner_id \ and record.move_ids_without_package[0].partner_id.id != record.partner_id.id: data.append((_('Customer Address:'), record.partner_id))
47.666667
1,144
514
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Mass mailing on attendees', 'category': 'Hidden', 'version': '1.0', 'description': """ Mass mail event attendees ========================= Bridge module adding UX requirements to ease mass mailing of event attendees. """, 'depends': ['event', 'mass_mailing'], 'data': [ 'views/event_views.xml' ], 'auto_install': True, 'license': 'LGPL-3', }
24.47619
514
325
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class EventRegistration(models.Model): _inherit = 'event.registration' _mailing_enabled = True def _mailing_get_default_domain(self, mailing): return [('state', '!=', 'cancel')]
27.083333
325
1,055
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class Event(models.Model): _inherit = "event.event" def action_mass_mailing_attendees(self): return { 'name': 'Mass Mail Attendees', 'type': 'ir.actions.act_window', 'res_model': 'mailing.mailing', 'view_mode': 'form', 'target': 'current', 'context': { 'default_mailing_model_id': self.env.ref('event.model_event_registration').id, 'default_mailing_domain': repr([('event_id', 'in', self.ids), ('state', '!=', 'cancel')]) }, } def action_invite_contacts(self): return { 'name': 'Mass Mail Invitation', 'type': 'ir.actions.act_window', 'res_model': 'mailing.mailing', 'view_mode': 'form', 'target': 'current', 'context': {'default_mailing_model_id': self.env.ref('base.model_res_partner').id}, }
34.032258
1,055
4,537
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Email Marketing', 'summary': 'Design, send and track emails', 'description': "", 'version': '2.5', 'sequence': 60, 'website': 'https://www.odoo.com/app/email-marketing', 'category': 'Marketing/Email Marketing', 'depends': [ 'contacts', 'mail', 'utm', 'link_tracker', 'web_editor', 'web_kanban_gauge', 'social_media', 'web_tour', 'digest', ], 'data': [ 'security/mass_mailing_security.xml', 'security/ir.model.access.csv', 'data/mail_data.xml', 'data/mailing_data_templates.xml', 'data/mass_mailing_data.xml', 'data/ir_attachment_data.xml', 'wizard/mail_compose_message_views.xml', 'wizard/mailing_contact_to_list_views.xml', 'wizard/mailing_list_merge_views.xml', 'wizard/mailing_mailing_test_views.xml', 'wizard/mailing_mailing_schedule_date_views.xml', 'views/mailing_mailing_views_menus.xml', 'views/mailing_trace_views.xml', 'views/link_tracker_views.xml', 'views/mailing_contact_views.xml', 'views/mailing_list_views.xml', 'views/mailing_mailing_views.xml', 'views/res_config_settings_views.xml', 'views/utm_campaign_views.xml', 'report/mailing_trace_report_views.xml', 'views/assets.xml', 'views/mass_mailing_templates_portal.xml', 'views/themes_templates.xml', 'views/snippets_themes.xml', 'views/snippets/s_alert.xml', 'views/snippets/s_blockquote.xml', 'views/snippets/s_call_to_action.xml', 'views/snippets/s_coupon_code.xml', 'views/snippets/s_cover.xml', 'views/snippets/s_color_blocks_2.xml', 'views/snippets/s_company_team.xml', 'views/snippets/s_comparisons.xml', 'views/snippets/s_features.xml', 'views/snippets/s_features_grid.xml', 'views/snippets/s_hr.xml', 'views/snippets/s_image_text.xml', 'views/snippets/s_masonry_block.xml', 'views/snippets/s_media_list.xml', 'views/snippets/s_numbers.xml', 'views/snippets/s_picture.xml', 'views/snippets/s_product_list.xml', 'views/snippets/s_rating.xml', 'views/snippets/s_references.xml', 'views/snippets/s_showcase.xml', 'views/snippets/s_text_block.xml', 'views/snippets/s_text_highlight.xml', 'views/snippets/s_text_image.xml', 'views/snippets/s_three_columns.xml', 'views/snippets/s_title.xml', ], 'demo': [ 'data/mass_mailing_demo.xml', ], 'application': True, 'assets': { 'web.assets_backend': [ 'mass_mailing/static/src/scss/mass_mailing.scss', 'mass_mailing/static/src/scss/mass_mailing_mobile.scss', 'mass_mailing/static/src/css/email_template.css', 'mass_mailing/static/src/js/mass_mailing.js', 'mass_mailing/static/src/js/mass_mailing_widget.js', 'mass_mailing/static/src/js/mailing_mailing_view_form_full_width.js', 'mass_mailing/static/src/js/unsubscribe.js', ], 'mass_mailing.assets_mail_themes': [ 'mass_mailing/static/src/scss/themes/**/*', ], 'mass_mailing.assets_mail_themes_edition': [ ('include', 'web._assets_helpers'), 'web/static/lib/bootstrap/scss/_variables.scss', 'mass_mailing/static/src/scss/mass_mailing.ui.scss', ], 'web_editor.assets_wysiwyg': [ 'mass_mailing/static/src/js/snippets.editor.js', 'mass_mailing/static/src/js/wysiwyg.js', ], 'web.assets_common': [ 'mass_mailing/static/src/js/tours/**/*', ], 'web.qunit_suite_tests': [ 'mass_mailing/static/tests/field_html_test.js', 'mass_mailing/static/src/js/mass_mailing_snippets.js', 'mass_mailing/static/src/snippets/s_blockquote/options.js', 'mass_mailing/static/src/snippets/s_media_list/options.js', 'mass_mailing/static/src/snippets/s_showcase/options.js', 'mass_mailing/static/src/snippets/s_rating/options.js', 'mass_mailing/static/tests/mass_mailing_html_tests.js', ], 'web.assets_qweb': [ 'mass_mailing/static/src/xml/*.xml', ], }, 'license': 'LGPL-3', }
38.777778
4,537
6,961
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from freezegun import freeze_time from odoo.addons.base.tests.test_ir_cron import CronMixinCase from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.tests import users, Form from odoo.tools import mute_logger class TestMailingScheduleDateWizard(MassMailCommon, CronMixinCase): @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') def test_mailing_next_departure(self): # test if mailing.mailing.next_departure is correctly set taking into account # presence of implicitly created cron triggers (since odoo v15). These should # launch cron job before its schedule nextcall datetime (if scheduled_date < nextcall) cron_job = self.env.ref('mass_mailing.ir_cron_mass_mailing_queue').sudo() cron_job.write({'nextcall' : datetime(2023, 2, 18, 9, 0)}) cron_job_id = cron_job.id # case where user click on "Send" button (action_launch) with freeze_time(datetime(2023, 2, 17, 9, 0)): with self.capture_triggers(cron_job_id) as capt: mailing = self.env['mailing.mailing'].create({ 'name': 'mailing', 'subject': 'some subject', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'state' : 'draft' }) mailing.action_launch() capt.records.ensure_one() # assert that the schedule_date and schedule_type fields are correct and that the mailing is put in queue self.assertEqual(mailing.next_departure, datetime(2023, 2, 17, 9, 0)) self.assertIsNot(mailing.schedule_date, cron_job.nextcall) self.assertEqual(mailing.schedule_type, 'now') self.assertEqual(mailing.state, 'in_queue') self.assertEqual(capt.records.call_at, datetime(2023, 2, 17, 9, 0)) #verify that cron.trigger exists # case where client uses schedule wizard to chose a date between now and cron.job nextcall with freeze_time(datetime(2023, 2, 17, 9, 0)): with self.capture_triggers(cron_job_id) as capt: mailing = self.env['mailing.mailing'].create({ 'name': 'mailing', 'subject': 'some subject', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'state' : 'draft', 'schedule_date' : datetime(2023, 2, 17, 11, 0), 'schedule_type' : 'scheduled' }) mailing.action_schedule() capt.records.ensure_one() self.assertEqual(mailing.schedule_date, datetime(2023, 2, 17, 11, 0)) self.assertEqual(mailing.next_departure, datetime(2023, 2, 17, 11, 0)) self.assertEqual(mailing.schedule_type, 'scheduled') self.assertEqual(mailing.state, 'in_queue') self.assertEqual(capt.records.call_at, datetime(2023, 2, 17, 11, 0)) #verify that cron.trigger exists # case where client uses schedule wizard to chose a date after cron.job nextcall # which means mails will get send after that date (datetime(2023, 2, 18, 9, 0)) with freeze_time(datetime(2023, 2, 17, 9, 0)): with self.capture_triggers(cron_job_id) as capt: mailing = self.env['mailing.mailing'].create({ 'name': 'mailing', 'subject': 'some subject', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'state' : 'draft', 'schedule_date' : datetime(2024, 2, 17, 11, 0), 'schedule_type' : 'scheduled' }) mailing.action_schedule() capt.records.ensure_one() self.assertEqual(mailing.schedule_date, datetime(2024, 2, 17, 11, 0)) self.assertEqual(mailing.next_departure, datetime(2024, 2, 17, 11, 0)) self.assertEqual(mailing.schedule_type, 'scheduled') self.assertEqual(mailing.state, 'in_queue') self.assertEqual(capt.records.call_at, datetime(2024, 2, 17, 11, 0)) #verify that cron.trigger exists # case where client uses schedule wizard to chose a date in the past with freeze_time(datetime(2023, 2, 17, 9, 0)): with self.capture_triggers(cron_job_id) as capt: mailing = self.env['mailing.mailing'].create({ 'name': 'mailing', 'subject': 'some subject', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'state' : 'draft', 'schedule_date' : datetime(2024, 2, 17, 11, 0), 'schedule_type' : 'scheduled' }) # create a schedule date wizard # Have to use wizard for this case to simulate schedule date in the past # Otherwise "state" doesn't get update from draft to'in_queue' # in test env vs production env (see mailing.mailing.schedule.date wizard) wizard_form = Form( self.env['mailing.mailing.schedule.date'].with_context(default_mass_mailing_id=mailing.id)) # set a schedule date wizard_form.schedule_date = datetime(2022, 2, 17, 11, 0) wizard = wizard_form.save() wizard.action_schedule_date() capt.records.ensure_one() self.assertEqual(mailing.schedule_date, datetime(2022, 2, 17, 11, 0)) self.assertEqual(mailing.next_departure, datetime(2023, 2, 17, 9, 0)) #now self.assertEqual(mailing.schedule_type, 'scheduled') self.assertEqual(mailing.state, 'in_queue') self.assertEqual(capt.records.call_at, datetime(2022, 2, 17, 11, 0)) #verify that cron.trigger exists def test_mailing_schedule_date(self): mailing = self.env['mailing.mailing'].create({ 'name': 'mailing', 'subject': 'some subject', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) # create a schedule date wizard wizard_form = Form( self.env['mailing.mailing.schedule.date'].with_context(default_mass_mailing_id=mailing.id)) # set a schedule date wizard_form.schedule_date = datetime(2021, 4, 30, 9, 0) wizard = wizard_form.save() wizard.action_schedule_date() # assert that the schedule_date and schedule_type fields are correct and that the mailing is put in queue self.assertEqual(mailing.schedule_date, datetime(2021, 4, 30, 9, 0)) self.assertEqual(mailing.schedule_type, 'scheduled') self.assertEqual(mailing.state, 'in_queue')
51.562963
6,961
1,605
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.tests.common import HttpCase class TestMassMailingControllers(MassMailCommon, HttpCase): def test_tracking_url_token(self): mail_mail = self.env['mail.mail'].create({}) response = self.url_open(mail_mail._get_tracking_url()) self.assertEqual(response.status_code, 200) base_url = mail_mail.get_base_url() url = werkzeug.urls.url_join(base_url, 'mail/track/%s/fake_token/blank.gif' % mail_mail.id) response = self.url_open(url) self.assertEqual(response.status_code, 400) def test_mailing_view(self): mailing = self.env['mailing.mailing'].create({ 'name': 'TestMailing', 'subject': 'Test', 'mailing_type': 'mail', 'body_html': '<p>Hello <t t-out="object.name" contenteditable="false" data-oe-t-inline="true"></t></p>', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) partner_id = self.user_admin.partner_id self.authenticate('admin', 'admin') url = werkzeug.urls.url_join(mailing.get_base_url(), '/mailing/%s/view?res_id=%s' % (mailing.id, partner_id.id)) response = self.url_open(url) self.assertEqual(response.status_code, 200) self.assertNotIn('<t t-out', response.text) self.assertNotIn('</t>', response.text) self.assertIn("<p>Hello %s</p>" % partner_id.name, response.text)
38.214286
1,605
1,439
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests from odoo.addons.base.tests.common import HttpCaseWithUserDemo @odoo.tests.tagged('-at_install', 'post_install') class TestUi(HttpCaseWithUserDemo): def setUp(self): super().setUp() self.user_demo.groups_id |= self.env.ref('mass_mailing.group_mass_mailing_user') self.user_demo.groups_id |= self.env.ref('mail.group_mail_template_editor') def test_01_mass_mailing_editor_tour(self): self.start_tour("/web", 'mass_mailing_editor_tour', login="demo") mail = self.env['mailing.mailing'].search([('subject', '=', 'Test')])[0] # The tour created and saved an email. The edited version should be # saved in body_arch, and its transpiled version (see convert_inline) # for email client compatibility should be saved in body_html. This # ensures both fields have different values (the mailing body should # have been converted to a table in body_html). self.assertIn('data-snippet="s_title"', mail.body_arch) self.assertTrue(mail.body_arch.startswith('<div')) self.assertIn('data-snippet="s_title"', mail.body_html) self.assertTrue(mail.body_html.startswith('<table')) def test_02_mass_mailing_snippets_menu_tabs(self): self.start_tour("/web", 'mass_mailing_snippets_menu_tabs', login="demo")
49.62069
1,439
15,617
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from ast import literal_eval from datetime import datetime from freezegun import freeze_time from odoo.addons.base.tests.test_ir_cron import CronMixinCase from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.tests.common import users, Form from odoo.tools import formataddr, mute_logger class TestMassMailValues(MassMailCommon): @classmethod def setUpClass(cls): super(TestMassMailValues, cls).setUpClass() cls._create_mailing_list() @users('user_marketing') def test_mailing_body_responsive(self): """ Testing mail mailing responsive mail body Reference: https://litmus.com/community/learning/24-how-to-code-a-responsive-email-from-scratch https://www.campaignmonitor.com/css/link-element/link-in-head/ This template is meant to put inline CSS into an email's head """ recipient = self.env['res.partner'].create({ 'name': 'Mass Mail Partner', 'email': 'Customer <[email protected]>', }) mailing = self.env['mailing.mailing'].create({ 'name': 'Test', 'subject': 'Test', 'state': 'draft', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) composer = self.env['mail.compose.message'].with_user(self.user_marketing).with_context({ 'default_composition_mode': 'mass_mail', 'default_model': 'res.partner', 'default_res_id': recipient.id, }).create({ 'subject': 'Mass Mail Responsive', 'body': 'I am Responsive body', 'mass_mailing_id': mailing.id }) mail_values = composer.get_mail_values([recipient.id]) body_html = mail_values[recipient.id]['body_html'] self.assertIn('<!DOCTYPE html>', body_html) self.assertIn('<head>', body_html) self.assertIn('viewport', body_html) # This is important: we need inline css, and not <link/> self.assertIn('@media', body_html) self.assertIn('I am Responsive body', body_html) @users('user_marketing') def test_mailing_computed_fields(self): # Create on res.partner, with default values for computed fields mailing = self.env['mailing.mailing'].create({ 'name': 'TestMailing', 'subject': 'Test', 'mailing_type': 'mail', 'body_html': '<p>Hello <t t-out="object.name"/></p>', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) self.assertEqual(mailing.user_id, self.user_marketing) self.assertEqual(mailing.medium_id, self.env.ref('utm.utm_medium_email')) self.assertEqual(mailing.mailing_model_name, 'res.partner') self.assertEqual(mailing.mailing_model_real, 'res.partner') self.assertEqual(mailing.reply_to_mode, 'new') self.assertEqual(mailing.reply_to, self.user_marketing.email_formatted) # default for partner: remove blacklisted self.assertEqual(literal_eval(mailing.mailing_domain), [('is_blacklisted', '=', False)]) # update domain mailing.write({ 'mailing_domain': [('email', 'ilike', 'test.example.com')] }) self.assertEqual(literal_eval(mailing.mailing_domain), [('email', 'ilike', 'test.example.com')]) # reset mailing model -> reset domain; set reply_to -> keep it mailing.write({ 'mailing_model_id': self.env['ir.model']._get('mailing.list').id, 'reply_to': self.email_reply_to, }) self.assertEqual(mailing.mailing_model_name, 'mailing.list') self.assertEqual(mailing.mailing_model_real, 'mailing.contact') self.assertEqual(mailing.reply_to_mode, 'new') self.assertEqual(mailing.reply_to, self.email_reply_to) # default for mailing list: depends upon contact_list_ids self.assertEqual(literal_eval(mailing.mailing_domain), [('list_ids', 'in', [])]) mailing.write({ 'contact_list_ids': [(4, self.mailing_list_1.id), (4, self.mailing_list_2.id)] }) self.assertEqual(literal_eval(mailing.mailing_domain), [('list_ids', 'in', (self.mailing_list_1 | self.mailing_list_2).ids)]) # reset mailing model -> reset domain and reply to mode mailing.write({ 'mailing_model_id': self.env['ir.model']._get('mail.channel').id, }) self.assertEqual(mailing.mailing_model_name, 'mail.channel') self.assertEqual(mailing.mailing_model_real, 'mail.channel') self.assertEqual(mailing.reply_to_mode, 'update') self.assertFalse(mailing.reply_to) @users('user_marketing') def test_mailing_computed_fields_default(self): mailing = self.env['mailing.mailing'].with_context( default_mailing_domain=repr([('email', 'ilike', 'test.example.com')]) ).create({ 'name': 'TestMailing', 'subject': 'Test', 'mailing_type': 'mail', 'body_html': '<p>Hello <t t-out="object.name"/></p>', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) self.assertEqual(literal_eval(mailing.mailing_domain), [('email', 'ilike', 'test.example.com')]) @users('user_marketing') def test_mailing_computed_fields_form(self): mailing_form = Form(self.env['mailing.mailing'].with_context( default_mailing_domain="[('email', 'ilike', 'test.example.com')]", default_mailing_model_id=self.env['ir.model']._get('res.partner').id, )) self.assertEqual( literal_eval(mailing_form.mailing_domain), [('email', 'ilike', 'test.example.com')], ) self.assertEqual(mailing_form.mailing_model_real, 'res.partner') class TestMassMailFeatures(MassMailCommon, CronMixinCase): @classmethod def setUpClass(cls): super(TestMassMailFeatures, cls).setUpClass() cls._create_mailing_list() @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_cron_trigger(self): """ Technical test to ensure the cron is triggered at the correct time """ cron_id = self.env.ref('mass_mailing.ir_cron_mass_mailing_queue').id partner = self.env['res.partner'].create({ 'name': 'Jean-Alphonce', 'email': '[email protected]', }) common_mailing_values = { 'name': 'Knock knock', 'subject': "Who's there?", 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'mailing_domain': [('id', '=', partner.id)], 'body_html': 'The marketing mailing test.', 'schedule_type': 'scheduled', } now = datetime(2021, 2, 5, 16, 43, 20) then = datetime(2021, 2, 7, 12, 0, 0) with freeze_time(now): for (test, truth) in [(False, now), (then, then)]: with self.subTest(schedule_date=test): with self.capture_triggers(cron_id) as capt: mailing = self.env['mailing.mailing'].create({ **common_mailing_values, 'schedule_date': test, }) mailing.action_put_in_queue() capt.records.ensure_one() self.assertLessEqual(capt.records.call_at, truth) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_deletion(self): """ Test deletion in various use case, depending on reply-to """ # 1- Keep archives and reply-to set to 'answer = new thread' mailing = self.env['mailing.mailing'].create({ 'name': 'TestSource', 'subject': 'TestDeletion', 'body_html': "<div>Hello {object.name}</div>", 'mailing_model_id': self.env['ir.model']._get('mailing.list').id, 'contact_list_ids': [(6, 0, self.mailing_list_1.ids)], 'keep_archives': True, 'reply_to_mode': 'new', 'reply_to': self.email_reply_to, }) self.assertEqual(self.mailing_list_1.contact_ids.message_ids, self.env['mail.message']) with self.mock_mail_gateway(mail_unlink_sent=True): mailing.action_send_mail() self.assertEqual(len(self._mails), 3) self.assertEqual(len(self._new_mails.exists()), 3) self.assertEqual(len(self.mailing_list_1.contact_ids.message_ids), 3) # 2- Keep archives and reply-to set to 'answer = update thread' self.mailing_list_1.contact_ids.message_ids.unlink() mailing = mailing.copy() mailing.write({ 'reply_to_mode': 'update', }) self.assertEqual(self.mailing_list_1.contact_ids.message_ids, self.env['mail.message']) with self.mock_mail_gateway(mail_unlink_sent=True): mailing.action_send_mail() self.assertEqual(len(self._mails), 3) self.assertEqual(len(self._new_mails.exists()), 3) self.assertEqual(len(self.mailing_list_1.contact_ids.message_ids), 3) # 3- Remove archives and reply-to set to 'answer = new thread' self.mailing_list_1.contact_ids.message_ids.unlink() mailing = mailing.copy() mailing.write({ 'keep_archives': False, 'reply_to_mode': 'new', 'reply_to': self.email_reply_to, }) self.assertEqual(self.mailing_list_1.contact_ids.message_ids, self.env['mail.message']) with self.mock_mail_gateway(mail_unlink_sent=True): mailing.action_send_mail() self.assertEqual(len(self._mails), 3) self.assertEqual(len(self._new_mails.exists()), 0) self.assertEqual(self.mailing_list_1.contact_ids.message_ids, self.env['mail.message']) # 4- Remove archives and reply-to set to 'answer = update thread' # Imply keeping mail.message for gateway reply) self.mailing_list_1.contact_ids.message_ids.unlink() mailing = mailing.copy() mailing.write({ 'keep_archives': False, 'reply_to_mode': 'update', }) self.assertEqual(self.mailing_list_1.contact_ids.message_ids, self.env['mail.message']) with self.mock_mail_gateway(mail_unlink_sent=True): mailing.action_send_mail() self.assertEqual(len(self._mails), 3) self.assertEqual(len(self._new_mails.exists()), 0) self.assertEqual(len(self.mailing_list_1.contact_ids.message_ids), 3) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_on_res_partner(self): """ Test mailing on res.partner model: ensure default recipients are correctly computed """ partner_a = self.env['res.partner'].create({ 'name': 'test email 1', 'email': '[email protected]', }) partner_b = self.env['res.partner'].create({ 'name': 'test email 2', 'email': '[email protected]', }) self.env['mail.blacklist'].create({'email': '[email protected]',}) mailing = self.env['mailing.mailing'].create({ 'name': 'One', 'subject': 'One', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'mailing_domain': [('id', 'in', (partner_a | partner_b).ids)], 'body_html': 'This is mass mail marketing demo' }) mailing.action_put_in_queue() with self.mock_mail_gateway(mail_unlink_sent=False): mailing._process_mass_mailing_queue() self.assertMailTraces( [{'partner': partner_a}, {'partner': partner_b, 'trace_status': 'cancel', 'failure_type': 'mail_bl'}], mailing, partner_a + partner_b, check_mail=True ) @users('user_marketing') @mute_logger('odoo.addons.mail.models.mail_mail') def test_mailing_shortener(self): mailing = self.env['mailing.mailing'].create({ 'name': 'TestSource', 'subject': 'TestShortener', 'body_html': """<div> Hi, <t t-set="url" t-value="'www.odoo.com'"/> <t t-set="httpurl" t-value="'https://www.odoo.eu'"/> Website0: <a id="url0" t-attf-href="https://www.odoo.tz/my/{{object.name}}">https://www.odoo.tz/my/<t t-esc="object.name"/></a> Website1: <a id="url1" href="https://www.odoo.be">https://www.odoo.be</a> Website2: <a id="url2" t-attf-href="https://{{url}}">https://<t t-esc="url"/></a> Website3: <a id="url3" t-att-href="httpurl"><t t-esc="httpurl"/></a> External1: <a id="url4" href="https://www.example.com/foo/bar?baz=qux">Youpie</a> Email: <a id="url5" href="mailto:[email protected]">[email protected]</a></div>""", 'mailing_model_id': self.env['ir.model']._get('mailing.list').id, 'reply_to_mode': 'new', 'reply_to': self.email_reply_to, 'contact_list_ids': [(6, 0, self.mailing_list_1.ids)], 'keep_archives': True, }) mailing.action_put_in_queue() with self.mock_mail_gateway(mail_unlink_sent=False): mailing._process_mass_mailing_queue() self.assertMailTraces( [{'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]'}], mailing, self.mailing_list_1.contact_ids, check_mail=True ) for contact in self.mailing_list_1.contact_ids: new_mail = self._find_mail_mail_wrecord(contact) for link_info in [('url0', 'https://www.odoo.tz/my/%s' % contact.name, True), ('url1', 'https://www.odoo.be', True), ('url2', 'https://www.odoo.com', True), ('url3', 'https://www.odoo.eu', True), ('url4', 'https://www.example.com/foo/bar?baz=qux', True), ('url5', 'mailto:[email protected]', False)]: # TDE FIXME: why going to mail message id ? mail.body_html seems to fail, check link_params = {'utm_medium': 'Email', 'utm_source': mailing.name} if link_info[0] == 'url4': link_params['baz'] = 'qux' self.assertLinkShortenedHtml( new_mail.mail_message_id.body, link_info, link_params=link_params, ) class TestMailingScheduleDateWizard(MassMailCommon): @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') def test_mailing_schedule_date(self): mailing = self.env['mailing.mailing'].create({ 'name': 'mailing', 'subject': 'some subject' }) # create a schedule date wizard wizard_form = Form( self.env['mailing.mailing.schedule.date'].with_context(default_mass_mailing_id=mailing.id)) # set a schedule date wizard_form.schedule_date = datetime(2021, 4, 30, 9, 0) wizard = wizard_form.save() wizard.action_schedule_date() # assert that the schedule_date and schedule_type fields are correct and that the mailing is put in queue self.assertEqual(mailing.schedule_date, datetime(2021, 4, 30, 9, 0)) self.assertEqual(mailing.schedule_type, 'scheduled') self.assertEqual(mailing.state, 'in_queue')
43.745098
15,617
13,124
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import random import re import werkzeug from unittest.mock import patch from odoo import tools from odoo.addons.link_tracker.tests.common import MockLinkTracker from odoo.addons.mail.tests.common import MailCase, MailCommon, mail_new_test_user from odoo.sql_db import Cursor class MassMailCase(MailCase, MockLinkTracker): # ------------------------------------------------------------ # ASSERTS # ------------------------------------------------------------ def assertMailingStatistics(self, mailing, **kwargs): """ Helper to assert mailing statistics fields. As we have many of them it helps lessening test asserts. """ if not kwargs.get('expected'): kwargs['expected'] = len(mailing.mailing_trace_ids) if not kwargs.get('delivered'): kwargs['delivered'] = len(mailing.mailing_trace_ids) for fname in ['scheduled', 'expected', 'sent', 'delivered', 'opened', 'replied', 'clicked', 'canceled', 'failed', 'bounced']: self.assertEqual( mailing[fname], kwargs.get(fname, 0), 'Mailing %s statistics failed: got %s instead of %s' % (fname, mailing[fname], kwargs.get(fname, 0)) ) def assertMailTraces(self, recipients_info, mailing, records, check_mail=True, sent_unlink=False, author=None, mail_links_info=None): """ Check content of traces. Traces are fetched based on a given mailing and records. Their content is compared to recipients_info structure that holds expected information. Links content may be checked, notably to assert shortening or unsubscribe links. Mail.mail records may optionally be checked. :param recipients_info: list[{ # TRACE 'partner': res.partner record (may be empty), 'email': email used when sending email (may be empty, computed based on partner), 'trace_status': outgoing / sent / open / reply / bounce / error / cancel (sent by default), 'record: linked record, # MAIL.MAIL 'content': optional content that should be present in mail.mail body_html; 'failure_type': optional failure reason; }, { ... }] :param mailing: a mailing.mailing record from which traces have been generated; :param records: records given to mailing that generated traces. It is used notably to find traces using their IDs; :param check_mail: if True, also check mail.mail records that should be linked to traces; :param sent_unlink: it True, sent mail.mail are deleted and we check gateway output result instead of actual mail.mail records; :param mail_links_info: if given, should follow order of ``recipients_info`` and give details about links. See ``assertLinkShortenedHtml`` helper for more details about content to give; :param author: author of sent mail.mail; """ # map trace state to email state state_mapping = { 'sent': 'sent', 'open': 'sent', # opened implies something has been sent 'reply': 'sent', # replied implies something has been sent 'error': 'exception', 'cancel': 'cancel', 'bounce': 'cancel', } traces = self.env['mailing.trace'].search([ ('mass_mailing_id', 'in', mailing.ids), ('res_id', 'in', records.ids) ]) # ensure trace coherency self.assertTrue(all(s.model == records._name for s in traces)) self.assertEqual(set(s.res_id for s in traces), set(records.ids)) # check each traces if not mail_links_info: mail_links_info = [None] * len(recipients_info) for recipient_info, link_info, record in zip(recipients_info, mail_links_info, records): partner = recipient_info.get('partner', self.env['res.partner']) email = recipient_info.get('email') status = recipient_info.get('trace_status', 'sent') record = record or recipient_info.get('record') content = recipient_info.get('content') if email is None and partner: email = partner.email_normalized recipient_trace = traces.filtered( lambda t: (t.email == email or (not email and not t.email)) and \ t.trace_status == status and \ (t.res_id == record.id if record else True) ) self.assertTrue( len(recipient_trace) == 1, 'MailTrace: email %s (recipient %s, status: %s, record: %s): found %s records (1 expected)' % (email, partner, status, record, len(recipient_trace)) ) self.assertTrue(bool(recipient_trace.mail_mail_id_int)) if 'failure_type' in recipient_info or status in ('error', 'cancel', 'bounce'): self.assertEqual(recipient_trace.failure_type, recipient_info['failure_type']) if check_mail: if author is None: author = self.env.user.partner_id # mail.mail specific values to check fields_values = {'mailing_id': mailing} # specific for partner: email_formatted is used if partner: if status == 'sent' and sent_unlink: self.assertSentEmail(author, [partner]) else: self.assertMailMail(partner, state_mapping[status], author=author, content=content, fields_values=fields_values) # specific if email is False -> could have troubles finding it if several falsy traces elif not email and status in ('cancel', 'bounce'): self.assertMailMailWId(recipient_trace.mail_mail_id_int, state_mapping[status], content=content, fields_values=fields_values) else: self.assertMailMailWEmails([email], state_mapping[status], author=author, content=content, fields_values=fields_values) if link_info: trace_mail = self._find_mail_mail_wrecord(record) for (anchor_id, url, is_shortened, add_link_params) in link_info: link_params = {'utm_medium': 'Email', 'utm_source': mailing.name} if add_link_params: link_params.update(**add_link_params) self.assertLinkShortenedHtml( trace_mail.body_html, (anchor_id, url, is_shortened), link_params=link_params, ) # ------------------------------------------------------------ # TOOLS # ------------------------------------------------------------ def gateway_mail_bounce(self, mailing, record, bounce_base_values=None): """ Generate a bounce at mailgateway level. :param mailing: a ``mailing.mailing`` record on which we find a trace to bounce; :param record: record which should bounce; :param bounce_base_values: optional values given to routing; """ trace = mailing.mailing_trace_ids.filtered(lambda t: t.model == record._name and t.res_id == record.id) parsed_bounce_values = { 'email_from': '[email protected]', # TDE check: email_from -> trace email ? 'to': '[email protected]', # TDE check: bounce alias ? 'message_id': tools.generate_tracking_message_id('MailTest'), 'bounced_partner': self.env['res.partner'].sudo(), 'bounced_message': self.env['mail.message'].sudo() } if bounce_base_values: parsed_bounce_values.update(bounce_base_values) parsed_bounce_values.update({ 'bounced_email': trace.email, 'bounced_msg_id': [trace.message_id], }) self.env['mail.thread']._routing_handle_bounce(False, parsed_bounce_values) def gateway_mail_click(self, mailing, record, click_label): """ Simulate a click on a sent email. """ trace = mailing.mailing_trace_ids.filtered(lambda t: t.model == record._name and t.res_id == record.id) email = self._find_sent_mail_wemail(trace.email) self.assertTrue(bool(email)) for (_url_href, link_url, _dummy, label) in re.findall(tools.HTML_TAG_URL_REGEX, email['body']): if label == click_label and '/r/' in link_url: # shortened link, like 'http://localhost:8069/r/LBG/m/53' parsed_url = werkzeug.urls.url_parse(link_url) path_items = parsed_url.path.split('/') code, trace_id = path_items[2], int(path_items[4]) self.assertEqual(trace.id, trace_id) self.env['link.tracker.click'].sudo().add_click( code, ip='100.200.300.%3f' % random.random(), country_code='BE', mailing_trace_id=trace.id ) break else: raise AssertionError('url %s not found in mailing %s for record %s' % (click_label, mailing, record)) @classmethod def _create_bounce_trace(cls, mailing, records, dt=None): if dt is None: dt = datetime.datetime.now() - datetime.timedelta(days=1) return cls._create_traces(mailing, records, dt, trace_status='bounce') @classmethod def _create_sent_traces(cls, mailing, records, dt=None): if dt is None: dt = datetime.datetime.now() - datetime.timedelta(days=1) return cls._create_traces(mailing, records, dt, trace_status='sent') @classmethod def _create_traces(cls, mailing, records, dt, **values): if 'email_normalized' in records: fname = 'email_normalized' elif 'email_from' in records: fname = 'email_from' else: fname = 'email' randomized = random.random() # Cursor.now() uses transaction's timestamp and not datetime lib -> freeze_time # is not sufficient with patch.object(Cursor, 'now', lambda *args, **kwargs: dt): traces = cls.env['mailing.trace'].sudo().create([ dict({'mass_mailing_id': mailing.id, 'model': record._name, 'res_id': record.id, 'trace_status': values.get('trace_status', 'bounce'), # TDE FIXME: improve this with a mail-enabled heuristics 'email': record[fname], 'message_id': '<%[email protected]>' % randomized, }, **values) for record in records ]) return traces class MassMailCommon(MailCommon, MassMailCase): @classmethod def setUpClass(cls): super(MassMailCommon, cls).setUpClass() cls.user_marketing = mail_new_test_user( cls.env, login='user_marketing', groups='base.group_user,base.group_partner_manager,mass_mailing.group_mass_mailing_user', name='Martial Marketing', signature='--\nMartial') cls.email_reply_to = 'MyCompany SomehowAlias <[email protected]>' @classmethod def _create_mailing_list(cls): """ Shortcut to create mailing lists. Currently hardcoded, maybe evolve in a near future. """ cls.mailing_list_1 = cls.env['mailing.list'].with_context(cls._test_context).create({ 'name': 'List1', 'contact_ids': [ (0, 0, {'name': 'Déboulonneur', 'email': '[email protected]'}), (0, 0, {'name': 'Gorramts', 'email': '[email protected]'}), (0, 0, {'name': 'Ybrant', 'email': '[email protected]'}), ] }) cls.mailing_list_2 = cls.env['mailing.list'].with_context(cls._test_context).create({ 'name': 'List2', 'contact_ids': [ (0, 0, {'name': 'Gilberte', 'email': '[email protected]'}), (0, 0, {'name': 'Gilberte En Mieux', 'email': '[email protected]'}), (0, 0, {'name': 'Norbert', 'email': '[email protected]'}), (0, 0, {'name': 'Ybrant', 'email': '[email protected]'}), ] }) @classmethod def _create_mailing_list_of_x_contacts(cls, contacts_nbr): """ Shortcut to create a mailing list that contains a defined number of contacts. """ return cls.env['mailing.list'].with_context(cls._test_context).create({ 'name': 'Test List', 'contact_ids': [ (0, 0, {'name': 'Contact %s' % i, 'email': 'contact%[email protected]' % i}) for i in range(contacts_nbr) ], })
46.867857
13,123
8,523
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, timedelta from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.tests import users, tagged from odoo.tools import mute_logger @tagged('post_install', '-at_install') class TestMailingABTesting(MassMailCommon): def setUp(self): super().setUp() self.mailing_list = self._create_mailing_list_of_x_contacts(150) self.ab_testing_mailing_1 = self.env['mailing.mailing'].create({ 'subject': 'A/B Testing V1', 'contact_list_ids': self.mailing_list.ids, 'ab_testing_enabled': True, 'ab_testing_pc': 10, 'ab_testing_schedule_datetime': datetime.now(), }) self.ab_testing_mailing_2 = self.ab_testing_mailing_1.copy({ 'subject': 'A/B Testing V2', 'ab_testing_pc': 20, }) self.ab_testing_campaign = self.ab_testing_mailing_1.campaign_id self.ab_testing_mailing_ids = self.ab_testing_mailing_1 + self.ab_testing_mailing_2 self.ab_testing_mailing_ids.invalidate_cache() @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') def test_mailing_ab_testing_auto_flow(self): with self.mock_mail_gateway(): self.ab_testing_mailing_ids.action_send_mail() self.assertEqual(self.ab_testing_mailing_1.state, 'done') self.assertEqual(self.ab_testing_mailing_2.state, 'done') self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 0) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 0) total_trace_ids = self.ab_testing_mailing_ids.mailing_trace_ids unique_recipients_used = set(map(lambda mail: mail.res_id, total_trace_ids.mail_mail_id)) self.assertEqual(len(self.ab_testing_mailing_1.mailing_trace_ids), 15) self.assertEqual(len(self.ab_testing_mailing_2.mailing_trace_ids), 30) self.assertEqual(len(unique_recipients_used), 45) self.ab_testing_mailing_1.mailing_trace_ids[:10].set_opened() self.ab_testing_mailing_2.mailing_trace_ids[:15].set_opened() self.ab_testing_mailing_ids.invalidate_cache() self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 66) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 50) with self.mock_mail_gateway(): self.ab_testing_mailing_2.action_send_winner_mailing() self.ab_testing_mailing_ids.invalidate_cache() winner_mailing = self.ab_testing_campaign.mailing_mail_ids.filtered(lambda mailing: mailing.ab_testing_pc == 100) self.assertEqual(winner_mailing.subject, 'A/B Testing V1') @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') def test_mailing_ab_testing_auto_flow_cron(self): self.ab_testing_mailing_1.write({ 'ab_testing_schedule_datetime': datetime.now() + timedelta(days=-1), }) with self.mock_mail_gateway(): self.ab_testing_mailing_ids.action_send_mail() self.assertEqual(self.ab_testing_mailing_1.state, 'done') self.assertEqual(self.ab_testing_mailing_2.state, 'done') self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 0) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 0) total_trace_ids = self.ab_testing_mailing_ids.mailing_trace_ids unique_recipients_used = set(map(lambda mail: mail.res_id, total_trace_ids.mail_mail_id)) self.assertEqual(len(self.ab_testing_mailing_1.mailing_trace_ids), 15) self.assertEqual(len(self.ab_testing_mailing_2.mailing_trace_ids), 30) self.assertEqual(len(unique_recipients_used), 45) self.ab_testing_mailing_1.mailing_trace_ids[:10].set_opened() self.ab_testing_mailing_2.mailing_trace_ids[:15].set_opened() self.ab_testing_mailing_ids.invalidate_cache() self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 66) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 50) with self.mock_mail_gateway(): self.env.ref('mass_mailing.ir_cron_mass_mailing_ab_testing').sudo().method_direct_trigger() self.ab_testing_mailing_ids.invalidate_cache() winner_mailing = self.ab_testing_campaign.mailing_mail_ids.filtered(lambda mailing: mailing.ab_testing_pc == 100) self.assertEqual(winner_mailing.subject, 'A/B Testing V1') @users('user_marketing') def test_mailing_ab_testing_campaign(self): schedule_datetime = datetime.now() + timedelta(days=30) ab_mailing = self.env['mailing.mailing'].create({ 'subject': 'A/B Testing V1', 'contact_list_ids': self.mailing_list.ids, 'ab_testing_enabled': True, 'ab_testing_winner_selection': 'manual', 'ab_testing_schedule_datetime': schedule_datetime, }) ab_mailing.invalidate_cache() # Check if the campaign is correclty created and the values set on the mailing are still the same self.assertTrue(ab_mailing.campaign_id, "A campaign id is present for the A/B test mailing") self.assertEqual(ab_mailing.ab_testing_winner_selection, 'manual', "The selection winner has been propagated correctly") self.assertEqual(ab_mailing.ab_testing_schedule_datetime, schedule_datetime, "The schedule date has been propagated correctly") @users('user_marketing') def test_mailing_ab_testing_compare(self): # compare version feature should returns all mailings of the same # campaign having a/b testing enabled. compare_version = self.ab_testing_mailing_1.action_compare_versions() self.assertEqual( self.env['mailing.mailing'].search(compare_version.get('domain')), self.ab_testing_mailing_1 + self.ab_testing_mailing_2 ) @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') def test_mailing_ab_testing_manual_flow(self): self.ab_testing_mailing_1.write({ 'ab_testing_winner_selection': 'manual', }) with self.mock_mail_gateway(): self.ab_testing_mailing_ids.action_send_mail() self.assertEqual(self.ab_testing_mailing_1.state, 'done') self.assertEqual(self.ab_testing_mailing_2.state, 'done') self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 0) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 0) total_trace_ids = self.ab_testing_mailing_ids.mailing_trace_ids unique_recipients_used = set(map(lambda mail: mail.res_id, total_trace_ids.mail_mail_id)) self.assertEqual(len(self.ab_testing_mailing_1.mailing_trace_ids), 15) self.assertEqual(len(self.ab_testing_mailing_2.mailing_trace_ids), 30) self.assertEqual(len(unique_recipients_used), 45) self.ab_testing_mailing_1.mailing_trace_ids[:10].set_opened() self.ab_testing_mailing_2.mailing_trace_ids[:15].set_opened() self.ab_testing_mailing_ids.invalidate_cache() self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 66) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 50) with self.mock_mail_gateway(): self.ab_testing_mailing_2.action_send_winner_mailing() self.ab_testing_mailing_ids.invalidate_cache() winner_mailing = self.ab_testing_campaign.mailing_mail_ids.filtered(lambda mailing: mailing.ab_testing_pc == 100) self.assertEqual(winner_mailing.subject, 'A/B Testing V2') @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') def test_mailing_ab_testing_minimum_participants(self): """ Test that it should send minimum one mail(if possible) when ab_testing_pc is too small compared to the amount of targeted records.""" mailing_list = self._create_mailing_list_of_x_contacts(10) ab_testing = self.env['mailing.mailing'].create({ 'subject': 'A/B Testing SMS V1', 'contact_list_ids': mailing_list.ids, 'ab_testing_enabled': True, 'ab_testing_pc': 2, 'ab_testing_schedule_datetime': datetime.now(), 'mailing_type': 'mail', 'campaign_id': self.ab_testing_campaign.id, }) with self.mock_mail_gateway(): ab_testing.action_send_mail() self.assertEqual(ab_testing.state, 'done') self.assertEqual(len(self._mails), 1)
50.732143
8,523
8,021
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from freezegun import freeze_time from odoo import exceptions from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.tests.common import Form, users class TestMailingContactToList(MassMailCommon): @users('user_marketing') def test_mailing_contact_to_list(self): contacts = self.env['mailing.contact'].create([{ 'name': 'Contact %02d', 'email': 'contact_%[email protected]', } for x in range(30)]) self.assertEqual(len(contacts), 30) self.assertEqual(contacts.list_ids, self.env['mailing.list']) mailing = self.env['mailing.list'].create({ 'name': 'Contacts Agregator', }) # create wizard with context values wizard_form = Form(self.env['mailing.contact.to.list'].with_context(default_contact_ids=contacts.ids)) self.assertEqual(wizard_form.contact_ids._get_ids(), contacts.ids) # set mailing list and add contacts wizard_form.mailing_list_id = mailing wizard = wizard_form.save() action = wizard.action_add_contacts() self.assertEqual(contacts.list_ids, mailing) self.assertEqual(action["type"], "ir.actions.client") self.assertTrue(action.get("params", {}).get("next"), "Should return a notification with a next action") subaction = action["params"]["next"] self.assertEqual(subaction["type"], "ir.actions.act_window_close") # set mailing list, add contacts and redirect to mailing view mailing2 = self.env['mailing.list'].create({ 'name': 'Contacts Sublimator', }) wizard_form.mailing_list_id = mailing2 wizard = wizard_form.save() action = wizard.action_add_contacts_and_send_mailing() self.assertEqual(contacts.list_ids, mailing + mailing2) self.assertEqual(action["type"], "ir.actions.client") self.assertTrue(action.get("params", {}).get("next"), "Should return a notification with a next action") subaction = action["params"]["next"] self.assertEqual(subaction["type"], "ir.actions.act_window") self.assertEqual(subaction["context"]["default_contact_list_ids"], [mailing2.id]) class TestMailingListMerge(MassMailCommon): @classmethod def setUpClass(cls): super(TestMailingListMerge, cls).setUpClass() cls._create_mailing_list() cls.mailing_list_3 = cls.env['mailing.list'].with_context(cls._test_context).create({ 'name': 'ListC', 'contact_ids': [ (0, 0, {'name': 'Norberto', 'email': '[email protected]'}), ] }) @users('user_marketing') def test_mailing_contact_create(self): default_list_ids = (self.mailing_list_2 | self.mailing_list_3).ids # simply set default list in context new = self.env['mailing.contact'].with_context(default_list_ids=default_list_ids).create([{ 'name': 'Contact_%d' % x, 'email': 'contact_%[email protected]' % x, } for x in range(0, 5)]) self.assertEqual(new.list_ids, (self.mailing_list_2 | self.mailing_list_3)) # default list and subscriptions should be merged new = self.env['mailing.contact'].with_context(default_list_ids=default_list_ids).create([{ 'name': 'Contact_%d' % x, 'email': 'contact_%[email protected]' % x, 'subscription_list_ids': [(0, 0, { 'list_id': self.mailing_list_1.id, 'opt_out': True, }), (0, 0, { 'list_id': self.mailing_list_2.id, 'opt_out': True, })], } for x in range(0, 5)]) self.assertEqual(new.list_ids, (self.mailing_list_1 | self.mailing_list_2 | self.mailing_list_3)) # should correctly take subscription opt_out value for list_id in (self.mailing_list_1 | self.mailing_list_2).ids: new = new.with_context(default_list_ids=[list_id]) self.assertTrue(all(contact.opt_out for contact in new)) # not opt_out for new subscription without specific create values for list_id in self.mailing_list_3.ids: new = new.with_context(default_list_ids=[list_id]) self.assertFalse(any(contact.opt_out for contact in new)) with freeze_time('2022-01-01 12:00'): contact_form = Form(self.env['mailing.contact']) contact_form.name = 'Contact_test' with contact_form.subscription_list_ids.new() as subscription: subscription.list_id = self.mailing_list_1 subscription.opt_out = True with contact_form.subscription_list_ids.new() as subscription: subscription.list_id = self.mailing_list_2 subscription.opt_out = False contact = contact_form.save() self.assertEqual(contact.subscription_list_ids[0].unsubscription_date, datetime(2022, 1, 1, 12, 0, 0)) self.assertFalse(contact.subscription_list_ids[1].unsubscription_date) @users('user_marketing') def test_mailing_list_contact_copy_in_context_of_mailing_list(self): MailingContact = self.env['mailing.contact'] contact_1 = MailingContact.create({ 'name': 'Sam', 'email': '[email protected]', 'subscription_list_ids': [(0, 0, {'list_id': self.mailing_list_3.id})], }) # Copy the contact with default_list_ids in context, which should not raise anything contact_2 = contact_1.with_context(default_list_ids=self.mailing_list_3.ids).copy() self.assertEqual(contact_1.list_ids, contact_2.list_ids, 'Should copy the existing mailing list(s)') @users('user_marketing') def test_mailing_list_merge(self): # TEST CASE: Merge A,B into the existing mailing list C # The mailing list C contains the same email address than 'Norbert' in list B # This test ensure that the mailing lists are correctly merged and no # duplicates are appearing in C merge_form = Form(self.env['mailing.list.merge'].with_context( active_ids=[self.mailing_list_1.id, self.mailing_list_2.id], active_model='mailing.list' )) merge_form.new_list_name = False merge_form.dest_list_id = self.mailing_list_3 merge_form.merge_options = 'existing' merge_form.archive_src_lists = False result_list = merge_form.save().action_mailing_lists_merge() # Assert the number of contacts is correct self.assertEqual( len(result_list.contact_ids.ids), 5, 'The number of contacts on the mailing list C is not equal to 5') # Assert there's no duplicated email address self.assertEqual( len(list(set(result_list.contact_ids.mapped('email')))), 5, 'Duplicates have been merged into the destination mailing list. Check %s' % (result_list.contact_ids.mapped('email'))) @users('user_marketing') def test_mailing_list_merge_cornercase(self): """ Check wrong use of merge wizard """ with self.assertRaises(exceptions.UserError): merge_form = Form(self.env['mailing.list.merge'].with_context( active_ids=[self.mailing_list_1.id, self.mailing_list_2.id], )) merge_form = Form(self.env['mailing.list.merge'].with_context( active_ids=[self.mailing_list_1.id], active_model='mailing.list', default_src_list_ids=[self.mailing_list_1.id, self.mailing_list_2.id], default_dest_list_id=self.mailing_list_3.id, default_merge_options='existing', )) merge = merge_form.save() self.assertEqual(merge.src_list_ids, self.mailing_list_1 + self.mailing_list_2) self.assertEqual(merge.dest_list_id, self.mailing_list_3)
46.364162
8,021
1,837
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.addons.base.tests.test_ir_cron import CronMixinCase from odoo.tests.common import users from unittest.mock import patch class TestMailingRetry(MassMailCommon, CronMixinCase): @classmethod def setUpClass(cls): super(TestMailingRetry, cls).setUpClass() cls._create_mailing_list() @users('user_marketing') def test_mailing_retry_immediate_trigger(self): mailing = self.env['mailing.mailing'].create({ 'name': 'TestMailing', 'subject': 'Test', 'mailing_type': 'mail', 'body_html': '<div>Hello</div>', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'contact_list_ids': [(4, self.mailing_list_1.id)], }) mailing.action_launch() # force email sending to fail to test our retry mechanism def patched_mail_mail_send(mail_records, auto_commit=False, raise_exception=False, smtp_session=None): mail_records.write({'state': 'exception', 'failure_reason': 'forced_failure'}) with patch('odoo.addons.mail.models.mail_mail.MailMail._send', patched_mail_mail_send): self.env.ref('mass_mailing.ir_cron_mass_mailing_queue').sudo().method_direct_trigger() with self.capture_triggers('mass_mailing.ir_cron_mass_mailing_queue') as captured_triggers: mailing.action_retry_failed() self.assertEqual(len(captured_triggers.records), 1, "Should have created an additional trigger immediately") captured_trigger = captured_triggers.records[0] self.assertEqual(captured_trigger.cron_id, self.env.ref('mass_mailing.ir_cron_mass_mailing_queue'))
44.804878
1,837
4,170
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from markupsafe import Markup from odoo import _, fields, models, tools class TestMassMailing(models.TransientModel): _name = 'mailing.mailing.test' _description = 'Sample Mail Wizard' email_to = fields.Text(string='Recipients', required=True, help='Carriage-return-separated list of email addresses.', default=lambda self: self.env.user.email_formatted) mass_mailing_id = fields.Many2one('mailing.mailing', string='Mailing', required=True, ondelete='cascade') def send_mail_test(self): self.ensure_one() ctx = dict(self.env.context) ctx.pop('default_state', None) self = self.with_context(ctx) mails_sudo = self.env['mail.mail'].sudo() valid_emails = [] invalid_candidates = [] for candidate in self.email_to.splitlines(): test_email = tools.email_split(candidate) if test_email: valid_emails.append(test_email[0]) else: invalid_candidates.append(candidate) mailing = self.mass_mailing_id mass_mail_layout = self.env.ref('mass_mailing.mass_mailing_mail_layout') record = self.env[mailing.mailing_model_real].search([], limit=1) # If there is atleast 1 record for the model used in this mailing, then we use this one to render the template # Downside: Qweb syntax is only tested when there is atleast one record of the mailing's model if record: # Returns a proper error if there is a syntax error with Qweb body = mailing._render_field('body_html', record.ids, post_process=True)[record.id] preview = mailing._render_field('preview', record.ids, post_process=True)[record.id] full_body = mailing._prepend_preview(Markup(body), preview) subject = mailing._render_field('subject', record.ids)[record.id] else: full_body = mailing._prepend_preview(mailing.body_html, mailing.preview) subject = mailing.subject # Convert links in absolute URLs before the application of the shortener full_body = self.env['mail.render.mixin']._replace_local_links(full_body) for valid_email in valid_emails: mail_values = { 'email_from': mailing.email_from, 'reply_to': mailing.reply_to, 'email_to': valid_email, 'subject': subject, 'body_html': mass_mail_layout._render({'body': full_body}, engine='ir.qweb', minimal_qcontext=True), 'is_notification': True, 'mailing_id': mailing.id, 'attachment_ids': [(4, attachment.id) for attachment in mailing.attachment_ids], 'auto_delete': False, # they are manually deleted after notifying the document 'mail_server_id': mailing.mail_server_id.id, } mail = self.env['mail.mail'].sudo().create(mail_values) mails_sudo |= mail mails_sudo.send() notification_messages = [] if invalid_candidates: notification_messages.append( _('Mailing addresses incorrect: %s', ', '.join(invalid_candidates))) for mail_sudo in mails_sudo: if mail_sudo.state == 'sent': notification_messages.append( _('Test mailing successfully sent to %s', mail_sudo.email_to)) elif mail_sudo.state == 'exception': notification_messages.append( _('Test mailing could not be sent to %s:<br>%s', mail_sudo.email_to, mail_sudo.failure_reason) ) # manually delete the emails since we passed 'auto_delete: False' mails_sudo.unlink() if notification_messages: self.mass_mailing_id._message_log(body='<ul>%s</ul>' % ''.join( ['<li>%s</li>' % notification_message for notification_message in notification_messages] )) return True
44.361702
4,170
4,290
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' mass_mailing_id = fields.Many2one('mailing.mailing', string='Mass Mailing', ondelete='cascade') campaign_id = fields.Many2one('utm.campaign', string='Mass Mailing Campaign') mass_mailing_name = fields.Char(string='Mass Mailing Name') mailing_list_ids = fields.Many2many('mailing.list', string='Mailing List') def get_mail_values(self, res_ids): """ Override method that generated the mail content by creating the mailing.trace values in the o2m of mail_mail, when doing pure email mass mailing. """ now = fields.Datetime.now() self.ensure_one() res = super(MailComposeMessage, self).get_mail_values(res_ids) # use only for allowed models in mass mailing if self.composition_mode == 'mass_mail' and \ (self.mass_mailing_name or self.mass_mailing_id) and \ self.env['ir.model'].sudo().search_count([('model', '=', self.model), ('is_mail_thread', '=', True)]): mass_mailing = self.mass_mailing_id if not mass_mailing: mass_mailing = self.env['mailing.mailing'].create({ 'campaign_id': self.campaign_id.id, 'name': self.mass_mailing_name, 'subject': self.subject, 'state': 'done', 'reply_to_mode': self.reply_to_mode, 'reply_to': self.reply_to if self.reply_to_mode == 'new' else False, 'sent_date': now, 'body_html': self.body, 'mailing_model_id': self.env['ir.model']._get(self.model).id, 'mailing_domain': self.active_domain, 'attachment_ids': [(6, 0, self.attachment_ids.ids)], }) self.mass_mailing_id = mass_mailing.id recipients_info = self._process_recipient_values(res) mass_mail_layout = self.env.ref('mass_mailing.mass_mailing_mail_layout', raise_if_not_found=False) for res_id in res_ids: mail_values = res[res_id] if mail_values.get('body_html') and mass_mail_layout: mail_values['body_html'] = mass_mail_layout._render({'body': mail_values['body_html']}, engine='ir.qweb', minimal_qcontext=True) trace_vals = { 'model': self.model, 'res_id': res_id, 'mass_mailing_id': mass_mailing.id, # if mail_to is void, keep falsy values to allow searching / debugging traces 'email': recipients_info[res_id]['mail_to'][0] if recipients_info[res_id]['mail_to'] else '', } # propagate failed states to trace when still-born if mail_values.get('state') == 'cancel': trace_vals['trace_status'] = 'cancel' elif mail_values.get('state') == 'exception': trace_vals['trace_status'] = 'error' if mail_values.get('failure_type'): trace_vals['failure_type'] = mail_values['failure_type'] mail_values.update({ 'mailing_id': mass_mailing.id, 'mailing_trace_ids': [(0, 0, trace_vals)], # email-mode: keep original message for routing 'is_notification': mass_mailing.reply_to_mode == 'update', 'auto_delete': not mass_mailing.keep_archives, }) return res def _get_done_emails(self, mail_values_dict): seen_list = super(MailComposeMessage, self)._get_done_emails(mail_values_dict) if self.mass_mailing_id: seen_list += self.mass_mailing_id._get_seen_list() return seen_list def _get_optout_emails(self, mail_values_dict): opt_out_list = super(MailComposeMessage, self)._get_optout_emails(mail_values_dict) if self.mass_mailing_id: opt_out_list += self.mass_mailing_id._get_opt_out_list() return opt_out_list
51.071429
4,290
600
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class MailingMailingScheduleDate(models.TransientModel): _name = "mailing.mailing.schedule.date" _description = "schedule a mailing" schedule_date = fields.Datetime(string='Scheduled for') mass_mailing_id = fields.Many2one('mailing.mailing', required=True) def action_schedule_date(self): self.mass_mailing_id.write({'schedule_type': 'scheduled', 'schedule_date': self.schedule_date}) self.mass_mailing_id.action_put_in_queue()
37.5
600
1,942
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class MassMailingListMerge(models.TransientModel): _name = 'mailing.list.merge' _description = 'Merge Mass Mailing List' @api.model def default_get(self, fields): res = super(MassMailingListMerge, self).default_get(fields) if not res.get('src_list_ids') and 'src_list_ids' in fields: if self.env.context.get('active_model') != 'mailing.list': raise UserError(_('You can only apply this action from Mailing Lists.')) src_list_ids = self.env.context.get('active_ids') res.update({ 'src_list_ids': [(6, 0, src_list_ids)], }) if not res.get('dest_list_id') and 'dest_list_id' in fields: src_list_ids = res.get('src_list_ids') or self.env.context.get('active_ids') res.update({ 'dest_list_id': src_list_ids and src_list_ids[0] or False, }) return res src_list_ids = fields.Many2many('mailing.list', string='Mailing Lists') dest_list_id = fields.Many2one('mailing.list', string='Destination Mailing List') merge_options = fields.Selection([ ('new', 'Merge into a new mailing list'), ('existing', 'Merge into an existing mailing list'), ], 'Merge Option', required=True, default='new') new_list_name = fields.Char('New Mailing List Name') archive_src_lists = fields.Boolean('Archive source mailing lists', default=True) def action_mailing_lists_merge(self): if self.merge_options == 'new': self.dest_list_id = self.env['mailing.list'].create({ 'name': self.new_list_name, }).id self.dest_list_id.action_merge(self.src_list_ids, self.archive_src_lists) return self.dest_list_id
43.155556
1,942
1,977
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ class MailingContactToList(models.TransientModel): _name = "mailing.contact.to.list" _description = "Add Contacts to Mailing List" contact_ids = fields.Many2many('mailing.contact', string='Contacts') mailing_list_id = fields.Many2one('mailing.list', string='Mailing List', required=True) def action_add_contacts(self): """ Simply add contacts to the mailing list and close wizard. """ return self._add_contacts_to_mailing_list({'type': 'ir.actions.act_window_close'}) def action_add_contacts_and_send_mailing(self): """ Add contacts to the mailing list and redirect to a new mailing on this list. """ self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.mailing_mailing_action_mail") action['views'] = [[False, "form"]] action['target'] = 'current' action['context'] = { 'default_contact_list_ids': [self.mailing_list_id.id] } return self._add_contacts_to_mailing_list(action) def _add_contacts_to_mailing_list(self, action): self.ensure_one() previous_count = len(self.mailing_list_id.contact_ids) self.mailing_list_id.write({ 'contact_ids': [ (4, contact.id) for contact in self.contact_ids if contact not in self.mailing_list_id.contact_ids] }) return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'type': 'info', 'message': _("%s Mailing Contacts have been added. ", len(self.mailing_list_id.contact_ids) - previous_count ), 'sticky': False, 'next': action, } }
38.019231
1,977
1,373
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ class IrModel(models.Model): _inherit = 'ir.model' is_mailing_enabled = fields.Boolean( string="Mailing Enabled", compute='_compute_is_mailing_enabled', search='_search_is_mailing_enabled', help="Whether this model supports marketing mailing capabilities (notably email and SMS).", ) def _compute_is_mailing_enabled(self): for model in self: model.is_mailing_enabled = getattr(self.env[model.model], '_mailing_enabled', False) def _search_is_mailing_enabled(self, operator, value): if operator not in ('=', '!='): raise ValueError(_("Searching Mailing Enabled models supports only direct search using '='' or '!='.")) valid_models = self.env['ir.model'] for model in self.search([]): if model.model not in self.env or model.is_transient(): continue if getattr(self.env[model.model], '_mailing_enabled', False): valid_models |= model search_is_mailing_enabled = (operator == '=' and value) or (operator == '!=' and not value) if search_is_mailing_enabled: return [('id', 'in', valid_models.ids)] return [('id', 'not in', valid_models.ids)]
40.382353
1,373
8,921
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from odoo.osv import expression class MassMailingContactListRel(models.Model): """ Intermediate model between mass mailing list and mass mailing contact Indicates if a contact is opted out for a particular list """ _name = 'mailing.contact.subscription' _description = 'Mass Mailing Subscription Information' _table = 'mailing_contact_list_rel' _rec_name = 'contact_id' contact_id = fields.Many2one('mailing.contact', string='Contact', ondelete='cascade', required=True) list_id = fields.Many2one('mailing.list', string='Mailing List', ondelete='cascade', required=True) opt_out = fields.Boolean(string='Opt Out', help='The contact has chosen not to receive mails anymore from this list', default=False) unsubscription_date = fields.Datetime(string='Unsubscription Date') message_bounce = fields.Integer(related='contact_id.message_bounce', store=False, readonly=False) is_blacklisted = fields.Boolean(related='contact_id.is_blacklisted', store=False, readonly=False) _sql_constraints = [ ('unique_contact_list', 'unique (contact_id, list_id)', 'A mailing contact cannot subscribe to the same mailing list multiple times.') ] @api.model_create_multi def create(self, vals_list): now = fields.Datetime.now() for vals in vals_list: if 'opt_out' in vals and not vals.get('unsubscription_date'): vals['unsubscription_date'] = now if vals['opt_out'] else False if vals.get('unsubscription_date'): vals['opt_out'] = True return super().create(vals_list) def write(self, vals): if 'opt_out' in vals and 'unsubscription_date' not in vals: vals['unsubscription_date'] = fields.Datetime.now() if vals['opt_out'] else False if vals.get('unsubscription_date'): vals['opt_out'] = True return super(MassMailingContactListRel, self).write(vals) class MassMailingContact(models.Model): """Model of a contact. This model is different from the partner model because it holds only some basic information: name, email. The purpose is to be able to deal with large contact list to email without bloating the partner base.""" _name = 'mailing.contact' _inherit = ['mail.thread.blacklist'] _description = 'Mailing Contact' _order = 'email' _mailing_enabled = True def default_get(self, fields): """ When coming from a mailing list we may have a default_list_ids context key. We should use it to create subscription_list_ids default value that are displayed to the user as list_ids is not displayed on form view. """ res = super(MassMailingContact, self).default_get(fields) if 'subscription_list_ids' in fields and not res.get('subscription_list_ids'): list_ids = self.env.context.get('default_list_ids') if 'default_list_ids' not in res and list_ids and isinstance(list_ids, (list, tuple)): res['subscription_list_ids'] = [ (0, 0, {'list_id': list_id}) for list_id in list_ids] return res name = fields.Char() company_name = fields.Char(string='Company Name') title_id = fields.Many2one('res.partner.title', string='Title') email = fields.Char('Email') list_ids = fields.Many2many( 'mailing.list', 'mailing_contact_list_rel', 'contact_id', 'list_id', string='Mailing Lists') subscription_list_ids = fields.One2many('mailing.contact.subscription', 'contact_id', string='Subscription Information') country_id = fields.Many2one('res.country', string='Country') tag_ids = fields.Many2many('res.partner.category', string='Tags') opt_out = fields.Boolean('Opt Out', compute='_compute_opt_out', search='_search_opt_out', help='Opt out flag for a specific mailing list.' 'This field should not be used in a view without a unique and active mailing list context.') @api.model def _search_opt_out(self, operator, value): # Assumes operator is '=' or '!=' and value is True or False if operator != '=': if operator == '!=' and isinstance(value, bool): value = not value else: raise NotImplementedError() if 'default_list_ids' in self._context and isinstance(self._context['default_list_ids'], (list, tuple)) and len(self._context['default_list_ids']) == 1: [active_list_id] = self._context['default_list_ids'] contacts = self.env['mailing.contact.subscription'].search([('list_id', '=', active_list_id)]) return [('id', 'in', [record.contact_id.id for record in contacts if record.opt_out == value])] else: return expression.FALSE_DOMAIN if value else expression.TRUE_DOMAIN @api.depends('subscription_list_ids') @api.depends_context('default_list_ids') def _compute_opt_out(self): if 'default_list_ids' in self._context and isinstance(self._context['default_list_ids'], (list, tuple)) and len(self._context['default_list_ids']) == 1: [active_list_id] = self._context['default_list_ids'] for record in self: active_subscription_list = record.subscription_list_ids.filtered(lambda l: l.list_id.id == active_list_id) record.opt_out = active_subscription_list.opt_out else: for record in self: record.opt_out = False def get_name_email(self, name): name, email = self.env['res.partner']._parse_partner_name(name) if name and not email: email = name if email and not name: name = email return name, email @api.model_create_multi def create(self, vals_list): """ Synchronize default_list_ids (currently used notably for computed fields) default key with subscription_list_ids given by user when creating contacts. Those two values have the same purpose, adding a list to to the contact either through a direct write on m2m, either through a write on middle model subscription. This is a bit hackish but is due to default_list_ids key being used to compute oupt_out field. This should be cleaned in master but here we simply try to limit issues while keeping current behavior. """ default_list_ids = self._context.get('default_list_ids') default_list_ids = default_list_ids if isinstance(default_list_ids, (list, tuple)) else [] if default_list_ids: for vals in vals_list: current_list_ids = [] subscription_ids = vals.get('subscription_list_ids') or [] for subscription in subscription_ids: if len(subscription) == 3: current_list_ids.append(subscription[2]['list_id']) for list_id in set(default_list_ids) - set(current_list_ids): subscription_ids.append((0, 0, {'list_id': list_id})) vals['subscription_list_ids'] = subscription_ids return super(MassMailingContact, self.with_context(default_list_ids=False)).create(vals_list) @api.returns('self', lambda value: value.id) def copy(self, default=None): """ Cleans the default_list_ids while duplicating mailing contact in context of a mailing list because we already have subscription lists copied over for newly created contact, no need to add the ones from default_list_ids again """ if self.env.context.get('default_list_ids'): self = self.with_context(default_list_ids=False) return super().copy(default) @api.model def name_create(self, name): name, email = self.get_name_email(name) contact = self.create({'name': name, 'email': email}) return contact.name_get()[0] @api.model def add_to_list(self, name, list_id): name, email = self.get_name_email(name) contact = self.create({'name': name, 'email': email, 'list_ids': [(4, list_id)]}) return contact.name_get()[0] def _message_get_default_recipients(self): return {r.id: { 'partner_ids': [], 'email_to': r.email_normalized, 'email_cc': False} for r in self } def action_add_to_mailing_list(self): ctx = dict(self.env.context, default_contact_ids=self.ids) action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.mailing_contact_to_list_action") action['view_mode'] = 'form' action['target'] = 'new' action['context'] = ctx return action
47.962366
8,921
54,695
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import hashlib import hmac import logging import lxml import random import re import threading import werkzeug.urls from ast import literal_eval from dateutil.relativedelta import relativedelta from werkzeug.urls import url_join from odoo import api, fields, models, tools, _ from odoo.exceptions import UserError, ValidationError from odoo.osv import expression _logger = logging.getLogger(__name__) # Syntax of the data URL Scheme: https://tools.ietf.org/html/rfc2397#section-3 # Used to find inline images image_re = re.compile(r"data:(image/[A-Za-z]+);base64,(.*)") class MassMailing(models.Model): """ Mass Mailing models the sending of emails to a list of recipients for a mass mailing campaign.""" _name = 'mailing.mailing' _description = 'Mass Mailing' _inherit = ['mail.thread', 'mail.activity.mixin', 'mail.render.mixin'] _order = 'sent_date DESC' _inherits = {'utm.source': 'source_id'} _rec_name = "subject" @api.model def default_get(self, fields_list): vals = super(MassMailing, self).default_get(fields_list) # field sent by the calendar view when clicking on a date block # we use it to setup the scheduled date of the created mailing.mailing default_calendar_date = self.env.context.get('default_calendar_date') if default_calendar_date and ('schedule_type' in fields_list and 'schedule_date' in fields_list) \ and fields.Datetime.from_string(default_calendar_date) > fields.Datetime.now(): vals.update({ 'schedule_type': 'scheduled', 'schedule_date': default_calendar_date }) if 'contact_list_ids' in fields_list and not vals.get('contact_list_ids') and vals.get('mailing_model_id'): if vals.get('mailing_model_id') == self.env['ir.model']._get('mailing.list').id: mailing_list = self.env['mailing.list'].search([], limit=2) if len(mailing_list) == 1: vals['contact_list_ids'] = [(6, 0, [mailing_list.id])] return vals @api.model def _get_default_mail_server_id(self): server_id = self.env['ir.config_parameter'].sudo().get_param('mass_mailing.mail_server_id') try: server_id = literal_eval(server_id) if server_id else False return self.env['ir.mail_server'].search([('id', '=', server_id)]).id except ValueError: return False active = fields.Boolean(default=True, tracking=True) subject = fields.Char('Subject', help='Subject of your Mailing', required=True, translate=False) preview = fields.Char( 'Preview', translate=False, help='Catchy preview sentence that encourages recipients to open this email.\n' 'In most inboxes, this is displayed next to the subject.\n' 'Keep it empty if you prefer the first characters of your email content to appear instead.') email_from = fields.Char(string='Send From', required=True, store=True, readonly=False, compute='_compute_email_from', default=lambda self: self.env.user.email_formatted) sent_date = fields.Datetime(string='Sent Date', copy=False) schedule_type = fields.Selection([('now', 'Send now'), ('scheduled', 'Send on')], string='Schedule', default='now', required=True, readonly=True, states={'draft': [('readonly', False)], 'in_queue': [('readonly', False)]}) schedule_date = fields.Datetime(string='Scheduled for', tracking=True, readonly=True, states={'draft': [('readonly', False)], 'in_queue': [('readonly', False)]}, compute='_compute_schedule_date', store=True, copy=True) calendar_date = fields.Datetime('Calendar Date', compute='_compute_calendar_date', store=True, copy=False, help="Date at which the mailing was or will be sent.") # don't translate 'body_arch', the translations are only on 'body_html' body_arch = fields.Html(string='Body', translate=False, sanitize=False) body_html = fields.Html(string='Body converted to be sent by mail', render_engine='qweb', sanitize=False) is_body_empty = fields.Boolean(compute="_compute_is_body_empty", help='Technical field used to determine if the mail body is empty') attachment_ids = fields.Many2many('ir.attachment', 'mass_mailing_ir_attachments_rel', 'mass_mailing_id', 'attachment_id', string='Attachments') keep_archives = fields.Boolean(string='Keep Archives') campaign_id = fields.Many2one('utm.campaign', string='UTM Campaign', index=True) source_id = fields.Many2one('utm.source', string='Source', required=True, ondelete='cascade', help="This is the link source, e.g. Search Engine, another domain, or name of email list") medium_id = fields.Many2one( 'utm.medium', string='Medium', compute='_compute_medium_id', readonly=False, store=True, help="UTM Medium: delivery method (email, sms, ...)") state = fields.Selection([('draft', 'Draft'), ('in_queue', 'In Queue'), ('sending', 'Sending'), ('done', 'Sent')], string='Status', required=True, tracking=True, copy=False, default='draft', group_expand='_group_expand_states') color = fields.Integer(string='Color Index') user_id = fields.Many2one('res.users', string='Responsible', tracking=True, default=lambda self: self.env.user) # mailing options mailing_type = fields.Selection([('mail', 'Email')], string="Mailing Type", default="mail", required=True) mailing_type_description = fields.Char('Mailing Type Description', compute="_compute_mailing_type_description") reply_to_mode = fields.Selection([ ('update', 'Recipient Followers'), ('new', 'Specified Email Address')], string='Reply-To Mode', compute='_compute_reply_to_mode', readonly=False, store=True, help='Thread: replies go to target document. Email: replies are routed to a given email.') reply_to = fields.Char( string='Reply To', compute='_compute_reply_to', readonly=False, store=True, help='Preferred Reply-To Address') # recipients mailing_model_real = fields.Char(string='Recipients Real Model', compute='_compute_mailing_model_real') mailing_model_id = fields.Many2one( 'ir.model', string='Recipients Model', ondelete='cascade', required=True, domain=[('is_mailing_enabled', '=', True)], default=lambda self: self.env.ref('mass_mailing.model_mailing_list').id) mailing_model_name = fields.Char( string='Recipients Model Name', related='mailing_model_id.model', readonly=True, related_sudo=True) mailing_domain = fields.Char( string='Domain', compute='_compute_mailing_domain', readonly=False, store=True) mail_server_available = fields.Boolean( compute='_compute_mail_server_available', help="Technical field used to know if the user has activated the outgoing mail server option in the settings") mail_server_id = fields.Many2one('ir.mail_server', string='Mail Server', default=_get_default_mail_server_id, help="Use a specific mail server in priority. Otherwise Odoo relies on the first outgoing mail server available (based on their sequencing) as it does for normal mails.") contact_list_ids = fields.Many2many('mailing.list', 'mail_mass_mailing_list_rel', string='Mailing Lists') # A/B Testing ab_testing_completed = fields.Boolean(related='campaign_id.ab_testing_completed', store=True) ab_testing_description = fields.Html('A/B Testing Description', compute="_compute_ab_testing_description") ab_testing_enabled = fields.Boolean(string='Allow A/B Testing', default=False, help='If checked, recipients will be mailed only once for the whole campaign. ' 'This lets you send different mailings to randomly selected recipients and test ' 'the effectiveness of the mailings, without causing duplicate messages.') ab_testing_mailings_count = fields.Integer(related="campaign_id.ab_testing_mailings_count") ab_testing_pc = fields.Integer(string='A/B Testing percentage', help='Percentage of the contacts that will be mailed. Recipients will be chosen randomly.', default=10) ab_testing_schedule_datetime = fields.Datetime(related="campaign_id.ab_testing_schedule_datetime", readonly=False, default=lambda self: fields.Datetime.now() + relativedelta(days=1)) ab_testing_winner_selection = fields.Selection(related="campaign_id.ab_testing_winner_selection", default="opened_ratio", readonly=False, copy=True) kpi_mail_required = fields.Boolean('KPI mail required', copy=False) # statistics data mailing_trace_ids = fields.One2many('mailing.trace', 'mass_mailing_id', string='Emails Statistics') total = fields.Integer(compute="_compute_total") scheduled = fields.Integer(compute="_compute_statistics") expected = fields.Integer(compute="_compute_statistics") canceled = fields.Integer(compute="_compute_statistics") sent = fields.Integer(compute="_compute_statistics") delivered = fields.Integer(compute="_compute_statistics") opened = fields.Integer(compute="_compute_statistics") clicked = fields.Integer(compute="_compute_statistics") replied = fields.Integer(compute="_compute_statistics") bounced = fields.Integer(compute="_compute_statistics") failed = fields.Integer(compute="_compute_statistics") received_ratio = fields.Integer(compute="_compute_statistics", string='Received Ratio') opened_ratio = fields.Integer(compute="_compute_statistics", string='Opened Ratio') replied_ratio = fields.Integer(compute="_compute_statistics", string='Replied Ratio') bounced_ratio = fields.Integer(compute="_compute_statistics", string='Bounced Ratio') clicks_ratio = fields.Integer(compute="_compute_clicks_ratio", string="Number of Clicks") next_departure = fields.Datetime(compute="_compute_next_departure", string='Scheduled date') # UX warning_message = fields.Char( 'Warning Message', compute='_compute_warning_message', help='Warning message displayed in the mailing form view') _sql_constraints = [( 'percentage_valid', 'CHECK(ab_testing_pc >= 0 AND ab_testing_pc <= 100)', 'The A/B Testing Percentage needs to be between 0 and 100%' )] @api.depends('mail_server_id') def _compute_email_from(self): user_email = self.env.user.email_formatted notification_email = self.env['ir.mail_server']._get_default_from_address() for mailing in self: server = mailing.mail_server_id if not server: mailing.email_from = mailing.email_from or user_email elif mailing.email_from and server._match_from_filter(mailing.email_from, server.from_filter): mailing.email_from = mailing.email_from elif server._match_from_filter(user_email, server.from_filter): mailing.email_from = user_email elif server._match_from_filter(notification_email, server.from_filter): mailing.email_from = notification_email else: mailing.email_from = mailing.email_from or user_email def _compute_total(self): for mass_mailing in self: total = self.env[mass_mailing.mailing_model_real].search_count(mass_mailing._parse_mailing_domain()) if total and mass_mailing.ab_testing_enabled and mass_mailing.ab_testing_pc < 100: total = max(int(total / 100.0 * mass_mailing.ab_testing_pc), 1) mass_mailing.total = total def _compute_clicks_ratio(self): self.env.cr.execute(""" SELECT COUNT(DISTINCT(stats.id)) AS nb_mails, COUNT(DISTINCT(clicks.mailing_trace_id)) AS nb_clicks, stats.mass_mailing_id AS id FROM mailing_trace AS stats LEFT OUTER JOIN link_tracker_click AS clicks ON clicks.mailing_trace_id = stats.id WHERE stats.mass_mailing_id IN %s GROUP BY stats.mass_mailing_id """, [tuple(self.ids) or (None,)]) mass_mailing_data = self.env.cr.dictfetchall() mapped_data = dict([(m['id'], 100 * m['nb_clicks'] / m['nb_mails']) for m in mass_mailing_data]) for mass_mailing in self: mass_mailing.clicks_ratio = mapped_data.get(mass_mailing.id, 0) def _compute_statistics(self): """ Compute statistics of the mass mailing """ for key in ( 'scheduled', 'expected', 'canceled', 'sent', 'delivered', 'opened', 'clicked', 'replied', 'bounced', 'failed', 'received_ratio', 'opened_ratio', 'replied_ratio', 'bounced_ratio', ): self[key] = False if not self.ids: return # ensure traces are sent to db self.flush() self.env.cr.execute(""" SELECT m.id as mailing_id, COUNT(s.id) AS expected, COUNT(s.sent_datetime) AS sent, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'outgoing') AS scheduled, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'cancel') AS canceled, COUNT(s.trace_status) FILTER (WHERE s.trace_status in ('sent', 'open', 'reply')) AS delivered, COUNT(s.trace_status) FILTER (WHERE s.trace_status in ('open', 'reply')) AS opened, COUNT(s.links_click_datetime) AS clicked, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'reply') AS replied, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'bounce') AS bounced, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'error') AS failed FROM mailing_trace s RIGHT JOIN mailing_mailing m ON (m.id = s.mass_mailing_id) WHERE m.id IN %s GROUP BY m.id """, (tuple(self.ids), )) for row in self.env.cr.dictfetchall(): total = (row['expected'] - row['canceled']) or 1 row['received_ratio'] = 100.0 * row['delivered'] / total row['opened_ratio'] = 100.0 * row['opened'] / total row['replied_ratio'] = 100.0 * row['replied'] / total row['bounced_ratio'] = 100.0 * row['bounced'] / total self.browse(row.pop('mailing_id')).update(row) def _compute_next_departure(self): # Schedule_date should only be False if schedule_type = "now" or # mass_mailing is canceled. # A cron.trigger is created when mailing is put "in queue" # so we can reasonably expect that the cron worker will # execute this based on the cron.trigger's call_at which should # be now() when clicking "Send" or schedule_date if scheduled for mass_mailing in self: if mass_mailing.schedule_date: # max in case the user schedules a date in the past mass_mailing.next_departure = max(mass_mailing.schedule_date, fields.datetime.now()) else: mass_mailing.next_departure = fields.datetime.now() @api.depends('email_from', 'mail_server_id') def _compute_warning_message(self): for mailing in self: mail_server = mailing.mail_server_id if mail_server and not mail_server._match_from_filter(mailing.email_from, mail_server.from_filter): mailing.warning_message = _( 'This email from can not be used with this mail server.\n' 'Your emails might be marked as spam on the mail clients.' ) else: mailing.warning_message = False @api.depends('mailing_type') def _compute_medium_id(self): for mailing in self: if mailing.mailing_type == 'mail' and not mailing.medium_id: mailing.medium_id = self.env.ref('utm.utm_medium_email').id @api.depends('mailing_model_id') def _compute_mailing_model_real(self): for mailing in self: mailing.mailing_model_real = (mailing.mailing_model_id.model != 'mailing.list') and mailing.mailing_model_id.model or 'mailing.contact' @api.depends('mailing_model_id') def _compute_reply_to_mode(self): """ For main models not really using chatter to gather answers (contacts and mailing contacts), set reply-to as email-based. Otherwise answers by default go on the original discussion thread (business document). Note that mailing_model being mailing.list means contacting mailing.contact (see mailing_model_name versus mailing_model_real). """ for mailing in self: if mailing.mailing_model_id.model in ['res.partner', 'mailing.list', 'mailing.contact']: mailing.reply_to_mode = 'new' else: mailing.reply_to_mode = 'update' @api.depends('reply_to_mode') def _compute_reply_to(self): for mailing in self: if mailing.reply_to_mode == 'new' and not mailing.reply_to: mailing.reply_to = self.env.user.email_formatted elif mailing.reply_to_mode == 'update': mailing.reply_to = False @api.depends('mailing_model_id', 'contact_list_ids', 'mailing_type') def _compute_mailing_domain(self): for mailing in self: if not mailing.mailing_model_id: mailing.mailing_domain = '' else: mailing.mailing_domain = repr(mailing._get_default_mailing_domain()) @api.depends('schedule_type') def _compute_schedule_date(self): for mailing in self: if mailing.schedule_type == 'now' or not mailing.schedule_date: mailing.schedule_date = False @api.depends('state', 'schedule_date', 'sent_date', 'next_departure') def _compute_calendar_date(self): for mailing in self: if mailing.state == 'done': mailing.calendar_date = mailing.sent_date elif mailing.state == 'in_queue': mailing.calendar_date = mailing.next_departure elif mailing.state == 'sending': mailing.calendar_date = fields.Datetime.now() else: mailing.calendar_date = False @api.depends('body_arch') def _compute_is_body_empty(self): for mailing in self: mailing.is_body_empty = tools.is_html_empty(mailing.body_arch) def _compute_mail_server_available(self): self.mail_server_available = self.env['ir.config_parameter'].sudo().get_param('mass_mailing.outgoing_mail_server') # Overrides of mail.render.mixin @api.depends('mailing_model_real') def _compute_render_model(self): for mailing in self: mailing.render_model = mailing.mailing_model_real @api.depends('mailing_type') def _compute_mailing_type_description(self): for mailing in self: mailing.mailing_type_description = dict(self._fields.get('mailing_type').selection).get(mailing.mailing_type) @api.depends(lambda self: self._get_ab_testing_description_modifying_fields()) def _compute_ab_testing_description(self): mailing_ab_test = self.filtered('ab_testing_enabled') (self - mailing_ab_test).ab_testing_description = False for mailing in mailing_ab_test: mailing.ab_testing_description = self.env['ir.qweb']._render( 'mass_mailing.ab_testing_description', mailing._get_ab_testing_description_values() ) def _get_ab_testing_description_modifying_fields(self): return ['ab_testing_enabled', 'ab_testing_pc', 'ab_testing_schedule_datetime', 'ab_testing_winner_selection', 'campaign_id'] # ------------------------------------------------------ # ORM # ------------------------------------------------------ @api.model_create_multi def create(self, vals_list): now = fields.Datetime.now() ab_testing_cron = self.env.ref('mass_mailing.ir_cron_mass_mailing_ab_testing').sudo() for values in vals_list: if values.get('subject') and not values.get('name'): values['name'] = "%s %s" % (values['subject'], now) if values.get('body_html'): values['body_html'] = self._convert_inline_images_to_urls(values['body_html']) if values.get('ab_testing_schedule_datetime'): at = fields.Datetime.from_string(values['ab_testing_schedule_datetime']) ab_testing_cron._trigger(at=at) mailings = super().create(vals_list) campaign_vals = [ mailing._get_default_ab_testing_campaign_values() for mailing in mailings if mailing.ab_testing_enabled and not mailing.campaign_id ] self.env['utm.campaign'].create(campaign_vals) mailings._fix_attachment_ownership() return mailings def write(self, values): if values.get('body_html'): values['body_html'] = self._convert_inline_images_to_urls(values['body_html']) # When ab_testing_enabled is checked we create a campaign if there is none set. if values.get('ab_testing_enabled') and not values.get('campaign_id'): # Compute the values of the A/B test campaign based on the first mailing values['campaign_id'] = self.env['utm.campaign'].create(self[0]._get_default_ab_testing_campaign_values(values)).id # If ab_testing is already enabled on a mailing and the campaign is removed, we raise a ValidationError if values.get('campaign_id') is False and any(mailing.ab_testing_enabled for mailing in self) and 'ab_testing_enabled' not in values: raise ValidationError(_("A campaign should be set when A/B test is enabled")) result = super(MassMailing, self).write(values) self._fix_attachment_ownership() if any(self.mapped('ab_testing_schedule_datetime')): schedule_date = min(m.ab_testing_schedule_datetime for m in self if m.ab_testing_schedule_datetime) ab_testing_cron = self.env.ref('mass_mailing.ir_cron_mass_mailing_ab_testing').sudo() ab_testing_cron._trigger(at=schedule_date) return result def _fix_attachment_ownership(self): for record in self: record.attachment_ids.write({'res_model': record._name, 'res_id': record.id}) return self @api.returns('self', lambda value: value.id) def copy(self, default=None): self.ensure_one() default = dict(default or {}, name=_('%s (copy)', self.name), contact_list_ids=self.contact_list_ids.ids) return super(MassMailing, self).copy(default=default) def _group_expand_states(self, states, domain, order): return [key for key, val in type(self).state.selection] # ------------------------------------------------------ # ACTIONS # ------------------------------------------------------ def action_duplicate(self): self.ensure_one() mass_mailing_copy = self.copy() if mass_mailing_copy: context = dict(self.env.context) context['form_view_initial_mode'] = 'edit' action = { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'mailing.mailing', 'res_id': mass_mailing_copy.id, 'context': context, } if self.mailing_type == 'mail': action['views'] = [ (self.env.ref('mass_mailing.mailing_mailing_view_form_full_width').id, 'form'), ] return action return False def action_test(self): self.ensure_one() ctx = dict(self.env.context, default_mass_mailing_id=self.id) return { 'name': _('Test Mailing'), 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'mailing.mailing.test', 'target': 'new', 'context': ctx, } def action_launch(self): self.write({'schedule_type': 'now'}) return self.action_put_in_queue() def action_schedule(self): self.ensure_one() if self.schedule_date and self.schedule_date > fields.Datetime.now(): return self.action_put_in_queue() else: action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.mailing_mailing_schedule_date_action") action['context'] = dict(self.env.context, default_mass_mailing_id=self.id) return action def action_put_in_queue(self): self.write({'state': 'in_queue'}) cron = self.env.ref('mass_mailing.ir_cron_mass_mailing_queue') cron._trigger( schedule_date or fields.Datetime.now() for schedule_date in self.mapped('schedule_date') ) def action_cancel(self): self.write({'state': 'draft', 'schedule_date': False, 'schedule_type': 'now', 'next_departure': False}) def action_retry_failed(self): failed_mails = self.env['mail.mail'].sudo().search([ ('mailing_id', 'in', self.ids), ('state', '=', 'exception') ]) failed_mails.mapped('mailing_trace_ids').unlink() failed_mails.unlink() self.action_put_in_queue() def action_view_traces_scheduled(self): return self._action_view_traces_filtered('scheduled') def action_view_traces_canceled(self): return self._action_view_traces_filtered('canceled') def action_view_traces_failed(self): return self._action_view_traces_filtered('failed') def action_view_traces_sent(self): return self._action_view_traces_filtered('sent') def _action_view_traces_filtered(self, view_filter): action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.mailing_trace_action") action['name'] = _('Sent Mailings') action['context'] = {'search_default_mass_mailing_id': self.id,} filter_key = 'search_default_filter_%s' % (view_filter) action['context'][filter_key] = True action['views'] = [ (self.env.ref('mass_mailing.mailing_trace_view_tree_mail').id, 'tree'), (self.env.ref('mass_mailing.mailing_trace_view_form').id, 'form') ] return action def action_view_clicked(self): model_name = self.env['ir.model']._get('link.tracker').display_name return { 'name': model_name, 'type': 'ir.actions.act_window', 'view_mode': 'tree', 'res_model': 'link.tracker', 'domain': [('mass_mailing_id.id', '=', self.id)], 'context': dict(self._context, create=False) } def action_view_opened(self): return self._action_view_documents_filtered('open') def action_view_replied(self): return self._action_view_documents_filtered('reply') def action_view_bounced(self): return self._action_view_documents_filtered('bounce') def action_view_delivered(self): return self._action_view_documents_filtered('delivered') def _action_view_documents_filtered(self, view_filter): if view_filter in ('reply', 'bounce'): found_traces = self.mailing_trace_ids.filtered(lambda trace: trace.trace_status == view_filter) elif view_filter == 'open': found_traces = self.mailing_trace_ids.filtered(lambda trace: trace.trace_status in ('open', 'reply')) elif view_filter == 'click': found_traces = self.mailing_trace_ids.filtered(lambda trace: trace.links_click_datetime) elif view_filter == 'delivered': found_traces = self.mailing_trace_ids.filtered(lambda trace: trace.trace_status in ('sent', 'open', 'reply')) elif view_filter == 'sent': found_traces = self.mailing_trace_ids.filtered(lambda trace: trace.sent_datetime) else: found_traces = self.env['mailing.trace'] res_ids = found_traces.mapped('res_id') model_name = self.env['ir.model']._get(self.mailing_model_real).display_name return { 'name': model_name, 'type': 'ir.actions.act_window', 'view_mode': 'tree', 'res_model': self.mailing_model_real, 'domain': [('id', 'in', res_ids)], 'context': dict(self._context, create=False) } def update_opt_out(self, email, list_ids, value): if len(list_ids) > 0: model = self.env['mailing.contact'].with_context(active_test=False) records = model.search([('email_normalized', '=', tools.email_normalize(email))]) opt_out_records = self.env['mailing.contact.subscription'].search([ ('contact_id', 'in', records.ids), ('list_id', 'in', list_ids), ('opt_out', '!=', value) ]) opt_out_records.write({'opt_out': value}) message = _('The recipient <strong>unsubscribed from %s</strong> mailing list(s)') \ if value else _('The recipient <strong>subscribed to %s</strong> mailing list(s)') for record in records: # filter the list_id by record record_lists = opt_out_records.filtered(lambda rec: rec.contact_id.id == record.id) if len(record_lists) > 0: record.sudo().message_post(body=message % ', '.join(str(list.name) for list in record_lists.mapped('list_id'))) # ------------------------------------------------------ # A/B Test # ------------------------------------------------------ def action_compare_versions(self): self.ensure_one() if not self.campaign_id: raise ValueError(_("No mailing campaign has been found")) action = { 'name': _('A/B Tests'), 'type': 'ir.actions.act_window', 'view_mode': 'tree,kanban,form,calendar,graph', 'res_model': 'mailing.mailing', 'domain': [('campaign_id', '=', self.campaign_id.id), ('ab_testing_enabled', '=', True), ('mailing_type', '=', self.mailing_type)], } if self.mailing_type == 'mail': action['views'] = [ (False, 'tree'), (False, 'kanban'), (self.env.ref('mass_mailing.mailing_mailing_view_form_full_width').id, 'form'), (False, 'calendar'), (False, 'graph'), ] return action def action_send_winner_mailing(self): """Send the winner mailing based on the winner selection field. This action is used in 2 cases: - When the user clicks on a button to send the winner mailing. There is only one mailing in self - When the cron is executed to send winner mailing based on the A/B testing schedule datetime. In this case 'self' contains all the mailing for the campaigns so we just need to take the first to determine the winner. If the winner mailing is computed automatically, we sudo the mailings of the campaign in order to sort correctly the mailings based on the selection that can be used with sub-modules like CRM and Sales """ if len(self.campaign_id) != 1: raise ValueError(_("To send the winner mailing the same campaign should be used by the mailings")) if any(mailing.ab_testing_completed for mailing in self): raise ValueError(_("To send the winner mailing the campaign should not have been completed.")) final_mailing = self[0] sorted_by = final_mailing._get_ab_testing_winner_selection()['value'] if sorted_by != 'manual': ab_testing_mailings = final_mailing._get_ab_testing_siblings_mailings().sudo() selected_mailings = ab_testing_mailings.filtered(lambda m: m.state == 'done').sorted(sorted_by, reverse=True) if selected_mailings: final_mailing = selected_mailings[0] else: raise ValidationError(_("No mailing for this A/B testing campaign has been sent yet! Send one first and try again later.")) return final_mailing.action_select_as_winner() def action_select_as_winner(self): self.ensure_one() if not self.ab_testing_enabled: raise ValueError(_("A/B test option has not been enabled")) self.campaign_id.write({ 'ab_testing_completed': True, }) final_mailing = self.copy({ 'ab_testing_pc': 100, }) final_mailing.action_launch() action = self.env['ir.actions.act_window']._for_xml_id('mass_mailing.action_ab_testing_open_winner_mailing') action['res_id'] = final_mailing.id if self.mailing_type == 'mail': action['views'] = [ (self.env.ref('mass_mailing.mailing_mailing_view_form_full_width').id, 'form'), ] return action def _get_ab_testing_description_values(self): self.ensure_one() other_ab_testing_mailings = self._get_ab_testing_siblings_mailings().filtered(lambda m: m.id != self.id) other_ab_testing_pc = sum([mailing.ab_testing_pc for mailing in other_ab_testing_mailings]) return { 'mailing': self, 'ab_testing_winner_selection_description': self._get_ab_testing_winner_selection()['description'], 'other_ab_testing_pc': other_ab_testing_pc, 'remaining_ab_testing_pc': 100 - (other_ab_testing_pc + self.ab_testing_pc), } def _get_ab_testing_siblings_mailings(self): return self.campaign_id.mailing_mail_ids.filtered(lambda m: m.ab_testing_enabled) def _get_ab_testing_winner_selection(self): ab_testing_winner_selection_description = dict( self._fields.get('ab_testing_winner_selection').related_field.selection ).get(self.ab_testing_winner_selection) return { 'value': self.ab_testing_winner_selection, 'description': ab_testing_winner_selection_description, } def _get_default_ab_testing_campaign_values(self, values=None): values = values or dict() return { 'ab_testing_schedule_datetime': values.get('ab_testing_schedule_datetime') or self.ab_testing_schedule_datetime, 'ab_testing_winner_selection': values.get('ab_testing_winner_selection') or self.ab_testing_winner_selection, 'mailing_mail_ids': self.ids, 'name': _('A/B Test: %s', values.get('subject') or self.subject or fields.Datetime.now()), 'user_id': values.get('user_id') or self.user_id.id or self.env.user.id, } # ------------------------------------------------------ # Email Sending # ------------------------------------------------------ def _get_opt_out_list(self): """ Give list of opt-outed emails, depending on specific model-based computation if available. :return list: opt-outed emails, preferably normalized (aka not records) """ self.ensure_one() opt_out = {} target = self.env[self.mailing_model_real] if hasattr(self.env[self.mailing_model_name], '_mailing_get_opt_out_list'): opt_out = self.env[self.mailing_model_name]._mailing_get_opt_out_list(self) _logger.info( "Mass-mailing %s targets %s, blacklist: %s emails", self, target._name, len(opt_out)) else: _logger.info("Mass-mailing %s targets %s, no opt out list available", self, target._name) return opt_out def _get_link_tracker_values(self): self.ensure_one() vals = {'mass_mailing_id': self.id} if self.campaign_id: vals['campaign_id'] = self.campaign_id.id if self.source_id: vals['source_id'] = self.source_id.id if self.medium_id: vals['medium_id'] = self.medium_id.id return vals def _get_seen_list(self): """Returns a set of emails already targeted by current mailing/campaign (no duplicates)""" self.ensure_one() target = self.env[self.mailing_model_real] # avoid loading a large number of records in memory # + use a basic heuristic for extracting emails query = """ SELECT lower(substring(t.%(mail_field)s, '([^ ,;<@]+@[^> ,;]+)')) FROM mailing_trace s JOIN %(target)s t ON (s.res_id = t.id) %(join_domain)s WHERE substring(t.%(mail_field)s, '([^ ,;<@]+@[^> ,;]+)') IS NOT NULL %(where_domain)s """ # Apply same 'get email field' rule from mail_thread.message_get_default_recipients if 'partner_id' in target._fields and target._fields['partner_id'].store: mail_field = 'email' query = """ SELECT lower(substring(p.%(mail_field)s, '([^ ,;<@]+@[^> ,;]+)')) FROM mailing_trace s JOIN %(target)s t ON (s.res_id = t.id) JOIN res_partner p ON (t.partner_id = p.id) %(join_domain)s WHERE substring(p.%(mail_field)s, '([^ ,;<@]+@[^> ,;]+)') IS NOT NULL %(where_domain)s """ elif issubclass(type(target), self.pool['mail.thread.blacklist']): mail_field = 'email_normalized' elif 'email_from' in target._fields and target._fields['email_from'].store: mail_field = 'email_from' elif 'partner_email' in target._fields and target._fields['partner_email'].store: mail_field = 'partner_email' elif 'email' in target._fields and target._fields['email'].store: mail_field = 'email' else: raise UserError(_("Unsupported mass mailing model %s", self.mailing_model_id.name)) if self.ab_testing_enabled: query += """ AND s.campaign_id = %%(mailing_campaign_id)s; """ else: query += """ AND s.mass_mailing_id = %%(mailing_id)s AND s.model = %%(target_model)s; """ join_domain, where_domain = self._get_seen_list_extra() query = query % {'target': target._table, 'mail_field': mail_field, 'join_domain': join_domain, 'where_domain': where_domain} params = {'mailing_id': self.id, 'mailing_campaign_id': self.campaign_id.id, 'target_model': self.mailing_model_real} self._cr.execute(query, params) seen_list = set(m[0] for m in self._cr.fetchall()) _logger.info( "Mass-mailing %s has already reached %s %s emails", self, len(seen_list), target._name) return seen_list def _get_seen_list_extra(self): return ('', '') def _get_mass_mailing_context(self): """Returns extra context items with pre-filled blacklist and seen list for massmailing""" return { 'post_convert_links': self._get_link_tracker_values(), } def _get_recipients(self): mailing_domain = self._parse_mailing_domain() res_ids = self.env[self.mailing_model_real].search(mailing_domain).ids # randomly choose a fragment if self.ab_testing_enabled and self.ab_testing_pc < 100: contact_nbr = self.env[self.mailing_model_real].search_count(mailing_domain) topick = 0 if contact_nbr: topick = max(int(contact_nbr / 100.0 * self.ab_testing_pc), 1) if self.campaign_id and self.ab_testing_enabled: already_mailed = self.campaign_id._get_mailing_recipients()[self.campaign_id.id] else: already_mailed = set([]) remaining = set(res_ids).difference(already_mailed) if topick > len(remaining) or (len(remaining) > 0 and topick == 0): topick = len(remaining) res_ids = random.sample(remaining, topick) return res_ids def _get_remaining_recipients(self): res_ids = self._get_recipients() trace_domain = [('model', '=', self.mailing_model_real)] if self.ab_testing_enabled and self.ab_testing_pc == 100: trace_domain = expression.AND([trace_domain, [('mass_mailing_id', 'in', self._get_ab_testing_siblings_mailings().ids)]]) else: trace_domain = expression.AND([trace_domain, [ ('res_id', 'in', res_ids), ('mass_mailing_id', '=', self.id), ]]) already_mailed = self.env['mailing.trace'].search_read(trace_domain, ['res_id']) done_res_ids = {record['res_id'] for record in already_mailed} return [rid for rid in res_ids if rid not in done_res_ids] def _get_unsubscribe_url(self, email_to, res_id): url = werkzeug.urls.url_join( self.get_base_url(), 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % { 'mailing_id': self.id, 'params': werkzeug.urls.url_encode({ 'res_id': res_id, 'email': email_to, 'token': self._unsubscribe_token(res_id, email_to), }), } ) return url def _get_view_url(self, email_to, res_id): url = werkzeug.urls.url_join( self.get_base_url(), 'mailing/%(mailing_id)s/view?%(params)s' % { 'mailing_id': self.id, 'params': werkzeug.urls.url_encode({ 'res_id': res_id, 'email': email_to, 'token': self._unsubscribe_token(res_id, email_to), }), } ) return url def action_send_mail(self, res_ids=None): author_id = self.env.user.partner_id.id # If no recipient is passed, we don't want to use the recipients of the first # mailing for all the others initial_res_ids = res_ids for mailing in self: if not initial_res_ids: res_ids = mailing._get_remaining_recipients() if not res_ids: raise UserError(_('There are no recipients selected.')) composer_values = { 'author_id': author_id, 'attachment_ids': [(4, attachment.id) for attachment in mailing.attachment_ids], 'body': mailing._prepend_preview(mailing.body_html, mailing.preview), 'subject': mailing.subject, 'model': mailing.mailing_model_real, 'email_from': mailing.email_from, 'record_name': False, 'composition_mode': 'mass_mail', 'mass_mailing_id': mailing.id, 'mailing_list_ids': [(4, l.id) for l in mailing.contact_list_ids], 'reply_to_force_new': mailing.reply_to_mode == 'new', 'template_id': None, 'mail_server_id': mailing.mail_server_id.id, } if mailing.reply_to_mode == 'new': composer_values['reply_to'] = mailing.reply_to composer = self.env['mail.compose.message'].with_context(active_ids=res_ids).create(composer_values) extra_context = mailing._get_mass_mailing_context() composer = composer.with_context(active_ids=res_ids, **extra_context) # auto-commit except in testing mode auto_commit = not getattr(threading.current_thread(), 'testing', False) composer._action_send_mail(auto_commit=auto_commit) mailing.write({ 'state': 'done', 'sent_date': fields.Datetime.now(), # send the KPI mail only if it's the first sending 'kpi_mail_required': not mailing.sent_date, }) return True def convert_links(self): res = {} for mass_mailing in self: html = mass_mailing.body_html if mass_mailing.body_html else '' vals = {'mass_mailing_id': mass_mailing.id} if mass_mailing.campaign_id: vals['campaign_id'] = mass_mailing.campaign_id.id if mass_mailing.source_id: vals['source_id'] = mass_mailing.source_id.id if mass_mailing.medium_id: vals['medium_id'] = mass_mailing.medium_id.id res[mass_mailing.id] = mass_mailing._shorten_links(html, vals, blacklist=['/unsubscribe_from_list', '/view']) return res @api.model def _process_mass_mailing_queue(self): mass_mailings = self.search([('state', 'in', ('in_queue', 'sending')), '|', ('schedule_date', '<', fields.Datetime.now()), ('schedule_date', '=', False)]) for mass_mailing in mass_mailings: user = mass_mailing.write_uid or self.env.user mass_mailing = mass_mailing.with_context(**user.with_user(user).context_get()) if len(mass_mailing._get_remaining_recipients()) > 0: mass_mailing.state = 'sending' mass_mailing.action_send_mail() else: mass_mailing.write({ 'state': 'done', 'sent_date': fields.Datetime.now(), # send the KPI mail only if it's the first sending 'kpi_mail_required': not mass_mailing.sent_date, }) mailings = self.env['mailing.mailing'].search([ ('kpi_mail_required', '=', True), ('state', '=', 'done'), ('sent_date', '<=', fields.Datetime.now() - relativedelta(days=1)), ('sent_date', '>=', fields.Datetime.now() - relativedelta(days=5)), ]) if mailings: mailings._action_send_statistics() # ------------------------------------------------------ # STATISTICS # ------------------------------------------------------ def _action_send_statistics(self): """Send an email to the responsible of each finished mailing with the statistics.""" self.kpi_mail_required = False mails_sudo = self.env['mail.mail'].sudo() for mailing in self: if mailing.user_id: mailing = mailing.with_user(mailing.user_id).with_context( lang=mailing.user_id.lang or self._context.get('lang') ) mailing_type = mailing._get_pretty_mailing_type() mail_user = mailing.user_id or self.env.user mail_company = mail_user.company_id link_trackers = self.env['link.tracker'].search( [('mass_mailing_id', '=', mailing.id)] ).sorted('count', reverse=True) link_trackers_body = self.env['ir.qweb']._render( 'mass_mailing.mass_mailing_kpi_link_trackers', { 'object': mailing, 'link_trackers': link_trackers, 'mailing_type': mailing_type, }, ) rendered_body = self.env['ir.qweb']._render( 'digest.digest_mail_main', { 'body': tools.html_sanitize(link_trackers_body), 'company': mail_company, 'user': mail_user, 'display_mobile_banner': True, ** mailing._prepare_statistics_email_values() }, ) full_mail = self.env['mail.render.mixin']._render_encapsulate( 'digest.digest_mail_layout', rendered_body, ) mail_values = { 'auto_delete': True, 'author_id': mail_user.partner_id.id, 'email_from': mail_user.email_formatted, 'email_to': mail_user.email_formatted, 'body_html': full_mail, 'reply_to': mail_company.email_formatted or mail_user.email_formatted, 'state': 'outgoing', 'subject': _('24H Stats of %(mailing_type)s "%(mailing_name)s"', mailing_type=mailing._get_pretty_mailing_type(), mailing_name=mailing.subject ), } mails_sudo += self.env['mail.mail'].sudo().create(mail_values) return mails_sudo def _prepare_statistics_email_values(self): """Return some statistics that will be displayed in the mailing statistics email. Each item in the returned list will be displayed as a table, with a title and 1, 2 or 3 columns. """ self.ensure_one() mailing_type = self._get_pretty_mailing_type() kpi = {} if self.mailing_type == 'mail': kpi = { 'kpi_fullname': _('Engagement on %(expected)i %(mailing_type)s Sent', expected=self.expected, mailing_type=mailing_type ), 'kpi_col1': { 'value': f'{self.received_ratio}%', 'col_subtitle': _('RECEIVED (%i)', self.delivered), }, 'kpi_col2': { 'value': f'{self.opened_ratio}%', 'col_subtitle': _('OPENED (%i)', self.opened), }, 'kpi_col3': { 'value': f'{self.replied_ratio}%', 'col_subtitle': _('REPLIED (%i)', self.replied), }, 'kpi_action': None, 'kpi_name': self.mailing_type, } random_tip = self.env['digest.tip'].search( [('group_id.category_id', '=', self.env.ref('base.module_category_marketing_email_marketing').id)] ) if random_tip: random_tip = random.choice(random_tip).tip_description formatted_date = tools.format_datetime( self.env, self.sent_date, self.user_id.tz, 'MMM dd, YYYY', self.user_id.lang ) if self.sent_date else False web_base_url = self.get_base_url() return { 'title': _('24H Stats of %(mailing_type)s "%(mailing_name)s"', mailing_type=mailing_type, mailing_name=self.subject ), 'top_button_label': _('More Info'), 'top_button_url': url_join(web_base_url, f'/web#id={self.id}&model=mailing.mailing&view_type=form'), 'kpi_data': [ kpi, { 'kpi_fullname': _('Business Benefits on %(expected)i %(mailing_type)s Sent', expected=self.expected, mailing_type=mailing_type ), 'kpi_action': None, 'kpi_col1': {}, 'kpi_col2': {}, 'kpi_col3': {}, 'kpi_name': 'trace', }, ], 'tips': [random_tip] if random_tip else False, 'formatted_date': formatted_date, } def _get_pretty_mailing_type(self): if self.mailing_type == 'mail': return _('Emails') # ------------------------------------------------------ # TOOLS # ------------------------------------------------------ def _get_default_mailing_domain(self): mailing_domain = [] if hasattr(self.env[self.mailing_model_name], '_mailing_get_default_domain'): mailing_domain = self.env[self.mailing_model_name]._mailing_get_default_domain(self) if self.mailing_type == 'mail' and 'is_blacklisted' in self.env[self.mailing_model_name]._fields: mailing_domain = expression.AND([[('is_blacklisted', '=', False)], mailing_domain]) return mailing_domain def _parse_mailing_domain(self): self.ensure_one() try: mailing_domain = literal_eval(self.mailing_domain) except Exception: mailing_domain = [('id', 'in', [])] return mailing_domain def _unsubscribe_token(self, res_id, email): """Generate a secure hash for this mailing list and parameters. This is appended to the unsubscription URL and then checked at unsubscription time to ensure no malicious unsubscriptions are performed. :param int res_id: ID of the resource that will be unsubscribed. :param str email: Email of the resource that will be unsubscribed. """ secret = self.env["ir.config_parameter"].sudo().get_param("database.secret") token = (self.env.cr.dbname, self.id, int(res_id), tools.ustr(email)) return hmac.new(secret.encode('utf-8'), repr(token).encode('utf-8'), hashlib.sha512).hexdigest() def _convert_inline_images_to_urls(self, body_html): """ Find inline base64 encoded images, make an attachement out of them and replace the inline image with an url to the attachement. """ def _image_to_url(b64image: bytes): """Store an image in an attachement and returns an url""" attachment = self.env['ir.attachment'].create({ 'datas': b64image, 'name': "cropped_image_mailing_{}".format(self.id), 'type': 'binary',}) attachment.generate_access_token() return '/web/image/%s?access_token=%s' % ( attachment.id, attachment.access_token) modified = False root = lxml.html.fromstring(body_html) for node in root.iter('img'): match = image_re.match(node.attrib.get('src', '')) if match: mime = match.group(1) # unsed image = match.group(2).encode() # base64 image as bytes node.attrib['src'] = _image_to_url(image) modified = True if modified: return lxml.html.tostring(root, encoding='unicode') return body_html
47.232297
54,695
7,588
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class MailingTrace(models.Model): """ MailingTrace models the statistics collected about emails. Those statistics are stored in a separated model and table to avoid bloating the mail_mail table with statistics values. This also allows to delete emails send with mass mailing without loosing the statistics about them. Note:: State management / Error codes / Failure types summary * trace_status 'outgoing', 'sent', 'opened', 'replied', 'error', 'bouce', 'cancel' * failure_type # generic 'unknown', # mass_mailing "mail_email_invalid", "mail_smtp", "mail_email_missing" # mass mailing mass mode specific codes "mail_bl", "mail_optout", "mail_dup" # mass_mailing_sms 'sms_number_missing', 'sms_number_format', 'sms_credit', 'sms_server', 'sms_acc' # mass_mailing_sms mass mode specific codes 'sms_blacklist', 'sms_duplicate', 'sms_optout', * cancel: * mail: set in get_mail_values in composer, if email is blacklisted (mail) or in opt_out / seen list (mass_mailing) or email_to is void or incorrectly formatted (mass_mailing) - based on mail cancel state * sms: set in _prepare_mass_sms_trace_values in composer if sms is in cancel state; either blacklisted (sms) or in opt_out / seen list (sms); * void mail / void sms number -> error (mail_missing, sms_number_missing) * invalid mail / invalid sms number -> error (RECIPIENT, sms_number_format) * exception: set in _postprocess_sent_message (_postprocess_iap_sent_sms) if mail (sms) not sent with failure type, reset if sent; * sent: set in _postprocess_sent_message (_postprocess_iap_sent_sms) if mail (sms) sent * clicked: triggered by add_click * opened: triggered by add_click + blank gif (mail) + gateway reply (mail) * replied: triggered by gateway reply (mail) * bounced: triggered by gateway bounce (mail) or in _prepare_mass_sms_trace_values if sms_number_format error when sending sms (sms) """ _name = 'mailing.trace' _description = 'Mailing Statistics' _rec_name = 'id' _order = 'create_date DESC' trace_type = fields.Selection([('mail', 'Email')], string='Type', default='mail', required=True) display_name = fields.Char(compute='_compute_display_name') # mail data mail_mail_id = fields.Many2one('mail.mail', string='Mail', index=True) mail_mail_id_int = fields.Integer( string='Mail ID (tech)', help='ID of the related mail_mail. This field is an integer field because ' 'the related mail_mail can be deleted separately from its statistics. ' 'However the ID is needed for several action and controllers.', index=True, ) email = fields.Char(string="Email", help="Normalized email address") message_id = fields.Char(string='Message-ID', help="Technical field for the email Message-ID (RFC 2392)") medium_id = fields.Many2one(related='mass_mailing_id.medium_id') source_id = fields.Many2one(related='mass_mailing_id.source_id') # document model = fields.Char(string='Document model', required=True) res_id = fields.Many2oneReference(string='Document ID', model_field='model', required=True) # campaign data mass_mailing_id = fields.Many2one('mailing.mailing', string='Mailing', index=True, ondelete='cascade') campaign_id = fields.Many2one( related='mass_mailing_id.campaign_id', string='Campaign', store=True, readonly=True, index=True) # Status sent_datetime = fields.Datetime('Sent On') open_datetime = fields.Datetime('Opened On') reply_datetime = fields.Datetime('Replied On') trace_status = fields.Selection(selection=[ ('outgoing', 'Outgoing'), ('sent', 'Sent'), ('open', 'Opened'), ('reply', 'Replied'), ('bounce', 'Bounced'), ('error', 'Exception'), ('cancel', 'Canceled')], string='Status', default='outgoing') failure_type = fields.Selection(selection=[ # generic ("unknown", "Unknown error"), # mail ("mail_email_invalid", "Invalid email address"), ("mail_email_missing", "Missing email address"), ("mail_smtp", "Connection failed (outgoing mail server problem)"), # mass mode ("mail_bl", "Blacklisted Address"), ("mail_optout", "Opted Out"), ("mail_dup", "Duplicated Email"), ], string='Failure type') # Link tracking links_click_ids = fields.One2many('link.tracker.click', 'mailing_trace_id', string='Links click') links_click_datetime = fields.Datetime('Clicked On', help='Stores last click datetime in case of multi clicks.') @api.depends('trace_type', 'mass_mailing_id') def _compute_display_name(self): for trace in self: trace.display_name = '%s: %s (%s)' % (trace.trace_type, trace.mass_mailing_id.name, trace.id) @api.model_create_multi def create(self, values_list): for values in values_list: if 'mail_mail_id' in values: values['mail_mail_id_int'] = values['mail_mail_id'] return super(MailingTrace, self).create(values_list) def action_view_contact(self): self.ensure_one() return { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': self.model, 'target': 'current', 'res_id': self.res_id } def set_sent(self, domain=None): traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.write({'trace_status': 'sent', 'sent_datetime': fields.Datetime.now(), 'failure_type': False}) return traces def set_opened(self, domain=None): """ Reply / Open are a bit shared in various processes: reply implies open, click implies open. Let us avoid status override by skipping traces that are not already opened or replied. """ traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.filtered(lambda t: t.trace_status not in ('open', 'reply')).write({'trace_status': 'open', 'open_datetime': fields.Datetime.now()}) return traces def set_clicked(self, domain=None): traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.write({'links_click_datetime': fields.Datetime.now()}) return traces def set_replied(self, domain=None): traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.write({'trace_status': 'reply', 'reply_datetime': fields.Datetime.now()}) return traces def set_bounced(self, domain=None): traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.write({'trace_status': 'bounce'}) return traces def set_failed(self, domain=None, failure_type=False): traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.write({'trace_status': 'error', 'failure_type': failure_type}) return traces def set_canceled(self, domain=None): traces = self + (self.search(domain) if domain else self.env['mailing.trace']) traces.write({'trace_status': 'cancel'}) return traces
46.268293
7,588
15,634
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, fields, models from odoo.exceptions import UserError class MassMailingList(models.Model): """Model of a contact list. """ _name = 'mailing.list' _order = 'name' _description = 'Mailing List' _mailing_enabled = True # As this model has his own data merge, avoid to enable the generic data_merge on that model. _disable_data_merge = True name = fields.Char(string='Mailing List', required=True) active = fields.Boolean(default=True) contact_count = fields.Integer(compute="_compute_mailing_list_statistics", string='Number of Contacts') contact_count_email = fields.Integer(compute="_compute_mailing_list_statistics", string="Number of Emails") contact_count_opt_out = fields.Integer(compute="_compute_mailing_list_statistics", string="Number of Opted-out") contact_pct_opt_out = fields.Float(compute="_compute_mailing_list_statistics", string="Percentage of Opted-out") contact_count_blacklisted = fields.Integer(compute="_compute_mailing_list_statistics", string="Number of Blacklisted") contact_pct_blacklisted = fields.Float(compute="_compute_mailing_list_statistics", string="Percentage of Blacklisted") contact_pct_bounce = fields.Float(compute="_compute_mailing_list_statistics", string="Percentage of Bouncing") contact_ids = fields.Many2many( 'mailing.contact', 'mailing_contact_list_rel', 'list_id', 'contact_id', string='Mailing Lists', copy=False) mailing_count = fields.Integer(compute="_compute_mailing_list_count", string="Number of Mailing") mailing_ids = fields.Many2many('mailing.mailing', 'mail_mass_mailing_list_rel', string='Mass Mailings', copy=False) subscription_ids = fields.One2many( 'mailing.contact.subscription', 'list_id', string='Subscription Information', copy=True, depends=['contact_ids']) is_public = fields.Boolean(default=True, help="The mailing list can be accessible by recipient in the unsubscription" " page to allows him to update his subscription preferences.") # ------------------------------------------------------ # COMPUTE / ONCHANGE # ------------------------------------------------------ def _compute_mailing_list_count(self): data = {} if self.ids: self.env.cr.execute(''' SELECT mailing_list_id, count(*) FROM mail_mass_mailing_list_rel WHERE mailing_list_id IN %s GROUP BY mailing_list_id''', (tuple(self.ids),)) data = dict(self.env.cr.fetchall()) for mailing_list in self: mailing_list.mailing_count = data.get(mailing_list._origin.id, 0) def _compute_mailing_list_statistics(self): """ Computes various statistics for this mailing.list that allow users to have a global idea of its quality (based on blacklist, opt-outs, ...). As some fields depend on the value of each other (mainly percentages), we compute everything in a single method. """ # 1. Fetch contact data and associated counts (total / blacklist / opt-out) contact_statistics_per_mailing = self._fetch_contact_statistics() # 2. Fetch bounce data # Optimized SQL way of fetching the count of contacts that have # at least 1 message bouncing for passed mailing.lists """ bounce_per_mailing = {} if self.ids: sql = ''' SELECT mclr.list_id, COUNT(DISTINCT mc.id) FROM mailing_contact mc LEFT OUTER JOIN mailing_contact_list_rel mclr ON mc.id = mclr.contact_id WHERE mc.message_bounce > 0 AND mclr.list_id in %s GROUP BY mclr.list_id ''' self.env.cr.execute(sql, (tuple(self.ids),)) bounce_per_mailing = dict(self.env.cr.fetchall()) # 3. Compute and assign all counts / pct fields for mailing_list in self: contact_counts = contact_statistics_per_mailing.get(mailing_list.id, {}) for field, value in contact_counts.items(): if field in self._fields: mailing_list[field] = value if mailing_list.contact_count != 0: mailing_list.contact_pct_opt_out = 100 * (mailing_list.contact_count_opt_out / mailing_list.contact_count) mailing_list.contact_pct_blacklisted = 100 * (mailing_list.contact_count_blacklisted / mailing_list.contact_count) mailing_list.contact_pct_bounce = 100 * (bounce_per_mailing.get(mailing_list.id, 0) / mailing_list.contact_count) else: mailing_list.contact_pct_opt_out = 0 mailing_list.contact_pct_blacklisted = 0 mailing_list.contact_pct_bounce = 0 # ------------------------------------------------------ # ORM overrides # ------------------------------------------------------ def write(self, vals): # Prevent archiving used mailing list if 'active' in vals and not vals.get('active'): mass_mailings = self.env['mailing.mailing'].search_count([ ('state', '!=', 'done'), ('contact_list_ids', 'in', self.ids), ]) if mass_mailings > 0: raise UserError(_("At least one of the mailing list you are trying to archive is used in an ongoing mailing campaign.")) return super(MassMailingList, self).write(vals) def name_get(self): return [(list.id, "%s (%s)" % (list.name, list.contact_count)) for list in self] def copy(self, default=None): self.ensure_one() default = dict(default or {}, name=_('%s (copy)', self.name),) return super(MassMailingList, self).copy(default) # ------------------------------------------------------ # ACTIONS # ------------------------------------------------------ def action_view_contacts(self): action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.action_view_mass_mailing_contacts") action['domain'] = [('list_ids', 'in', self.ids)] action['context'] = {'default_list_ids': self.ids} return action def action_view_contacts_email(self): action = self.action_view_contacts() action['context'] = dict(action.get('context', {}), search_default_filter_valid_email_recipient=1) return action def action_view_mailings(self): action = self.env["ir.actions.actions"]._for_xml_id('mass_mailing.mailing_mailing_action_mail') action['domain'] = [('contact_list_ids', 'in', self.ids)] action['context'] = {'default_mailing_type': 'mail', 'default_contact_list_ids': self.ids} return action def action_view_contacts_opt_out(self): action = self.env["ir.actions.actions"]._for_xml_id('mass_mailing.action_view_mass_mailing_contacts') action['domain'] = [('list_ids', 'in', self.id)] action['context'] = {'default_list_ids': self.ids, 'create': False, 'search_default_filter_opt_out': 1} return action def action_view_contacts_blacklisted(self): action = self.env["ir.actions.actions"]._for_xml_id('mass_mailing.action_view_mass_mailing_contacts') action['domain'] = [('list_ids', 'in', self.id)] action['context'] = {'default_list_ids': self.ids, 'create': False, 'search_default_filter_blacklisted': 1} return action def action_view_contacts_bouncing(self): action = self.env["ir.actions.actions"]._for_xml_id('mass_mailing.action_view_mass_mailing_contacts') action['domain'] = [('list_ids', 'in', self.id)] action['context'] = {'default_list_ids': self.ids, 'create': False, 'search_default_filter_bounce': 1} return action def action_merge(self, src_lists, archive): """ Insert all the contact from the mailing lists 'src_lists' to the mailing list in 'self'. Possibility to archive the mailing lists 'src_lists' after the merge except the destination mailing list 'self'. """ # Explation of the SQL query with an example. There are the following lists # A (id=4): [email protected]; [email protected] # B (id=5): [email protected]; [email protected] # C (id=6): nothing # To merge the mailing lists A and B into C, we build the view st that looks # like this with our example: # # contact_id | email | row_number | list_id | # ------------+---------------------------+------------------------ # 4 | [email protected] | 1 | 4 | # 6 | [email protected] | 2 | 5 | # 5 | [email protected] | 1 | 4 | # 7 | [email protected] | 1 | 5 | # # The row_column is kind of an occurence counter for the email address. # Then we create the Many2many relation between the destination list and the contacts # while avoiding to insert an existing email address (if the destination is in the source # for example) self.ensure_one() # Put destination is sources lists if not already the case src_lists |= self self.env['mailing.contact'].flush(['email', 'email_normalized']) self.env['mailing.contact.subscription'].flush(['contact_id', 'opt_out', 'list_id']) self.env.cr.execute(""" INSERT INTO mailing_contact_list_rel (contact_id, list_id) SELECT st.contact_id AS contact_id, %s AS list_id FROM ( SELECT contact.id AS contact_id, contact.email AS email, list.id AS list_id, row_number() OVER (PARTITION BY email ORDER BY email) AS rn FROM mailing_contact contact, mailing_contact_list_rel contact_list_rel, mailing_list list WHERE contact.id=contact_list_rel.contact_id AND COALESCE(contact_list_rel.opt_out,FALSE) = FALSE AND contact.email_normalized NOT IN (select email from mail_blacklist where active = TRUE) AND list.id=contact_list_rel.list_id AND list.id IN %s AND NOT EXISTS ( SELECT 1 FROM mailing_contact contact2, mailing_contact_list_rel contact_list_rel2 WHERE contact2.email = contact.email AND contact_list_rel2.contact_id = contact2.id AND contact_list_rel2.list_id = %s ) ) st WHERE st.rn = 1;""", (self.id, tuple(src_lists.ids), self.id)) self.flush() self.invalidate_cache() if archive: (src_lists - self).action_archive() def close_dialog(self): return {'type': 'ir.actions.act_window_close'} # ------------------------------------------------------ # MAILING # ------------------------------------------------------ def _mailing_get_default_domain(self, mailing): return [('list_ids', 'in', mailing.contact_list_ids.ids)] def _mailing_get_opt_out_list(self, mailing): """ Check subscription on all involved mailing lists. If user is opt_out on one list but not on another if two users with same email address, one opted in and the other one opted out, send the mail anyway. """ # TODO DBE Fixme : Optimize the following to get real opt_out and opt_in subscriptions = self.subscription_ids if self else mailing.contact_list_ids.subscription_ids opt_out_contacts = subscriptions.filtered(lambda rel: rel.opt_out).mapped('contact_id.email_normalized') opt_in_contacts = subscriptions.filtered(lambda rel: not rel.opt_out).mapped('contact_id.email_normalized') opt_out = set(c for c in opt_out_contacts if c not in opt_in_contacts) return opt_out # ------------------------------------------------------ # UTILITY # ------------------------------------------------------ def _fetch_contact_statistics(self): """ Compute number of contacts matching various conditions. (see '_get_contact_count_select_fields' for details) Will return a dict under the form: { 42: { # 42 being the mailing list ID 'contact_count': 52, 'contact_count_email': 35, 'contact_count_opt_out': 5, 'contact_count_blacklisted': 2 }, ... } """ res = [] if self.ids: self.env.cr.execute(f''' SELECT {','.join(self._get_contact_statistics_fields().values())} FROM mailing_contact_list_rel r {self._get_contact_statistics_joins()} WHERE list_id IN %s GROUP BY list_id; ''', (tuple(self.ids), )) res = self.env.cr.dictfetchall() contact_counts = {} for res_item in res: mailing_list_id = res_item.pop('mailing_list_id') contact_counts[mailing_list_id] = res_item for mass_mailing in self: # adds default 0 values for ids that don't have statistics if mass_mailing.id not in contact_counts: contact_counts[mass_mailing.id] = { field: 0 for field in self._get_contact_statistics_fields().keys() } return contact_counts def _get_contact_statistics_fields(self): """ Returns fields and SQL query select path in a dictionnary. This is done to be easily overridable in subsequent modules. - mailing_list_id id of the associated mailing.list - contact_count: all contacts - contact_count_email: all valid emails - contact_count_opt_out: all opted-out contacts - contact_count_blacklisted: all blacklisted contacts """ return { 'mailing_list_id': 'list_id AS mailing_list_id', 'contact_count': 'COUNT(*) AS contact_count', 'contact_count_email': ''' SUM(CASE WHEN (c.email_normalized IS NOT NULL AND COALESCE(r.opt_out,FALSE) = FALSE AND bl.id IS NULL) THEN 1 ELSE 0 END) AS contact_count_email''', 'contact_count_opt_out': ''' SUM(CASE WHEN COALESCE(r.opt_out,FALSE) = TRUE THEN 1 ELSE 0 END) AS contact_count_opt_out''', 'contact_count_blacklisted': f''' SUM(CASE WHEN bl.id IS NOT NULL THEN 1 ELSE 0 END) AS contact_count_blacklisted''' } def _get_contact_statistics_joins(self): """ Extracted to be easily overridable by sub-modules (such as mass_mailing_sms). """ return """ LEFT JOIN mailing_contact c ON (r.contact_id=c.id) LEFT JOIN mail_blacklist bl on c.email_normalized = bl.email and bl.active"""
47.810398
15,634
812
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class MailRenderMixin(models.AbstractModel): _inherit = "mail.render.mixin" @api.model def _render_template_postprocess(self, rendered): # super will transform relative url to absolute rendered = super(MailRenderMixin, self)._render_template_postprocess(rendered) # apply shortener after if self.env.context.get('post_convert_links'): for res_id, html in rendered.items(): rendered[res_id] = self._shorten_links( html, self.env.context['post_convert_links'], blacklist=['/unsubscribe_from_list', '/view'] ) return rendered
35.304348
812
7,008
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from dateutil.relativedelta import relativedelta from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class UtmCampaign(models.Model): _inherit = 'utm.campaign' mailing_mail_ids = fields.One2many( 'mailing.mailing', 'campaign_id', domain=[('mailing_type', '=', 'mail')], string='Mass Mailings') mailing_mail_count = fields.Integer('Number of Mass Mailing', compute="_compute_mailing_mail_count") # A/B Testing ab_testing_mailings_count = fields.Integer("A/B Test Mailings #", compute="_compute_mailing_mail_count") ab_testing_completed = fields.Boolean("A/B Testing Campaign Finished") ab_testing_schedule_datetime = fields.Datetime('Send Final On', default=lambda self: fields.Datetime.now() + relativedelta(days=1), help="Date that will be used to know when to determine and send the winner mailing") ab_testing_total_pc = fields.Integer("Total A/B test percentage", compute="_compute_ab_testing_total_pc", store=True) ab_testing_winner_selection = fields.Selection([ ('manual', 'Manual'), ('opened_ratio', 'Highest Open Rate'), ('clicks_ratio', 'Highest Click Rate'), ('replied_ratio', 'Highest Reply Rate')], string="Winner Selection", default="opened_ratio", help="Selection to determine the winner mailing that will be sent.") # stat fields received_ratio = fields.Integer(compute="_compute_statistics", string='Received Ratio') opened_ratio = fields.Integer(compute="_compute_statistics", string='Opened Ratio') replied_ratio = fields.Integer(compute="_compute_statistics", string='Replied Ratio') bounced_ratio = fields.Integer(compute="_compute_statistics", string='Bounced Ratio') @api.depends('mailing_mail_ids') def _compute_ab_testing_total_pc(self): for campaign in self: campaign.ab_testing_total_pc = sum([ mailing.ab_testing_pc for mailing in campaign.mailing_mail_ids.filtered('ab_testing_enabled') ]) @api.depends('mailing_mail_ids') def _compute_mailing_mail_count(self): if self.ids: mailing_data = self.env['mailing.mailing'].read_group( [('campaign_id', 'in', self.ids), ('mailing_type', '=', 'mail')], ['campaign_id', 'ab_testing_enabled'], ['campaign_id', 'ab_testing_enabled'], lazy=False, ) ab_testing_mapped_data = {} mapped_data = {} for data in mailing_data: if data['ab_testing_enabled']: ab_testing_mapped_data.setdefault(data['campaign_id'][0], []).append(data['__count']) mapped_data.setdefault(data['campaign_id'][0], []).append(data['__count']) else: mapped_data = dict() ab_testing_mapped_data = dict() for campaign in self: campaign.mailing_mail_count = sum(mapped_data.get(campaign.id, [])) campaign.ab_testing_mailings_count = sum(ab_testing_mapped_data.get(campaign.id, [])) @api.constrains('ab_testing_total_pc', 'ab_testing_completed') def _check_ab_testing_total_pc(self): for campaign in self: if not campaign.ab_testing_completed and campaign.ab_testing_total_pc >= 100: raise ValidationError(_("The total percentage for an A/B testing campaign should be less than 100%")) def _compute_statistics(self): """ Compute statistics of the mass mailing campaign """ default_vals = { 'received_ratio': 0, 'opened_ratio': 0, 'replied_ratio': 0, 'bounced_ratio': 0 } if not self.ids: self.update(default_vals) return self.env.cr.execute(""" SELECT c.id as campaign_id, COUNT(s.id) AS expected, COUNT(s.sent_datetime) AS sent, COUNT(s.trace_status) FILTER (WHERE s.trace_status in ('sent', 'open', 'reply')) AS delivered, COUNT(s.trace_status) FILTER (WHERE s.trace_status in ('open', 'reply')) AS open, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'reply') AS reply, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'bounce') AS bounce, COUNT(s.trace_status) FILTER (WHERE s.trace_status = 'cancel') AS cancel FROM mailing_trace s RIGHT JOIN utm_campaign c ON (c.id = s.campaign_id) WHERE c.id IN %s GROUP BY c.id """, (tuple(self.ids), )) all_stats = self.env.cr.dictfetchall() stats_per_campaign = { stats['campaign_id']: stats for stats in all_stats } for campaign in self: stats = stats_per_campaign.get(campaign.id) if not stats: vals = default_vals else: total = (stats['expected'] - stats['cancel']) or 1 delivered = stats['sent'] - stats['bounce'] vals = { 'received_ratio': 100.0 * delivered / total, 'opened_ratio': 100.0 * stats['open'] / total, 'replied_ratio': 100.0 * stats['reply'] / total, 'bounced_ratio': 100.0 * stats['bounce'] / total } campaign.update(vals) def _get_mailing_recipients(self, model=None): """Return the recipients of a mailing campaign. This is based on the statistics build for each mailing. """ res = dict.fromkeys(self.ids, {}) for campaign in self: domain = [('campaign_id', '=', campaign.id)] if model: domain += [('model', '=', model)] res[campaign.id] = set(self.env['mailing.trace'].search(domain).mapped('res_id')) return res @api.model def _cron_process_mass_mailing_ab_testing(self): """ Cron that manages A/B testing and sends a winner mailing computed based on the value set on the A/B testing campaign. In case there is no mailing sent for an A/B testing campaign we ignore this campaign """ ab_testing_campaign = self.search([ ('ab_testing_schedule_datetime', '<=', fields.Datetime.now()), ('ab_testing_winner_selection', '!=', 'manual'), ('ab_testing_completed', '=', False), ]) for campaign in ab_testing_campaign: ab_testing_mailings = campaign.mailing_mail_ids.filtered(lambda m: m.ab_testing_enabled) if not ab_testing_mailings.filtered(lambda m: m.state == 'done'): continue ab_testing_mailings.action_send_winner_mailing() return ab_testing_campaign
45.212903
7,008
4,776
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo import api, models, fields, tools BLACKLIST_MAX_BOUNCED_LIMIT = 5 class MailThread(models.AbstractModel): """ Update MailThread to add the support of bounce management in mass mailing traces. """ _inherit = 'mail.thread' @api.model def _message_route_process(self, message, message_dict, routes): """ Override to update the parent mailing traces. The parent is found by using the References header of the incoming message and looking for matching message_id in mailing.trace. """ if routes: # even if 'reply_to' in ref (cfr mail/mail_thread) that indicates a new thread redirection # (aka bypass alias configuration in gateway) consider it as a reply for statistics purpose thread_references = message_dict['references'] or message_dict['in_reply_to'] msg_references = tools.mail_header_msgid_re.findall(thread_references) if msg_references: self.env['mailing.trace'].set_opened(domain=[('message_id', 'in', msg_references)]) self.env['mailing.trace'].set_replied(domain=[('message_id', 'in', msg_references)]) return super(MailThread, self)._message_route_process(message, message_dict, routes) def message_post_with_template(self, template_id, **kwargs): # avoid having message send through `message_post*` methods being implicitly considered as # mass-mailing no_massmail = self.with_context( default_mass_mailing_name=False, default_mass_mailing_id=False, ) return super(MailThread, no_massmail).message_post_with_template(template_id, **kwargs) @api.model def _routing_handle_bounce(self, email_message, message_dict): """ In addition, an auto blacklist rule check if the email can be blacklisted to avoid sending mails indefinitely to this email address. This rule checks if the email bounced too much. If this is the case, the email address is added to the blacklist in order to avoid continuing to send mass_mail to that email address. If it bounced too much times in the last month and the bounced are at least separated by one week, to avoid blacklist someone because of a temporary mail server error, then the email is considered as invalid and is blacklisted.""" super(MailThread, self)._routing_handle_bounce(email_message, message_dict) bounced_email = message_dict['bounced_email'] bounced_msg_id = message_dict['bounced_msg_id'] bounced_partner = message_dict['bounced_partner'] if bounced_msg_id: self.env['mailing.trace'].set_bounced(domain=[('message_id', 'in', bounced_msg_id)]) if bounced_email: three_months_ago = fields.Datetime.to_string(datetime.datetime.now() - datetime.timedelta(weeks=13)) stats = self.env['mailing.trace'].search(['&', '&', ('trace_status', '=', 'bounce'), ('write_date', '>', three_months_ago), ('email', '=ilike', bounced_email)]).mapped('write_date') if len(stats) >= BLACKLIST_MAX_BOUNCED_LIMIT and (not bounced_partner or any(p.message_bounce >= BLACKLIST_MAX_BOUNCED_LIMIT for p in bounced_partner)): if max(stats) > min(stats) + datetime.timedelta(weeks=1): blacklist_rec = self.env['mail.blacklist'].sudo()._add(bounced_email) blacklist_rec._message_log( body='This email has been automatically blacklisted because of too much bounced.') @api.model def message_new(self, msg_dict, custom_values=None): """ Overrides mail_thread message_new that is called by the mailgateway through message_process. This override updates the document according to the email. """ defaults = {} if issubclass(type(self), self.pool['utm.mixin']): thread_references = msg_dict.get('references', '') or msg_dict.get('in_reply_to', '') msg_references = tools.mail_header_msgid_re.findall(thread_references) if msg_references: traces = self.env['mailing.trace'].search([('message_id', 'in', msg_references)], limit=1) if traces: defaults['campaign_id'] = traces.campaign_id.id defaults['source_id'] = traces.mass_mailing_id.source_id.id defaults['medium_id'] = traces.mass_mailing_id.medium_id.id if custom_values: defaults.update(custom_values) return super(MailThread, self).message_new(msg_dict, custom_values=defaults)
54.896552
4,776
491
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ResCompany(models.Model): _inherit = "res.company" def _get_social_media_links(self): self.ensure_one() return { 'social_facebook': self.social_facebook, 'social_linkedin': self.social_linkedin, 'social_twitter': self.social_twitter, 'social_instagram': self.social_instagram }
28.882353
491
649
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ class Users(models.Model): _name = 'res.users' _inherit = ['res.users'] @api.model def systray_get_activities(self): """ Update systray name of mailing.mailing from "Mass Mailing" to "Email Marketing". """ activities = super(Users, self).systray_get_activities() for activity in activities: if activity.get('model') == 'mailing.mailing': activity['name'] = _('Email Marketing') break return activities
30.904762
649
1,771
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' group_mass_mailing_campaign = fields.Boolean(string="Mailing Campaigns", implied_group='mass_mailing.group_mass_mailing_campaign', help="""This is useful if your marketing campaigns are composed of several emails""") mass_mailing_outgoing_mail_server = fields.Boolean(string="Dedicated Server", config_parameter='mass_mailing.outgoing_mail_server', help='Use a specific mail server in priority. Otherwise Odoo relies on the first outgoing mail server available (based on their sequencing) as it does for normal mails.') mass_mailing_mail_server_id = fields.Many2one('ir.mail_server', string='Mail Server', config_parameter='mass_mailing.mail_server_id') show_blacklist_buttons = fields.Boolean(string="Blacklist Option when Unsubscribing", config_parameter='mass_mailing.show_blacklist_buttons', help="""Allow the recipient to manage himself his state in the blacklist via the unsubscription page.""") @api.onchange('mass_mailing_outgoing_mail_server') def _onchange_mass_mailing_outgoing_mail_server(self): if not self.mass_mailing_outgoing_mail_server: self.mass_mailing_mail_server_id = False def set_values(self): super().set_values() ab_test_cron = self.env.ref('mass_mailing.ir_cron_mass_mailing_ab_testing').sudo() if ab_test_cron and ab_test_cron.active != self.group_mass_mailing_campaign: ab_test_cron.active = self.group_mass_mailing_campaign
65.592593
1,771
4,006
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re import werkzeug.urls from odoo import api, fields, models, tools class MailMail(models.Model): """Add the mass mailing campaign data to mail""" _inherit = ['mail.mail'] mailing_id = fields.Many2one('mailing.mailing', string='Mass Mailing') mailing_trace_ids = fields.One2many('mailing.trace', 'mail_mail_id', string='Statistics') @api.model_create_multi def create(self, values_list): """ Override mail_mail creation to create an entry in mail.mail.statistics """ # TDE note: should be after 'all values computed', to have values (FIXME after merging other branch holding create refactoring) mails = super(MailMail, self).create(values_list) for mail, values in zip(mails, values_list): if values.get('mailing_trace_ids'): mail.mailing_trace_ids.write({'message_id': mail.message_id}) return mails def _get_tracking_url(self): token = tools.hmac(self.env(su=True), 'mass_mailing-mail_mail-open', self.id) return werkzeug.urls.url_join(self.get_base_url(), 'mail/track/%s/%s/blank.gif' % (self.id, token)) def _send_prepare_body(self): """ Override to add the tracking URL to the body and to add trace ID in shortened urls """ # TDE: temporary addition (mail was parameter) due to semi-new-API self.ensure_one() body = super(MailMail, self)._send_prepare_body() if self.mailing_id and body and self.mailing_trace_ids: for match in set(re.findall(tools.URL_REGEX, self.body_html)): href = match[0] url = match[1] parsed = werkzeug.urls.url_parse(url, scheme='http') if parsed.scheme.startswith('http') and parsed.path.startswith('/r/'): new_href = href.replace(url, url + '/m/' + str(self.mailing_trace_ids[0].id)) body = body.replace(href, new_href) # generate tracking URL tracking_url = self._get_tracking_url() body = tools.append_content_to_html( body, '<img src="%s"/>' % tracking_url, plaintext=False, ) body = self.env['mail.render.mixin']._replace_local_links(body) return body def _send_prepare_values(self, partner=None): # TDE: temporary addition (mail was parameter) due to semi-new-API res = super(MailMail, self)._send_prepare_values(partner) if self.mailing_id and res.get('body') and res.get('email_to'): base_url = self.mailing_id.get_base_url() emails = tools.email_split(res.get('email_to')[0]) email_to = emails and emails[0] or False urls_to_replace = [ (base_url + '/unsubscribe_from_list', self.mailing_id._get_unsubscribe_url(email_to, self.res_id)), (base_url + '/view', self.mailing_id._get_view_url(email_to, self.res_id)) ] for url_to_replace, new_url in urls_to_replace: if url_to_replace in res['body']: res['body'] = res['body'].replace(url_to_replace, new_url if new_url else '#') return res def _postprocess_sent_message(self, success_pids, failure_reason=False, failure_type=None): mail_sent = not failure_type # we consider that a recipient error is a failure with mass mailling and show them as failed for mail in self: if mail.mailing_id: if mail_sent is True and mail.mailing_trace_ids: mail.mailing_trace_ids.set_sent() elif mail_sent is False and mail.mailing_trace_ids: mail.mailing_trace_ids.set_failed(failure_type=failure_type) return super(MailMail, self)._postprocess_sent_message(success_pids, failure_reason=failure_reason, failure_type=failure_type)
46.045977
4,006
212
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class Partner(models.Model): _inherit = 'res.partner' _mailing_enabled = True
23.555556
212
1,564
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class LinkTracker(models.Model): _inherit = "link.tracker" mass_mailing_id = fields.Many2one('mailing.mailing', string='Mass Mailing') class LinkTrackerClick(models.Model): _inherit = "link.tracker.click" mailing_trace_id = fields.Many2one('mailing.trace', string='Mail Statistics') mass_mailing_id = fields.Many2one('mailing.mailing', string='Mass Mailing') def _prepare_click_values_from_route(self, **route_values): click_values = super(LinkTrackerClick, self)._prepare_click_values_from_route(**route_values) if click_values.get('mailing_trace_id'): trace_sudo = self.env['mailing.trace'].sudo().browse(route_values['mailing_trace_id']).exists() if not trace_sudo: click_values['mailing_trace_id'] = False else: if not click_values.get('campaign_id'): click_values['campaign_id'] = trace_sudo.campaign_id.id if not click_values.get('mass_mailing_id'): click_values['mass_mailing_id'] = trace_sudo.mass_mailing_id.id return click_values @api.model def add_click(self, code, **route_values): click = super(LinkTrackerClick, self).add_click(code, **route_values) if click and click.mailing_trace_id: click.mailing_trace_id.set_opened() click.mailing_trace_id.set_clicked() return click
37.238095
1,564
4,136
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, tools class MailingTraceReport(models.Model): _name = 'mailing.trace.report' _auto = False _description = 'Mass Mailing Statistics' # mailing name = fields.Char(string='Mass Mail', readonly=True) mailing_type = fields.Selection([('mail', 'Mail')], string='Type', default='mail', required=True) campaign = fields.Char(string='Mailing Campaign', readonly=True) scheduled_date = fields.Datetime(string='Scheduled Date', readonly=True) state = fields.Selection( [('draft', 'Draft'), ('test', 'Tested'), ('done', 'Sent')], string='Status', readonly=True) email_from = fields.Char('From', readonly=True) # traces scheduled = fields.Integer(readonly=True) sent = fields.Integer(readonly=True) delivered = fields.Integer(readonly=True) error = fields.Integer(readonly=True) opened = fields.Integer(readonly=True) replied = fields.Integer(readonly=True) bounced = fields.Integer(readonly=True) canceled = fields.Integer(readonly=True) clicked = fields.Integer(readonly=True) def init(self): """Mass Mail Statistical Report: based on mailing.trace that models the various statistics collected for each mailing, and mailing.mailing model that models the various mailing performed. """ tools.drop_view_if_exists(self.env.cr, 'mailing_trace_report') self.env.cr.execute(self._report_get_request()) def _report_get_request(self): sql_select = 'SELECT %s' % ', '.join(self._report_get_request_select_items()) sql_from = 'FROM %s' % ' '.join(self._report_get_request_from_items()) sql_where_items = self._report_get_request_where_items() if sql_where_items and len(sql_where_items) == 1: sql_where = 'WHERE %s' % sql_where_items[0] elif sql_where_items: sql_where = 'WHERE %s' % ' AND '.join(sql_where_items) else: sql_where = '' sql_group_by = 'GROUP BY %s' % ', '.join(self._report_get_request_group_by_items()) return f"CREATE OR REPLACE VIEW mailing_trace_report AS ({sql_select} {sql_from} {sql_where} {sql_group_by} )" def _report_get_request_select_items(self): return [ 'min(trace.id) as id', 'utm_source.name as name', 'mailing.mailing_type', 'utm_campaign.name as campaign', 'trace.create_date as scheduled_date', 'mailing.state', 'mailing.email_from', "COUNT(trace.id) as scheduled", 'COUNT(trace.sent_datetime) as sent', "(COUNT(trace.id) - COUNT(trace.trace_status) FILTER (WHERE trace.trace_status IN ('error', 'bounce', 'cancel'))) as delivered", "COUNT(trace.trace_status) FILTER (WHERE trace.trace_status = 'error') as error", "COUNT(trace.trace_status) FILTER (WHERE trace.trace_status = 'bounce') as bounced", "COUNT(trace.trace_status) FILTER (WHERE trace.trace_status = 'cancel') as canceled", "COUNT(trace.trace_status) FILTER (WHERE trace.trace_status = 'open') as opened", "COUNT(trace.trace_status) FILTER (WHERE trace.trace_status = 'reply') as replied", "COUNT(trace.links_click_datetime) as clicked", ] def _report_get_request_from_items(self): return [ 'mailing_trace as trace', 'LEFT JOIN mailing_mailing as mailing ON (trace.mass_mailing_id=mailing.id)', 'LEFT JOIN utm_campaign as utm_campaign ON (mailing.campaign_id = utm_campaign.id)', 'LEFT JOIN utm_source as utm_source ON (mailing.source_id = utm_source.id)' ] def _report_get_request_where_items(self): return [] def _report_get_request_group_by_items(self): return [ 'trace.create_date', 'utm_source.name', 'utm_campaign.name', 'mailing.mailing_type', 'mailing.state', 'mailing.email_from' ]
45.450549
4,136
10,428
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import werkzeug from odoo import _, exceptions, http, tools from odoo.http import request from odoo.tools import consteq from werkzeug.exceptions import BadRequest class MassMailController(http.Controller): def _valid_unsubscribe_token(self, mailing_id, res_id, email, token): if not (mailing_id and res_id and email and token): return False mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) return consteq(mailing._unsubscribe_token(res_id, email), token) def _log_blacklist_action(self, blacklist_entry, mailing_id, description): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) model_display = mailing.mailing_model_id.display_name blacklist_entry._message_log(body=description + " ({})".format(model_display)) @http.route(['/unsubscribe_from_list'], type='http', website=True, multilang=False, auth='public', sitemap=False) def unsubscribe_placeholder_link(self, **post): """Dummy route so placeholder is not prefixed by language, MUST have multilang=False""" raise werkzeug.exceptions.NotFound() @http.route(['/mail/mailing/<int:mailing_id>/unsubscribe'], type='http', website=True, auth='public') def mailing(self, mailing_id, email=None, res_id=None, token="", **post): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) if mailing.exists(): res_id = res_id and int(res_id) if not self._valid_unsubscribe_token(mailing_id, res_id, email, str(token)): raise exceptions.AccessDenied() if mailing.mailing_model_real == 'mailing.contact': # Unsubscribe directly + Let the user choose his subscriptions mailing.update_opt_out(email, mailing.contact_list_ids.ids, True) contacts = request.env['mailing.contact'].sudo().search([('email_normalized', '=', tools.email_normalize(email))]) subscription_list_ids = contacts.mapped('subscription_list_ids') # In many user are found : if user is opt_out on the list with contact_id 1 but not with contact_id 2, # assume that the user is not opt_out on both # TODO DBE Fixme : Optimise the following to get real opt_out and opt_in opt_out_list_ids = subscription_list_ids.filtered(lambda rel: rel.opt_out).mapped('list_id') opt_in_list_ids = subscription_list_ids.filtered(lambda rel: not rel.opt_out).mapped('list_id') opt_out_list_ids = set([list.id for list in opt_out_list_ids if list not in opt_in_list_ids]) unique_list_ids = set([list.list_id.id for list in subscription_list_ids]) list_ids = request.env['mailing.list'].sudo().browse(unique_list_ids) unsubscribed_list = ', '.join(str(list.name) for list in mailing.contact_list_ids if list.is_public) return request.render('mass_mailing.page_unsubscribe', { 'contacts': contacts, 'list_ids': list_ids, 'opt_out_list_ids': opt_out_list_ids, 'unsubscribed_list': unsubscribed_list, 'email': email, 'mailing_id': mailing_id, 'res_id': res_id, 'show_blacklist_button': request.env['ir.config_parameter'].sudo().get_param('mass_mailing.show_blacklist_buttons'), }) else: opt_in_lists = request.env['mailing.contact.subscription'].sudo().search([ ('contact_id.email_normalized', '=', email), ('opt_out', '=', False) ]).mapped('list_id') blacklist_rec = request.env['mail.blacklist'].sudo()._add(email) self._log_blacklist_action( blacklist_rec, mailing_id, _("""Requested blacklisting via unsubscribe link.""")) return request.render('mass_mailing.page_unsubscribed', { 'email': email, 'mailing_id': mailing_id, 'res_id': res_id, 'list_ids': opt_in_lists, 'show_blacklist_button': request.env['ir.config_parameter'].sudo().get_param( 'mass_mailing.show_blacklist_buttons'), }) return request.redirect('/web') @http.route('/mail/mailing/unsubscribe', type='json', auth='public') def unsubscribe(self, mailing_id, opt_in_ids, opt_out_ids, email, res_id, token): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) if mailing.exists(): if not self._valid_unsubscribe_token(mailing_id, res_id, email, token): return 'unauthorized' mailing.update_opt_out(email, opt_in_ids, False) mailing.update_opt_out(email, opt_out_ids, True) return True return 'error' @http.route('/mail/track/<int:mail_id>/<string:token>/blank.gif', type='http', auth='public') def track_mail_open(self, mail_id, token, **post): """ Email tracking. """ if not consteq(token, tools.hmac(request.env(su=True), 'mass_mailing-mail_mail-open', mail_id)): raise BadRequest() request.env['mailing.trace'].sudo().set_opened(domain=[('mail_mail_id_int', 'in', [mail_id])]) response = werkzeug.wrappers.Response() response.mimetype = 'image/gif' response.data = base64.b64decode(b'R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==') return response @http.route(['/mailing/<int:mailing_id>/view'], type='http', website=True, auth='public') def view(self, mailing_id, email=None, res_id=None, token=""): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) if mailing.exists(): res_id = int(res_id) if res_id else False if not self._valid_unsubscribe_token(mailing_id, res_id, email, str(token)) and not request.env.user.has_group('mass_mailing.group_mass_mailing_user'): raise exceptions.AccessDenied() res = mailing.convert_links() base_url = mailing.get_base_url().rstrip('/') urls_to_replace = [ (base_url + '/unsubscribe_from_list', mailing._get_unsubscribe_url(email, res_id)), (base_url + '/view', mailing._get_view_url(email, res_id)) ] for url_to_replace, new_url in urls_to_replace: if url_to_replace in res[mailing_id]: res[mailing_id] = res[mailing_id].replace(url_to_replace, new_url if new_url else '#') res[mailing_id] = res[mailing_id].replace( 'class="o_snippet_view_in_browser"', 'class="o_snippet_view_in_browser" style="display: none;"' ) if res_id: res[mailing_id] = mailing._render_field('body_html', [res_id], post_process=True)[res_id] return request.render('mass_mailing.view', { 'body': res[mailing_id], }) return request.redirect('/web') @http.route('/r/<string:code>/m/<int:mailing_trace_id>', type='http', auth="public") def full_url_redirect(self, code, mailing_trace_id, **post): # don't assume geoip is set, it is part of the website module # which mass_mailing doesn't depend on country_code = request.session.get('geoip', False) and request.session.geoip.get('country_code', False) request.env['link.tracker.click'].sudo().add_click( code, ip=request.httprequest.remote_addr, country_code=country_code, mailing_trace_id=mailing_trace_id ) return request.redirect(request.env['link.tracker'].get_url_from_code(code), code=301, local=False) @http.route('/mailing/blacklist/check', type='json', auth='public') def blacklist_check(self, mailing_id, res_id, email, token): if not self._valid_unsubscribe_token(mailing_id, res_id, email, token): return 'unauthorized' if email: record = request.env['mail.blacklist'].sudo().with_context(active_test=False).search([('email', '=', tools.email_normalize(email))]) if record['active']: return True return False return 'error' @http.route('/mailing/blacklist/add', type='json', auth='public') def blacklist_add(self, mailing_id, res_id, email, token): if not self._valid_unsubscribe_token(mailing_id, res_id, email, token): return 'unauthorized' if email: blacklist_rec = request.env['mail.blacklist'].sudo()._add(email) self._log_blacklist_action( blacklist_rec, mailing_id, _("""Requested blacklisting via unsubscription page.""")) return True return 'error' @http.route('/mailing/blacklist/remove', type='json', auth='public') def blacklist_remove(self, mailing_id, res_id, email, token): if not self._valid_unsubscribe_token(mailing_id, res_id, email, token): return 'unauthorized' if email: blacklist_rec = request.env['mail.blacklist'].sudo()._remove(email) self._log_blacklist_action( blacklist_rec, mailing_id, _("""Requested de-blacklisting via unsubscription page.""")) return True return 'error' @http.route('/mailing/feedback', type='json', auth='public') def send_feedback(self, mailing_id, res_id, email, feedback, token): mailing = request.env['mailing.mailing'].sudo().browse(mailing_id) if mailing.exists() and email: if not self._valid_unsubscribe_token(mailing_id, res_id, email, token): return 'unauthorized' model = request.env[mailing.mailing_model_real] records = model.sudo().search([('email_normalized', '=', tools.email_normalize(email))]) for record in records: record.sudo().message_post(body=_("Feedback from %(email)s: %(feedback)s", email=email, feedback=feedback)) return bool(records) return 'error'
52.14
10,428
894
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'HR Gamification', 'version': '1.0', 'category': 'Human Resources', 'depends': ['gamification', 'hr'], 'description': """Use the HR resources for the gamification process. The HR officer can now manage challenges and badges. This allow the user to send badges to employees instead of simple users. Badge received are displayed on the user profile. """, 'data': [ 'security/gamification_security.xml', 'security/ir.model.access.csv', 'wizard/gamification_badge_user_wizard_views.xml', 'views/gamification_views.xml', 'views/hr_employee_views.xml', ], 'auto_install': True, 'assets': { 'web.assets_backend': [ 'hr_gamification/static/**/*', ], }, 'license': 'LGPL-3', }
31.928571
894
1,184
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError, AccessError class GamificationBadgeUserWizard(models.TransientModel): _inherit = 'gamification.badge.user.wizard' employee_id = fields.Many2one('hr.employee', string='Employee', required=True) user_id = fields.Many2one('res.users', string='User', related='employee_id.user_id', store=False, readonly=True, compute_sudo=True) def action_grant_badge(self): """Wizard action for sending a badge to a chosen employee""" if not self.user_id: raise UserError(_('You can send badges only to employees linked to a user.')) if self.env.uid == self.user_id.id: raise UserError(_('You can not send a badge to yourself.')) values = { 'user_id': self.user_id.id, 'sender_id': self.env.uid, 'badge_id': self.badge_id.id, 'employee_id': self.employee_id.id, 'comment': self.comment, } return self.env['gamification.badge.user'].create(values)._send_badge()
38.193548
1,184
1,683
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class HrEmployeeBase(models.AbstractModel): _inherit = "hr.employee.base" goal_ids = fields.One2many('gamification.goal', string='Employee HR Goals', compute='_compute_employee_goals') badge_ids = fields.One2many( 'gamification.badge.user', string='Employee Badges', compute='_compute_employee_badges', help="All employee badges, linked to the employee either directly or through the user" ) has_badges = fields.Boolean(compute='_compute_employee_badges') # necessary for correct dependencies of badge_ids and has_badges direct_badge_ids = fields.One2many( 'gamification.badge.user', 'employee_id', help="Badges directly linked to the employee") @api.depends('user_id.goal_ids.challenge_id.challenge_category') def _compute_employee_goals(self): for employee in self: employee.goal_ids = self.env['gamification.goal'].search([ ('user_id', '=', employee.user_id.id), ('challenge_id.challenge_category', '=', 'hr'), ]) @api.depends('direct_badge_ids', 'user_id.badge_ids.employee_id') def _compute_employee_badges(self): for employee in self: badge_ids = self.env['gamification.badge.user'].search([ '|', ('employee_id', '=', employee.id), '&', ('employee_id', '=', False), ('user_id', '=', employee.user_id.id) ]) employee.has_badges = bool(badge_ids) employee.badge_ids = badge_ids
44.289474
1,683
325
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResUsers(models.Model): _inherit = 'res.users' goal_ids = fields.One2many('gamification.goal', 'user_id') badge_ids = fields.One2many('gamification.badge.user', 'user_id')
29.545455
325
1,601
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class GamificationBadgeUser(models.Model): """User having received a badge""" _inherit = 'gamification.badge.user' employee_id = fields.Many2one('hr.employee', string='Employee') @api.constrains('employee_id') def _check_employee_related_user(self): for badge_user in self: if badge_user.employee_id not in badge_user.user_id.\ with_context(allowed_company_ids=self.env.user.company_ids.ids).employee_ids: raise ValidationError(_('The selected employee does not correspond to the selected user.')) class GamificationBadge(models.Model): _inherit = 'gamification.badge' granted_employees_count = fields.Integer(compute="_compute_granted_employees_count") @api.depends('owner_ids.employee_id') def _compute_granted_employees_count(self): for badge in self: badge.granted_employees_count = self.env['gamification.badge.user'].search_count([ ('badge_id', '=', badge.id), ('employee_id', '!=', False) ]) def get_granted_employees(self): employee_ids = self.mapped('owner_ids.employee_id').ids return { 'type': 'ir.actions.act_window', 'name': 'Granted Employees', 'view_mode': 'kanban,tree,form', 'res_model': 'hr.employee.public', 'domain': [('id', 'in', employee_ids)] }
37.232558
1,601
3,950
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Author: Gustavo Valverde <[email protected]> iterativo | Consultores # Contributors: Edser Solis - iterativo # Odoo 8.0 author: Eneldo Serrata <[email protected]> # (Marcos Organizador de Negocios SRL..) # Odoo 7.0 author: Jose Ernesto Mendez <[email protected]> # (Open Business Solutions SRL.) # Copyright (c) 2016 - Present | iterativo, SRL. - http://iterativo.do # All rights reserved. { 'name': 'Dominican Republic - Accounting', 'version': '2.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Localization Module for Dominican Republic =========================================== Catálogo de Cuentas e Impuestos para República Dominicana, Compatible para **Internacionalización** con **NIIF** y alineado a las normas y regulaciones de la Dirección General de Impuestos Internos (**DGII**). **Este módulo consiste de:** - Catálogo de Cuentas Estándar (alineado a DGII y NIIF) - Catálogo de Impuestos con la mayoría de Impuestos Preconfigurados - ITBIS para compras y ventas - Retenciones de ITBIS - Retenciones de ISR - Grupos de Impuestos y Retenciones: - Telecomunicaiones - Proveedores de Materiales de Construcción - Personas Físicas Proveedoras de Servicios - Otros impuestos - Secuencias Preconfiguradas para manejo de todos los NCF - Facturas con Valor Fiscal (para Ventas) - Facturas para Consumidores Finales - Notas de Débito y Crédito - Registro de Proveedores Informales - Registro de Ingreso Único - Registro de Gastos Menores - Gubernamentales - Posiciones Fiscales para automatización de impuestos y retenciones - Cambios de Impuestos a Exenciones (Ej. Ventas al Estado) - Cambios de Impuestos a Retenciones (Ej. Compra Servicios al Exterior) - Entre otros **Nota:** Esta localización, aunque posee las secuencias para NCF, las mismas no pueden ser utilizadas sin la instalación de módulos de terceros o desarrollo adicional. Estructura de Codificación del Catálogo de Cuentas: =================================================== **Un dígito** representa la categoría/tipo de cuenta del del estado financiero. **1** - Activo **4** - Cuentas de Ingresos y Ganancias **2** - Pasivo **5** - Costos, Gastos y Pérdidas **3** - Capital **6** - Cuentas Liquidadoras de Resultados **Dos dígitos** representan los rubros de agrupación: 11- Activo Corriente 21- Pasivo Corriente 31- Capital Contable **Cuatro dígitos** se asignan a las cuentas de mayor: cuentas de primer orden 1101- Efectivo y Equivalentes de Efectivo 2101- Cuentas y Documentos por pagar 3101- Capital Social **Seis dígitos** se asignan a las sub-cuentas: cuentas de segundo orden 110101 - Caja 210101 - Proveedores locales **Ocho dígitos** son para las cuentas de tercer orden (las visualizadas en Odoo): 1101- Efectivo y Equivalentes 110101- Caja 11010101 Caja General """, 'author': 'Gustavo Valverde - iterativo | Consultores de Odoo', 'website': 'http://iterativo.do', 'depends': ['account', 'base_iban' ], 'data': [ # Basic accounting data 'data/l10n_do_chart_data.xml', 'data/account_group.xml', 'data/account_account_tag_data.xml', 'data/account.account.template.csv', 'data/account_chart_template_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account.tax.template.xml', 'data/l10n_do_res_partner_title.xml', # Adds fiscal position 'data/fiscal_position_template.xml', # configuration wizard, views, reports... 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
35.654545
3,922
1,825
py
PYTHON
15.0
# coding: utf-8 # Copyright 2016 iterativo (https://www.iterativo.do) <[email protected]> from odoo import models, api, _ class AccountChartTemplate(models.Model): _inherit = "account.chart.template" @api.model def _get_default_bank_journals_data(self): if self.env.company.account_fiscal_country_id.code == 'DO': return [ {'acc_name': _('Cash'), 'account_type': 'cash'}, {'acc_name': _('Caja Chica'), 'account_type': 'cash'}, {'acc_name': _('Cheques Clientes'), 'account_type': 'cash'}, {'acc_name': _('Bank'), 'account_type': 'bank'} ] return super(AccountChartTemplate, self)._get_default_bank_journals_data() def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None): """Create fiscal journals for buys""" res = super(AccountChartTemplate, self)._prepare_all_journals( acc_template_ref, company, journals_dict=journals_dict) if not self == self.env.ref('l10n_do.do_chart_template'): return res for journal in res: if journal['code'] == 'FACT': journal['name'] = _('Compras Fiscales') res += [{ 'type': 'purchase', 'name': _('Gastos No Deducibles'), 'code': 'GASTO', 'company_id': company.id, 'show_on_dashboard': True }, { 'type': 'purchase', 'name': _('Migración CxP'), 'code': 'CXP', 'company_id': company.id, 'show_on_dashboard': True }, { 'type': 'sale', 'name': _('Migración CxC'), 'code': 'CXC', 'company_id': company.id, 'show_on_dashboard': True }] return res
36.46
1,823
553
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Project Sales Accounting', 'version': '1.0', 'category': 'Services/account', 'summary': 'Project sales accounting', 'description': 'Bridge created to add the number of vendor bills linked to an AA to a project form', 'depends': ['sale_timesheet', 'account'], 'data': [ 'views/project_project_views.xml', ], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
29.105263
553
568
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models class AccountMoveLine(models.Model): _inherit = 'account.move.line' def _compute_analytic_account_id(self): # when a project creates an aml, it adds an analytic account to it. the following filter is to save this # analytic account from being overridden by analytic default rules and lack thereof project_amls = self.filtered(lambda aml: aml.analytic_account_id and any(aml.sale_line_ids.project_id)) super(AccountMoveLine, self - project_amls)._compute_analytic_account_id()
43.692308
568
1,980
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _, _lt class Project(models.Model): _inherit = 'project.project' vendor_bill_count = fields.Integer(related='analytic_account_id.vendor_bill_count', groups='account.group_account_readonly') # ---------------------------- # Actions # ---------------------------- def action_open_project_vendor_bills(self): purchase_types = self.env['account.move'].get_purchase_types() vendor_bills = self.env['account.move'].search([ ('line_ids.analytic_account_id', '!=', False), ('line_ids.analytic_account_id', 'in', self.analytic_account_id.ids), ('move_type', 'in', purchase_types), ]) action_window = { 'name': _('Vendor Bills'), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'views': [[False, 'tree'], [False, 'form'], [False, 'kanban']], 'domain': [('id', 'in', vendor_bills.ids)], 'context': { 'create': False, } } if len(vendor_bills) == 1: action_window['views'] = [[False, 'form']] action_window['res_id'] = vendor_bills.id return action_window # ---------------------------- # Project Updates # ---------------------------- def _get_stat_buttons(self): buttons = super(Project, self)._get_stat_buttons() if self.user_has_groups('account.group_account_readonly'): buttons.append({ 'icon': 'pencil-square-o', 'text': _lt('Vendor Bills'), 'number': self.vendor_bill_count, 'action_type': 'object', 'action': 'action_open_project_vendor_bills', 'show': self.vendor_bill_count > 0, 'sequence': 14, }) return buttons
37.358491
1,980
1,226
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2015 Willow IT Pty Ltd (<http://www.willowit.com.au>). { 'name': 'New Zealand - Accounting', 'version': '1.1', 'category': 'Accounting/Localizations/Account Charts', 'description': """ New Zealand Accounting Module ============================= New Zealand accounting basic charts and localizations. Also: - activates a number of regional currencies. - sets up New Zealand taxes. """, 'author': 'Richard deMeester - Willow IT', 'website': 'http://www.willowit.com', 'depends': ['account'], 'data': [ 'data/l10n_nz_chart_data.xml', 'data/account.account.template.csv', 'data/account_chart_template_data.xml', 'data/account.tax.group.csv', 'data/account_tax_report_data.xml', 'data/account_tax_template_data.xml', 'data/account_fiscal_position_tax_template_data.xml', 'data/account_chart_template_configure_data.xml', 'data/res_currency_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
32.263158
1,226
5,264
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Project', 'version': '1.2', 'website': 'https://www.odoo.com/app/project', 'category': 'Services/Project', 'sequence': 45, 'summary': 'Organize and plan your projects', 'depends': [ 'analytic', 'base_setup', 'mail', 'portal', 'rating', 'resource', 'web', 'web_tour', 'digest', ], 'description': "", 'data': [ 'security/project_security.xml', 'security/ir.model.access.csv', 'security/ir.model.access.xml', 'data/digest_data.xml', 'report/project_report_views.xml', 'report/project_task_burndown_chart_report_views.xml', 'views/analytic_views.xml', 'views/digest_views.xml', 'views/rating_views.xml', 'views/project_update_views.xml', 'views/project_update_templates.xml', 'views/project_project_stage_views.xml', 'wizard/project_share_wizard_views.xml', 'views/project_collaborator_views.xml', 'views/project_views.xml', 'views/res_partner_views.xml', 'views/res_config_settings_views.xml', 'views/mail_activity_views.xml', 'views/project_sharing_views.xml', 'views/project_portal_templates.xml', 'views/project_task_templates.xml', 'views/project_sharing_templates.xml', 'data/ir_cron_data.xml', 'data/mail_data.xml', 'data/mail_template_data.xml', 'data/project_data.xml', 'wizard/project_delete_wizard_views.xml', 'wizard/project_task_type_delete_views.xml', ], 'demo': ['data/project_demo.xml'], 'test': [ ], 'installable': True, 'auto_install': False, 'application': True, 'post_init_hook': '_project_post_init', 'assets': { 'web.assets_backend': [ 'project/static/src/burndown_chart/*', 'project/static/src/project_control_panel/*', 'project/static/src/css/project.css', 'project/static/src/js/project_activity.js', 'project/static/src/js/project_control_panel.js', 'project/static/src/js/project_form.js', 'project/static/src/js/project_graph_view.js', 'project/static/src/js/project_kanban.js', 'project/static/src/js/project_list.js', 'project/static/src/js/project_pivot_view.js', 'project/static/src/js/project_rating_graph_view.js', 'project/static/src/js/project_rating_pivot_view.js', 'project/static/src/js/project_task_kanban_examples.js', 'project/static/src/js/tours/project.js', 'project/static/src/js/project_calendar.js', 'project/static/src/js/right_panel/*', 'project/static/src/js/update/*', 'project/static/src/js/widgets/*', 'project/static/src/scss/project_dashboard.scss', 'project/static/src/scss/project_form.scss', 'project/static/src/scss/project_rightpanel.scss', 'project/static/src/scss/project_widgets.scss', ], "web.assets_backend_legacy_lazy": [ 'project/static/src/js/*_legacy.js', ], 'web.assets_frontend': [ 'project/static/src/scss/portal_rating.scss', 'project/static/src/js/portal_rating.js', ], 'web.assets_qweb': [ 'project/static/src/xml/**/*', 'project/static/src/burndown_chart/**/*.xml', 'project/static/src/project_control_panel/**/*.xml', ], 'web.qunit_suite_tests': [ 'project/static/tests/burndown_chart_tests.js', 'project/static/tests/project_form_tests.js', ], 'web.assets_tests': [ 'project/static/tests/tours/**/*', ], 'project.assets_qweb': [ ('include', 'web.assets_qweb'), 'project/static/src/project_sharing/**/*.xml', ], 'project.webclient': [ ('include', 'web.assets_backend'), # Remove Longpolling bus and packages needed this bus ('remove', 'bus/static/src/js/services/assets_watchdog_service.js'), ('remove', 'mail/static/src/services/messaging/messaging.js'), ('remove', 'mail/static/src/components/dialog_manager/dialog_manager.js'), ('remove', 'mail/static/src/services/dialog_service/dialog_service.js'), ('remove', 'mail/static/src/components/chat_window_manager/chat_window_manager.js'), ('remove', 'mail/static/src/services/chat_window_service/chat_window_service.js'), 'web/static/src/legacy/js/public/public_widget.js', 'portal/static/src/js/portal_chatter.js', 'portal/static/src/js/portal_composer.js', 'project/static/src/project_sharing/search/favorite_menu/custom_favorite_item.xml', 'project/static/src/project_sharing/**/*.js', 'project/static/src/scss/project_sharing/*', 'web/static/src/start.js', 'web/static/src/legacy/legacy_setup.js', ], }, 'license': 'LGPL-3', }
40.183206
5,264
4,281
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import collections from odoo import models from odoo.tools import populate _logger = logging.getLogger(__name__) class ProjectStage(models.Model): _inherit = "project.task.type" _populate_sizes = {"small": 10, "medium": 50, "large": 500} def _populate_factories(self): return [ ("name", populate.constant('stage_{counter}')), ("sequence", populate.randomize([False] + [i for i in range(1, 101)])), ("description", populate.constant('project_stage_description_{counter}')), ("active", populate.randomize([True, False], [0.8, 0.2])), ("fold", populate.randomize([True, False], [0.9, 0.1])) ] class ProjectProject(models.Model): _inherit = "project.project" _populate_sizes = {"small": 10, "medium": 50, "large": 1000} _populate_dependencies = ["res.company", "project.task.type"] def _populate_factories(self): company_ids = self.env.registry.populated_models["res.company"] stage_ids = self.env.registry.populated_models["project.task.type"] def get_company_id(random, **kwargs): return random.choice(company_ids) # user_ids from company.user_ids ? # Also add a partner_ids on res_company ? def get_stage_ids(random, **kwargs): return [ (6, 0, [ random.choice(stage_ids) for i in range(random.choice([j for j in range(1, 10)])) ]) ] return [ ("name", populate.constant('project_{counter}')), ("sequence", populate.randomize([False] + [i for i in range(1, 101)])), ("active", populate.randomize([True, False], [0.8, 0.2])), ("company_id", populate.compute(get_company_id)), ("type_ids", populate.compute(get_stage_ids)), ('color', populate.randomize([False] + [i for i in range(1, 7)])), # TODO user_id but what about multi-company coherence ?? ] class ProjectTask(models.Model): _inherit = "project.task" _populate_sizes = {"small": 500, "medium": 5000, "large": 50000} _populate_dependencies = ["project.project"] def _populate_factories(self): project_ids = self.env.registry.populated_models["project.project"] stage_ids = self.env.registry.populated_models["project.task.type"] def get_project_id(random, **kwargs): return random.choice([False, False, False] + project_ids) def get_stage_id(random, **kwargs): return random.choice([False, False] + stage_ids) return [ ("name", populate.constant('project_task_{counter}')), ("sequence", populate.randomize([False] + [i for i in range(1, 101)])), ("active", populate.randomize([True, False], [0.8, 0.2])), ("color", populate.randomize([False] + [i for i in range(1, 7)])), ("kanban_state", populate.randomize(['normal', 'done', 'blocked'])), ("project_id", populate.compute(get_project_id)), ("stage_id", populate.compute(get_stage_id)), ] def _populate(self, size): records = super()._populate(size) # set parent_ids self._populate_set_children_tasks(records, size) return records def _populate_set_children_tasks(self, tasks, size): _logger.info('Setting parent tasks') rand = populate.Random('project.task+children_generator') parents = self.env["project.task"] for task in tasks: if not rand.getrandbits(4): parents |= task parent_ids = parents.ids tasks -= parents parent_childs = collections.defaultdict(lambda: self.env['project.task']) for count, task in enumerate(tasks): if not rand.getrandbits(4): parent_childs[rand.choice(parent_ids)] |= task for count, (parent, childs) in enumerate(parent_childs.items()): if (count + 1) % 100 == 0: _logger.info('Setting parent: %s/%s', count + 1, len(parent_childs)) childs.write({'parent_id': parent})
41.970588
4,281
709
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from .test_project_base import TestProjectCommon from odoo.tests import tagged, TransactionCase class TestTaskFollow(TestProjectCommon): def test_follow_on_create(self): # Tests that the user is follower of the task upon creation self.assertTrue(self.user_projectuser.partner_id in self.task_1.message_partner_ids) def test_follow_on_write(self): # Tests that the user is follower of the task upon writing new assignees self.task_2.user_ids += self.user_projectmanager self.assertTrue(self.user_projectmanager.partner_id in self.task_2.message_partner_ids)
41.705882
709
281
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestUi(odoo.tests.HttpCase): def test_01_project_tour(self): self.start_tour("/web", 'project_tour', login="admin")
28.1
281
1,974
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import UserError from odoo.addons.project.tests.test_project_base import TestProjectCommon class TestProjectTaskType(TestProjectCommon): @classmethod def setUpClass(cls): super(TestProjectTaskType, cls).setUpClass() cls.stage_created = cls.env['project.task.type'].create({ 'name': 'Stage Already Created', }) def test_create_stage(self): ''' Verify that it is not possible to add to a newly created stage a `user_id` and a `project_ids` ''' with self.assertRaises(UserError): self.env['project.task.type'].create({ 'name': 'New Stage', 'user_id': self.uid, 'project_ids': [self.project_goats.id], }) def test_modify_existing_stage(self): ''' - case 1: [`user_id`: not set, `project_ids`: not set] | Add `user_id` and `project_ids` => UserError - case 2: [`user_id`: set, `project_ids`: not set] | Add `project_ids` => UserError - case 3: [`user_id`: not set, `project_ids`: set] | Add `user_id` => UserError ''' # case 1 with self.assertRaises(UserError): self.stage_created.write({ 'user_id': self.uid, 'project_ids': [self.project_goats.id], }) # case 2 self.stage_created.write({ 'user_id': self.uid, }) with self.assertRaises(UserError): self.stage_created.write({ 'project_ids': [self.project_goats.id], }) # case 3 self.stage_created.write({ 'user_id': False, 'project_ids': [self.project_goats.id], }) with self.assertRaises(UserError): self.stage_created.write({ 'user_id': self.uid, })
33.457627
1,974
17,285
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from .test_project_base import TestProjectCommon from odoo import Command from odoo.tools import mute_logger from odoo.addons.mail.tests.common import MockEmail EMAIL_TPL = """Return-Path: <[email protected]> X-Original-To: {to} Delivered-To: {to} To: {to} cc: {cc} Received: by mail1.odoo.com (Postfix, from userid 10002) id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST) Message-ID: {msg_id} Date: Tue, 29 Nov 2011 12:43:21 +0530 From: {email_from} MIME-Version: 1.0 Subject: {subject} Content-Type: text/plain; charset=ISO-8859-1; format=flowed Hello, This email should create a new entry in your module. Please check that it effectively works. Thanks, -- Raoul Boitempoils Integrator at Agrolait""" class TestProjectFlow(TestProjectCommon, MockEmail): def test_project_process_project_manager_duplicate(self): Task = self.env['project.task'].with_context({'tracking_disable': True}) pigs = self.project_pigs.with_user(self.user_projectmanager) root_task = self.task_1 sub_task = Task.create({ 'name': 'Sub Task', 'parent_id': root_task.id, 'project_id': self.project_pigs.id, }) Task.create({ 'name': 'Sub Sub Task', 'parent_id': sub_task.id, 'project_id': self.project_pigs.id, }) dogs = pigs.copy() self.assertEqual(len(dogs.tasks), 4, 'project: duplicating a project must duplicate its tasks') self.assertEqual(dogs.task_count, 2, 'project: duplicating a project must not change the original project') self.assertEqual(pigs.task_count, 2, 'project: duplicating a project must duplicate its displayed tasks') self.assertEqual(dogs.task_count_with_subtasks, 4, 'project: duplicating a project must duplicate its subtasks') @mute_logger('odoo.addons.mail.mail_thread') def test_task_process_without_stage(self): # Do: incoming mail from an unknown partner on an alias creates a new task 'Frogs' task = self.format_and_process( EMAIL_TPL, to='[email protected], [email protected]', cc='[email protected]', email_from='%s' % self.user_projectuser.email, subject='Frogs', msg_id='<[email protected]>', target_model='project.task') # Test: one task created by mailgateway administrator self.assertEqual(len(task), 1, 'project: message_process: a new project.task should have been created') # Test: check partner in message followers self.assertIn(self.partner_2, task.message_partner_ids, "Partner in message cc is not added as a task followers.") # Test: messages self.assertEqual(len(task.message_ids), 1, 'project: message_process: newly created task should have 1 message: email') self.assertEqual(task.message_ids[0].subtype_id, self.env.ref('project.mt_task_new'), 'project: message_process: first message of new task should have Task Created subtype') self.assertEqual(task.message_ids[0].author_id, self.user_projectuser.partner_id, 'project: message_process: second message should be the one from Agrolait (partner failed)') self.assertEqual(task.message_ids[0].subject, 'Frogs', 'project: message_process: second message should be the one from Agrolait (subject failed)') # Test: task content self.assertEqual(task.name, 'Frogs', 'project_task: name should be the email subject') self.assertEqual(task.project_id.id, self.project_pigs.id, 'project_task: incorrect project') self.assertEqual(task.stage_id.sequence, False, "project_task: shouldn't have a stage, i.e. sequence=False") @mute_logger('odoo.addons.mail.mail_thread') def test_task_process_with_stages(self): # Do: incoming mail from an unknown partner on an alias creates a new task 'Cats' task = self.format_and_process( EMAIL_TPL, to='[email protected], [email protected]', cc='[email protected]', email_from='%s' % self.user_projectuser.email, subject='Cats', msg_id='<[email protected]>', target_model='project.task') # Test: one task created by mailgateway administrator self.assertEqual(len(task), 1, 'project: message_process: a new project.task should have been created') # Test: check partner in message followers self.assertIn(self.partner_2, task.message_partner_ids, "Partner in message cc is not added as a task followers.") # Test: messages self.assertEqual(len(task.message_ids), 1, 'project: message_process: newly created task should have 1 messages: email') self.assertEqual(task.message_ids[0].subtype_id, self.env.ref('project.mt_task_new'), 'project: message_process: first message of new task should have Task Created subtype') self.assertEqual(task.message_ids[0].author_id, self.user_projectuser.partner_id, 'project: message_process: first message should be the one from Agrolait (partner failed)') self.assertEqual(task.message_ids[0].subject, 'Cats', 'project: message_process: first message should be the one from Agrolait (subject failed)') # Test: task content self.assertEqual(task.name, 'Cats', 'project_task: name should be the email subject') self.assertEqual(task.project_id.id, self.project_goats.id, 'project_task: incorrect project') self.assertEqual(task.stage_id.sequence, 1, "project_task: should have a stage with sequence=1") def test_subtask_process(self): """ Check subtask mecanism and change it from project. For this test, 2 projects are used: - the 'pigs' project which has a partner_id - the 'goats' project where the partner_id is removed at the beginning of the tests and then restored. 2 parent tasks are also used to be able to switch the parent task of a sub-task: - 'parent_task' linked to the partner_2 - 'another_parent_task' linked to the partner_3 """ Task = self.env['project.task'].with_context({'tracking_disable': True}) parent_task = Task.create({ 'name': 'Mother Task', 'user_ids': self.user_projectuser, 'project_id': self.project_pigs.id, 'partner_id': self.partner_2.id, 'planned_hours': 12, }) another_parent_task = Task.create({ 'name': 'Another Mother Task', 'user_ids': self.user_projectuser, 'project_id': self.project_pigs.id, 'partner_id': self.partner_3.id, 'planned_hours': 0, }) # remove the partner_id of the 'goats' project goats_partner_id = self.project_goats.partner_id self.project_goats.write({ 'partner_id': False }) # the child task 1 is linked to a project without partner_id (goats project) child_task_1 = Task.with_context(default_project_id=self.project_goats.id, default_parent_id=parent_task.id).create({ 'name': 'Task Child with project', 'planned_hours': 3, }) # the child task 2 is linked to a project with a partner_id (pigs project) child_task_2 = Task.create({ 'name': 'Task Child without project', 'parent_id': parent_task.id, 'project_id': self.project_pigs.id, 'display_project_id': self.project_pigs.id, 'planned_hours': 5, }) self.assertEqual( child_task_1.partner_id, child_task_1.parent_id.partner_id, "When no project partner_id has been set, a subtask should have the same partner as its parent") self.assertEqual( child_task_2.partner_id, child_task_2.parent_id.partner_id, "When a project partner_id has been set, a subtask should have the same partner as its parent") self.assertEqual( parent_task.subtask_count, 2, "Parent task should have 2 children") self.assertEqual( parent_task.subtask_planned_hours, 8, "Planned hours of subtask should impact parent task") # change the parent of a subtask without a project partner_id child_task_1.write({ 'parent_id': another_parent_task.id }) self.assertEqual( child_task_1.partner_id, parent_task.partner_id, "When changing the parent task of a subtask with no project partner_id, the partner_id should remain the same.") # change the parent of a subtask with a project partner_id child_task_2.write({ 'parent_id': another_parent_task.id }) self.assertEqual( child_task_2.partner_id, parent_task.partner_id, "When changing the parent task of a subtask with a project, the partner_id should remain the same.") # set a project with partner_id to a subtask without project partner_id child_task_1.write({ 'display_project_id': self.project_pigs.id }) self.assertNotEqual( child_task_1.partner_id, self.project_pigs.partner_id, "When the project changes, the subtask should keep its partner id as its partner id is set.") # restore the partner_id of the 'goats' project self.project_goats.write({ 'partner_id': goats_partner_id }) # set a project with partner_id to a subtask with a project partner_id child_task_2.write({ 'display_project_id': self.project_goats.id }) self.assertEqual( child_task_2.partner_id, parent_task.partner_id, "When the project changes, the subtask should keep the same partner id even it has a new project.") def test_rating(self): """Check if rating works correctly even when task is changed from project A to project B""" Task = self.env['project.task'].with_context({'tracking_disable': True}) first_task = Task.create({ 'name': 'first task', 'user_ids': self.user_projectuser, 'project_id': self.project_pigs.id, 'partner_id': self.partner_2.id, }) self.assertEqual(first_task.rating_count, 0, "Task should have no rating associated with it") rating_good = self.env['rating.rating'].create({ 'res_model_id': self.env['ir.model']._get('project.task').id, 'res_id': first_task.id, 'parent_res_model_id': self.env['ir.model']._get('project.project').id, 'parent_res_id': self.project_pigs.id, 'rated_partner_id': self.partner_2.id, 'partner_id': self.partner_2.id, 'rating': 5, 'consumed': False, }) rating_bad = self.env['rating.rating'].create({ 'res_model_id': self.env['ir.model']._get('project.task').id, 'res_id': first_task.id, 'parent_res_model_id': self.env['ir.model']._get('project.project').id, 'parent_res_id': self.project_pigs.id, 'rated_partner_id': self.partner_2.id, 'partner_id': self.partner_2.id, 'rating': 3, 'consumed': True, }) # We need to invalidate cache since it is not done automatically by the ORM # Our One2Many is linked to a res_id (int) for which the orm doesn't create an inverse first_task.invalidate_cache() self.assertEqual(rating_good.rating_text, 'top') self.assertEqual(rating_bad.rating_text, 'ok') self.assertEqual(first_task.rating_count, 1, "Task should have only one rating associated, since one is not consumed") self.assertEqual(rating_good.parent_res_id, self.project_pigs.id) self.assertEqual(self.project_goats.rating_percentage_satisfaction, -1) self.assertEqual(self.project_pigs.rating_percentage_satisfaction, 0) # There is a rating but not a "great" on, just an "okay". # Consuming rating_good first_task.rating_apply(5, rating_good.access_token) # We need to invalidate cache since it is not done automatically by the ORM # Our One2Many is linked to a res_id (int) for which the orm doesn't create an inverse first_task.invalidate_cache() self.assertEqual(first_task.rating_count, 2, "Task should have two ratings associated with it") self.assertEqual(rating_good.parent_res_id, self.project_pigs.id) self.assertEqual(self.project_goats.rating_percentage_satisfaction, -1) self.assertEqual(self.project_pigs.rating_percentage_satisfaction, 50) # We change the task from project_pigs to project_goats, ratings should be associated with the new project first_task.project_id = self.project_goats.id # We need to invalidate cache since it is not done automatically by the ORM # Our One2Many is linked to a res_id (int) for which the orm doesn't create an inverse first_task.invalidate_cache() self.assertEqual(rating_good.parent_res_id, self.project_goats.id) self.assertEqual(self.project_goats.rating_percentage_satisfaction, 50) self.assertEqual(self.project_pigs.rating_percentage_satisfaction, -1) def test_task_with_no_project(self): """ With this test, we want to make sure the fact that a task has no project doesn't affect the entire behaviours of projects. 1) Try to compute every field of a task which has no project. 2) Try to compute every field of a project and assert it isn't affected by this use case. """ task_without_project = self.env['project.task'].with_context({'mail_create_nolog': True}).create({ 'name': 'Test task without project' }) for field in task_without_project._fields.keys(): try: task_without_project[field] except Exception as e: raise AssertionError("Error raised unexpectedly while computing a field of the task ! Exception : " + e.args[0]) for field in self.project_pigs._fields.keys(): try: self.project_pigs[field] except Exception as e: raise AssertionError("Error raised unexpectedly while computing a field of the project ! Exception : " + e.args[0]) def test_send_rating_review(self): project_settings = self.env["res.config.settings"].create({'group_project_rating': True}) project_settings.execute() self.assertTrue(self.project_goats.rating_active, 'The customer ratings should be enabled in this project.') won_stage = self.project_goats.type_ids[-1] rating_request_mail_template = self.env.ref('project.rating_project_request_email_template') won_stage.write({'rating_template_id': rating_request_mail_template.id}) tasks = self.env['project.task'].with_context(mail_create_nolog=True, default_project_id=self.project_goats.id).create([ {'name': 'Goat Task 1', 'user_ids': [Command.set([])]}, {'name': 'Goat Task 2', 'user_ids': [Command.link(self.user_projectuser.id)]}, { 'name': 'Goat Task 3', 'user_ids': [ Command.link(self.user_projectmanager.id), Command.link(self.user_projectuser.id), ], }, ]) with self.mock_mail_gateway(): tasks.with_user(self.user_projectmanager).write({'stage_id': won_stage.id}) tasks.invalidate_cache(fnames=['rating_ids']) for task in tasks: self.assertEqual(len(task.rating_ids), 1, 'This task should have a generated rating when it arrives in the Won stage.') rating_request_message = task.message_ids[:1] if not task.user_ids or len(task.user_ids) > 1: self.assertFalse(task.rating_ids.rated_partner_id, 'This rating should have no assigned user if the task related have no assignees or more than one assignee.') self.assertEqual(rating_request_message.email_from, self.user_projectmanager.partner_id.email_formatted, 'The message should have the email of the Project Manager as email from.') else: self.assertEqual(task.rating_ids.rated_partner_id, task.user_ids.partner_id, 'The rating should have an assigned user if the task has only one assignee.') self.assertEqual(rating_request_message.email_from, task.user_ids.partner_id.email_formatted, 'The message should have the email of the assigned user in the task as email from.') self.assertTrue(self.partner_1 in rating_request_message.partner_ids, 'The customer of the task should be in the partner_ids of the rating request message.')
49.66954
17,285
3,056
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import OrderedDict from odoo import Command from odoo.exceptions import AccessError from odoo.tests import tagged from .test_project_sharing import TestProjectSharingCommon @tagged('post_install', '-at_install') class TestProjectSharingPortalAccess(TestProjectSharingCommon): @classmethod def setUpClass(cls): super().setUpClass() project_share_wizard = cls.env['project.share.wizard'].create({ 'access_mode': 'edit', 'res_model': 'project.project', 'res_id': cls.project_portal.id, 'partner_ids': [ Command.link(cls.partner_portal.id), ], }) project_share_wizard.action_send_mail() Task = cls.env['project.task'] cls.read_protected_fields_task = OrderedDict([ (k, v) for k, v in Task._fields.items() if k in Task.SELF_READABLE_FIELDS ]) cls.write_protected_fields_task = OrderedDict([ (k, v) for k, v in Task._fields.items() if k in Task.SELF_WRITABLE_FIELDS ]) cls.readonly_protected_fields_task = OrderedDict([ (k, v) for k, v in Task._fields.items() if k in Task.SELF_READABLE_FIELDS and k not in Task.SELF_WRITABLE_FIELDS ]) cls.other_fields_task = OrderedDict([ (k, v) for k, v in Task._fields.items() if k not in Task.SELF_READABLE_FIELDS ]) def test_readonly_fields(self): """ The fields are not writeable should not be editable by the portal user. """ view_infos = self.task_portal.fields_view_get(view_id=self.env.ref(self.project_sharing_form_view_xml_id).id) project_task_fields = { field_name for field_name, field_attrs in view_infos['fields'].items() if field_name not in self.write_protected_fields_task } with self.get_project_sharing_form_view(self.task_portal, self.user_portal) as form: for field in project_task_fields: with self.assertRaises(AssertionError, msg="Field '%s' should be readonly in the project sharing form view "): form.__setattr__(field, 'coucou') def test_read_task_with_portal_user(self): self.task_portal.with_user(self.user_portal).read(self.read_protected_fields_task) with self.assertRaises(AccessError): self.task_portal.with_user(self.user_portal).read(self.other_fields_task) def test_write_with_portal_user(self): for field in self.readonly_protected_fields_task: with self.assertRaises(AccessError): self.task_portal.with_user(self.user_portal).write({field: 'dummy'}) for field in self.other_fields_task: with self.assertRaises(AccessError): self.task_portal.with_user(self.user_portal).write({field: 'dummy'})
40.210526
3,056
19,199
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mail.tests.common import mail_new_test_user from odoo.addons.project.tests.test_project_base import TestProjectCommon from odoo import Command from odoo.exceptions import AccessError, ValidationError from odoo.tests.common import users from odoo.tools import mute_logger class TestAccessRights(TestProjectCommon): def setUp(self): super().setUp() self.task = self.create_task('Make the world a better place') self.user = mail_new_test_user(self.env, 'Internal user', groups='base.group_user') self.portal = mail_new_test_user(self.env, 'Portal user', groups='base.group_portal') def create_task(self, name, *, with_user=None, **kwargs): values = dict(name=name, project_id=self.project_pigs.id, **kwargs) return self.env['project.task'].with_user(with_user or self.env.user).create(values) class TestCRUDVisibilityFollowers(TestAccessRights): def setUp(self): super().setUp() self.project_pigs.privacy_visibility = 'followers' @users('Internal user', 'Portal user') def test_project_no_write(self): with self.assertRaises(AccessError, msg="%s should not be able to write on the project" % self.env.user.name): self.project_pigs.with_user(self.env.user).name = "Take over the world" self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) with self.assertRaises(AccessError, msg="%s should not be able to write on the project" % self.env.user.name): self.project_pigs.with_user(self.env.user).name = "Take over the world" @users('Internal user', 'Portal user') def test_project_no_unlink(self): self.project_pigs.task_ids.unlink() with self.assertRaises(AccessError, msg="%s should not be able to unlink the project" % self.env.user.name): self.project_pigs.with_user(self.env.user).unlink() self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) self.project_pigs.task_ids.unlink() with self.assertRaises(AccessError, msg="%s should not be able to unlink the project" % self.env.user.name): self.project_pigs.with_user(self.env.user).unlink() @users('Internal user', 'Portal user') def test_project_no_read(self): with self.assertRaises(AccessError, msg="%s should not be able to read the project" % self.env.user.name): self.project_pigs.with_user(self.env.user).name @users('Portal user') def test_project_allowed_portal_no_read(self): self.project_pigs.privacy_visibility = 'portal' self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) self.project_pigs.privacy_visibility = 'followers' with self.assertRaises(AccessError, msg="%s should not be able to read the project" % self.env.user.name): self.project_pigs.with_user(self.env.user).name @users('Internal user') def test_project_allowed_internal_read(self): self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) self.project_pigs.flush() self.project_pigs.invalidate_cache() self.project_pigs.with_user(self.env.user).name @users('Internal user', 'Portal user') def test_task_no_read(self): with self.assertRaises(AccessError, msg="%s should not be able to read the task" % self.env.user.name): self.task.with_user(self.env.user).name @users('Portal user') def test_task_allowed_portal_no_read(self): self.project_pigs.privacy_visibility = 'portal' self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) self.project_pigs.privacy_visibility = 'followers' with self.assertRaises(AccessError, msg="%s should not be able to read the task" % self.env.user.name): self.task.with_user(self.env.user).name @users('Internal user') def test_task_allowed_internal_read(self): self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) self.task.flush() self.task.invalidate_cache() self.task.with_user(self.env.user).name @users('Internal user', 'Portal user') def test_task_no_write(self): with self.assertRaises(AccessError, msg="%s should not be able to write on the task" % self.env.user.name): self.task.with_user(self.env.user).name = "Paint the world in black & white" self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) with self.assertRaises(AccessError, msg="%s should not be able to write on the task" % self.env.user.name): self.task.with_user(self.env.user).name = "Paint the world in black & white" @users('Internal user', 'Portal user') def test_task_no_create(self): with self.assertRaises(AccessError, msg="%s should not be able to create a task" % self.env.user.name): self.create_task("Archive the world, it's not needed anymore") self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) with self.assertRaises(AccessError, msg="%s should not be able to create a task" % self.env.user.name): self.create_task("Archive the world, it's not needed anymore") @users('Internal user', 'Portal user') def test_task_no_unlink(self): with self.assertRaises(AccessError, msg="%s should not be able to unlink the task" % self.env.user.name): self.task.with_user(self.env.user).unlink() self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) with self.assertRaises(AccessError, msg="%s should not be able to unlink the task" % self.env.user.name): self.task.with_user(self.env.user).unlink() class TestCRUDVisibilityPortal(TestAccessRights): def setUp(self): super().setUp() self.project_pigs.privacy_visibility = 'portal' @users('Portal user') def test_task_portal_no_read(self): with self.assertRaises(AccessError, msg="%s should not be able to read the task" % self.env.user.name): self.task.with_user(self.env.user).name @users('Portal user') def test_task_allowed_portal_read(self): self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) self.task.flush() self.task.invalidate_cache() self.task.with_user(self.env.user).name @users('Internal user') def test_task_internal_read(self): self.task.flush() self.task.invalidate_cache() self.task.with_user(self.env.user).name class TestCRUDVisibilityEmployees(TestAccessRights): def setUp(self): super().setUp() self.project_pigs.privacy_visibility = 'employees' @users('Portal user') def test_task_portal_no_read(self): with self.assertRaises(AccessError, msg="%s should not be able to read the task" % self.env.user.name): self.task.with_user(self.env.user).name self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) with self.assertRaises(AccessError, msg="%s should not be able to read the task" % self.env.user.name): self.task.with_user(self.env.user).name @users('Internal user') def test_task_allowed_portal_read(self): self.task.flush() self.task.invalidate_cache() self.task.with_user(self.env.user).name class TestAllowedUsers(TestAccessRights): def setUp(self): super().setUp() self.project_pigs.privacy_visibility = 'followers' def test_project_permission_added(self): self.project_pigs.message_subscribe(partner_ids=[self.user.partner_id.id]) self.assertIn(self.user.partner_id, self.task.message_partner_ids) def test_project_default_permission(self): self.project_pigs.message_subscribe(partner_ids=[self.user.partner_id.id]) task = self.create_task("Review the end of the world") self.assertIn(self.user.partner_id, self.task.message_partner_ids) def test_project_default_customer_permission(self): self.project_pigs.privacy_visibility = 'portal' self.project_pigs.message_subscribe(partner_ids=[self.portal.partner_id.id]) self.assertIn(self.portal.partner_id, self.task.message_partner_ids) self.assertIn(self.portal.partner_id, self.project_pigs.message_partner_ids) def test_project_permission_removed(self): self.project_pigs.message_subscribe(partner_ids=[self.user.partner_id.id]) self.project_pigs.message_unsubscribe(partner_ids=[self.user.partner_id.id]) self.assertNotIn(self.user.partner_id, self.task.message_partner_ids) def test_project_specific_permission(self): self.project_pigs.message_subscribe(partner_ids=[self.user.partner_id.id]) john = mail_new_test_user(self.env, 'John') self.project_pigs.message_subscribe(partner_ids=[john.partner_id.id]) self.project_pigs.message_unsubscribe(partner_ids=[self.user.partner_id.id]) self.assertIn(john.partner_id, self.task.message_partner_ids, "John should still be allowed to read the task") def test_project_specific_remove_mutliple_tasks(self): self.project_pigs.message_subscribe(partner_ids=[self.user.partner_id.id]) john = mail_new_test_user(self.env, 'John') task = self.create_task('task') self.task.message_subscribe(partner_ids=[john.partner_id.id]) self.project_pigs.message_unsubscribe(partner_ids=[self.user.partner_id.id]) self.assertIn(john.partner_id, self.task.message_partner_ids) self.assertNotIn(john.partner_id, task.message_partner_ids) self.assertNotIn(self.user.partner_id, task.message_partner_ids) self.assertNotIn(self.user.partner_id, self.task.message_partner_ids) def test_visibility_changed(self): self.project_pigs.privacy_visibility = 'portal' self.task.message_subscribe(partner_ids=[self.portal.partner_id.id]) self.assertNotIn(self.user.partner_id, self.task.message_partner_ids, "Internal user should have been removed from allowed users") self.project_pigs.write({'privacy_visibility': 'employees'}) self.assertNotIn(self.portal.partner_id, self.task.message_partner_ids, "Portal user should have been removed from allowed users") def test_write_task(self): self.user.groups_id |= self.env.ref('project.group_project_user') self.assertNotIn(self.user.partner_id, self.project_pigs.message_partner_ids) self.task.message_subscribe(partner_ids=[self.user.partner_id.id]) self.project_pigs.invalidate_cache() self.task.invalidate_cache() self.task.with_user(self.user).name = "I can edit a task!" def test_no_write_project(self): self.user.groups_id |= self.env.ref('project.group_project_user') self.assertNotIn(self.user.partner_id, self.project_pigs.message_partner_ids) with self.assertRaises(AccessError, msg="User should not be able to edit project"): self.project_pigs.with_user(self.user).name = "I can't edit a task!" class TestProjectPortalCommon(TestProjectCommon): def setUp(self): super(TestProjectPortalCommon, self).setUp() self.user_noone = self.env['res.users'].with_context({'no_reset_password': True, 'mail_create_nosubscribe': True}).create({ 'name': 'Noemie NoOne', 'login': 'noemie', 'email': '[email protected]', 'signature': '--\nNoemie', 'notification_type': 'email', 'groups_id': [(6, 0, [])]}) self.task_3 = self.env['project.task'].with_context({'mail_create_nolog': True}).create({ 'name': 'Test3', 'user_ids': self.user_portal, 'project_id': self.project_pigs.id}) self.task_4 = self.env['project.task'].with_context({'mail_create_nolog': True}).create({ 'name': 'Test4', 'user_ids': self.user_public, 'project_id': self.project_pigs.id}) self.task_5 = self.env['project.task'].with_context({'mail_create_nolog': True}).create({ 'name': 'Test5', 'user_ids': False, 'project_id': self.project_pigs.id}) self.task_6 = self.env['project.task'].with_context({'mail_create_nolog': True}).create({ 'name': 'Test5', 'user_ids': False, 'project_id': self.project_pigs.id}) class TestPortalProject(TestProjectPortalCommon): @mute_logger('odoo.addons.base.models.ir_model') def test_employee_project_access_rights(self): pigs = self.project_pigs pigs.write({'privacy_visibility': 'employees'}) # Do: Alfred reads project -> ok (employee ok employee) pigs.with_user(self.user_projectuser).read(['user_id']) # Test: all project tasks visible tasks = self.env['project.task'].with_user(self.user_projectuser).search([('project_id', '=', pigs.id)]) test_task_ids = set([self.task_1.id, self.task_2.id, self.task_3.id, self.task_4.id, self.task_5.id, self.task_6.id]) self.assertEqual(set(tasks.ids), test_task_ids, 'access rights: project user cannot see all tasks of an employees project') # Do: Bert reads project -> crash, no group self.assertRaises(AccessError, pigs.with_user(self.user_noone).read, ['user_id']) # Do: Donovan reads project -> ko (public ko employee) self.assertRaises(AccessError, pigs.with_user(self.user_public).read, ['user_id']) # Do: project user is employee and can create a task tmp_task = self.env['project.task'].with_user(self.user_projectuser).with_context({'mail_create_nolog': True}).create({ 'name': 'Pigs task', 'project_id': pigs.id}) tmp_task.with_user(self.user_projectuser).unlink() @mute_logger('odoo.addons.base.models.ir_model') def test_favorite_project_access_rights(self): pigs = self.project_pigs.with_user(self.user_projectuser) # we can't write on project name self.assertRaises(AccessError, pigs.write, {'name': 'False Pigs'}) # we can write on is_favorite pigs.write({'is_favorite': True}) @mute_logger('odoo.addons.base.ir.ir_model') def test_followers_project_access_rights(self): pigs = self.project_pigs pigs.write({'privacy_visibility': 'followers'}) pigs.flush(['privacy_visibility']) # Do: Alfred reads project -> ko (employee ko followers) self.assertRaises(AccessError, pigs.with_user(self.user_projectuser).read, ['user_id']) # Test: no project task visible tasks = self.env['project.task'].with_user(self.user_projectuser).search([('project_id', '=', pigs.id)]) self.assertEqual(tasks, self.task_1, 'access rights: employee user should not see tasks of a not-followed followers project, only assigned') # Do: Bert reads project -> crash, no group self.assertRaises(AccessError, pigs.with_user(self.user_noone).read, ['user_id']) # Do: Donovan reads project -> ko (public ko employee) self.assertRaises(AccessError, pigs.with_user(self.user_public).read, ['user_id']) pigs.message_subscribe(partner_ids=[self.user_projectuser.partner_id.id]) # Do: Alfred reads project -> ok (follower ok followers) donkey = pigs.with_user(self.user_projectuser) donkey.invalidate_cache() donkey.read(['user_id']) # Do: Donovan reads project -> ko (public ko follower even if follower) self.assertRaises(AccessError, pigs.with_user(self.user_public).read, ['user_id']) # Do: project user is follower of the project and can create a task self.env['project.task'].with_user(self.user_projectuser).with_context({'mail_create_nolog': True}).create({ 'name': 'Pigs task', 'project_id': pigs.id }) # not follower user should not be able to create a task pigs.with_user(self.user_projectuser).message_unsubscribe(partner_ids=[self.user_projectuser.partner_id.id]) self.assertRaises(AccessError, self.env['project.task'].with_user(self.user_projectuser).with_context({ 'mail_create_nolog': True}).create, {'name': 'Pigs task', 'project_id': pigs.id}) # Do: project user can create a task without project self.assertRaises(AccessError, self.env['project.task'].with_user(self.user_projectuser).with_context({ 'mail_create_nolog': True}).create, {'name': 'Pigs task', 'project_id': pigs.id}) class TestAccessRightsPrivateTask(TestAccessRights): @classmethod def setUpClass(cls): super().setUpClass() cls.private_task = cls.env['project.task'].create({'name': 'OdooBot Private Task'}) def setUp(self): super().setUp() self.project_user = mail_new_test_user(self.env, 'Project user', groups='project.group_project_user') def create_private_task(self, name, with_user=None, **kwargs): values = dict(name=name, **kwargs) return self.env['project.task'].with_user(with_user or self.env.user).create(values) @users('Internal user', 'Portal user') def test_internal_cannot_crud_private_task(self): with self.assertRaises(AccessError): self.create_private_task('Private task') with self.assertRaises(AccessError): self.private_task.with_user(self.env.user).write({'name': 'Test write'}) with self.assertRaises(AccessError): self.private_task.with_user(self.env.user).unlink() with self.assertRaises(AccessError): self.private_task.with_user(self.env.user).read(['name']) @users('Project user') def test_project_user_crud_own_private_task(self): private_task = self.create_private_task('Private task') private_task.with_user(self.env.user).write({'name': 'Test write'}) vals = private_task.with_user(self.env.user).read(['name']) self.assertEqual(vals[0]['id'], private_task.id) self.assertEqual(vals[0]['name'], private_task.name) @users('Project user') def test_project_user_cannot_create_private_task_for_another_user(self): with self.assertRaises(AccessError): self.create_private_task('test private for another user', self.env.user, user_ids=[Command.set(self.user_projectuser.ids)]) @users('Project user') def test_project_user_cannot_write_private_task_of_another_user(self): with self.assertRaises(AccessError): self.private_task.with_user(self.env.user).write({'name': 'Test write'}) @users('Project user') def test_project_user_cannot_read_private_task_of_another_user(self): with self.assertRaises(AccessError): self.private_task.with_user(self.env.user).read(['name']) @users('Project user') def test_project_user_cannot_unlink_private_task_of_another_user(self): with self.assertRaises(AccessError): self.private_task.with_user(self.env.user).unlink()
51.06117
19,199