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
377
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.point_of_sale.controllers.main import PosController from odoo import http from odoo.http import request class PosCache(PosController): @http.route() def load_onboarding_data(self): super().load_onboarding_data() request.env["pos.cache"].refresh_all_caches()
31.416667
377
921
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Drop Shipping', 'version': '1.0', 'category': 'Inventory/Inventory', 'summary': 'Drop Shipping', 'description': """ Manage drop shipping orders =========================== This module adds a pre-configured Drop Shipping operation type as well as a procurement route that allow configuring Drop Shipping products and orders. When drop shipping is used the goods are directly transferred from vendors to customers (direct delivery) without going through the retailer's warehouse. In this case no internal transfer document is needed. """, 'depends': ['sale_purchase_stock'], 'data': [ 'data/stock_data.xml', 'views/sale_order_views.xml', 'views/purchase_order_views.xml' ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
28.78125
921
5,894
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, Form from odoo.tools import mute_logger class TestDropship(common.TransactionCase): def test_change_qty(self): # enable the dropship and MTO route on the product prod = self.env['product.product'].create({'name': 'Large Desk'}) dropshipping_route = self.env.ref('stock_dropshipping.route_drop_shipping') mto_route = self.env.ref('stock.route_warehouse0_mto') prod.write({'route_ids': [(6, 0, [dropshipping_route.id, mto_route.id])]}) # add a vendor vendor1 = self.env['res.partner'].create({'name': 'vendor1'}) seller1 = self.env['product.supplierinfo'].create({ 'name': vendor1.id, 'price': 8, }) prod.write({'seller_ids': [(6, 0, [seller1.id])]}) # sell one unit of this product cust = self.env['res.partner'].create({'name': 'customer1'}) so = self.env['sale.order'].create({ 'partner_id': cust.id, 'partner_invoice_id': cust.id, 'partner_shipping_id': cust.id, 'order_line': [(0, 0, { 'name': prod.name, 'product_id': prod.id, 'product_uom_qty': 1.00, 'product_uom': prod.uom_id.id, 'price_unit': 12, })], 'pricelist_id': self.env.ref('product.list0').id, 'picking_policy': 'direct', }) so.action_confirm() po = self.env['purchase.order'].search([('group_id', '=', so.procurement_group_id.id)]) po_line = po.order_line # Check dropship count on SO and PO self.assertEqual(po.incoming_picking_count, 0) self.assertEqual(so.delivery_count, 0) # Check the qty on the P0 self.assertAlmostEqual(po_line.product_qty, 1.00) # Update qty on SO and check PO so.write({'order_line': [[1, so.order_line.id, {'product_uom_qty': 2.00}]]}) self.assertAlmostEqual(po_line.product_qty, 2.00) # Create a new so line sol2 = self.env['sale.order.line'].create({ 'order_id': so.id, 'name': prod.name, 'product_id': prod.id, 'product_uom_qty': 3.00, 'product_uom': prod.uom_id.id, 'price_unit': 12, }) # there is a new line pol2 = po.order_line - po_line # the first line is unchanged self.assertAlmostEqual(po_line.product_qty, 2.00) # the new line matches the new line on the so self.assertAlmostEqual(pol2.product_qty, sol2.product_uom_qty) def test_00_dropship(self): # Create a vendor supplier_dropship = self.env['res.partner'].create({'name': 'Vendor of Dropshipping test'}) # Create new product without any routes drop_shop_product = self.env['product.product'].create({ 'name': "Pen drive", 'type': "product", 'categ_id': self.env.ref('product.product_category_1').id, 'lst_price': 100.0, 'standard_price': 0.0, 'uom_id': self.env.ref('uom.product_uom_unit').id, 'uom_po_id': self.env.ref('uom.product_uom_unit').id, 'seller_ids': [(0, 0, { 'delay': 1, 'name': supplier_dropship.id, 'min_qty': 2.0 })] }) # Create a sales order with a line of 200 PCE incoming shipment, with route_id drop shipping so_form = Form(self.env['sale.order']) so_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) so_form.payment_term_id = self.env.ref('account.account_payment_term_end_following_month') with mute_logger('odoo.tests.common.onchange'): # otherwise complains that there's not enough inventory and # apparently that's normal according to @jco and @sle with so_form.order_line.new() as line: line.product_id = drop_shop_product line.product_uom_qty = 200 line.price_unit = 1.00 line.route_id = self.env.ref('stock_dropshipping.route_drop_shipping') sale_order_drp_shpng = so_form.save() # Confirm sales order sale_order_drp_shpng.action_confirm() # Check the sales order created a procurement group which has a procurement of 200 pieces self.assertTrue(sale_order_drp_shpng.procurement_group_id, 'SO should have procurement group') # Check a quotation was created to a certain vendor and confirm so it becomes a confirmed purchase order purchase = self.env['purchase.order'].search([('partner_id', '=', supplier_dropship.id)]) self.assertTrue(purchase, "an RFQ should have been created by the scheduler") purchase.button_confirm() self.assertEqual(purchase.state, 'purchase', 'Purchase order should be in the approved state') # Check dropship count on SO and PO self.assertEqual(purchase.incoming_picking_count, 0) self.assertEqual(sale_order_drp_shpng.delivery_count, 0) self.assertEqual(sale_order_drp_shpng.dropship_picking_count, 1) self.assertEqual(purchase.dropship_picking_count, 1) # Send the 200 pieces purchase.picking_ids.move_lines.quantity_done = purchase.picking_ids.move_lines.product_qty purchase.picking_ids.button_validate() # Check one move line was created in Customers location with 200 pieces move_line = self.env['stock.move.line'].search([ ('location_dest_id', '=', self.env.ref('stock.stock_location_customers').id), ('product_id', '=', drop_shop_product.id)]) self.assertEqual(len(move_line.ids), 1, 'There should be exactly one move line')
44.651515
5,894
4,663
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, tools from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests import tagged, common, Form @tagged('-at_install', 'post_install') class TestLifoPrice(ValuationReconciliationTestCommon): def test_lifoprice(self): # Set product category removal strategy as LIFO product_category_001 = self.env['product.category'].create({ 'name': 'Lifo Category', 'removal_strategy_id': self.env.ref('stock.removal_lifo').id, 'property_valuation': 'real_time', 'property_cost_method': 'fifo', }) res_partner_3 = self.env['res.partner'].create({'name': 'My Test Partner'}) self.company_data['default_warehouse'].out_type_id.show_operations = False # Set a product as using lifo price product_form = Form(self.env['product.product']) product_form.default_code = 'LIFO' product_form.name = 'LIFO Ice Cream' product_form.detailed_type = 'product' product_form.categ_id = product_category_001 product_form.list_price = 100.0 product_form.uom_id = self.env.ref('uom.product_uom_kgm') product_form.uom_po_id = self.env.ref('uom.product_uom_kgm') # these are not available (visible) in either product or variant # for views, apparently from the UI you can only set the product # category (or hand-assign the property_* version which seems...) # product_form.categ_id.valuation = 'real_time' # product_form.categ_id.property_cost_method = 'fifo' product_form.categ_id.property_stock_account_input_categ_id = self.company_data['default_account_stock_in'] product_form.categ_id.property_stock_account_output_categ_id = self.company_data['default_account_stock_out'] product_lifo_icecream = product_form.save() product_lifo_icecream.standard_price = 70.0 # I create a draft Purchase Order for first in move for 10 pieces at 60 euro order_form = Form(self.env['purchase.order']) order_form.partner_id = res_partner_3 with order_form.order_line.new() as line: line.product_id = product_lifo_icecream line.product_qty = 10.0 line.price_unit = 60.0 purchase_order_lifo1 = order_form.save() # I create a draft Purchase Order for second shipment for 30 pieces at 80 euro order2_form = Form(self.env['purchase.order']) order2_form.partner_id = res_partner_3 with order2_form.order_line.new() as line: line.product_id = product_lifo_icecream line.product_qty = 30.0 line.price_unit = 80.0 purchase_order_lifo2 = order2_form.save() # I confirm the first purchase order purchase_order_lifo1.button_confirm() # I check the "Approved" status of purchase order 1 self.assertEqual(purchase_order_lifo1.state, 'purchase') # Process the receipt of purchase order 1 purchase_order_lifo1.picking_ids[0].move_lines.quantity_done = purchase_order_lifo1.picking_ids[0].move_lines.product_qty purchase_order_lifo1.picking_ids[0].button_validate() # I confirm the second purchase order purchase_order_lifo2.button_confirm() # Process the receipt of purchase order 2 purchase_order_lifo2.picking_ids[0].move_lines.quantity_done = purchase_order_lifo2.picking_ids[0].move_lines.product_qty purchase_order_lifo2.picking_ids[0].button_validate() # Let us send some goods self.company_data['default_warehouse'].out_type_id.show_operations = False out_form = Form(self.env['stock.picking']) out_form.picking_type_id = self.company_data['default_warehouse'].out_type_id out_form.immediate_transfer = True with out_form.move_ids_without_package.new() as move: move.product_id = product_lifo_icecream move.quantity_done = 20.0 move.date = fields.Datetime.now() outgoing_lifo_shipment = out_form.save() # I assign this outgoing shipment outgoing_lifo_shipment.action_assign() # Process the delivery of the outgoing shipment outgoing_lifo_shipment.button_validate() # Check if the move value correctly reflects the fifo costing method self.assertEqual(outgoing_lifo_shipment.move_lines.stock_valuation_layer_ids.value, -1400.0, 'Stock move value should have been 1400 euro')
48.072165
4,663
2,514
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, Form from odoo.tools import mute_logger class TestCrossdock(common.TransactionCase): def test_00_crossdock(self): # Create a supplier supplier_crossdock = self.env['res.partner'].create({'name': "Crossdocking supplier"}) # I first create a warehouse with pick-pack-ship and reception in 2 steps wh_pps = self.env['stock.warehouse'].create({ 'name': 'WareHouse PickPackShip', 'code': 'whpps', 'reception_steps': 'two_steps', 'delivery_steps': 'pick_pack_ship', }) # Check that cross-dock route is active self.assertTrue(wh_pps.crossdock_route_id.active, "Crossdock route should be active when reception_steps is not in 'single_step'") p_f = Form(self.env['product.template']) p_f.name = 'PCE' p_f.detailed_type = 'product' p_f.categ_id = self.env.ref('product.product_category_1') p_f.list_price = 100.0 with p_f.seller_ids.new() as seller: seller.name = supplier_crossdock p_f.route_ids.add(wh_pps.crossdock_route_id) cross_shop_product = p_f.save() p_f.standard_price = 70.0 # Create a sales order with a line of 100 PCE incoming shipment with route_id crossdock shipping so_form = Form(self.env['sale.order']) so_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) so_form.warehouse_id = wh_pps with mute_logger('odoo.tests.common.onchange'): # otherwise complains that there's not enough inventory and # apparently that's normal according to @jco and @sle with so_form.order_line.new() as line: line.product_id = cross_shop_product.product_variant_ids line.product_uom_qty = 100.0 sale_order_crossdock = so_form.save() # Confirm sales order sale_order_crossdock.action_confirm() # Run the scheduler self.env['procurement.group'].run_scheduler() # Check a quotation was created for the created supplier and confirm it po = self.env['purchase.order'].search([ ('partner_id', '=', supplier_crossdock.id), ('state', '=', 'draft') ]) self.assertTrue(po, "an RFQ should have been created by the scheduler") po.button_confirm()
39.28125
2,514
2,352
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, Form class TestProcurementException(common.TransactionCase): def test_00_procurement_exception(self): res_partner_2 = self.env['res.partner'].create({'name': 'My Test Partner'}) res_partner_address = self.env['res.partner'].create({ 'name': 'My Test Partner Address', 'parent_id': res_partner_2.id, }) # I create a product with no supplier define for it. product_form = Form(self.env['product.product']) product_form.name = 'product with no seller' product_form.list_price = 20.00 product_form.categ_id = self.env.ref('product.product_category_1') product_with_no_seller = product_form.save() product_with_no_seller.standard_price = 70.0 # I create a sales order with this product with route dropship. so_form = Form(self.env['sale.order']) so_form.partner_id = res_partner_2 so_form.partner_invoice_id = res_partner_address so_form.partner_shipping_id = res_partner_address so_form.payment_term_id = self.env.ref('account.account_payment_term_end_following_month') with so_form.order_line.new() as line: line.product_id = product_with_no_seller line.product_uom_qty = 3 line.route_id = self.env.ref('stock_dropshipping.route_drop_shipping') sale_order_route_dropship01 = so_form.save() # I confirm the sales order, but it will raise an error with self.assertRaises(Exception): sale_order_route_dropship01.action_confirm() # I set the at least one supplier on the product. with Form(product_with_no_seller) as f: with f.seller_ids.new() as seller: seller.delay = 1 seller.name = res_partner_2 seller.min_qty = 2.0 # I confirm the sales order, no error this time sale_order_route_dropship01.action_confirm() # I check a purchase quotation was created. purchase = self.env['purchase.order.line'].search([ ('sale_line_id', '=', sale_order_route_dropship01.order_line.ids[0])]).order_id self.assertTrue(purchase, 'No Purchase Quotation is created')
42
2,352
17,147
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests import Form, tagged @tagged('post_install', '-at_install') class TestStockValuation(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.supplier_location = cls.env.ref('stock.stock_location_suppliers') cls.stock_location = cls.company_data['default_warehouse'].lot_stock_id cls.partner_id = cls.env['res.partner'].create({'name': 'My Test Partner'}) cls.product1 = cls.env['product.product'].create({ 'name': 'Large Desk', 'type': 'product', 'categ_id': cls.stock_account_product_categ.id, 'taxes_id': [(6, 0, [])], }) def _dropship_product1(self): # enable the dropship and MTO route on the product dropshipping_route = self.env.ref('stock_dropshipping.route_drop_shipping') mto_route = self.env.ref('stock.route_warehouse0_mto') self.product1.write({'route_ids': [(6, 0, [dropshipping_route.id, mto_route.id])]}) # add a vendor vendor1 = self.env['res.partner'].create({'name': 'vendor1'}) seller1 = self.env['product.supplierinfo'].create({ 'name': vendor1.id, 'price': 8, }) self.product1.write({'seller_ids': [(6, 0, [seller1.id])]}) # sell one unit of this product customer1 = self.env['res.partner'].create({'name': 'customer1'}) self.sale_order1 = self.env['sale.order'].create({ 'partner_id': customer1.id, 'partner_invoice_id': customer1.id, 'partner_shipping_id': customer1.id, 'order_line': [(0, 0, { 'name': self.product1.name, 'product_id': self.product1.id, 'product_uom_qty': 1, 'product_uom': self.product1.uom_id.id, 'price_unit': 12, 'tax_id': [(6, 0, [])], })], 'pricelist_id': self.env.ref('product.list0').id, 'picking_policy': 'direct', }) self.sale_order1.action_confirm() # confirm the purchase order self.purchase_order1 = self.env['purchase.order'].search([('group_id', '=', self.sale_order1.procurement_group_id.id)]) self.purchase_order1.button_confirm() # validate the dropshipping picking self.assertEqual(len(self.sale_order1.picking_ids), 1) wizard = self.sale_order1.picking_ids.button_validate() immediate_transfer = Form(self.env[wizard['res_model']].with_context(wizard['context'])).save() immediate_transfer.process() self.assertEqual(self.sale_order1.picking_ids.state, 'done') # create the vendor bill move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.partner_id = vendor1 move_form.purchase_id = self.purchase_order1 move_form.invoice_date = move_form.date for i in range(len(self.purchase_order1.order_line)): with move_form.invoice_line_ids.edit(i) as line_form: line_form.tax_ids.clear() self.vendor_bill1 = move_form.save() self.vendor_bill1.action_post() # create the customer invoice self.customer_invoice1 = self.sale_order1._create_invoices() self.customer_invoice1.action_post() all_amls = self.vendor_bill1.line_ids + self.customer_invoice1.line_ids if self.sale_order1.picking_ids.move_lines.account_move_ids: all_amls |= self.sale_order1.picking_ids.move_lines.account_move_ids.line_ids return all_amls def _check_results(self, expected_aml, expected_aml_count, all_amls): # Construct a dict similar to `expected_aml` with `all_amls` in order to # compare them. result_aml = {} for aml in all_amls: account_id = aml.account_id.id if result_aml.get(account_id): debit = result_aml[account_id][0] credit = result_aml[account_id][1] result_aml[account_id] = (debit + aml.debit, credit + aml.credit) else: result_aml[account_id] = (aml.debit, aml.credit) self.assertEqual(len(all_amls), expected_aml_count) for k, v in expected_aml.items(): self.assertEqual(result_aml[k], v) # ------------------------------------------------------------------------- # Continental # ------------------------------------------------------------------------- def test_dropship_standard_perpetual_continental_ordered(self): self.env.company.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'order' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (8.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), } self._check_results(expected_aml, 4, all_amls) def test_dropship_standard_perpetual_continental_delivered(self): self.env.company.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'delivery' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (8.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), } self._check_results(expected_aml, 4, all_amls) def test_dropship_fifo_perpetual_continental_ordered(self): self.env.company.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'order' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (8.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), } self._check_results(expected_aml, 4, all_amls) def test_dropship_fifo_perpetual_continental_delivered(self): self.env.company.anglo_saxon_accounting = False self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'delivery' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (8.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), } self._check_results(expected_aml, 4, all_amls) # ------------------------------------------------------------------------- # Anglosaxon # ------------------------------------------------------------------------- def test_dropship_standard_perpetual_anglosaxon_ordered(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'order' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (10.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), self.company_data['default_account_stock_in'].id: (8.0, 10.0), self.company_data['default_account_stock_out'].id: (10.0, 10.0), } # Interim IN is not balanced because because there's a difference between the po line # price unit and the standard price. We could set a price difference account on the # category to compensate. self._check_results(expected_aml, 10, all_amls) def test_dropship_standard_perpetual_anglosaxon_delivered(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'delivery' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (10.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), self.company_data['default_account_stock_in'].id: (8.0, 10.0), self.company_data['default_account_stock_out'].id: (10.0, 10.0), } # Interim IN is not balanced because because there's a difference between the po line # price unit and the standard price. We could set a price difference account on the # category to compensate. self._check_results(expected_aml, 10, all_amls) def test_dropship_fifo_perpetual_anglosaxon_ordered(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'order' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (8.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), self.company_data['default_account_stock_in'].id: (8.0, 8.0), self.company_data['default_account_stock_out'].id: (8.0, 8.0), } self._check_results(expected_aml, 10, all_amls) def test_dropship_fifo_perpetual_anglosaxon_delivered(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'delivery' all_amls = self._dropship_product1() expected_aml = { self.company_data['default_account_payable'].id: (0.0, 8.0), self.company_data['default_account_expense'].id: (8.0, 0.0), self.company_data['default_account_receivable'].id: (12.0, 0.0), self.company_data['default_account_revenue'].id: (0.0, 12.0), self.company_data['default_account_stock_in'].id: (8.0, 8.0), self.company_data['default_account_stock_out'].id: (8.0, 8.0), } self._check_results(expected_aml, 10, all_amls) def test_dropship_standard_perpetual_anglosaxon_ordered_return(self): self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard' self.product1.product_tmpl_id.standard_price = 10 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'order' all_amls = self._dropship_product1() # return what we've done stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=self.sale_order1.picking_ids.ids, active_id=self.sale_order1.picking_ids.ids[0], active_model='stock.picking')) stock_return_picking = stock_return_picking_form.save() stock_return_picking_action = stock_return_picking.create_returns() return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id']) return_pick.move_lines[0].move_line_ids[0].qty_done = 1.0 return_pick._action_done() self.assertEqual(return_pick.move_lines._is_dropshipped_returned(), True) all_amls_return = self.vendor_bill1.line_ids + self.customer_invoice1.line_ids if self.sale_order1.picking_ids.mapped('move_lines.account_move_ids'): all_amls_return |= self.sale_order1.picking_ids.mapped('move_lines.account_move_ids.line_ids') # Two extra AML should have been created for the return expected_aml = { self.company_data['default_account_stock_in'].id: (10.0, 0.0), self.company_data['default_account_stock_out'].id: (0.0, 10.0), } self._check_results(expected_aml, 4, all_amls_return - all_amls) def test_dropship_fifo_return(self): """Test the return of a dropship order with a product set to FIFO costing method. The unit price is correctly computed on the return picking svl. """ self.env.company.anglo_saxon_accounting = True self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo' self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time' self.product1.product_tmpl_id.invoice_policy = 'order' self._dropship_product1() self.assertTrue(8 in self.purchase_order1.picking_ids.move_lines.stock_valuation_layer_ids.mapped('value')) self.assertTrue(-8 in self.purchase_order1.picking_ids.move_lines.stock_valuation_layer_ids.mapped('value')) # return what we've done stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=self.sale_order1.picking_ids.ids, active_id=self.sale_order1.picking_ids.ids[0], active_model='stock.picking')) stock_return_picking = stock_return_picking_form.save() stock_return_picking_action = stock_return_picking.create_returns() return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id']) return_pick.move_lines[0].move_line_ids[0].qty_done = 1.0 return_pick._action_done() self.assertTrue(8 in return_pick.move_lines.stock_valuation_layer_ids.mapped('value')) self.assertTrue(-8 in return_pick.move_lines.stock_valuation_layer_ids.mapped('value')) # return again to have a new dropship picking from a dropship return stock_return_picking_form_2 = Form(self.env['stock.return.picking'] .with_context(active_ids=return_pick.ids, active_id=return_pick.ids[0], active_model='stock.picking')) stock_return_picking_2 = stock_return_picking_form_2.save() stock_return_picking_action_2 = stock_return_picking_2.create_returns() return_pick_2 = self.env['stock.picking'].browse(stock_return_picking_action_2['res_id']) return_pick_2.move_lines[0].move_line_ids[0].qty_done = 1.0 return_pick_2._action_done() self.assertTrue(8 in return_pick_2.move_lines.stock_valuation_layer_ids.mapped('value')) self.assertTrue(-8 in return_pick_2.move_lines.stock_valuation_layer_ids.mapped('value'))
50.581121
17,147
2,141
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields class PurchaseOrder(models.Model): _inherit = 'purchase.order' dropship_picking_count = fields.Integer("Dropship Count", compute='_compute_incoming_picking_count') @api.depends('picking_ids.is_dropship') def _compute_incoming_picking_count(self): super()._compute_incoming_picking_count() for order in self: dropship_count = len(order.picking_ids.filtered(lambda p: p.is_dropship)) order.incoming_picking_count -= dropship_count order.dropship_picking_count = dropship_count def action_view_picking(self): return self._get_action_view_picking(self.picking_ids.filtered(lambda p: not p.is_dropship)) def action_view_dropship(self): return self._get_action_view_picking(self.picking_ids.filtered(lambda p: p.is_dropship)) class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' def _prepare_stock_moves(self, picking): res = super(PurchaseOrderLine, self)._prepare_stock_moves(picking) for re in res: re['sale_line_id'] = self.sale_line_id.id return res def _find_candidate(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values): # if this is defined, this is a dropshipping line, so no # this is to correctly map delivered quantities to the so lines lines = self.filtered(lambda po_line: po_line.sale_line_id.id == values['sale_line_id']) if values.get('sale_line_id') else self return super(PurchaseOrderLine, lines)._find_candidate(product_id, product_qty, product_uom, location_id, name, origin, company_id, values) @api.model def _prepare_purchase_order_line_from_procurement(self, product_id, product_qty, product_uom, company_id, values, po): res = super()._prepare_purchase_order_line_from_procurement(product_id, product_qty, product_uom, company_id, values, po) res['sale_line_id'] = values.get('sale_line_id', False) return res
46.543478
2,141
1,743
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields class StockRule(models.Model): _inherit = 'stock.rule' @api.model def _get_procurements_to_merge_groupby(self, procurement): """ Do not group purchase order line if they are linked to different sale order line. The purpose is to compute the delivered quantities. """ return procurement.values.get('sale_line_id'), super(StockRule, self)._get_procurements_to_merge_groupby(procurement) @api.model def _get_procurements_to_merge_sorted(self, procurement): return procurement.values.get('sale_line_id'), super(StockRule, self)._get_procurements_to_merge_sorted(procurement) class ProcurementGroup(models.Model): _inherit = "procurement.group" @api.model def _get_rule_domain(self, location, values): if 'sale_line_id' in values and values.get('company_id'): return [('location_id', '=', location.id), ('action', '!=', 'push'), ('company_id', '=', values['company_id'].id)] else: return super(ProcurementGroup, self)._get_rule_domain(location, values) class StockPicking(models.Model): _inherit = 'stock.picking' is_dropship = fields.Boolean("Is a Dropship", compute='_compute_is_dropship') @api.depends('location_dest_id.usage', 'location_id.usage') def _compute_is_dropship(self): for picking in self: picking.is_dropship = picking.location_dest_id.usage == 'customer' and picking.location_id.usage == 'supplier' def _is_to_external_location(self): self.ensure_one() return super()._is_to_external_location() or self.is_dropship
39.613636
1,743
5,165
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 ResCompany(models.Model): _inherit = 'res.company' # ------------------------------------------------------------------------- # Sequences # ------------------------------------------------------------------------- def _create_dropship_sequence(self): dropship_vals = [] for company in self: dropship_vals.append({ 'name': 'Dropship (%s)' % company.name, 'code': 'stock.dropshipping', 'company_id': company.id, 'prefix': 'DS/', 'padding': 5, }) if dropship_vals: self.env['ir.sequence'].create(dropship_vals) @api.model def create_missing_dropship_sequence(self): company_ids = self.env['res.company'].search([]) company_has_dropship_seq = self.env['ir.sequence'].search([('code', '=', 'stock.dropshipping')]).mapped('company_id') company_todo_sequence = company_ids - company_has_dropship_seq company_todo_sequence._create_dropship_sequence() def _create_per_company_sequences(self): super(ResCompany, self)._create_per_company_sequences() self._create_dropship_sequence() # ------------------------------------------------------------------------- # Picking types # ------------------------------------------------------------------------- def _create_dropship_picking_type(self): dropship_vals = [] for company in self: sequence = self.env['ir.sequence'].search([ ('code', '=', 'stock.dropshipping'), ('company_id', '=', company.id), ]) dropship_vals.append({ 'name': 'Dropship', 'company_id': company.id, 'warehouse_id': False, 'sequence_id': sequence.id, 'code': 'incoming', 'default_location_src_id': self.env.ref('stock.stock_location_suppliers').id, 'default_location_dest_id': self.env.ref('stock.stock_location_customers').id, 'sequence_code': 'DS', 'use_existing_lots': False, }) if dropship_vals: self.env['stock.picking.type'].create(dropship_vals) @api.model def create_missing_dropship_picking_type(self): company_ids = self.env['res.company'].search([]) company_has_dropship_picking_type = ( self.env['stock.picking.type'] .search([ ('default_location_src_id.usage', '=', 'supplier'), ('default_location_dest_id.usage', '=', 'customer'), ]) .mapped('company_id') ) company_todo_picking_type = company_ids - company_has_dropship_picking_type company_todo_picking_type._create_dropship_picking_type() def _create_per_company_picking_types(self): super(ResCompany, self)._create_per_company_picking_types() self._create_dropship_picking_type() # ------------------------------------------------------------------------- # Stock rules # ------------------------------------------------------------------------- def _create_dropship_rule(self): dropship_route = self.env.ref('stock_dropshipping.route_drop_shipping') supplier_location = self.env.ref('stock.stock_location_suppliers') customer_location = self.env.ref('stock.stock_location_customers') dropship_vals = [] for company in self: dropship_picking_type = self.env['stock.picking.type'].search([ ('company_id', '=', company.id), ('default_location_src_id.usage', '=', 'supplier'), ('default_location_dest_id.usage', '=', 'customer'), ], limit=1, order='sequence') if not dropship_picking_type: continue dropship_vals.append({ 'name': '%s → %s' % (supplier_location.name, customer_location.name), 'action': 'buy', 'location_id': customer_location.id, 'location_src_id': supplier_location.id, 'procure_method': 'make_to_stock', 'route_id': dropship_route.id, 'picking_type_id': dropship_picking_type.id, 'company_id': company.id, }) if dropship_vals: self.env['stock.rule'].create(dropship_vals) @api.model def create_missing_dropship_rule(self): dropship_route = self.env.ref('stock_dropshipping.route_drop_shipping') company_ids = self.env['res.company'].search([]) company_has_dropship_rule = self.env['stock.rule'].search([('route_id', '=', dropship_route.id)]).mapped('company_id') company_todo_rule = company_ids - company_has_dropship_rule company_todo_rule._create_dropship_rule() def _create_per_company_rules(self): super(ResCompany, self)._create_per_company_rules() self._create_dropship_rule()
43.025
5,163
2,286
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class SaleOrder(models.Model): _inherit = 'sale.order' dropship_picking_count = fields.Integer("Dropship Count", compute='_compute_picking_ids') @api.depends('picking_ids.is_dropship') def _compute_picking_ids(self): super()._compute_picking_ids() for order in self: dropship_count = len(order.picking_ids.filtered(lambda p: p.is_dropship)) order.delivery_count -= dropship_count order.dropship_picking_count = dropship_count def action_view_delivery(self): return self._get_action_view_picking(self.picking_ids.filtered(lambda p: not p.is_dropship)) def action_view_dropship(self): return self._get_action_view_picking(self.picking_ids.filtered(lambda p: p.is_dropship)) class SaleOrderLine(models.Model): _inherit = 'sale.order.line' def _compute_is_mto(self): super(SaleOrderLine, self)._compute_is_mto() for line in self: if not line.display_qty_widget or line.is_mto: continue product_routes = line.route_id or (line.product_id.route_ids + line.product_id.categ_id.total_route_ids) for pull_rule in product_routes.mapped('rule_ids'): if pull_rule.picking_type_id.sudo().default_location_src_id.usage == 'supplier' and\ pull_rule.picking_type_id.sudo().default_location_dest_id.usage == 'customer': line.is_mto = True break def _get_qty_procurement(self, previous_product_uom_qty): # People without purchase rights should be able to do this operation purchase_lines_sudo = self.sudo().purchase_line_ids if purchase_lines_sudo.filtered(lambda r: r.state != 'cancel'): qty = 0.0 for po_line in purchase_lines_sudo.filtered(lambda r: r.state != 'cancel'): qty += po_line.product_uom._compute_quantity(po_line.product_qty, self.product_uom, rounding_method='HALF-UP') return qty else: return super(SaleOrderLine, self)._get_qty_procurement(previous_product_uom_qty=previous_product_uom_qty)
44.823529
2,286
1,107
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'SMS Marketing', 'summary': 'Design, send and track SMS', 'description': '', 'version': '1.0', 'category': 'Marketing/Email Marketing', 'sequence': 245, 'depends': [ 'portal', 'mass_mailing', 'sms', ], 'data': [ 'data/utm_data.xml', 'security/ir.model.access.csv', 'views/mailing_sms_menus.xml', 'views/mailing_list_views.xml', 'views/mailing_contact_views.xml', 'views/mailing_trace_views.xml', 'views/mailing_mailing_views.xml', 'views/link_tracker_views.xml', 'views/mass_mailing_sms_templates_portal.xml', 'views/utm_campaign_views.xml', 'report/mailing_trace_report_views.xml', 'wizard/sms_composer_views.xml', 'wizard/mailing_sms_test_views.xml', ], 'demo': [ 'data/utm_demo.xml', 'data/mailing_list_demo.xml', 'data/mailing_demo.xml', ], 'application': True, 'license': 'LGPL-3', }
29.131579
1,107
2,831
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 odoo.addons.mass_mailing_sms.tests.common import MassSMSCommon from odoo.tests.common import users class TestMassMailValues(MassSMSCommon): @classmethod def setUpClass(cls): super(TestMassMailValues, cls).setUpClass() cls._create_mailing_list() cls.sms_template_partner = cls.env['sms.template'].create({ 'name': 'Test Template', 'model_id': cls.env['ir.model']._get('res.partner').id, 'body': 'Dear {{ object.display_name }} this is an SMS.' }) @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': 'sms', 'body_plaintext': 'Coucou hibou', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, }) self.assertEqual(mailing.user_id, self.user_marketing) self.assertEqual(mailing.body_plaintext, 'Coucou hibou') self.assertEqual(mailing.medium_id, self.env.ref('mass_mailing_sms.utm_medium_sms')) self.assertEqual(mailing.mailing_model_name, 'res.partner') self.assertEqual(mailing.mailing_model_real, 'res.partner') # default for partner: remove blacklisted self.assertEqual(literal_eval(mailing.mailing_domain), [('phone_sanitized_blacklisted', '=', False)]) # update template -> update body mailing.write({'sms_template_id': self.sms_template_partner.id}) self.assertEqual(mailing.body_plaintext, self.sms_template_partner.body) # 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') # 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)])
46.409836
2,831
1,462
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from odoo.addons.mass_mailing_sms.tests.common import MassSMSCommon from odoo.addons.mass_mailing.tests.test_mailing_ab_testing import TestMailingABTesting from odoo.tests import tagged @tagged('post_install', '-at_install') class TestMailingSMSABTesting(MassSMSCommon, TestMailingABTesting): def setUp(self): super().setUp() self.ab_testing_mailing_sms_1 = self.env['mailing.mailing'].create({ 'subject': 'A/B Testing SMS V1', 'contact_list_ids': self.mailing_list.ids, 'ab_testing_enabled': True, 'ab_testing_pc': 10, 'ab_testing_schedule_datetime': datetime.now(), 'mailing_type': 'sms' }) self.ab_testing_mailing_sms_2 = self.ab_testing_mailing_sms_1.copy({ 'subject': 'A/B Testing SMS V2', 'ab_testing_pc': 20, }) def test_mailing_sms_ab_testing_compare(self): # compare version feature should returns all mailings of the same # campaign having a/b testing enabled and of mailing_type 'sms'. compare_version = self.ab_testing_mailing_sms_1.action_compare_versions() self.assertEqual( self.env['mailing.mailing'].search(compare_version.get('domain')), self.ab_testing_mailing_sms_1 + self.ab_testing_mailing_sms_2 )
41.771429
1,462
7,704
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import random import re import werkzeug from odoo import tools from odoo.addons.mass_mailing.tests.common import MassMailCommon from odoo.addons.sms.tests.common import SMSCase, SMSCommon class MassSMSCase(SMSCase): # ------------------------------------------------------------ # ASSERTS # ------------------------------------------------------------ def assertSMSStatistics(self, recipients_info, mailing, records, check_sms=True): """ Deprecated, remove in 14.4 """ return self.assertSMSTraces(recipients_info, mailing, records, check_sms=check_sms) def assertSMSTraces(self, recipients_info, mailing, records, check_sms=True, sent_unlink=False, sms_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. Sms.sms records may optionally be checked. :param recipients_info: list[{ # TRACE 'partner': res.partner record (may be empty), 'number': number used for notification (may be empty, computed based on partner), 'trace_status': outgoing / sent / cancel / bounce / error / opened (sent by default), 'record: linked record, # SMS.SMS 'content': optional: if set, check content of sent SMS; 'failure_type': error code linked to sms failure (see ``error_code`` field on ``sms.sms`` model); }, { ... }]; :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_sms: if set, check sms.sms records that should be linked to traces; :param sent_unlink: it True, sent sms.sms are deleted and we check gateway output result instead of actual sms.sms records; :param sms_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; ] """ # map trace state to sms state state_mapping = { 'sent': 'sent', 'outgoing': 'outgoing', 'error': 'error', 'cancel': 'canceled', 'bounce': 'error', } traces = self.env['mailing.trace'].search([ ('mass_mailing_id', 'in', mailing.ids), ('res_id', 'in', records.ids) ]) self.assertTrue(all(s.model == records._name for s in traces)) # self.assertTrue(all(s.utm_campaign_id == mailing.campaign_id for s in traces)) self.assertEqual(set(s.res_id for s in traces), set(records.ids)) # check each trace if not sms_links_info: sms_links_info = [None] * len(recipients_info) for recipient_info, link_info, record in zip(recipients_info, sms_links_info, records): partner = recipient_info.get('partner', self.env['res.partner']) number = recipient_info.get('number') status = recipient_info.get('trace_status', 'outgoing') content = recipient_info.get('content', None) if number is None and partner: number = partner._sms_get_recipients_info()[partner.id]['sanitized'] trace = traces.filtered( lambda t: t.sms_number == number and t.trace_status == status and (t.res_id == record.id if record else True) ) self.assertTrue(len(trace) == 1, 'SMS: found %s notification for number %s, (status: %s) (1 expected)' % (len(trace), number, status)) self.assertTrue(bool(trace.sms_sms_id_int)) if check_sms: if status == 'sent': if sent_unlink: self.assertSMSIapSent([number], content=content) else: self.assertSMS(partner, number, 'sent', content=content) elif status in state_mapping: sms_state = state_mapping[status] failure_type = recipient_info['failure_type'] if status in ('error', 'cancel', 'bounce') else None self.assertSMS(partner, number, sms_state, failure_type=failure_type, content=content) else: raise NotImplementedError() if link_info: # shortened links are directly included in sms.sms record as well as # in sent sms (not like mails who are post-processed) sms_sent = self._find_sms_sent(partner, number) sms_sms = self._find_sms_sms(partner, number, state_mapping[status]) for (url, is_shortened, add_link_params) in link_info: if url == 'unsubscribe': url = '%s/sms/%d/%s' % (mailing.get_base_url(), mailing.id, trace.sms_code) link_params = {'utm_medium': 'SMS', 'utm_source': mailing.name} if add_link_params: link_params.update(**add_link_params) self.assertLinkShortenedText( sms_sms.body, (url, is_shortened), link_params=link_params, ) self.assertLinkShortenedText( sms_sent['body'], (url, is_shortened), link_params=link_params, ) # ------------------------------------------------------------ # GATEWAY TOOLS # ------------------------------------------------------------ def gateway_sms_click(self, mailing, record): """ Simulate a click on a sent SMS. Usage: giving a partner and/or a number, find an SMS sent to him, find shortened links in its body and call add_click to simulate a click. """ trace = mailing.mailing_trace_ids.filtered(lambda t: t.model == record._name and t.res_id == record.id) sms_sent = self._find_sms_sent(self.env['res.partner'], trace.sms_number) self.assertTrue(bool(sms_sent)) return self.gateway_sms_sent_click(sms_sent) def gateway_sms_sent_click(self, sms_sent): """ When clicking on a link in a SMS we actually don't have any easy information in body, only body. We currently click on all found shortened links. """ for url in re.findall(tools.TEXT_URL_REGEX, sms_sent['body']): if '/r/' in url: # shortened link, like 'http://localhost:8069/r/LBG/s/53' parsed_url = werkzeug.urls.url_parse(url) path_items = parsed_url.path.split('/') code, sms_sms_id = path_items[2], int(path_items[4]) trace_id = self.env['mailing.trace'].sudo().search([('sms_sms_id_int', '=', sms_sms_id)]).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 ) class MassSMSCommon(MassMailCommon, SMSCommon, MassSMSCase): @classmethod def setUpClass(cls): super(MassSMSCommon, cls).setUpClass()
47.555556
7,704
1,817
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mass_mailing_sms.tests.common import MassSMSCommon from odoo.addons.base.tests.test_ir_cron import CronMixinCase from odoo.tests.common import users from unittest.mock import patch class TestMailingRetrySMS(MassSMSCommon, CronMixinCase): @classmethod def setUpClass(cls): super(TestMailingRetrySMS, cls).setUpClass() cls._create_mailing_list() @users('user_marketing') def test_sms_retry_immediate_trigger(self): mailing = self.env['mailing.mailing'].create({ 'name': 'TestMailing', 'subject': 'Test', 'mailing_type': 'sms', 'body_plaintext': 'Coucou hibou', 'mailing_model_id': self.env['ir.model']._get('res.partner').id, 'contact_list_ids': [(4, self.mailing_list_1.id)], }) mailing.action_send_sms() # force the SMS sending to fail to test our retry mechanism def patched_sms_sms_send(sms_records, unlink_failed=False, unlink_sent=True, raise_exception=False): sms_records.write({'state': 'error', 'failure_type':'sms_credit'}) with patch('odoo.addons.sms.models.sms_sms.SmsSms._send', patched_sms_sms_send): self.env.ref('sms.ir_cron_sms_scheduler_action').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.317073
1,817
3,935
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug.urls from odoo import fields, models, _ class SMSComposer(models.TransientModel): _inherit = 'sms.composer' # mass mode with mass sms mass_sms_allow_unsubscribe = fields.Boolean('Include opt-out link', default=True) mailing_id = fields.Many2one('mailing.mailing', string='Mailing') utm_campaign_id = fields.Many2one('utm.campaign', string='Campaign') # ------------------------------------------------------------ # Mass mode specific # ------------------------------------------------------------ def _get_unsubscribe_url(self, res_id, trace_code, number): return werkzeug.urls.url_join( self.get_base_url(), '/sms/%s/%s' % (self.mailing_id.id, trace_code) ) def _prepare_mass_sms_trace_values(self, record, sms_values): trace_code = self.env['mailing.trace']._get_random_code() trace_values = { 'model': self.res_model, 'res_id': record.id, 'trace_type': 'sms', 'mass_mailing_id': self.mailing_id.id, 'sms_number': sms_values['number'], 'sms_code': trace_code, } if sms_values['state'] == 'error': trace_values['failure_type'] = sms_values['failure_type'] trace_values['trace_status'] = 'error' elif sms_values['state'] == 'canceled': trace_values['failure_type'] = sms_values['failure_type'] trace_values['trace_status'] = 'cancel' else: if self.mass_sms_allow_unsubscribe: sms_values['body'] = '%s\n%s' % (sms_values['body'] or '', _('STOP SMS : %s', self._get_unsubscribe_url(record.id, trace_code, sms_values['number']))) return trace_values def _get_optout_record_ids(self, records, recipients_info): """ Fetch opt-out records based on mailing. """ res = super(SMSComposer, self)._get_optout_record_ids(records, recipients_info) if self.mailing_id: optout_res_ids = self.mailing_id._get_opt_out_list_sms() res += optout_res_ids return res def _get_done_record_ids(self, records, recipients_info): """ A/B testing could lead to records having been already mailed. """ res = super(SMSComposer, self)._get_done_record_ids(records, recipients_info) if self.mailing_id: seen_ids, seen_list = self.mailing_id._get_seen_list_sms() res += seen_ids return res def _prepare_body_values(self, records): all_bodies = super(SMSComposer, self)._prepare_body_values(records) if self.mailing_id: tracker_values = self.mailing_id._get_link_tracker_values() for sms_id, body in all_bodies.items(): body = self.env['mail.render.mixin'].sudo()._shorten_links_text(body, tracker_values) all_bodies[sms_id] = body return all_bodies def _prepare_mass_sms_values(self, records): result = super(SMSComposer, self)._prepare_mass_sms_values(records) if self.composition_mode == 'mass' and self.mailing_id: for record in records: sms_values = result[record.id] trace_values = self._prepare_mass_sms_trace_values(record, sms_values) sms_values.update({ 'mailing_id': self.mailing_id.id, 'mailing_trace_ids': [(0, 0, trace_values)], }) return result def _prepare_mass_sms(self, records, sms_record_values): sms_all = super(SMSComposer, self)._prepare_mass_sms(records, sms_record_values) if self.mailing_id: updated_bodies = sms_all._update_body_short_links() for sms in sms_all: sms.body = updated_bodies[sms.id] return sms_all
42.771739
3,935
3,049
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.addons.phone_validation.tools import phone_validation class MassSMSTest(models.TransientModel): _name = 'mailing.sms.test' _description = 'Test SMS Mailing' def _default_numbers(self): return self.env.user.partner_id.phone_sanitized or "" numbers = fields.Text(string='Number(s)', required=True, default=_default_numbers, help='Carriage-return-separated list of phone numbers') mailing_id = fields.Many2one('mailing.mailing', string='Mailing', required=True, ondelete='cascade') def action_send_sms(self): self.ensure_one() numbers = [number.strip() for number in self.numbers.splitlines()] sanitize_res = phone_validation.phone_sanitize_numbers_w_record(numbers, self.env.user) sanitized_numbers = [info['sanitized'] for info in sanitize_res.values() if info['sanitized']] invalid_numbers = [number for number, info in sanitize_res.items() if info['code']] record = self.env[self.mailing_id.mailing_model_real].search([], limit=1) body = self.mailing_id.body_plaintext if record: # Returns a proper error if there is a syntax error with qweb body = self.env['mail.render.mixin']._render_template(body, self.mailing_id.mailing_model_real, record.ids)[record.id] # res_id is used to map the result to the number to log notifications as IAP does not return numbers... # TODO: clean IAP to make it return a clean dict with numbers / use custom keys / rename res_id to external_id sent_sms_list = self.env['sms.api']._send_sms_batch([{ 'res_id': number, 'number': number, 'content': body, } for number in sanitized_numbers]) error_messages = {} if any(sent_sms.get('state') != 'success' for sent_sms in sent_sms_list): error_messages = self.env['sms.api']._get_sms_api_error_messages() notification_messages = [] if invalid_numbers: notification_messages.append(_('The following numbers are not correctly encoded: %s', ', '.join(invalid_numbers))) for sent_sms in sent_sms_list: if sent_sms.get('state') == 'success': notification_messages.append( _('Test SMS successfully sent to %s', sent_sms.get('res_id'))) elif sent_sms.get('state'): notification_messages.append( _('Test SMS could not be sent to %s:<br>%s', sent_sms.get('res_id'), error_messages.get(sent_sms['state'], _("An error occurred."))) ) if notification_messages: self.mailing_id._message_log(body='<ul>%s</ul>' % ''.join( ['<li>%s</li>' % notification_message for notification_message in notification_messages] )) return True
46.19697
3,049
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 MailingContact(models.Model): _name = 'mailing.contact' _inherit = ['mailing.contact', 'mail.thread.phone'] mobile = fields.Char(string='Mobile') def _phone_get_number_fields(self): return ['mobile']
26.142857
366
2,249
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import random import string from odoo import api, fields, models from odoo.osv import expression class MailingTrace(models.Model): """ Improve statistics model to add SMS support. Main attributes of statistics model are used, only some specific data is required. """ _inherit = 'mailing.trace' CODE_SIZE = 3 trace_type = fields.Selection(selection_add=[ ('sms', 'SMS') ], ondelete={'sms': 'set default'}) sms_sms_id = fields.Many2one('sms.sms', string='SMS', index=True, ondelete='set null') sms_sms_id_int = fields.Integer( string='SMS ID (tech)', help='ID of the related sms.sms. This field is an integer field because ' 'the related sms.sms can be deleted separately from its statistics. ' 'However the ID is needed for several action and controllers.', index=True, ) sms_number = fields.Char('Number') sms_code = fields.Char('Code') failure_type = fields.Selection(selection_add=[ ('sms_number_missing', 'Missing Number'), ('sms_number_format', 'Wrong Number Format'), ('sms_credit', 'Insufficient Credit'), ('sms_server', 'Server Error'), ('sms_acc', 'Unregistered Account'), # mass mode specific codes ('sms_blacklist', 'Blacklisted'), ('sms_duplicate', 'Duplicate'), ('sms_optout', 'Opted Out'), ]) @api.model_create_multi def create(self, values_list): for values in values_list: if 'sms_sms_id' in values: values['sms_sms_id_int'] = values['sms_sms_id'] if values.get('trace_type') == 'sms' and not values.get('sms_code'): values['sms_code'] = self._get_random_code() return super(MailingTrace, self).create(values_list) def _get_random_code(self): """ Generate a random code for trace. Uniqueness is not really necessary as it serves as obfuscation when unsubscribing. A valid trio code / mailing_id / number will be requested. """ return ''.join(random.choice(string.ascii_letters + string.digits) for dummy in range(self.CODE_SIZE))
40.890909
2,249
2,859
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 MailingList(models.Model): _inherit = 'mailing.list' contact_count_sms = fields.Integer(compute="_compute_mailing_list_statistics", string="SMS Contacts") def action_view_mailings(self): if self.env.context.get('mailing_sms'): action = self.env["ir.actions.actions"]._for_xml_id('mass_mailing_sms.mailing_mailing_action_sms') action['domain'] = [('id', 'in', self.mailing_ids.ids)] action['context'] = { 'default_mailing_type': 'sms', 'default_contact_list_ids': self.ids, 'mailing_sms': True } return action else: return super(MailingList, self).action_view_mailings() def action_view_contacts_sms(self): action = self.action_view_contacts() action['context'] = dict(action.get('context', {}), search_default_filter_valid_sms_recipient=1) return action def _get_contact_statistics_fields(self): """ See super method docstring for more info. Adds: - contact_count_sms: all valid sms - contact_count_blacklisted: override the dict entry to add SMS blacklist condition """ values = super(MailingList, self)._get_contact_statistics_fields() values.update({ 'contact_count_sms': ''' SUM(CASE WHEN (c.phone_sanitized IS NOT NULL AND COALESCE(r.opt_out,FALSE) = FALSE AND bl_sms.id IS NULL) THEN 1 ELSE 0 END) AS contact_count_sms''', 'contact_count_blacklisted': f''' SUM(CASE WHEN (bl.id IS NOT NULL OR bl_sms.id IS NOT NULL) THEN 1 ELSE 0 END) AS contact_count_blacklisted''' }) return values def _get_contact_statistics_joins(self): return super(MailingList, self)._get_contact_statistics_joins() + ''' LEFT JOIN phone_blacklist bl_sms ON c.phone_sanitized = bl_sms.number and bl_sms.active ''' def _mailing_get_opt_out_list_sms(self, mailing): """ Check subscription on all involved mailing lists. If user is opt_out on one list but not on another, one opted in and the other one opted out, send mailing anyway. :return list: opt-outed record IDs """ subscriptions = self.subscription_ids if self else mailing.contact_list_ids.subscription_ids opt_out_contacts = subscriptions.filtered(lambda sub: sub.opt_out).mapped('contact_id') opt_in_contacts = subscriptions.filtered(lambda sub: not sub.opt_out).mapped('contact_id') return list(set(c.id for c in opt_out_contacts if c not in opt_in_contacts))
43.984615
2,859
1,989
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from odoo import fields, models, tools class SmsSms(models.Model): _inherit = ['sms.sms'] mailing_id = fields.Many2one('mailing.mailing', string='Mass Mailing') mailing_trace_ids = fields.One2many('mailing.trace', 'sms_sms_id', string='Statistics') def _update_body_short_links(self): """ Override to tweak shortened URLs by adding statistics ids, allowing to find customer back once clicked. """ res = dict.fromkeys(self.ids, False) for sms in self: if not sms.mailing_id or not sms.body: res[sms.id] = sms.body continue body = sms.body for url in set(re.findall(tools.TEXT_URL_REGEX, body)): if url.startswith(sms.get_base_url() + '/r/'): body = re.sub(re.escape(url) + r'(?![\w@:%.+&~#=/-])', url + f'/s/{sms.id}', body) res[sms.id] = body return res def _postprocess_iap_sent_sms(self, iap_results, failure_reason=None, unlink_failed=False, unlink_sent=True): all_sms_ids = [item['res_id'] for item in iap_results] if any(sms.mailing_id for sms in self.env['sms.sms'].sudo().browse(all_sms_ids)): for state in self.IAP_TO_SMS_STATE.keys(): sms_ids = [item['res_id'] for item in iap_results if item['state'] == state] traces = self.env['mailing.trace'].sudo().search([ ('sms_sms_id_int', 'in', sms_ids) ]) if traces and state == 'success': traces.set_sent() elif traces: traces.set_failed(failure_type=self.IAP_TO_SMS_STATE[state]) return super(SmsSms, self)._postprocess_iap_sent_sms( iap_results, failure_reason=failure_reason, unlink_failed=unlink_failed, unlink_sent=unlink_sent )
43.23913
1,989
2,653
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 UtmCampaign(models.Model): _inherit = 'utm.campaign' mailing_sms_ids = fields.One2many( 'mailing.mailing', 'campaign_id', domain=[('mailing_type', '=', 'sms')], string='Mass SMS') mailing_sms_count = fields.Integer('Number of Mass SMS', compute="_compute_mailing_sms_count") # A/B Testing ab_testing_sms_winner_selection = fields.Selection([ ('manual', 'Manual'), ('clicks_ratio', 'Highest Click Rate')], string="SMS Winner Selection", default="clicks_ratio") @api.depends('mailing_mail_ids', 'mailing_sms_ids') def _compute_ab_testing_total_pc(self): super()._compute_ab_testing_total_pc() for campaign in self: campaign.ab_testing_total_pc += sum([ mailing.ab_testing_pc for mailing in campaign.mailing_sms_ids.filtered('ab_testing_enabled') ]) @api.depends('mailing_sms_ids') def _compute_mailing_sms_count(self): for campaign in self: campaign.mailing_sms_count = len(campaign.mailing_sms_ids) def action_create_mass_sms(self): action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.action_create_mass_mailings_from_campaign") action['context'] = { 'default_campaign_id': self.id, 'default_mailing_type': 'sms', 'search_default_assigned_to_me': 1, 'search_default_campaign_id': self.id, 'default_user_id': self.env.user.id, } return action def action_redirect_to_mailing_sms(self): action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing_sms.mailing_mailing_action_sms") action['context'] = { 'default_campaign_id': self.id, 'default_mailing_type': 'sms', 'search_default_assigned_to_me': 1, 'search_default_campaign_id': self.id, 'default_user_id': self.env.user.id, } action['domain'] = [('mailing_type', '=', 'sms')] return action @api.model def _cron_process_mass_mailing_ab_testing(self): ab_testing_campaign = super()._cron_process_mass_mailing_ab_testing() for campaign in ab_testing_campaign: ab_testing_mailings = campaign.mailing_sms_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
40.815385
2,653
3,577
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from odoo import api, fields, models, modules, _ class Users(models.Model): _name = 'res.users' _inherit = ['res.users'] @api.model def systray_get_activities(self): """ Split mass_mailing and mass_mailing_sms activities in systray by removing the single mailing.mailing activity represented and doing a new query to split them by mailing_type. """ activities = super(Users, self).systray_get_activities() for activity in activities: if activity.get('model') == 'mailing.mailing': activities.remove(activity) query = """SELECT m.mailing_type, count(*), act.res_model as model, act.res_id, CASE WHEN %(today)s::date - act.date_deadline::date = 0 Then 'today' WHEN %(today)s::date - act.date_deadline::date > 0 Then 'overdue' WHEN %(today)s::date - act.date_deadline::date < 0 Then 'planned' END AS states FROM mail_activity AS act JOIN mailing_mailing AS m ON act.res_id = m.id WHERE act.res_model = 'mailing.mailing' AND act.user_id = %(user_id)s GROUP BY m.mailing_type, states, act.res_model, act.res_id; """ self.env.cr.execute(query, { 'today': fields.Date.context_today(self), 'user_id': self.env.uid, }) activity_data = self.env.cr.dictfetchall() user_activities = {} for act in activity_data: if not user_activities.get(act['mailing_type']): if act['mailing_type'] == 'sms': module = 'mass_mailing_sms' name = _('SMS Marketing') else: module = 'mass_mailing' name = _('Email Marketing') icon = module and modules.module.get_module_icon(module) res_ids = set() user_activities[act['mailing_type']] = { 'name': name, 'model': 'mailing.mailing', 'type': 'activity', 'icon': icon, 'total_count': 0, 'today_count': 0, 'overdue_count': 0, 'planned_count': 0, 'res_ids': res_ids, } user_activities[act['mailing_type']]['res_ids'].add(act['res_id']) user_activities[act['mailing_type']]['%s_count' % act['states']] += act['count'] if act['states'] in ('today', 'overdue'): user_activities[act['mailing_type']]['total_count'] += act['count'] for mailing_type in user_activities.keys(): user_activities[mailing_type].update({ 'actions': [{'icon': 'fa-clock-o', 'name': 'Summary',}], 'domain': json.dumps([['activity_ids.res_id', 'in', list(user_activities[mailing_type]['res_ids'])]]) }) activities.extend(list(user_activities.values())) break return activities
49.680556
3,577
16,926
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.osv import expression _logger = logging.getLogger(__name__) class Mailing(models.Model): _inherit = 'mailing.mailing' @api.model def default_get(self, fields): res = super(Mailing, self).default_get(fields) if fields is not None and 'keep_archives' in fields and res.get('mailing_type') == 'sms': res['keep_archives'] = True return res # mailing options mailing_type = fields.Selection(selection_add=[ ('sms', 'SMS') ], ondelete={'sms': 'set default'}) # 'sms_subject' added to override 'subject' field (string attribute should be labelled "Title" when mailing_type == 'sms'). # 'sms_subject' should have the same helper as 'subject' field when 'mass_mailing_sms' installed. # otherwise 'sms_subject' will get the old helper from 'mass_mailing' module. # overriding 'subject' field helper in this model is not working, since the helper will keep the new value # even when 'mass_mailing_sms' removed (see 'mailing_mailing_view_form_sms' for more details). sms_subject = fields.Char('Title', help='For an email, the subject your recipients will see in their inbox.\n' 'For an SMS, the internal title of the message.', related='subject', translate=False, readonly=False) # sms options body_plaintext = fields.Text('SMS Body', compute='_compute_body_plaintext', store=True, readonly=False) sms_template_id = fields.Many2one('sms.template', string='SMS Template', ondelete='set null') sms_has_insufficient_credit = fields.Boolean( 'Insufficient IAP credits', compute='_compute_sms_has_iap_failure', help='UX Field to propose to buy IAP credits') sms_has_unregistered_account = fields.Boolean( 'Unregistered IAP account', compute='_compute_sms_has_iap_failure', help='UX Field to propose to Register the SMS IAP account') sms_force_send = fields.Boolean( 'Send Directly', help='Immediately send the SMS Mailing instead of queuing up. Use at your own risk.') # opt_out_link sms_allow_unsubscribe = fields.Boolean('Include opt-out link', default=False) # A/B Testing ab_testing_sms_winner_selection = fields.Selection(related="campaign_id.ab_testing_sms_winner_selection", default="clicks_ratio", readonly=False, copy=True) @api.depends('mailing_type') def _compute_medium_id(self): super(Mailing, self)._compute_medium_id() for mailing in self: if mailing.mailing_type == 'sms' and (not mailing.medium_id or mailing.medium_id == self.env.ref('utm.utm_medium_email')): mailing.medium_id = self.env.ref('mass_mailing_sms.utm_medium_sms').id elif mailing.mailing_type == 'mail' and (not mailing.medium_id or mailing.medium_id == self.env.ref('mass_mailing_sms.utm_medium_sms')): mailing.medium_id = self.env.ref('utm.utm_medium_email').id @api.depends('sms_template_id', 'mailing_type') def _compute_body_plaintext(self): for mailing in self: if mailing.mailing_type == 'sms' and mailing.sms_template_id: mailing.body_plaintext = mailing.sms_template_id.body @api.depends('mailing_trace_ids.failure_type') def _compute_sms_has_iap_failure(self): failures = ['sms_acc', 'sms_credit'] if not self.ids: self.sms_has_insufficient_credit = self.sms_has_unregistered_account = False else: traces = self.env['mailing.trace'].sudo().read_group([ ('mass_mailing_id', 'in', self.ids), ('trace_type', '=', 'sms'), ('failure_type', 'in', failures) ], ['mass_mailing_id', 'failure_type'], ['mass_mailing_id', 'failure_type'], lazy=False) trace_dict = dict.fromkeys(self.ids, {key: False for key in failures}) for t in traces: trace_dict[t['mass_mailing_id'][0]][t['failure_type']] = t['__count'] and True or False for mail in self: mail.sms_has_insufficient_credit = trace_dict[mail.id]['sms_credit'] mail.sms_has_unregistered_account = trace_dict[mail.id]['sms_acc'] # -------------------------------------------------- # ORM OVERRIDES # -------------------------------------------------- @api.model def create(self, values): # Get subject from "sms_subject" field when SMS installed (used to build the name of record in the super 'create' method) if values.get('mailing_type') == 'sms' and values.get('sms_subject'): values['subject'] = values['sms_subject'] return super(Mailing, self).create(values) # -------------------------------------------------- # BUSINESS / VIEWS ACTIONS # -------------------------------------------------- def action_retry_failed(self): mass_sms = self.filtered(lambda m: m.mailing_type == 'sms') if mass_sms: mass_sms.action_retry_failed_sms() return super(Mailing, self - mass_sms).action_retry_failed() def action_retry_failed_sms(self): failed_sms = self.env['sms.sms'].sudo().search([ ('mailing_id', 'in', self.ids), ('state', '=', 'error') ]) failed_sms.mapped('mailing_trace_ids').unlink() failed_sms.unlink() self.action_put_in_queue() def action_test(self): if self.mailing_type == 'sms': ctx = dict(self.env.context, default_mailing_id=self.id) return { 'name': _('Test SMS marketing'), 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'mailing.sms.test', 'target': 'new', 'context': ctx, } return super(Mailing, self).action_test() def _action_view_traces_filtered(self, view_filter): action = super(Mailing, self)._action_view_traces_filtered(view_filter) if self.mailing_type == 'sms': action['views'] = [(self.env.ref('mass_mailing_sms.mailing_trace_view_tree_sms').id, 'tree'), (self.env.ref('mass_mailing_sms.mailing_trace_view_form_sms').id, 'form')] return action def action_buy_sms_credits(self): url = self.env['iap.account'].get_credits_url(service_name='sms') return { 'type': 'ir.actions.act_url', 'url': url, } # -------------------------------------------------- # SMS SEND # -------------------------------------------------- def _get_opt_out_list_sms(self): """ Give list of opt-outed records, depending on specific model-based computation if available. :return list: opt-outed record IDs """ 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_sms'): opt_out = self.env[self.mailing_model_name]._mailing_get_opt_out_list_sms(self) _logger.info("Mass SMS %s targets %s: optout: %s contacts", self, target._name, len(opt_out)) else: _logger.info("Mass SMS %s targets %s: no opt out list available", self, target._name) return opt_out def _get_seen_list_sms(self): """Returns a set of emails already targeted by current mailing/campaign (no duplicates)""" self.ensure_one() target = self.env[self.mailing_model_real] partner_fields = [] if issubclass(type(target), self.pool['mail.thread.phone']): phone_fields = ['phone_sanitized'] elif issubclass(type(target), self.pool['mail.thread']): phone_fields = [ fname for fname in target._sms_get_number_fields() if fname in target._fields and target._fields[fname].store ] partner_fields = target._sms_get_partner_fields() else: phone_fields = [] if 'mobile' in target._fields and target._fields['mobile'].store: phone_fields.append('mobile') if 'phone' in target._fields and target._fields['phone'].store: phone_fields.append('phone') partner_field = next( (fname for fname in partner_fields if target._fields[fname].store and target._fields[fname].type == 'many2one'), False ) if not phone_fields and not partner_field: raise UserError(_("Unsupported %s for mass SMS", self.mailing_model_id.name)) query = """ SELECT %(select_query)s FROM mailing_trace trace JOIN %(target_table)s target ON (trace.res_id = target.id) %(join_add_query)s WHERE (%(where_query)s) AND trace.mass_mailing_id = %%(mailing_id)s AND trace.model = %%(target_model)s """ if phone_fields: # phone fields are checked on target mailed model select_query = 'target.id, ' + ', '.join('target.%s' % fname for fname in phone_fields) where_query = ' OR '.join('target.%s IS NOT NULL' % fname for fname in phone_fields) join_add_query = '' else: # phone fields are checked on res.partner model partner_phone_fields = ['mobile', 'phone'] select_query = 'target.id, ' + ', '.join('partner.%s' % fname for fname in partner_phone_fields) where_query = ' OR '.join('partner.%s IS NOT NULL' % fname for fname in partner_phone_fields) join_add_query = 'JOIN res_partner partner ON (target.%s = partner.id)' % partner_field query = query % { 'select_query': select_query, 'where_query': where_query, 'target_table': target._table, 'join_add_query': join_add_query, } params = {'mailing_id': self.id, 'target_model': self.mailing_model_real} self._cr.execute(query, params) query_res = self._cr.fetchall() seen_list = set(number for item in query_res for number in item[1:] if number) seen_ids = set(item[0] for item in query_res) _logger.info("Mass SMS %s targets %s: already reached %s SMS", self, target._name, len(seen_list)) return list(seen_ids), list(seen_list) def _send_sms_get_composer_values(self, res_ids): return { # content 'body': self.body_plaintext, 'template_id': self.sms_template_id.id, 'res_model': self.mailing_model_real, 'res_ids': repr(res_ids), # options 'composition_mode': 'mass', 'mailing_id': self.id, 'mass_keep_log': self.keep_archives, 'mass_force_send': self.sms_force_send, 'mass_sms_allow_unsubscribe': self.sms_allow_unsubscribe, } def action_send_mail(self, res_ids=None): mass_sms = self.filtered(lambda m: m.mailing_type == 'sms') if mass_sms: mass_sms.action_send_sms(res_ids=res_ids) return super(Mailing, self - mass_sms).action_send_mail(res_ids=res_ids) def action_send_sms(self, res_ids=None): for mailing in self: if not res_ids: res_ids = mailing._get_remaining_recipients() if res_ids: composer = self.env['sms.composer'].with_context(active_id=False).create(mailing._send_sms_get_composer_values(res_ids)) composer._action_send_sms() mailing.write({ 'state': 'done', 'sent_date': fields.Datetime.now(), 'kpi_mail_required': not mailing.sent_date, }) return True # ------------------------------------------------------ # STATISTICS # ------------------------------------------------------ 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. """ values = super(Mailing, self)._prepare_statistics_email_values() if self.mailing_type == 'sms': mailing_type = self._get_pretty_mailing_type() values['title'] = _('24H Stats of %(mailing_type)s "%(mailing_name)s"', mailing_type=mailing_type, mailing_name=self.subject ) values['kpi_data'][0] = { 'kpi_fullname': _('Report for %(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.clicks_ratio}%', 'col_subtitle': _('CLICKED (%i)', self.clicked), }, 'kpi_col3': { 'value': f'{self.bounced_ratio}%', 'col_subtitle': _('BOUNCED (%i)', self.bounced), }, 'kpi_action': None, 'kpi_name': self.mailing_type, } return values def _get_pretty_mailing_type(self): if self.mailing_type == 'sms': return _('SMS Text Message') return super(Mailing, self)._get_pretty_mailing_type() # -------------------------------------------------- # TOOLS # -------------------------------------------------- def _get_default_mailing_domain(self): mailing_domain = super(Mailing, self)._get_default_mailing_domain() if self.mailing_type == 'sms' and 'phone_sanitized_blacklisted' in self.env[self.mailing_model_name]._fields: mailing_domain = expression.AND([mailing_domain, [('phone_sanitized_blacklisted', '=', False)]]) return mailing_domain def convert_links(self): sms_mailings = self.filtered(lambda m: m.mailing_type == 'sms') res = {} for mailing in sms_mailings: tracker_values = mailing._get_link_tracker_values() body = mailing._shorten_links_text(mailing.body_plaintext, tracker_values) res[mailing.id] = body res.update(super(Mailing, self - sms_mailings).convert_links()) return res # ------------------------------------------------------ # A/B Test Override # ------------------------------------------------------ def _get_ab_testing_description_modifying_fields(self): fields_list = super()._get_ab_testing_description_modifying_fields() return fields_list + ['ab_testing_sms_winner_selection'] def _get_ab_testing_description_values(self): values = super()._get_ab_testing_description_values() if self.mailing_type == 'sms': values.update({ 'ab_testing_winner_selection': self.ab_testing_sms_winner_selection, }) return values def _get_ab_testing_winner_selection(self): result = super()._get_ab_testing_winner_selection() if self.mailing_type == 'sms': ab_testing_winner_selection_description = dict( self._fields.get('ab_testing_sms_winner_selection').related_field.selection ).get(self.ab_testing_sms_winner_selection) result.update({ 'value': self.campaign_id.ab_testing_sms_winner_selection, 'description': ab_testing_winner_selection_description }) return result def _get_ab_testing_siblings_mailings(self): mailings = super()._get_ab_testing_siblings_mailings() if self.mailing_type == 'sms': mailings = self.campaign_id.mailing_sms_ids.filtered('ab_testing_enabled') return mailings def _get_default_ab_testing_campaign_values(self, values=None): campaign_values = super()._get_default_ab_testing_campaign_values(values) values = values or dict() if self.mailing_type == 'sms': sms_subject = values.get('sms_subject') or self.sms_subject if sms_subject: campaign_values['name'] = _("A/B Test: %s", sms_subject) campaign_values['ab_testing_sms_winner_selection'] = self.ab_testing_sms_winner_selection return campaign_values
45.869919
16,926
4,879
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.addons.phone_validation.tools import phone_validation from odoo.http import request class MailingSMSController(http.Controller): def _check_trace(self, mailing_id, trace_code): try: mailing = request.env['mailing.mailing'].sudo().search([('id', '=', mailing_id)]) except: mailing = False if not mailing: return {'error': 'mailing_error'} trace = request.env['mailing.trace'].sudo().search([ ('trace_type', '=', 'sms'), ('sms_code', '=', trace_code), ('mass_mailing_id', '=', mailing.id) ]) if not trace: return {'error': 'trace_error'} return {'trace': trace} @http.route(['/sms/<int:mailing_id>/<string:trace_code>'], type='http', website=True, auth='public') def blacklist_page(self, mailing_id, trace_code, **post): check_res = self._check_trace(mailing_id, trace_code) if not check_res.get('trace'): return request.redirect('/web') return request.render('mass_mailing_sms.blacklist_main', { 'mailing_id': mailing_id, 'trace_code': trace_code, }) @http.route(['/sms/<int:mailing_id>/unsubscribe/<string:trace_code>'], type='http', website=True, auth='public') def blacklist_number(self, mailing_id, trace_code, **post): check_res = self._check_trace(mailing_id, trace_code) if not check_res.get('trace'): return request.redirect('/web') country_code = request.session.get('geoip', False) and request.session.geoip.get('country_code', False) if request.session.get('geoip') else None # parse and validate number sms_number = post.get('sms_number', '').strip(' ') sanitize_res = phone_validation.phone_sanitize_numbers([sms_number], country_code, None)[sms_number] tocheck_number = sanitize_res['sanitized'] or sms_number trace = check_res['trace'].filtered(lambda r: r.sms_number == tocheck_number)[:1] mailing_list_ids = trace.mass_mailing_id.contact_list_ids # compute opt-out / blacklist information lists_optout = request.env['mailing.list'].sudo() lists_optin = request.env['mailing.list'].sudo() unsubscribe_error = False if tocheck_number and trace: if mailing_list_ids: subscriptions = request.env['mailing.contact.subscription'].sudo().search([ ('list_id', 'in', mailing_list_ids.ids), ('contact_id.phone_sanitized', '=', tocheck_number), ]) subscriptions.write({'opt_out': True}) lists_optout = subscriptions.mapped('list_id') else: blacklist_rec = request.env['phone.blacklist'].sudo().add(tocheck_number) blacklist_rec._message_log( body=_('Blacklist through SMS Marketing unsubscribe (mailing ID: %s - model: %s)') % (trace.mass_mailing_id.id, trace.mass_mailing_id.mailing_model_id.display_name)) lists_optin = request.env['mailing.contact.subscription'].sudo().search([ ('contact_id.phone_sanitized', '=', tocheck_number), ('list_id', 'not in', mailing_list_ids.ids), ('opt_out', '=', False), ]).mapped('list_id') elif tocheck_number: unsubscribe_error = _('Number %s not found', tocheck_number) else: unsubscribe_error = sanitize_res['msg'] return request.render('mass_mailing_sms.blacklist_number', { 'mailing_id': mailing_id, 'trace_code': trace_code, 'sms_number': sms_number, 'lists_optin': lists_optin, 'lists_optout': lists_optout, 'unsubscribe_error': unsubscribe_error, }) @http.route('/r/<string:code>/s/<int:sms_sms_id>', type='http', auth="public") def sms_short_link_redirect(self, code, sms_sms_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) if sms_sms_id: trace_id = request.env['mailing.trace'].sudo().search([('sms_sms_id_int', '=', int(sms_sms_id))]).id else: trace_id = False request.env['link.tracker.click'].sudo().add_click( code, ip=request.httprequest.remote_addr, country_code=country_code, mailing_trace_id=trace_id ) return request.redirect(request.env['link.tracker'].get_url_from_code(code), code=301, local=False)
47.368932
4,879
1,391
py
PYTHON
15.0
{ 'name': 'Link Tracker', 'category': 'Website/Website', 'summary': 'Generate trackable & short URLs', 'description': """ Generate short links with analytics trackers (UTM) to share your pages through marketing campaigns. Those trackers can be used in Google Analytics to track clicks and visitors, or in Odoo reports to analyze the efficiency of those campaigns in terms of lead generation, related revenues (sales orders), recruitment, etc. """, 'version': '1.0', 'depends': ['website', 'link_tracker'], 'data': [ 'views/link_tracker_views.xml', 'views/website_links_template.xml', 'views/website_links_graphs.xml', 'security/ir.model.access.csv', ], 'auto_install': True, 'assets': { 'web.assets_frontend': [ 'website_links/static/src/js/website_links.js', 'website_links/static/src/js/website_links_code_editor.js', 'website_links/static/src/js/website_links_charts.js', 'website_links/static/src/css/website_links.css', ], 'web.assets_tests': [ 'website_links/static/tests/**/*', ], 'website.assets_editor': [ 'website_links/static/src/js/website_links_menu.js', ], 'web.assets_qweb': [ 'website_links/static/src/xml/*.xml', ], }, 'license': 'LGPL-3', }
38.638889
1,391
911
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch import odoo.tests @odoo.tests.common.tagged('post_install', '-at_install') class TestUi(odoo.tests.HttpCase): def setUp(self): super(TestUi, self).setUp() def _get_title_from_url(addr, **kw): return 'Contact Us | My Website' patcher = patch('odoo.addons.link_tracker.models.link_tracker.LinkTracker._get_title_from_url', wraps=_get_title_from_url) patcher.start() self.addCleanup(patcher.stop) def test_01_test_ui(self): self.env['link.tracker'].search_or_create({ 'campaign_id': 2, 'medium_id': 2, 'source_id': 2, 'url': self.env["ir.config_parameter"].sudo().get_param("web.base.url") + '/contactus', }) self.start_tour("/", 'website_links_tour', login="admin")
32.535714
911
677
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ from werkzeug import urls class LinkTracker(models.Model): _inherit = ['link.tracker'] def action_visit_page_statistics(self): return { 'name': _("Visit Webpage Statistics"), 'type': 'ir.actions.act_url', 'url': '%s+' % (self.short_url), 'target': 'new', } def _compute_short_url_host(self): for tracker in self: base_url = self.env['website'].get_current_website().get_base_url() tracker.short_url_host = urls.url_join(base_url, '/r/')
29.434783
677
1,760
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 class WebsiteUrl(http.Controller): @http.route('/website_links/new', type='json', auth='user', methods=['POST']) def create_shorten_url(self, **post): if 'url' not in post or post['url'] == '': return {'error': 'empty_url'} return request.env['link.tracker'].search_or_create(post).read() @http.route('/r', type='http', auth='user', website=True) def shorten_url(self, **post): return request.render("website_links.page_shorten_url", post) @http.route('/website_links/add_code', type='json', auth='user') def add_code(self, **post): link_id = request.env['link.tracker.code'].search([('code', '=', post['init_code'])], limit=1).link_id.id new_code = request.env['link.tracker.code'].search_count([('code', '=', post['new_code']), ('link_id', '=', link_id)]) if new_code > 0: return new_code.read() else: return request.env['link.tracker.code'].create({'code': post['new_code'], 'link_id': link_id})[0].read() @http.route('/website_links/recent_links', type='json', auth='user') def recent_links(self, **post): return request.env['link.tracker'].recent_links(post['filter'], post['limit']) @http.route('/r/<string:code>+', type='http', auth="user", website=True) def statistics_shorten_url(self, code, **post): code = request.env['link.tracker.code'].search([('code', '=', code)], limit=1) if code: return request.render("website_links.graphs", code.link_id.read()[0]) else: return request.redirect('/', code=301)
45.128205
1,760
1,076
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Outlook Calendar', 'version': '1.0', 'category': 'Productivity', 'description': "", 'depends': ['microsoft_account', 'calendar'], 'data': [ 'data/microsoft_calendar_data.xml', 'security/ir.model.access.csv', 'wizard/reset_account_views.xml', 'views/res_config_settings_views.xml', 'views/res_users_views.xml', 'views/microsoft_calendar_views.xml', ], 'demo': [], 'installable': True, 'auto_install': False, 'post_init_hook': 'init_initiating_microsoft_uuid', 'assets': { 'web.assets_backend': [ 'microsoft_calendar/static/src/js/microsoft_calendar_popover.js', 'microsoft_calendar/static/src/js/microsoft_calendar.js', 'microsoft_calendar/static/src/scss/microsoft_calendar.scss', ], 'web.assets_qweb': [ 'microsoft_calendar/static/src/xml/*.xml', ], }, 'license': 'LGPL-3', }
32.606061
1,076
17,656
py
PYTHON
15.0
import json import requests from unittest.mock import patch, call, MagicMock from odoo import fields from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_account.models.microsoft_service import MicrosoftService from odoo.tests import TransactionCase DEFAULT_TIMEOUT = 20 class TestMicrosoftService(TransactionCase): def _do_request_result(self, data): """ _do_request returns a tuple (status, data, time) but only the data part is used """ return (None, data, None) def setUp(self): super(TestMicrosoftService, self).setUp() self.service = MicrosoftCalendarService(self.env["microsoft.service"]) self.fake_token = "MY_TOKEN" self.fake_sync_token = "MY_SYNC_TOKEN" self.fake_next_sync_token = "MY_NEXT_SYNC_TOKEN" self.fake_next_sync_token_url = f"https://graph.microsoft.com/v1.0/me/calendarView/delta?$deltatoken={self.fake_next_sync_token}" self.header_prefer = 'outlook.body-content-type="html", odata.maxpagesize=50' self.header = {'Content-type': 'application/json', 'Authorization': 'Bearer %s' % self.fake_token} self.call_with_sync_token = call( "/v1.0/me/calendarView/delta", {"$deltatoken": self.fake_sync_token}, {**self.header, 'Prefer': self.header_prefer}, method="GET", timeout=DEFAULT_TIMEOUT, ) self.call_without_sync_token = call( "/v1.0/me/calendarView/delta", { 'startDateTime': fields.Datetime.subtract(fields.Datetime.now(), years=2).strftime("%Y-%m-%dT00:00:00Z"), 'endDateTime': fields.Datetime.add(fields.Datetime.now(), years=2).strftime("%Y-%m-%dT00:00:00Z"), }, {**self.header, 'Prefer': self.header_prefer}, method="GET", timeout=DEFAULT_TIMEOUT, ) def test_get_events_delta_without_token(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service._get_events_delta() @patch.object(MicrosoftService, "_do_request") def test_get_events_unexpected_exception(self, mock_do_request): """ When an unexpected exception is raised, just propagate it. """ mock_do_request.side_effect = Exception() with self.assertRaises(Exception): self.service._get_events_delta(token=self.fake_token, timeout=DEFAULT_TIMEOUT) @patch.object(MicrosoftService, "_do_request") def test_get_events_delta_token_error(self, mock_do_request): """ When the provided sync token is invalid, an exception should be raised and then a full sync should be done. """ mock_do_request.side_effect = [ requests.HTTPError(response=MagicMock(status_code=410, content="fullSyncRequired")), self._do_request_result({"value": []}), ] events, next_token = self.service._get_events_delta( token=self.fake_token, sync_token=self.fake_sync_token, timeout=DEFAULT_TIMEOUT ) self.assertEqual(next_token, None) self.assertFalse(events) mock_do_request.assert_has_calls([self.call_with_sync_token, self.call_without_sync_token]) @patch.object(MicrosoftService, "_do_request") def test_get_events_delta_without_sync_token(self, mock_do_request): """ when no sync token is provided, a full sync should be done """ # returns empty data without any next sync token mock_do_request.return_value = self._do_request_result({"value": []}) events, next_token = self.service._get_events_delta(token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(next_token, None) self.assertFalse(events) mock_do_request.assert_has_calls([self.call_without_sync_token]) @patch.object(MicrosoftService, "_do_request") def test_get_events_delta_with_sync_token(self, mock_do_request): """ when a sync token is provided, we should retrieve the sync token to use for the next sync. """ # returns empty data with a next sync token mock_do_request.return_value = self._do_request_result({ "value": [], "@odata.deltaLink": self.fake_next_sync_token_url }) events, next_token = self.service._get_events_delta( token=self.fake_token, sync_token=self.fake_sync_token, timeout=DEFAULT_TIMEOUT ) self.assertEqual(next_token, "MY_NEXT_SYNC_TOKEN") self.assertFalse(events) mock_do_request.assert_has_calls([self.call_with_sync_token]) @patch.object(MicrosoftService, "_do_request") def test_get_events_one_page(self, mock_do_request): """ When all events are on one page, just get them. """ mock_do_request.return_value = self._do_request_result({ "value": [ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "singleInstance", "subject": "ev2"}, {"id": 3, "type": "singleInstance", "subject": "ev3"}, ], }) events, _ = self.service._get_events_delta(token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(events, MicrosoftEvent([ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "singleInstance", "subject": "ev2"}, {"id": 3, "type": "singleInstance", "subject": "ev3"}, ])) mock_do_request.assert_has_calls([self.call_without_sync_token]) @patch.object(MicrosoftService, "_do_request") def test_get_events_loop_over_pages(self, mock_do_request): """ Loop over pages to retrieve all the events. """ mock_do_request.side_effect = [ self._do_request_result({ "value": [{"id": 1, "type": "singleInstance", "subject": "ev1"}], "@odata.nextLink": "link_1" }), self._do_request_result({ "value": [{"id": 2, "type": "singleInstance", "subject": "ev2"}], "@odata.nextLink": "link_2" }), self._do_request_result({ "value": [{"id": 3, "type": "singleInstance", "subject": "ev3"}], }), ] events, _ = self.service._get_events_delta(token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(events, MicrosoftEvent([ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "singleInstance", "subject": "ev2"}, {"id": 3, "type": "singleInstance", "subject": "ev3"}, ])) mock_do_request.assert_has_calls([ self.call_without_sync_token, call( "link_1", {}, {**self.header, 'Prefer': self.header_prefer}, preuri='', method="GET", timeout=DEFAULT_TIMEOUT ), call( "link_2", {}, {**self.header, 'Prefer': self.header_prefer}, preuri='', method="GET", timeout=DEFAULT_TIMEOUT ), ]) @patch.object(MicrosoftService, "_do_request") def test_get_events_filter_out_occurrences(self, mock_do_request): """ When all events are on one page, just get them. """ mock_do_request.return_value = self._do_request_result({ "value": [ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "occurrence", "subject": "ev2"}, {"id": 3, "type": "seriesMaster", "subject": "ev3"}, ], }) events, _ = self.service._get_events_delta(token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(events, MicrosoftEvent([ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 3, "type": "seriesMaster", "subject": "ev3"}, ])) mock_do_request.assert_has_calls([self.call_without_sync_token]) def test_get_occurrence_details_token_error(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service._get_occurrence_details(1) @patch.object(MicrosoftService, "_do_request") def test_get_occurrence_details(self, mock_do_request): mock_do_request.return_value = self._do_request_result({ "value": [ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "occurrence", "subject": "ev2"}, {"id": 3, "type": "seriesMaster", "subject": "ev3"}, ], }) events = self.service._get_occurrence_details(123, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(events, MicrosoftEvent([ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "occurrence", "subject": "ev2"}, {"id": 3, "type": "seriesMaster", "subject": "ev3"}, ])) mock_do_request.assert_called_with( "/v1.0/me/events/123/instances", { 'startDateTime': fields.Datetime.subtract(fields.Datetime.now(), years=2).strftime("%Y-%m-%dT00:00:00Z"), 'endDateTime': fields.Datetime.add(fields.Datetime.now(), years=2).strftime("%Y-%m-%dT00:00:00Z"), }, {**self.header, 'Prefer': self.header_prefer}, method='GET', timeout=DEFAULT_TIMEOUT, ) def test_get_events_token_error(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service.get_events() @patch.object(MicrosoftService, "_do_request") def test_get_events_no_serie_master(self, mock_do_request): """ When there is no serie master, just retrieve the list of events. """ mock_do_request.return_value = self._do_request_result({ "value": [ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "singleInstance", "subject": "ev2"}, {"id": 3, "type": "singleInstance", "subject": "ev3"}, ], }) events, _ = self.service.get_events(token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(events, MicrosoftEvent([ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "singleInstance", "subject": "ev2"}, {"id": 3, "type": "singleInstance", "subject": "ev3"}, ])) @patch.object(MicrosoftService, "_do_request") def test_get_events_with_one_serie_master(self, mock_do_request): """ When there is a serie master, retrieve the list of events and event occurrences linked to the serie master """ mock_do_request.side_effect = [ self._do_request_result({ "value": [ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "seriesMaster", "subject": "ev2"}, ], }), self._do_request_result({ "value": [ {"id": 3, "type": "occurrence", "subject": "ev3"}, ], }), ] events, _ = self.service.get_events(token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(events, MicrosoftEvent([ {"id": 1, "type": "singleInstance", "subject": "ev1"}, {"id": 2, "type": "seriesMaster", "subject": "ev2"}, {"id": 3, "type": "occurrence", "subject": "ev3"}, ])) def test_insert_token_error(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service.insert({}) @patch.object(MicrosoftService, "_do_request") def test_insert(self, mock_do_request): mock_do_request.return_value = self._do_request_result({'id': 1, 'iCalUId': 2}) instance_id, event_id = self.service.insert({"subject": "ev1"}, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertEqual(instance_id, 1) self.assertEqual(event_id, 2) mock_do_request.assert_called_with( "/v1.0/me/calendar/events", json.dumps({"subject": "ev1"}), self.header, method="POST", timeout=DEFAULT_TIMEOUT ) def test_patch_token_error(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service.patch(123, {}) @patch.object(MicrosoftService, "_do_request") def test_patch_returns_false_if_event_does_not_exist(self, mock_do_request): event_id = 123 values = {"subject": "ev2"} mock_do_request.return_value = (404, "", None) res = self.service.patch(event_id, values, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertFalse(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}", json.dumps(values), self.header, method="PATCH", timeout=DEFAULT_TIMEOUT ) @patch.object(MicrosoftService, "_do_request") def test_patch_an_existing_event(self, mock_do_request): event_id = 123 values = {"subject": "ev2"} mock_do_request.return_value = (200, "", None) res = self.service.patch(event_id, values, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertTrue(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}", json.dumps(values), self.header, method="PATCH", timeout=DEFAULT_TIMEOUT ) def test_delete_token_error(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service.delete(123) @patch.object(MicrosoftService, "_do_request") def test_delete_returns_false_if_event_does_not_exist(self, mock_do_request): event_id = 123 mock_do_request.return_value = (404, "", None) res = self.service.delete(event_id, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertFalse(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}", {}, headers={'Authorization': 'Bearer %s' % self.fake_token}, method="DELETE", timeout=DEFAULT_TIMEOUT ) @patch.object(MicrosoftService, "_do_request") def test_delete_an_already_cancelled_event(self, mock_do_request): """ When an event has already been cancelled, Outlook may return a status code equals to 403 or 410. In this case, the delete method should return True. """ event_id = 123 for status in (403, 410): mock_do_request.return_value = (status, "", None) res = self.service.delete(event_id, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertTrue(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}", {}, headers={'Authorization': 'Bearer %s' % self.fake_token}, method="DELETE", timeout=DEFAULT_TIMEOUT ) @patch.object(MicrosoftService, "_do_request") def test_delete_an_existing_event(self, mock_do_request): event_id = 123 mock_do_request.return_value = (200, "", None) res = self.service.delete(event_id, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertTrue(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}", {}, headers={'Authorization': 'Bearer %s' % self.fake_token}, method="DELETE", timeout=DEFAULT_TIMEOUT ) def test_answer_token_error(self): """ if no token is provided, an exception is raised """ with self.assertRaises(AttributeError): self.service.answer(123, 'ok', {}) @patch.object(MicrosoftService, "_do_request") def test_answer_returns_false_if_event_does_not_exist(self, mock_do_request): event_id = 123 answer = "accept" values = {"a": 1, "b": 2} mock_do_request.return_value = (404, "", None) res = self.service.answer(event_id, answer, values, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertFalse(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}/{answer}", json.dumps(values), self.header, method="POST", timeout=DEFAULT_TIMEOUT ) @patch.object(MicrosoftService, "_do_request") def test_answer_to_an_existing_event(self, mock_do_request): event_id = 123 answer = "decline" values = {"a": 1, "b": 2} mock_do_request.return_value = (200, "", None) res = self.service.answer(event_id, answer, values, token=self.fake_token, timeout=DEFAULT_TIMEOUT) self.assertTrue(res) mock_do_request.assert_called_with( f"/v1.0/me/calendar/events/{event_id}/{answer}", json.dumps(values), self.header, method="POST", timeout=DEFAULT_TIMEOUT )
40.218679
17,656
9,806
py
PYTHON
15.0
from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_calendar.tests.common import TestCommon, patch_api class TestMicrosoftEvent(TestCommon): @patch_api def setUp(self): super().setUp() self.create_events_for_tests() def test_already_mapped_events(self): # arrange event_id = self.simple_event.ms_organizer_event_id event_uid = self.simple_event.ms_universal_event_id events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": self.simple_event.id, "iCalUId": event_uid, "id": event_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[event_id]["_odoo_id"], self.simple_event.id) def test_map_an_event_using_global_id(self): # arrange event_id = self.simple_event.ms_organizer_event_id event_uid = self.simple_event.ms_universal_event_id events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": False, "iCalUId": event_uid, "id": event_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[event_id]["_odoo_id"], self.simple_event.id) def test_map_an_event_using_instance_id(self): """ Here, the Odoo event has an uid but the Outlook event has not. """ # arrange event_id = self.simple_event.ms_organizer_event_id events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": False, "iCalUId": False, "id": event_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[event_id]["_odoo_id"], self.simple_event.id) def test_map_an_event_without_uid_using_instance_id(self): """ Here, the Odoo event has no uid but the Outlook event has one. """ # arrange event_id = self.simple_event.ms_organizer_event_id event_uid = self.simple_event.ms_universal_event_id self.simple_event.ms_universal_event_id = False events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": False, "iCalUId": event_uid, "id": event_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[event_id]["_odoo_id"], self.simple_event.id) self.assertEqual(self.simple_event.ms_universal_event_id, event_uid) def test_map_an_event_without_uid_using_instance_id_2(self): """ Here, both Odoo event and Outlook event have no uid. """ # arrange event_id = self.simple_event.ms_organizer_event_id self.simple_event.ms_universal_event_id = False events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": False, "iCalUId": False, "id": event_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[event_id]["_odoo_id"], self.simple_event.id) self.assertEqual(self.simple_event.ms_universal_event_id, False) def test_map_a_recurrence_using_global_id(self): # arrange rec_id = self.recurrence.ms_organizer_event_id rec_uid = self.recurrence.ms_universal_event_id events = MicrosoftEvent([{ "type": "seriesMaster", "_odoo_id": False, "iCalUId": rec_uid, "id": rec_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[rec_id]["_odoo_id"], self.recurrence.id) def test_map_a_recurrence_using_instance_id(self): # arrange rec_id = self.recurrence.ms_organizer_event_id events = MicrosoftEvent([{ "type": "seriesMaster", "_odoo_id": False, "iCalUId": False, "id": rec_id, }]) # act mapped = events._load_odoo_ids_from_db(self.env) # assert self.assertEqual(len(mapped._events), 1) self.assertEqual(mapped._events[rec_id]["_odoo_id"], self.recurrence.id) def test_try_to_map_mixed_of_single_events_and_recurrences(self): # arrange event_id = self.simple_event.ms_organizer_event_id event_uid = self.simple_event.ms_universal_event_id rec_id = self.recurrence.ms_organizer_event_id rec_uid = self.recurrence.ms_universal_event_id events = MicrosoftEvent([ { "type": "seriesMaster", "_odoo_id": False, "iCalUId": rec_uid, "id": rec_id, }, { "type": "singleInstance", "_odoo_id": False, "iCalUId": event_uid, "id": event_id, }, ]) # act & assert with self.assertRaises(TypeError): events._load_odoo_ids_from_db(self.env) def test_match_event_only(self): # arrange event_id = self.simple_event.ms_organizer_event_id event_uid = self.simple_event.ms_universal_event_id events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": False, "iCalUId": event_uid, "id": event_id, }]) # act matched = events.match_with_odoo_events(self.env) # assert self.assertEqual(len(matched._events), 1) self.assertEqual(matched._events[event_id]["_odoo_id"], self.simple_event.id) def test_match_recurrence_only(self): # arrange rec_id = self.recurrence.ms_organizer_event_id rec_uid = self.recurrence.ms_universal_event_id events = MicrosoftEvent([{ "type": "seriesMaster", "_odoo_id": False, "iCalUId": rec_uid, "id": rec_id, }]) # act matched = events.match_with_odoo_events(self.env) # assert self.assertEqual(len(matched._events), 1) self.assertEqual(matched._events[rec_id]["_odoo_id"], self.recurrence.id) def test_match_not_typed_recurrence(self): """ When a recurrence is deleted, Outlook returns the id of the deleted recurrence without the type of event, so it's not directly possible to know that it's a recurrence. """ # arrange rec_id = self.recurrence.ms_organizer_event_id rec_uid = self.recurrence.ms_universal_event_id events = MicrosoftEvent([{ "@removed": { "reason": "deleted", }, "_odoo_id": False, "iCalUId": rec_uid, "id": rec_id, }]) # act matched = events.match_with_odoo_events(self.env) # assert self.assertEqual(len(matched._events), 1) self.assertEqual(matched._events[rec_id]["_odoo_id"], self.recurrence.id) def test_match_mix_of_events_and_recurrences(self): # arrange event_id = self.simple_event.ms_organizer_event_id event_uid = self.simple_event.ms_universal_event_id rec_id = self.recurrence.ms_organizer_event_id rec_uid = self.recurrence.ms_universal_event_id events = MicrosoftEvent([ { "type": "singleInstance", "_odoo_id": False, "iCalUId": event_uid, "id": event_id, }, { "@removed": { "reason": "deleted", }, "_odoo_id": False, "iCalUId": rec_uid, "id": rec_id, } ]) # act matched = events.match_with_odoo_events(self.env) # assert self.assertEqual(len(matched._events), 2) self.assertEqual(matched._events[event_id]["_odoo_id"], self.simple_event.id) self.assertEqual(matched._events[rec_id]["_odoo_id"], self.recurrence.id) def test_ignore_not_found_items(self): # arrange events = MicrosoftEvent([{ "type": "singleInstance", "_odoo_id": False, "iCalUId": "UNKNOWN_EVENT", "id": "UNKNOWN_EVENT", }]) # act matched = events.match_with_odoo_events(self.env) # assert self.assertEqual(len(matched._events), 0) def test_search_set_ms_universal_event_id(self): not_synced_events = self.env['calendar.event'].search([('ms_universal_event_id', '=', False)]) synced_events = self.env['calendar.event'].search([('ms_universal_event_id', '!=', False)]) self.assertIn(self.simple_event, synced_events) self.assertNotIn(self.simple_event, not_synced_events) self.simple_event.ms_universal_event_id = '' not_synced_events = self.env['calendar.event'].search([('ms_universal_event_id', '=', False)]) synced_events = self.env['calendar.event'].search([('ms_universal_event_id', '!=', False)]) self.assertNotIn(self.simple_event, synced_events) self.assertIn(self.simple_event, not_synced_events)
32.256579
9,806
10,822
py
PYTHON
15.0
# -*- coding: utf-8 -*- from unittest.mock import patch, ANY, call from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_calendar.models.res_users import User from odoo.addons.microsoft_calendar.tests.common import ( TestCommon, mock_get_token, _modified_date_in_the_future, patch_api ) @patch.object(User, '_get_microsoft_calendar_token', mock_get_token) class TestDeleteEvents(TestCommon): @patch_api def setUp(self): super(TestDeleteEvents, self).setUp() self.create_events_for_tests() @patch.object(MicrosoftCalendarService, 'delete') def test_delete_simple_event_from_odoo_organizer_calendar(self, mock_delete): event_id = self.simple_event.ms_organizer_event_id self.simple_event.with_user(self.organizer_user).unlink() self.call_post_commit_hooks() self.simple_event.invalidate_cache() self.assertFalse(self.simple_event.exists()) mock_delete.assert_called_once_with( event_id, token=mock_get_token(self.organizer_user), timeout=ANY ) @patch.object(MicrosoftCalendarService, 'delete') def test_delete_simple_event_from_odoo_attendee_calendar(self, mock_delete): event_id = self.simple_event.ms_organizer_event_id self.simple_event.with_user(self.attendee_user).unlink() self.call_post_commit_hooks() self.simple_event.invalidate_cache() self.assertFalse(self.simple_event.exists()) mock_delete.assert_called_once_with( event_id, token=mock_get_token(self.organizer_user), timeout=ANY ) @patch.object(MicrosoftCalendarService, 'delete') def test_archive_simple_event_from_odoo_organizer_calendar(self, mock_delete): event_id = self.simple_event.ms_organizer_event_id self.simple_event.with_user(self.organizer_user).write({'active': False}) self.call_post_commit_hooks() self.simple_event.invalidate_cache() self.assertTrue(self.simple_event.exists()) self.assertFalse(self.simple_event.active) mock_delete.assert_called_once_with( event_id, token=mock_get_token(self.organizer_user), timeout=ANY ) @patch.object(MicrosoftCalendarService, 'delete') def test_archive_simple_event_from_odoo_attendee_calendar(self, mock_delete): event_id = self.simple_event.ms_organizer_event_id self.simple_event.with_user(self.attendee_user).write({'active': False}) self.call_post_commit_hooks() self.simple_event.invalidate_cache() self.assertTrue(self.simple_event.exists()) self.assertFalse(self.simple_event.active) mock_delete.assert_called_once_with( event_id, token=mock_get_token(self.organizer_user), timeout=ANY ) @patch.object(MicrosoftCalendarService, 'delete') def test_archive_several_events_at_once(self, mock_delete): """ Archive several events at once should not produce any exception. """ # act self.several_events.action_archive() self.call_post_commit_hooks() self.several_events.invalidate_cache() # assert self.assertFalse(all(e.active for e in self.several_events)) mock_delete.assert_has_calls([ call(e.ms_organizer_event_id, token=ANY, timeout=ANY) for e in self.several_events ]) @patch.object(MicrosoftCalendarService, 'get_events') def test_cancel_simple_event_from_outlook_organizer_calendar(self, mock_get_events): """ In his Outlook calendar, the organizer cannot delete the event, he can only cancel it. """ event_id = self.simple_event.ms_organizer_event_id mock_get_events.return_value = ( MicrosoftEvent([{ "id": event_id, "@removed": {"reason": "deleted"} }]), None ) self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() self.assertFalse(self.simple_event.exists()) def test_delete_simple_event_from_outlook_attendee_calendar(self): """ If an attendee deletes an event from its Outlook calendar, during the sync, Odoo will be notified that this event has been deleted BUT only with the attendees's calendar event id and not with the global one (called iCalUId). That means, it's not possible to match this deleted event with an Odoo event. LIMITATION: Unfortunately, there is no magic solution: 1) keep the list of calendar events ids linked to a unique iCalUId but all Odoo users may not have synced their Odoo calendar, leading to missing ids in the list => bad solution. 2) call the microsoft API to get the iCalUId matching the received event id => as the event has already been deleted, this call may return an error. """ @patch.object(MicrosoftCalendarService, 'delete') def test_delete_one_event_from_recurrence_from_odoo_calendar(self, mock_delete): # arrange idx = 2 event_id = self.recurrent_events[idx].ms_organizer_event_id # act self.recurrent_events[idx].with_user(self.organizer_user).unlink() self.call_post_commit_hooks() # assert self.assertFalse(self.recurrent_events[idx].exists()) self.assertEqual(len(self.recurrence.calendar_event_ids), self.recurrent_events_count - 1) mock_delete.assert_called_once_with( event_id, token=mock_get_token(self.organizer_user), timeout=ANY ) @patch.object(MicrosoftCalendarService, 'delete') def test_delete_first_event_from_recurrence_from_odoo_calendar(self, mock_delete): # arrange idx = 0 event_id = self.recurrent_events[idx].ms_organizer_event_id # act self.recurrent_events[idx].with_user(self.organizer_user).unlink() self.call_post_commit_hooks() # assert self.assertFalse(self.recurrent_events[idx].exists()) self.assertEqual(len(self.recurrence.calendar_event_ids), self.recurrent_events_count - 1) self.assertEqual(self.recurrence.base_event_id, self.recurrent_events[1]) mock_delete.assert_called_once_with( event_id, token=mock_get_token(self.organizer_user), timeout=ANY ) @patch.object(MicrosoftCalendarService, 'get_events') def test_delete_one_event_from_recurrence_from_outlook_calendar(self, mock_get_events): """ When a single event is removed from a recurrence, Outlook returns the recurrence and events which still exist. """ # arrange idx = 3 rec_values = [ dict( event, lastModifiedDateTime=_modified_date_in_the_future(self.recurrence) ) for i, event in enumerate(self.recurrent_event_from_outlook_organizer) if i != (idx + 1) # + 1 because recurrent_event_from_outlook_organizer contains the recurrence itself as first item ] event_to_remove = self.recurrent_events[idx] mock_get_events.return_value = (MicrosoftEvent(rec_values), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert self.assertFalse(event_to_remove.exists()) self.assertEqual(len(self.recurrence.calendar_event_ids), self.recurrent_events_count - 1) @patch.object(MicrosoftCalendarService, 'get_events') def test_delete_first_event_from_recurrence_from_outlook_calendar(self, mock_get_events): # arrange rec_values = [ dict( event, lastModifiedDateTime=_modified_date_in_the_future(self.recurrence) ) for i, event in enumerate(self.recurrent_event_from_outlook_organizer) if i != 1 ] event_to_remove = self.recurrent_events[0] next_base_event = self.recurrent_events[1] mock_get_events.return_value = (MicrosoftEvent(rec_values), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert self.assertFalse(event_to_remove.exists()) self.assertEqual(len(self.recurrence.calendar_event_ids), self.recurrent_events_count - 1) self.assertEqual(self.recurrence.base_event_id, next_base_event) @patch.object(MicrosoftCalendarService, 'get_events') def test_delete_one_event_and_future_from_recurrence_from_outlook_calendar(self, mock_get_events): # arrange idx = range(4, self.recurrent_events_count) rec_values = [ dict( event, lastModifiedDateTime=_modified_date_in_the_future(self.recurrence) ) for i, event in enumerate(self.recurrent_event_from_outlook_organizer) if i not in [x + 1 for x in idx] ] event_to_remove = [e for i, e in enumerate(self.recurrent_events) if i in idx] mock_get_events.return_value = (MicrosoftEvent(rec_values), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert for e in event_to_remove: self.assertFalse(e.exists()) self.assertEqual(len(self.recurrence.calendar_event_ids), self.recurrent_events_count - len(idx)) @patch.object(MicrosoftCalendarService, 'get_events') def test_delete_first_event_and_future_from_recurrence_from_outlook_calendar(self, mock_get_events): """ In Outlook, deleting the first event and future ones is the same than removing all the recurrence. """ # arrange mock_get_events.return_value = ( MicrosoftEvent([{ "id": self.recurrence.ms_organizer_event_id, "@removed": {"reason": "deleted"} }]), None ) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert self.assertFalse(self.recurrence.exists()) self.assertFalse(self.recurrence.calendar_event_ids.exists()) @patch.object(MicrosoftCalendarService, 'get_events') def test_delete_all_events_from_recurrence_from_outlook_calendar(self, mock_get_events): """ Same than test_delete_first_event_and_future_from_recurrence_from_outlook_calendar. """
39.786765
10,822
5,064
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 unittest.mock import MagicMock, patch from odoo.tests.common import TransactionCase from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.models.res_users import User from odoo.addons.microsoft_calendar.models.microsoft_sync import MicrosoftSync from odoo.modules.registry import Registry from odoo.addons.microsoft_account.models.microsoft_service import TIMEOUT def patch_api(func): @patch.object(MicrosoftSync, '_microsoft_insert', MagicMock()) @patch.object(MicrosoftSync, '_microsoft_delete', MagicMock()) @patch.object(MicrosoftSync, '_microsoft_patch', MagicMock()) def patched(self, *args, **kwargs): return func(self, *args, **kwargs) return patched @patch.object(User, '_get_microsoft_calendar_token', lambda user: 'dummy-token') class TestSyncOdoo2Microsoft(TransactionCase): def setUp(self): super().setUp() self.microsoft_service = MicrosoftCalendarService(self.env['microsoft.service']) def assertMicrosoftEventInserted(self, values): MicrosoftSync._microsoft_insert.assert_called_once_with(self.microsoft_service, values) def assertMicrosoftEventNotInserted(self): MicrosoftSync._microsoft_insert.assert_not_called() def assertMicrosoftEventPatched(self, microsoft_id, values, timeout=None): expected_args = (microsoft_id, values) expected_kwargs = {'timeout': timeout} if timeout else {} MicrosoftSync._microsoft_patch.assert_called_once() args, kwargs = MicrosoftSync._microsoft_patch.call_args self.assertEqual(args[1:], expected_args) # skip Google service arg self.assertEqual(kwargs, expected_kwargs) @patch_api def test_stop_synchronization(self): self.env.user.stop_microsoft_synchronization() self.assertTrue(self.env.user.microsoft_synchronization_stopped, "The microsoft synchronization flag should be switched on") self.assertFalse(self.env.user._sync_microsoft_calendar(self.microsoft_service), "The microsoft synchronization should be stopped") year = date.today().year - 1 # If synchronization stopped, creating a new event should not call _google_insert. self.env['calendar.event'].create({ 'name': "Event", 'start': datetime(year, 1, 15, 8, 0), 'stop': datetime(year, 1, 15, 18, 0), 'privacy': 'private', }) self.assertMicrosoftEventNotInserted() @patch_api def test_restart_synchronization(self): # Test new event created after stopping synchronization are correctly patched when restarting sync. self.maxDiff = None microsoft_id = 'aaaaaaaaa' year = date.today().year partner = self.env['res.partner'].create({'name': 'Jean-Luc', 'email': 'jean-luc@opoo.com'}) user = self.env['res.users'].create({ 'name': 'Test user Calendar', 'login': 'jean-luc@opoo.com', 'partner_id': partner.id, }) user.stop_microsoft_synchronization() # In case of full sync, limit to a range of 1y in past and 1y in the future by default event = self.env['calendar.event'].with_user(user).create({ 'microsoft_id': microsoft_id, 'name': "Event", 'start': datetime(year, 1, 15, 8, 0), 'stop': datetime(year, 1, 15, 18, 0), 'partner_ids': [(4, partner.id)], }) user.with_user(user).restart_microsoft_synchronization() event.with_user(user)._sync_odoo2microsoft(self.microsoft_service) microsoft_guid = self.env['ir.config_parameter'].sudo().get_param('microsoft_calendar.microsoft_guid', False) self.assertMicrosoftEventPatched(event.microsoft_id, { 'id': event.microsoft_id, 'start': {'dateTime': '%s-01-15T08:00:00+00:00' % year, 'timeZone': 'Europe/London'}, 'end': {'dateTime': '%s-01-15T18:00:00+00:00' % year, 'timeZone': 'Europe/London'}, 'subject': 'Event', 'body': {'content': '', 'contentType': 'html'}, 'attendees': [], 'isAllDay': False, 'isOrganizer': True, 'isReminderOn': False, 'sensitivity': 'normal', 'showAs': 'busy', 'location': {'displayName': ''}, 'organizer': {'emailAddress': {'address': 'jean-luc@opoo.com', 'name': 'Test user Calendar'}}, 'reminderMinutesBeforeStart': 0, 'singleValueExtendedProperties': [{ 'id': 'String {%s} Name odoo_id' % microsoft_guid, 'value': str(event.id), }, { 'id': 'String {%s} Name owner_odoo_id' % microsoft_guid, 'value': str(user.id), } ] })
46.458716
5,064
66,264
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService, MicrosoftEvent from odoo.exceptions import ValidationError import pytz from datetime import datetime, date from odoo.tests.common import TransactionCase from dateutil.relativedelta import relativedelta class TestSyncMicrosoft2Odoo(TransactionCase): @property def now(self): return pytz.utc.localize(datetime.now()).isoformat() def setUp(self): super().setUp() self.recurrence_id = 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA' values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAACyq4xQ=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': '2020-05-06T07:00:00Z', 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAACyq4xQ==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000D848B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAALKrjF"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAALKrjF"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAALKrjF"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) self.datetime_future = pytz.utc.localize(datetime.now() + relativedelta(days=1)).isoformat() def sync(self, events): self.env['calendar.event']._sync_microsoft2odoo(events) def test_new_microsoft_recurrence(self): recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = recurrence.calendar_event_ids self.assertTrue(recurrence, "It should have created an recurrence") self.assertEqual(len(events), 3, "It should have created 3 events") self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events.mapped('name'), ['My recurrent event', 'My recurrent event', 'My recurrent event']) self.assertFalse(events[0].allday) self.assertEqual(events[0].start, datetime(2020, 5, 3, 14, 30)) self.assertEqual(events[0].stop, datetime(2020, 5, 3, 16, 00)) self.assertEqual(events[1].start, datetime(2020, 5, 4, 14, 30)) self.assertEqual(events[1].stop, datetime(2020, 5, 4, 16, 00)) self.assertEqual(events[2].start, datetime(2020, 5, 5, 14, 30)) self.assertEqual(events[2].stop, datetime(2020, 5, 5, 16, 00)) def test_microsoft_recurrence_delete_one_event(self): values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') self.assertTrue(recurrence, "It should keep the recurrence") self.assertEqual(len(events), 2, "It should keep 2 events") self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events.mapped('name'), ['My recurrent event', 'My recurrent event']) def test_microsoft_recurrence_change_name_one_event(self): values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ=="', 'createdDateTime': '2020-05-06T08:01:32.4884797Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00807E40504874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event 2', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'originalStart': '2020-05-04T14:30:00Z', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'showAs': 'busy', 'type': 'exception', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA%3D&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') self.assertTrue(recurrence, "It should have created an recurrence") self.assertEqual(len(events), 3, "It should have created 3 events") self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events.mapped('name'), ['My recurrent event', 'My recurrent event 2', 'My recurrent event']) def test_microsoft_recurrence_change_name_all_event(self): values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADIaZKQ==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event 2', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpkp"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') self.assertTrue(recurrence, "It should keep the recurrence") self.assertEqual(len(events), 3, "It should keep the 3 events") self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events.mapped('name'), ['My recurrent event 2', 'My recurrent event 2', 'My recurrent event 2']) def test_microsoft_recurrence_change_date_one_event(self): values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADIaZPA=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADIaZPA==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpk8"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADIaZPA=="', 'createdDateTime': '2020-05-06T08:41:52.1067613Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADIaZPA==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00807E40504874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'originalStart': '2020-05-04T14:30:00Z', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'showAs': 'busy', 'type': 'exception', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA%3D&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T17:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMhpk8"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') special_event = self.env['calendar.event'].search([('microsoft_id', '=', 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=')]) self.assertTrue(recurrence, "It should have created an recurrence") self.assertTrue(special_event, "It should have created an special event") self.assertEqual(len(events), 3, "It should have created 3 events") self.assertTrue(special_event in events) self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events.mapped('name'), ['My recurrent event', 'My recurrent event', 'My recurrent event']) event_not_special = events - special_event self.assertEqual(event_not_special[0].start, datetime(2020, 5, 3, 14, 30)) self.assertEqual(event_not_special[0].stop, datetime(2020, 5, 3, 16, 00)) self.assertEqual(event_not_special[1].start, datetime(2020, 5, 5, 14, 30)) self.assertEqual(event_not_special[1].stop, datetime(2020, 5, 5, 16, 00)) self.assertEqual(special_event.start, datetime(2020, 5, 4, 14, 30)) self.assertEqual(special_event.stop, datetime(2020, 5, 4, 17, 00)) def test_microsoft_recurrence_delete_first_event(self): values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADI/Bnw=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADI/Bnw==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8Gf"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T16:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8Gf"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') self.assertTrue(recurrence, "It should have created an recurrence") self.assertEqual(len(events), 2, "It should left 2 events") self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events[0].start, datetime(2020, 5, 4, 14, 30)) self.assertEqual(events[0].stop, datetime(2020, 5, 4, 16, 00)) self.assertEqual(events[1].start, datetime(2020, 5, 5, 14, 30)) self.assertEqual(events[1].stop, datetime(2020, 5, 5, 16, 00)) # Now we delete lastest event in Outlook. values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADI/Bpg=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADI/Bpg==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8Gm"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T16:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') self.assertEqual(len(events), 1, "It should have created 1 events") self.assertEqual(recurrence.base_event_id, events[0]) # Now, we change end datetime of recurrence in Outlook, so all recurrence is recreated (even deleted events) values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADI/Bqg=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADI/Bqg==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:30:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-05', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8Gq"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:30:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8Gq"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAACyy0xAAAABA=', 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T16:30:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8Gq"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T16:30:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) events = self.env['calendar.event'].search([('recurrence_id', '=', recurrence.id)], order='start asc') self.assertEqual(len(events), 3, "It should have created 3 events") self.assertEqual(recurrence.base_event_id, events[0]) self.assertEqual(events.mapped('name'), ['My recurrent event', 'My recurrent event', 'My recurrent event']) self.assertEqual(events[0].start, datetime(2020, 5, 3, 14, 30)) self.assertEqual(events[0].stop, datetime(2020, 5, 3, 16, 30)) self.assertEqual(events[1].start, datetime(2020, 5, 4, 14, 30)) self.assertEqual(events[1].stop, datetime(2020, 5, 4, 16, 30)) self.assertEqual(events[2].start, datetime(2020, 5, 5, 14, 30)) self.assertEqual(events[2].stop, datetime(2020, 5, 5, 16, 30)) def test_microsoft_recurrence_split_recurrence(self): values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADI/Dig=="', 'createdDateTime': '2020-05-06T07:03:49.1444085Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADI/Dig==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000874F057E7423D601000000000000000010000000C6918C4B44D2D84586351FEC8B1B7F8C', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:30:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-03', 'endDate': '2020-05-03', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADI/Dkw=="', 'createdDateTime': '2020-05-06T13:24:10.0507138Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADI/Dkw==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E008000000001A4457A0A923D601000000000000000010000000476AE6084FD718418262DA1AE3E41411', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'busy', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAA&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAA', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T17:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2020-05-04', 'endDate': '2020-05-06', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8OK"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX7vTsS0AARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAAEA==', 'start': {'dateTime': '2020-05-03T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-03T16:30:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8OT"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX774WtQAAAEYAAAJAcu19N72jSr9Rp1mE2xWABwBlLa4RUBXJToExnebpwea2AAACAQ0AAABlLa4RUBXJToExnebpwea2AAAADJIEKwAAABA=', 'start': {'dateTime': '2020-05-04T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-04T17:00:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"ZS2uEVAVyU6BMZ3m6cHmtgAADI/Dkw=="', 'createdDateTime': '2020-05-06T13:25:05.9240043Z', 'lastModifiedDateTime': self.datetime_future, 'changeKey': 'ZS2uEVAVyU6BMZ3m6cHmtgAADI/Dkw==', 'categories': [], 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00807E405051A4457A0A923D601000000000000000010000000476AE6084FD718418262DA1AE3E41411', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'My recurrent event 2', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'originalStart': '2020-05-05T14:30:00Z', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': True, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAA', 'showAs': 'busy', 'type': 'exception', 'webLink': 'https://outlook.live.com/owa/?itemid=AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAAEA%3D%3D&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'AllowNewTimeProposals': True, 'IsDraft': False, 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8IdBHsAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAAEA==', 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2020-05-05T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-05T17:00:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'attendees': [], 'organizer': {'emailAddress': {'name': 'outlook_7BA43549E5FD4413@outlook.com', 'address': 'outlook_7BA43549E5FD4413@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAABlLa4RUBXJToExnebpwea2AAAMj8OT"', 'seriesMasterId': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAA', 'type': 'occurrence', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoBUQAICADX8VBriIAARgAAAkBy7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAAEA==', 'start': {'dateTime': '2020-05-06T14:30:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2020-05-06T17:00:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence_1 = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) recurrence_2 = self.env['calendar.recurrence'].search([('microsoft_id', '=', 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAAMkgQrAAAA')]) events_1 = self.env['calendar.event'].search([('recurrence_id', '=', recurrence_1.id)], order='start asc') events_2 = self.env['calendar.event'].search([('recurrence_id', '=', recurrence_2.id)], order='start asc') self.assertTrue(recurrence_1, "It should have created an recurrence") self.assertTrue(recurrence_2, "It should have created an recurrence") self.assertEqual(len(events_1), 1, "It should left 1 event") self.assertEqual(len(events_2), 3, "It should have created 3 events") self.assertEqual(recurrence_1.base_event_id, events_1[0]) self.assertEqual(recurrence_2.base_event_id, events_2[0]) self.assertEqual(events_1.mapped('name'), ['My recurrent event']) self.assertEqual(events_2.mapped('name'), ['My recurrent event', 'My recurrent event 2', 'My recurrent event']) self.assertEqual(events_1[0].start, datetime(2020, 5, 3, 14, 30)) self.assertEqual(events_1[0].stop, datetime(2020, 5, 3, 16, 30)) self.assertEqual(events_2[0].start, datetime(2020, 5, 4, 14, 30)) self.assertEqual(events_2[0].stop, datetime(2020, 5, 4, 17, 00)) self.assertEqual(events_2[1].start, datetime(2020, 5, 5, 14, 30)) self.assertEqual(events_2[1].stop, datetime(2020, 5, 5, 17, 00)) self.assertEqual(events_2[2].start, datetime(2020, 5, 6, 14, 30)) self.assertEqual(events_2[2].stop, datetime(2020, 5, 6, 17, 00)) def test_microsoft_recurrence_delete(self): recurrence_id = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) event_ids = self.env['calendar.event'].search([('recurrence_id', '=', recurrence_id.id)], order='start asc').ids values = [{'@odata.type': '#microsoft.graph.event', 'id': 'AQ8PojGtrADQATM3ZmYAZS0yY2MAMC00MDg1LTAwAi0wMAoARgAAA0By7X03vaNKv1GnWYTbFYAHAGUtrhFQFclOgTGd5unB5rYAAAIBDQAAAGUtrhFQFclOgTGd5unB5rYAAAALLLTEAAAA', '@removed': {'reason': 'deleted'}}] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(values)) recurrence = self.env['calendar.recurrence'].search([('microsoft_id', '=', self.recurrence_id)]) events = self.env['calendar.event'].browse(event_ids).exists() self.assertFalse(recurrence, "It should remove recurrence") self.assertFalse(events, "It should remove all events") def test_attendees_must_have_email(self): """ Synching with a partner without mail raises a ValidationError because Microsoft don't accept attendees without one. """ MicrosoftCal = MicrosoftCalendarService(self.env['microsoft.service']) partner = self.env['res.partner'].create({ 'name': 'SuperPartner', }) event = self.env['calendar.event'].create({ 'name': "SuperEvent", 'start': datetime(2020, 3, 16, 11, 0), 'stop': datetime(2020, 3, 16, 13, 0), 'partner_ids': [(4, partner.id)], }) with self.assertRaises(ValidationError): event._sync_odoo2microsoft(MicrosoftCal) def test_cancel_occurence_of_recurrent_event(self): """ The user is invited to a recurrent event. When synced, all events are present, there are three occurrences: - 07/15/2021, 15:00-15:30 - 07/16/2021, 15:00-15:30 - 07/17/2021, 15:00-15:30 Then, the organizer cancels the second occurrence -> The latter should not be displayed anymore """ microsoft_id = 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgBGAAADZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAA=' # self.env.user.partner_id.email = "odoo_bf_user01@outlook.com" first_sync_values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"pynKRnkCyUmnqILQHcLZEQAABElcNQ=="', 'createdDateTime': '2021-07-15T14:47:40.2996962Z', 'lastModifiedDateTime': '2021-07-15T14:47:40.3783507Z', 'changeKey': 'pynKRnkCyUmnqILQHcLZEQAABElcNQ==', 'categories': [], 'transactionId': None, 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000B35B3B5A8879D70100000000000000001000000008A0949F4EC0A1479E4ED178D87EF679', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'Recurrent Event 1646', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': False, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'tentative', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgBGAAADZ59RIxdyh0Kt%2FMXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAA%3D&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'allowNewTimeProposals': True, 'OccurrenceId': None, 'isDraft': False, 'hideAttendees': False, 'CalendarEventClassifications': [], 'AutoRoomBookingOptions': None, 'onlineMeeting': None, 'id': microsoft_id, 'responseStatus': {'response': 'notResponded', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2021-07-15T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-15T15:30:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2021-07-15', 'endDate': '2021-07-17', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [{'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': 'Odoo02 Outlook02', 'address': 'odoo_bf_user02@outlook.com'}}, {'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': 'Odoo01 Outlook01', 'address': 'odoo_bf_user01@outlook.com'}}], 'organizer': {'emailAddress': {'name': 'Odoo02 Outlook02', 'address': 'odoo_bf_user02@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAACnKcpGeQLJSaeogtAdwtkRAAAESVw1"', 'seriesMasterId': ('%s' % microsoft_id), 'type': 'occurrence', 'id': 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlHI305wABGAAACZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ', 'start': {'dateTime': '2021-07-15T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-15T15:30:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAACnKcpGeQLJSaeogtAdwtkRAAAESVw1"', 'seriesMasterId': microsoft_id, 'type': 'occurrence', 'id': 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlH7KejgABGAAACZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ', 'start': {'dateTime': '2021-07-16T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-16T15:30:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAACnKcpGeQLJSaeogtAdwtkRAAAESVw1"', 'seriesMasterId': microsoft_id, 'type': 'occurrence', 'id': 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlItdINQABGAAACZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ', 'start': {'dateTime': '2021-07-17T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-17T15:30:00.0000000', 'timeZone': 'UTC'}} ] second_sync_values = [ {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"pynKRnkCyUmnqILQHcLZEQAABElcUw=="', 'createdDateTime': '2021-07-15T14:47:40.2996962Z', 'lastModifiedDateTime': '2021-07-15T14:51:25.2560888Z', 'changeKey': 'pynKRnkCyUmnqILQHcLZEQAABElcUw==', 'categories': [], 'transactionId': None, 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00800000000B35B3B5A8879D70100000000000000001000000008A0949F4EC0A1479E4ED178D87EF679', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'Recurrent Event 1646', 'bodyPreview': '', 'importance': 'normal', 'sensitivity': 'normal', 'isAllDay': False, 'isCancelled': False, 'isOrganizer': False, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': None, 'showAs': 'tentative', 'type': 'seriesMaster', 'webLink': 'https://outlook.live.com/owa/?itemid=AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgBGAAADZ59RIxdyh0Kt%2FMXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAA%3D&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'allowNewTimeProposals': True, 'OccurrenceId': None, 'isDraft': False, 'hideAttendees': False, 'CalendarEventClassifications': [], 'id': microsoft_id, 'responseStatus': {'response': 'notResponded', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': ''}, 'start': {'dateTime': '2021-07-15T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-15T15:30:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'recurrence': {'pattern': {'type': 'daily', 'interval': 1, 'month': 0, 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first'}, 'range': {'type': 'endDate', 'startDate': '2021-07-15', 'endDate': '2021-07-17', 'recurrenceTimeZone': 'Romance Standard Time', 'numberOfOccurrences': 0}}, 'attendees': [{'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': 'Odoo02 Outlook02', 'address': 'odoo_bf_user02@outlook.com'}}, {'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': 'Odoo01 Outlook01', 'address': 'odoo_bf_user01@outlook.com'}}], 'organizer': {'emailAddress': {'name': 'Odoo02 Outlook02', 'address': 'odoo_bf_user02@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAACnKcpGeQLJSaeogtAdwtkRAAAESVxT"', 'seriesMasterId': microsoft_id, 'type': 'occurrence', 'id': 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlHI305wABGAAACZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ', 'start': {'dateTime': '2021-07-15T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-15T15:30:00.0000000', 'timeZone': 'UTC'}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"pynKRnkCyUmnqILQHcLZEQAABElcUw=="', 'createdDateTime': '2021-07-15T14:51:25.1366139Z', 'lastModifiedDateTime': '2021-07-15T14:51:25.136614Z', 'changeKey': 'pynKRnkCyUmnqILQHcLZEQAABElcUw==', 'categories': [], 'transactionId': None, 'originalStartTimeZone': 'Romance Standard Time', 'originalEndTimeZone': 'Romance Standard Time', 'iCalUId': '040000008200E00074C5B7101A82E00807E50710B35B3B5A8879D70100000000000000001000000008A0949F4EC0A1479E4ED178D87EF679', 'reminderMinutesBeforeStart': 15, 'isReminderOn': True, 'hasAttachments': False, 'subject': 'Canceled: Recurrent Event 1646', 'bodyPreview': '', 'importance': 'high', 'sensitivity': 'normal', 'originalStart': '2021-07-16T15:00:00Z', 'isAllDay': False, 'isCancelled': True, 'isOrganizer': False, 'IsRoomRequested': False, 'AutoRoomBookingStatus': 'None', 'responseRequested': True, 'seriesMasterId': microsoft_id, 'showAs': 'free', 'type': 'exception', 'webLink': 'https://outlook.live.com/owa/?itemid=AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlH7KejgABGAAACZ59RIxdyh0Kt%2FMXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ&exvsurl=1&path=/calendar/item', 'onlineMeetingUrl': None, 'isOnlineMeeting': False, 'onlineMeetingProvider': 'unknown', 'allowNewTimeProposals': True, 'OccurrenceId': ('OID.%s.2021-07-16' % microsoft_id), 'isDraft': False, 'hideAttendees': False, 'CalendarEventClassifications': [], 'id': 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlH7KejgABGAAACZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ', 'responseStatus': {'response': 'notResponded', 'time': '0001-01-01T00:00:00Z'}, 'body': {'contentType': 'html', 'content': '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">\r\n<meta name="Generator" content="Microsoft Exchange Server">\r\n<!-- converted from text -->\r\n<style><!-- .EmailQuote { margin-left: 1pt; padding-left: 4pt; border-left: #800000 2px solid; } --></style></head>\r\n<body>\r\n<font size="2"><span style="font-size:11pt;"><div class="PlainText">&nbsp;</div></span></font>\r\n</body>\r\n</html>\r\n'}, 'start': {'dateTime': '2021-07-16T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-16T15:30:00.0000000', 'timeZone': 'UTC'}, 'location': {'displayName': '', 'locationType': 'default', 'uniqueIdType': 'unknown', 'address': {}, 'coordinates': {}}, 'locations': [], 'attendees': [{'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': 'Odoo02 Outlook02', 'address': 'odoo_bf_user02@outlook.com'}}, {'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': 'Odoo01 Outlook01', 'address': 'odoo_bf_user01@outlook.com'}}], 'organizer': {'emailAddress': {'name': 'Odoo02 Outlook02', 'address': 'odoo_bf_user02@outlook.com'}}}, {'@odata.type': '#microsoft.graph.event', '@odata.etag': 'W/"DwAAABYAAACnKcpGeQLJSaeogtAdwtkRAAAESVxT"', 'seriesMasterId': microsoft_id, 'type': 'occurrence', 'id': 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgFRAAgIANlItdINQABGAAACZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAAQ', 'start': {'dateTime': '2021-07-17T15:00:00.0000000', 'timeZone': 'UTC'}, 'end': {'dateTime': '2021-07-17T15:30:00.0000000', 'timeZone': 'UTC'}} ] self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(first_sync_values)) recurrent_event = self.env['calendar.recurrence'].search([('microsoft_id', '=', 'AQMkADAwATM3ZmYAZS0zZmMyLWYxYjQtMDACLTAwCgBGAAADZ59RIxdyh0Kt-MXfyCpfwAcApynKRnkCyUmnqILQHcLZEQAAAgENAAAApynKRnkCyUmnqILQHcLZEQAAAARKsSQAAAA=')]) self.assertEqual(len(recurrent_event.calendar_event_ids), 3) # Need to cheat on the write date, otherwise the second sync won't update the events recurrent_event.write_date = datetime(2021, 7, 15, 14, 00) self.env['calendar.event']._sync_microsoft2odoo(MicrosoftEvent(second_sync_values)) self.assertEqual(len(recurrent_event.calendar_event_ids), 2) events = recurrent_event.calendar_event_ids.sorted(key=lambda e: e.start) self.assertEqual(events[0].start, datetime(2021, 7, 15, 15, 00)) self.assertEqual(events[0].stop, datetime(2021, 7, 15, 15, 30)) self.assertEqual(events[1].start, datetime(2021, 7, 17, 15, 00)) self.assertEqual(events[1].stop, datetime(2021, 7, 17, 15, 30))
237.505376
66,264
22,004
py
PYTHON
15.0
import pytz from datetime import datetime, timedelta from markupsafe import Markup from unittest.mock import patch, MagicMock from odoo.tests.common import HttpCase from odoo.addons.microsoft_calendar.models.microsoft_sync import MicrosoftSync from odoo.addons.microsoft_calendar.utils.event_id_storage import combine_ids def mock_get_token(user): return f"TOKEN_FOR_USER_{user.id}" def _modified_date_in_the_future(event): """ Add some seconds to the event write date to be sure to have a last modified date in the future """ return (event.write_date + timedelta(seconds=5)).strftime("%Y-%m-%dT%H:%M:%SZ") def patch_api(func): @patch.object(MicrosoftSync, '_microsoft_insert', MagicMock()) @patch.object(MicrosoftSync, '_microsoft_delete', MagicMock()) @patch.object(MicrosoftSync, '_microsoft_patch', MagicMock()) def patched(self, *args, **kwargs): return func(self, *args, **kwargs) return patched # By inheriting from TransactionCase, postcommit hooks (so methods tagged with `@after_commit` in MicrosoftSync), # are not called because no commit is done. # To be able to manually call these postcommit hooks, we need to inherit from HttpCase. # Note: as postcommit hooks are called separately, do not forget to invalidate cache for records read during the test. class TestCommon(HttpCase): @patch_api def setUp(self): super(TestCommon, self).setUp() # prepare users self.organizer_user = self.env["res.users"].search([("name", "=", "Mike Organizer")]) if not self.organizer_user: partner = self.env['res.partner'].create({'name': 'Mike Organizer', 'email': 'mike@organizer.com'}) self.organizer_user = self.env['res.users'].create({ 'name': 'Mike Organizer', 'login': 'mike@organizer.com', 'partner_id': partner.id, }) self.attendee_user = self.env["res.users"].search([("name", "=", "John Attendee")]) if not self.attendee_user: partner = self.env['res.partner'].create({'name': 'John Attendee', 'email': 'john@attendee.com'}) self.attendee_user = self.env['res.users'].create({ 'name': 'John Attendee', 'login': 'john@attendee.com', 'partner_id': partner.id, }) # ----------------------------------------------------------------------------------------- # To create Odoo events # ----------------------------------------------------------------------------------------- self.start_date = datetime(2021, 9, 22, 10, 0, 0, 0) self.end_date = datetime(2021, 9, 22, 11, 0, 0, 0) self.recurrent_event_interval = 2 self.recurrent_events_count = 7 self.recurrence_end_date = self.end_date + timedelta( days=self.recurrent_event_interval * self.recurrent_events_count ) # simple event values to create a Odoo event self.simple_event_values = { "name": "simple_event", "description": "my simple event", "active": True, "start": self.start_date, "stop": self.end_date, "partner_ids": [(4, self.organizer_user.partner_id.id), (4, self.attendee_user.partner_id.id)], } self.recurrent_event_values = { 'name': 'recurring_event', 'description': 'a recurring event', "partner_ids": [(4, self.attendee_user.partner_id.id)], 'recurrency': True, 'follow_recurrence': True, 'start': self.start_date.strftime("%Y-%m-%d %H:%M:%S"), 'stop': self.end_date.strftime("%Y-%m-%d %H:%M:%S"), 'event_tz': 'Europe/London', 'recurrence_update': 'self_only', 'rrule_type': 'daily', 'interval': self.recurrent_event_interval, 'count': self.recurrent_events_count, 'end_type': 'count', 'duration': 1, 'byday': '-1', 'day': 22, 'wed': True, 'weekday': 'WED' } # ----------------------------------------------------------------------------------------- # Expected values for Odoo events converted to Outlook events (to be posted through API) # ----------------------------------------------------------------------------------------- # simple event values converted in the Outlook format to be posted through the API self.simple_event_ms_values = { "subject": self.simple_event_values["name"], "body": { 'content': self.simple_event_values["description"], 'contentType': "text", }, "start": { 'dateTime': pytz.utc.localize(self.simple_event_values["start"]).isoformat(), 'timeZone': 'Europe/London' }, "end": { 'dateTime': pytz.utc.localize(self.simple_event_values["stop"]).isoformat(), 'timeZone': 'Europe/London' }, "isAllDay": False, "organizer": { 'emailAddress': { 'address': self.organizer_user.email, 'name': self.organizer_user.display_name, } }, "isOrganizer": True, "sensitivity": "normal", "showAs": "busy", "attendees": [ { 'emailAddress': { 'address': self.attendee_user.email, 'name': self.attendee_user.display_name }, 'status': {'response': "notresponded"} } ], "isReminderOn": False, "location": {'displayName': ''}, "reminderMinutesBeforeStart": 0, } self.recurrent_event_ms_values = { 'subject': self.recurrent_event_values["name"], "body": { 'content': Markup('<p>%s</p>' % self.recurrent_event_values["description"]), 'contentType': "html", }, 'start': { 'dateTime': self.start_date.strftime("%Y-%m-%dT%H:%M:%S+00:00"), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': self.end_date.strftime("%Y-%m-%dT%H:%M:%S+00:00"), 'timeZone': 'Europe/London' }, 'isAllDay': False, 'isOrganizer': True, 'isReminderOn': False, 'reminderMinutesBeforeStart': 0, 'sensitivity': 'normal', 'showAs': 'busy', 'type': 'seriesMaster', "attendees": [ { 'emailAddress': { 'address': self.attendee_user.email, 'name': self.attendee_user.display_name }, 'status': {'response': "notresponded"} } ], 'location': {'displayName': ''}, 'organizer': { 'emailAddress': { 'address': self.organizer_user.email, 'name': self.organizer_user.display_name, }, }, 'recurrence': { 'pattern': {'dayOfMonth': 22, 'interval': self.recurrent_event_interval, 'type': 'daily'}, 'range': { 'numberOfOccurrences': self.recurrent_events_count, 'startDate': self.start_date.strftime("%Y-%m-%d"), 'type': 'numbered' }, }, } # ----------------------------------------------------------------------------------------- # Events coming from Outlook (so from the API) # ----------------------------------------------------------------------------------------- self.simple_event_from_outlook_organizer = { 'type': 'singleInstance', 'seriesMasterId': None, 'id': '123', 'iCalUId': '456', 'subject': 'simple_event', 'body': { 'content': "my simple event", 'contentType': "text", }, 'start': {'dateTime': self.start_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC'}, 'end': {'dateTime': self.end_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC'}, 'attendees': [{ 'type': 'required', 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': self.attendee_user.display_name, 'address': self.attendee_user.email} }], 'isAllDay': False, 'isCancelled': False, 'sensitivity': 'normal', 'showAs': 'busy', 'isOnlineMeeting': False, 'onlineMeetingUrl': None, 'isOrganizer': True, 'isReminderOn': True, 'location': {'displayName': ''}, 'organizer': { 'emailAddress': {'address': self.organizer_user.email, 'name': self.organizer_user.display_name}, }, 'reminderMinutesBeforeStart': 15, 'responseRequested': True, 'responseStatus': { 'response': 'organizer', 'time': '0001-01-01T00:00:00Z', }, } self.simple_event_from_outlook_attendee = self.simple_event_from_outlook_organizer self.simple_event_from_outlook_attendee.update(isOrganizer=False) # ----------------------------------------------------------------------------------------- # Expected values for Outlook events converted to Odoo events # ----------------------------------------------------------------------------------------- self.expected_odoo_event_from_outlook = { "name": "simple_event", "description": Markup('<p>my simple event</p>'), "active": True, "start": self.start_date, "stop": self.end_date, "user_id": self.organizer_user, "microsoft_id": combine_ids("123", "456"), "partner_ids": [self.organizer_user.partner_id.id, self.attendee_user.partner_id.id], } self.expected_odoo_recurrency_from_outlook = { 'active': True, 'byday': '1', 'count': 0, 'day': 0, 'display_name': "Every %s Days until %s" % ( self.recurrent_event_interval, self.recurrence_end_date.strftime("%Y-%m-%d") ), 'dtstart': self.start_date, 'end_type': 'end_date', 'event_tz': False, 'fri': False, 'interval': self.recurrent_event_interval, 'month_by': 'date', 'microsoft_id': combine_ids('REC123', 'REC456'), 'name': "Every %s Days until %s" % ( self.recurrent_event_interval, self.recurrence_end_date.strftime("%Y-%m-%d") ), 'need_sync_m': False, 'rrule': 'DTSTART:%s\nRRULE:FREQ=DAILY;INTERVAL=%s;UNTIL=%s' % ( self.start_date.strftime("%Y%m%dT%H%M%S"), self.recurrent_event_interval, self.recurrence_end_date.strftime("%Y%m%dT235959"), ), 'rrule_type': 'daily', 'until': self.recurrence_end_date.date(), 'weekday': False, } self.recurrent_event_from_outlook_organizer = [{ 'attendees': [{ 'emailAddress': {'address': self.attendee_user.email, 'name': self.attendee_user.display_name}, 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'type': 'required' }], 'body': { 'content': "my recurrent event", 'contentType': "text", }, 'start': {'dateTime': self.start_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC'}, 'end': {'dateTime': self.end_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC'}, 'id': 'REC123', 'iCalUId': 'REC456', 'isAllDay': False, 'isCancelled': False, 'isOnlineMeeting': False, 'isOrganizer': True, 'isReminderOn': True, 'location': {'displayName': ''}, 'organizer': {'emailAddress': { 'address': self.organizer_user.email, 'name': self.organizer_user.display_name} }, 'recurrence': { 'pattern': { 'dayOfMonth': 0, 'firstDayOfWeek': 'sunday', 'index': 'first', 'interval': self.recurrent_event_interval, 'month': 0, 'type': 'daily' }, 'range': { 'startDate': self.start_date.strftime("%Y-%m-%d"), 'endDate': self.recurrence_end_date.strftime("%Y-%m-%d"), 'numberOfOccurrences': 0, 'recurrenceTimeZone': 'Romance Standard Time', 'type': 'endDate' } }, 'reminderMinutesBeforeStart': 15, 'responseRequested': True, 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'sensitivity': 'normal', 'seriesMasterId': None, 'showAs': 'busy', 'subject': "recurrent event", 'type': 'seriesMaster', }] self.recurrent_event_from_outlook_organizer += [ { 'attendees': [{ 'emailAddress': {'address': self.attendee_user.email, 'name': self.attendee_user.display_name}, 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'type': 'required' }], 'body': { 'content': "my recurrent event", 'contentType': "text", }, 'start': { 'dateTime': ( self.start_date + timedelta(days=i * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, 'end': { 'dateTime': ( self.end_date + timedelta(days=i * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, 'id': f'REC123_EVENT_{i+1}', 'iCalUId': f'REC456_EVENT_{i+1}', 'seriesMasterId': 'REC123', 'isAllDay': False, 'isCancelled': False, 'isOnlineMeeting': False, 'isOrganizer': True, 'isReminderOn': True, 'location': {'displayName': ''}, 'organizer': { 'emailAddress': {'address': self.organizer_user.email, 'name': self.organizer_user.display_name} }, 'recurrence': None, 'reminderMinutesBeforeStart': 15, 'responseRequested': True, 'responseStatus': {'response': 'organizer', 'time': '0001-01-01T00:00:00Z'}, 'sensitivity': 'normal', 'showAs': 'busy', 'subject': "recurrent event", 'type': 'occurrence', } for i in range(self.recurrent_events_count) ] self.recurrent_event_from_outlook_attendee = [ dict( d, isOrganizer=False, attendees=[ { 'emailAddress': {'address': self.organizer_user.email, 'name': self.organizer_user.display_name}, 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'type': 'required' }, { 'emailAddress': {'address': self.attendee_user.email, 'name': self.attendee_user.display_name}, 'status': {'response': 'none', 'time': '0001-01-01T00:00:00Z'}, 'type': 'required' }, ] ) for d in self.recurrent_event_from_outlook_organizer ] self.expected_odoo_recurrency_events_from_outlook = [ { "name": "recurrent event", "user_id": self.organizer_user, "partner_ids": [self.organizer_user.partner_id.id, self.attendee_user.partner_id.id], "start": self.start_date + timedelta(days=i * self.recurrent_event_interval), "stop": self.end_date + timedelta(days=i * self.recurrent_event_interval), "until": self.recurrence_end_date.date(), "microsoft_recurrence_master_id": "REC123", 'microsoft_id': combine_ids(f"REC123_EVENT_{i+1}", f"REC456_EVENT_{i+1}"), "recurrency": True, "follow_recurrence": True, "active": True, } for i in range(self.recurrent_events_count) ] self.env.cr.postcommit.clear() def create_events_for_tests(self): """ Create some events for test purpose """ # ---- create some events that will be updated during tests ----- # a simple event self.simple_event = self.env["calendar.event"].search([("name", "=", "simple_event")]) if not self.simple_event: self.simple_event = self.env["calendar.event"].with_user(self.organizer_user).create( dict( self.simple_event_values, microsoft_id=combine_ids("123", "456"), ) ) # a group of events self.several_events = self.env["calendar.event"].search([("name", "like", "event%")]) if not self.several_events: self.several_events = self.env["calendar.event"].with_user(self.organizer_user).create([ dict( self.simple_event_values, name=f"event{i}", microsoft_id=combine_ids(f"e{i}", f"u{i}"), ) for i in range(1, 4) ]) # a recurrent event with 7 occurrences self.recurrent_base_event = self.env["calendar.event"].search( [("name", "=", "recurrent_event")], order="id", limit=1, ) already_created = self.recurrent_base_event if not already_created: self.recurrent_base_event = self.env["calendar.event"].with_user(self.organizer_user).create( self.recurrent_event_values ) self.recurrence = self.env["calendar.recurrence"].search([("base_event_id", "=", self.recurrent_base_event.id)]) # set ids set by Outlook if not already_created: self.recurrence.write({ "microsoft_id": combine_ids("REC123", "REC456"), }) for i, e in enumerate(self.recurrence.calendar_event_ids.sorted(key=lambda r: r.start)): e.write({ "microsoft_id": combine_ids(f"REC123_EVENT_{i+1}", f"REC456_EVENT_{i+1}"), "microsoft_recurrence_master_id": "REC123", }) self.recurrence.invalidate_cache() self.recurrence.calendar_event_ids.invalidate_cache() self.recurrent_events = self.recurrence.calendar_event_ids.sorted(key=lambda r: r.start) self.recurrent_events_count = len(self.recurrent_events) def assert_odoo_event(self, odoo_event, expected_values): """ Assert that an Odoo event has the same values than in the expected_values dictionary, for the keys present in expected_values. """ self.assertTrue(expected_values) odoo_event_values = odoo_event.read(list(expected_values.keys()))[0] for k, v in expected_values.items(): if k in ("user_id", "recurrence_id"): v = (v.id, v.name) if v else False if isinstance(v, list): self.assertListEqual(sorted(v), sorted(odoo_event_values.get(k)), msg=f"'{k}' mismatch") else: self.assertEqual(v, odoo_event_values.get(k), msg=f"'{k}' mismatch") def assert_odoo_recurrence(self, odoo_recurrence, expected_values): """ Assert that an Odoo recurrence has the same values than in the expected_values dictionary, for the keys present in expected_values. """ odoo_recurrence_values = odoo_recurrence.read(list(expected_values.keys()))[0] for k, v in expected_values.items(): self.assertEqual(v, odoo_recurrence_values.get(k), msg=f"'{k}' mismatch") def assert_dict_equal(self, dict1, dict2): # check missing keys keys = set(dict1.keys()) ^ set(dict2.keys()) self.assertFalse(keys, msg="Following keys are not in both dicts: %s" % ", ".join(keys)) # compare key by key for k, v in dict1.items(): self.assertEqual(v, dict2.get(k), f"'{k}' mismatch") def call_post_commit_hooks(self): """ manually calls postcommit hooks defined with the decorator @after_commit """ # need to manually handle post-commit hooks calls as `self.env.cr.postcommit.run()` clean # the queue at the end of the first post-commit hook call ... funcs = self.env.cr.postcommit._funcs.copy() while funcs: func = funcs.popleft() func()
42.726214
22,004
11,079
py
PYTHON
15.0
from unittest.mock import patch from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_calendar.models.res_users import User from odoo.addons.microsoft_calendar.tests.common import TestCommon, mock_get_token from odoo.exceptions import ValidationError @patch.object(User, '_get_microsoft_calendar_token', mock_get_token) class TestCreateEvents(TestCommon): @patch.object(MicrosoftCalendarService, 'insert') def test_create_simple_event_without_sync(self, mock_insert): """ A Odoo event is created when Outlook sync is not enabled. """ # arrange self.organizer_user.microsoft_synchronization_stopped = True # act record = self.env["calendar.event"].with_user(self.organizer_user).create(self.simple_event_values) self.call_post_commit_hooks() record.invalidate_cache() # assert mock_insert.assert_not_called() self.assertEqual(record.need_sync_m, False) def test_create_simple_event_without_email(self): """ Outlook does not accept attendees without email. """ # arrange self.attendee_user.partner_id.email = False # act & assert record = self.env["calendar.event"].with_user(self.organizer_user).create(self.simple_event_values) with self.assertRaises(ValidationError): record._sync_odoo2microsoft() @patch.object(MicrosoftCalendarService, 'get_events') def test_create_simple_event_from_outlook_organizer_calendar(self, mock_get_events): """ An event has been created in Outlook and synced in the Odoo organizer calendar. """ # arrange mock_get_events.return_value = (MicrosoftEvent([self.simple_event_from_outlook_organizer]), None) existing_records = self.env["calendar.event"].search([]) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert records = self.env["calendar.event"].search([]) new_records = (records - existing_records) self.assertEqual(len(new_records), 1) self.assert_odoo_event(new_records, self.expected_odoo_event_from_outlook) self.assertEqual(new_records.user_id, self.organizer_user) self.assertEqual(new_records.need_sync_m, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_create_simple_event_from_outlook_attendee_calendar_and_organizer_exists_in_odoo(self, mock_get_events): """ An event has been created in Outlook and synced in the Odoo attendee calendar. There is a Odoo user that matches with the organizer email address. """ # arrange mock_get_events.return_value = (MicrosoftEvent([self.simple_event_from_outlook_attendee]), None) existing_records = self.env["calendar.event"].search([]) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert records = self.env["calendar.event"].search([]) new_records = (records - existing_records) self.assertEqual(len(new_records), 1) self.assert_odoo_event(new_records, self.expected_odoo_event_from_outlook) self.assertEqual(new_records.user_id, self.organizer_user) @patch.object(MicrosoftCalendarService, 'get_events') def test_create_simple_event_from_outlook_attendee_calendar_and_organizer_does_not_exist_in_odoo( self, mock_get_events ): """ An event has been created in Outlook and synced in the Odoo attendee calendar. no Odoo user that matches with the organizer email address. """ # arrange outlook_event = self.simple_event_from_outlook_attendee outlook_event = dict(self.simple_event_from_outlook_attendee, organizer={ 'emailAddress': {'address': "john.doe@odoo.com", 'name': "John Doe"}, }) expected_event = dict(self.expected_odoo_event_from_outlook, user_id=False) mock_get_events.return_value = (MicrosoftEvent([outlook_event]), None) existing_records = self.env["calendar.event"].search([]) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert records = self.env["calendar.event"].search([]) new_records = (records - existing_records) self.assertEqual(len(new_records), 1) self.assert_odoo_event(new_records, expected_event) @patch.object(MicrosoftCalendarService, 'insert') def test_create_recurrent_event_without_sync(self, mock_insert): """ A Odoo recurrent event is created when Outlook sync is not enabled. """ # arrange self.organizer_user.microsoft_synchronization_stopped = True # act record = self.env["calendar.event"].with_user(self.organizer_user).create(self.recurrent_event_values) self.call_post_commit_hooks() record.invalidate_cache() # assert mock_insert.assert_not_called() self.assertEqual(record.need_sync_m, False) @patch.object(MicrosoftCalendarService, 'get_events') @patch.object(MicrosoftCalendarService, 'insert') def test_create_recurrent_event_with_sync(self, mock_insert, mock_get_events): """ A Odoo recurrent event is created when Outlook sync is enabled. """ # >>> first phase: create the recurrence # act record = self.env["calendar.event"].with_user(self.organizer_user).create(self.recurrent_event_values) # assert recurrence = self.env["calendar.recurrence"].search([("base_event_id", "=", record.id)]) mock_insert.assert_not_called() self.assertEqual(record.name, "recurring_event") self.assertEqual(recurrence.name, "Every 2 Days for 7 events") self.assertEqual(len(recurrence.calendar_event_ids), 7) # >>> second phase: sync with organizer outlook calendar # arrange event_id = "123" event_iCalUId = "456" mock_insert.return_value = (event_id, event_iCalUId) mock_get_events.return_value = ([], None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() self.call_post_commit_hooks() recurrence.invalidate_cache() # assert self.assertEqual(recurrence.ms_organizer_event_id, event_id) self.assertEqual(recurrence.ms_universal_event_id, event_iCalUId) self.assertEqual(recurrence.need_sync_m, False) mock_insert.assert_called_once() self.assert_dict_equal(mock_insert.call_args[0][0], self.recurrent_event_ms_values) @patch.object(MicrosoftCalendarService, 'get_events') @patch.object(MicrosoftCalendarService, 'insert') def test_create_recurrent_event_with_sync_by_another_user(self, mock_insert, mock_get_events): """ A Odoo recurrent event has been created and synced with Outlook by another user, but nothing should happen as it we prevent sync of recurrences from other users ( see microsoft_calendar/models/calendar_recurrence_rule.py::_get_microsoft_sync_domain() ) """ # >>> first phase: create the recurrence # act record = self.env["calendar.event"].with_user(self.organizer_user).create(self.recurrent_event_values) # assert recurrence = self.env["calendar.recurrence"].search([("base_event_id", "=", record.id)]) mock_insert.assert_not_called() self.assertEqual(record.name, "recurring_event") self.assertEqual(recurrence.name, f"Every 2 Days for {self.recurrent_events_count} events") self.assertEqual(len(recurrence.calendar_event_ids), self.recurrent_events_count) # >>> second phase: sync with attendee Outlook calendar # arrange event_id = "123" event_iCalUId = "456" mock_insert.return_value = (event_id, event_iCalUId) mock_get_events.return_value = ([], None) # act self.attendee_user.with_user(self.attendee_user).sudo()._sync_microsoft_calendar() self.call_post_commit_hooks() recurrence.invalidate_cache() # assert mock_insert.assert_not_called() self.assertEqual(recurrence.ms_organizer_event_id, False) self.assertEqual(recurrence.ms_universal_event_id, False) self.assertEqual(recurrence.need_sync_m, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_create_recurrent_event_from_outlook_organizer_calendar(self, mock_get_events): """ A recurrent event has been created in Outlook and synced in the Odoo organizer calendar. """ # arrange mock_get_events.return_value = (MicrosoftEvent(self.recurrent_event_from_outlook_organizer), None) existing_events = self.env["calendar.event"].search([]) existing_recurrences = self.env["calendar.recurrence"].search([]) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert new_events = (self.env["calendar.event"].search([]) - existing_events) new_recurrences = (self.env["calendar.recurrence"].search([]) - existing_recurrences) self.assertEqual(len(new_recurrences), 1) self.assertEqual(len(new_events), self.recurrent_events_count) self.assert_odoo_recurrence(new_recurrences, self.expected_odoo_recurrency_from_outlook) for i, e in enumerate(sorted(new_events, key=lambda e: e.id)): self.assert_odoo_event(e, self.expected_odoo_recurrency_events_from_outlook[i]) @patch.object(MicrosoftCalendarService, 'get_events') def test_create_recurrent_event_from_outlook_attendee_calendar(self, mock_get_events): """ A recurrent event has been created in Outlook and synced in the Odoo attendee calendar. """ # arrange mock_get_events.return_value = (MicrosoftEvent(self.recurrent_event_from_outlook_attendee), None) existing_events = self.env["calendar.event"].search([]) existing_recurrences = self.env["calendar.recurrence"].search([]) # act self.attendee_user.with_user(self.attendee_user).sudo()._sync_microsoft_calendar() # assert new_events = (self.env["calendar.event"].search([]) - existing_events) new_recurrences = (self.env["calendar.recurrence"].search([]) - existing_recurrences) self.assertEqual(len(new_recurrences), 1) self.assertEqual(len(new_events), self.recurrent_events_count) self.assert_odoo_recurrence(new_recurrences, self.expected_odoo_recurrency_from_outlook) for i, e in enumerate(sorted(new_events, key=lambda e: e.id)): self.assert_odoo_event(e, self.expected_odoo_recurrency_events_from_outlook[i])
42.776062
11,079
52,916
py
PYTHON
15.0
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from dateutil.parser import parse import logging import pytz from unittest.mock import patch, ANY from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_calendar.models.res_users import User from odoo.addons.microsoft_calendar.utils.event_id_storage import combine_ids from odoo.addons.microsoft_calendar.tests.common import TestCommon, mock_get_token, _modified_date_in_the_future, patch_api from odoo.exceptions import UserError _logger = logging.getLogger(__name__) @patch.object(User, '_get_microsoft_calendar_token', mock_get_token) class TestUpdateEvents(TestCommon): @patch_api def setUp(self): super(TestUpdateEvents, self).setUp() self.create_events_for_tests() # ------------------------------------------------------------------------------- # Update from Odoo to Outlook # ------------------------------------------------------------------------------- # ------ Simple event ------ @patch.object(MicrosoftCalendarService, 'patch') def test_update_odoo_simple_event_without_sync(self, mock_patch): """ Update an Odoo event without Outlook sync enabled """ # arrange self.organizer_user.microsoft_synchronization_stopped = True self.simple_event.need_sync_m = False # act self.simple_event.write({"name": "my new simple event"}) self.call_post_commit_hooks() self.simple_event.invalidate_cache() # assert mock_patch.assert_not_called() self.assertEqual(self.simple_event.need_sync_m, False) @patch.object(MicrosoftCalendarService, 'patch') def test_update_simple_event_from_odoo(self, mock_patch): """ Update an Odoo event with Outlook sync enabled """ # arrange mock_patch.return_value = True # act res = self.simple_event.with_user(self.organizer_user).write({"name": "my new simple event"}) self.call_post_commit_hooks() self.simple_event.invalidate_cache() # assert self.assertTrue(res) mock_patch.assert_called_once_with( self.simple_event.ms_organizer_event_id, {"subject": "my new simple event"}, token=mock_get_token(self.organizer_user), timeout=ANY, ) self.assertEqual(self.simple_event.name, "my new simple event") @patch.object(MicrosoftCalendarService, 'patch') def test_update_simple_event_from_odoo_attendee_calendar(self, mock_patch): """ Update an Odoo event from the attendee calendar. """ # arrange mock_patch.return_value = True # act res = self.simple_event.with_user(self.attendee_user).write({"name": "my new simple event"}) self.call_post_commit_hooks() self.simple_event.invalidate_cache() # assert self.assertTrue(res) mock_patch.assert_called_once_with( self.simple_event.ms_organizer_event_id, {"subject": "my new simple event"}, token=mock_get_token(self.organizer_user), timeout=ANY, ) self.assertEqual(self.simple_event.name, "my new simple event") # ------ One event in a recurrence ------ @patch.object(MicrosoftCalendarService, 'patch') def test_update_name_of_one_event_of_recurrence_from_odoo(self, mock_patch): """ Update one Odoo event name from a recurrence from the organizer calendar. """ # arrange new_name = "my specific event in recurrence" modified_event_id = 4 # act res = self.recurrent_events[modified_event_id].with_user(self.organizer_user).write({ "recurrence_update": "self_only", "name": new_name, }) self.call_post_commit_hooks() self.recurrent_events[modified_event_id].invalidate_cache() # assert self.assertTrue(res) mock_patch.assert_called_once_with( self.recurrent_events[modified_event_id].ms_organizer_event_id, {'seriesMasterId': 'REC123', 'type': 'exception', "subject": new_name}, token=mock_get_token(self.organizer_user), timeout=ANY, ) self.assertEqual(self.recurrent_events[modified_event_id].name, new_name) self.assertEqual(self.recurrent_events[modified_event_id].follow_recurrence, True) for i in range(self.recurrent_events_count): if i != modified_event_id: self.assertNotEqual(self.recurrent_events[i].name, new_name) @patch.object(MicrosoftCalendarService, 'patch') def test_update_start_of_one_event_of_recurrence_from_odoo(self, mock_patch): """ Update one Odoo event start date from a recurrence from the organizer calendar. """ # arrange new_date = datetime(2021, 9, 29, 10, 0, 0) modified_event_id = 4 # act res = self.recurrent_events[modified_event_id].with_user(self.organizer_user).write({ "recurrence_update": "self_only", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events[modified_event_id].invalidate_cache() # assert self.assertTrue(res) mock_patch.assert_called_once_with( self.recurrent_events[modified_event_id].ms_organizer_event_id, { 'seriesMasterId': 'REC123', 'type': 'exception', 'start': { 'dateTime': pytz.utc.localize(new_date).isoformat(), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': pytz.utc.localize(new_date + timedelta(hours=1)).isoformat(), 'timeZone': 'Europe/London' }, 'isAllDay': False }, token=mock_get_token(self.organizer_user), timeout=ANY, ) self.assertEqual(self.recurrent_events[modified_event_id].start, new_date) self.assertEqual(self.recurrent_events[modified_event_id].follow_recurrence, False) for i in range(self.recurrent_events_count): if i != modified_event_id: self.assertNotEqual(self.recurrent_events[i].start, new_date) self.assertEqual(self.recurrent_events[i].follow_recurrence, True) @patch.object(MicrosoftCalendarService, 'patch') def test_update_start_of_one_event_of_recurrence_from_odoo_with_overlap(self, mock_patch): """ Update one Odoo event start date from a recurrence from the organizer calendar, in order to overlap another existing event. """ # arrange new_date = datetime(2021, 9, 27, 10, 0, 0) modified_event_id = 4 # act with self.assertRaises(UserError): self.recurrent_events[modified_event_id].with_user(self.organizer_user).write({ "recurrence_update": "self_only", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert mock_patch.assert_not_called() @patch.object(MicrosoftCalendarService, 'patch') def test_update_name_of_one_event_of_recurrence_from_odoo_attendee_calendar(self, mock_patch): """ Update one Odoo event name from a recurrence from the atendee calendar. """ # arrange new_name = "my specific event in recurrence" modified_event_id = 4 # act res = self.recurrent_events[modified_event_id].with_user(self.attendee_user).write({ "recurrence_update": "self_only", "name": new_name }) self.call_post_commit_hooks() self.recurrent_events[modified_event_id].invalidate_cache() # assert self.assertTrue(res) mock_patch.assert_called_once_with( self.recurrent_events[modified_event_id].ms_organizer_event_id, {'seriesMasterId': 'REC123', 'type': 'exception', "subject": new_name}, token=mock_get_token(self.organizer_user), timeout=ANY, ) self.assertEqual(self.recurrent_events[modified_event_id].name, new_name) self.assertEqual(self.recurrent_events[modified_event_id].follow_recurrence, True) # ------ One and future events in a recurrence ------ @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_name_of_one_and_future_events_of_recurrence_from_odoo( self, mock_patch, mock_insert, mock_delete ): """ Update a Odoo event name and future events from a recurrence from the organizer calendar. """ # arrange new_name = "my specific event in recurrence" modified_event_id = 4 # act res = self.recurrent_events[modified_event_id].with_user(self.organizer_user).write({ "recurrence_update": "future_events", "name": new_name, }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert self.assertTrue(res) self.assertEqual(mock_patch.call_count, self.recurrent_events_count - modified_event_id) for i in range(modified_event_id, self.recurrent_events_count): mock_patch.assert_any_call( self.recurrent_events[i].ms_organizer_event_id, {'seriesMasterId': 'REC123', 'type': 'exception', "subject": new_name}, token=mock_get_token(self.organizer_user), timeout=ANY, ) for i in range(modified_event_id, self.recurrent_events_count): self.assertEqual(self.recurrent_events[i].name, new_name) self.assertEqual(self.recurrent_events[i].follow_recurrence, True) for i in range(modified_event_id): self.assertNotEqual(self.recurrent_events[i].name, new_name) @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_start_of_one_and_future_events_of_recurrence_from_odoo( self, mock_patch, mock_insert, mock_delete ): """ Update a Odoo event start date and future events from a recurrence from the organizer calendar. """ # When a time-related field is changed, the event does not follow the recurrence scheme anymore. # With Outlook, another constraint is that the new start of the event cannot overlap/cross the start # date of another event of the recurrence (see microsoft_calendar/models/calendar.py # _check_recurrence_overlapping() for more explanation) # # In this case, as we also update future events, the recurrence should be splitted into 2 parts: # - the original recurrence should end just before the first updated event # - a second recurrence should start at the first updated event # arrange new_date = datetime(2021, 9, 29, 10, 0, 0) modified_event_id = 4 existing_recurrences = self.env["calendar.recurrence"].search([]) expected_deleted_event_ids = [ r.ms_organizer_event_id for i, r in enumerate(self.recurrent_events) if i in range(modified_event_id + 1, self.recurrent_events_count) ] # act res = self.recurrent_events[modified_event_id].with_user(self.organizer_user).write({ "recurrence_update": "future_events", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences self.assertTrue(res) # a new recurrence should be created from the modified event to the end self.assertEqual(len(new_recurrences), 1) self.assertEqual(new_recurrences.base_event_id.start, new_date) self.assertEqual(len(new_recurrences.calendar_event_ids), self.recurrent_events_count - modified_event_id) # future events of the old recurrence should have been removed for e_id in expected_deleted_event_ids: mock_delete.assert_any_call( e_id, token=mock_get_token(self.organizer_user), timeout=ANY, ) # the base event should have been modified mock_patch.assert_called_once_with( self.recurrent_events[modified_event_id].ms_organizer_event_id, { 'seriesMasterId': 'REC123', 'type': 'exception', 'start': { 'dateTime': pytz.utc.localize(new_date).isoformat(), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': pytz.utc.localize(new_date + timedelta(hours=1)).isoformat(), 'timeZone': 'Europe/London' }, 'isAllDay': False }, token=mock_get_token(self.organizer_user), timeout=ANY, ) @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_start_of_one_and_future_events_of_recurrence_from_odoo_with_overlap( self, mock_patch, mock_insert, mock_delete ): """ Update a Odoo event start date and future events from a recurrence from the organizer calendar, overlapping an existing event. """ # arrange new_date = datetime(2021, 9, 27, 10, 0, 0) modified_event_id = 4 existing_recurrences = self.env["calendar.recurrence"].search([]) expected_deleted_event_ids = [ r.ms_organizer_event_id for i, r in enumerate(self.recurrent_events) if i in range(modified_event_id + 1, self.recurrent_events_count) ] # as the test overlap the previous event of the updated event, this previous event # should be removed too expected_deleted_event_ids += [self.recurrent_events[modified_event_id - 1].ms_organizer_event_id] # act res = self.recurrent_events[modified_event_id].with_user(self.organizer_user).write({ "recurrence_update": "future_events", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences self.assertTrue(res) # a new recurrence should be created from the modified event to the end self.assertEqual(len(new_recurrences), 1) self.assertEqual(new_recurrences.base_event_id.start, new_date) self.assertEqual(len(new_recurrences.calendar_event_ids), self.recurrent_events_count - modified_event_id + 1) # future events of the old recurrence should have been removed + the overlapped event for e_id in expected_deleted_event_ids: mock_delete.assert_any_call( e_id, token=mock_get_token(self.organizer_user), timeout=ANY, ) # the base event should have been modified mock_patch.assert_called_once_with( self.recurrent_events[modified_event_id].ms_organizer_event_id, { 'seriesMasterId': 'REC123', 'type': 'exception', 'start': { 'dateTime': pytz.utc.localize(new_date).isoformat(), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': pytz.utc.localize(new_date + timedelta(hours=1)).isoformat(), 'timeZone': 'Europe/London' }, 'isAllDay': False }, token=mock_get_token(self.organizer_user), timeout=ANY, ) @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_one_and_future_events_of_recurrence_from_odoo_attendee_calendar( self, mock_patch, mock_insert, mock_delete ): """ Update a Odoo event name and future events from a recurrence from the attendee calendar. """ # arrange new_date = datetime(2021, 9, 29, 10, 0, 0) modified_event_id = 4 existing_recurrences = self.env["calendar.recurrence"].search([]) expected_deleted_event_ids = [ r.ms_organizer_event_id for i, r in enumerate(self.recurrent_events) if i in range(modified_event_id + 1, self.recurrent_events_count) ] # act res = self.recurrent_events[modified_event_id].with_user(self.attendee_user).write({ "recurrence_update": "future_events", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences self.assertTrue(res) # a new recurrence should be created from the modified event to the end self.assertEqual(len(new_recurrences), 1) self.assertEqual(new_recurrences.base_event_id.start, new_date) self.assertEqual(len(new_recurrences.calendar_event_ids), self.recurrent_events_count - modified_event_id) # future events of the old recurrence should have been removed for e_id in expected_deleted_event_ids: mock_delete.assert_any_call( e_id, token=mock_get_token(self.organizer_user), timeout=ANY, ) # the base event should have been modified mock_patch.assert_called_once_with( self.recurrent_events[modified_event_id].ms_organizer_event_id, { 'seriesMasterId': 'REC123', 'type': 'exception', 'start': { 'dateTime': pytz.utc.localize(new_date).isoformat(), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': pytz.utc.localize(new_date + timedelta(hours=1)).isoformat(), 'timeZone': 'Europe/London' }, 'isAllDay': False }, token=mock_get_token(self.organizer_user), timeout=ANY, ) # ------ All events in a recurrence ------ @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_name_of_all_events_of_recurrence_from_odoo( self, mock_patch, mock_insert, mock_delete ): """ Update all events name from a recurrence from the organizer calendar. """ # arrange new_name = "my specific event in recurrence" # act res = self.recurrent_events[0].with_user(self.organizer_user).write({ "recurrence_update": "all_events", "name": new_name, }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert self.assertTrue(res) self.assertEqual(mock_patch.call_count, self.recurrent_events_count) for i in range(self.recurrent_events_count): mock_patch.assert_any_call( self.recurrent_events[i].ms_organizer_event_id, {'seriesMasterId': 'REC123', 'type': 'exception', "subject": new_name}, token=mock_get_token(self.organizer_user), timeout=ANY, ) self.assertEqual(self.recurrent_events[i].name, new_name) self.assertEqual(self.recurrent_events[i].follow_recurrence, True) @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_start_of_all_events_of_recurrence_from_odoo( self, mock_patch, mock_insert, mock_delete ): """ Update all events start date from a recurrence from the organizer calendar. """ # arrange new_date = datetime(2021, 9, 25, 10, 0, 0) existing_recurrences = self.env["calendar.recurrence"].search([]) expected_deleted_event_ids = [ r.ms_organizer_event_id for i, r in enumerate(self.recurrent_events) if i in range(1, self.recurrent_events_count) ] # act res = self.recurrent_events[0].with_user(self.organizer_user).write({ "recurrence_update": "all_events", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences self.assertTrue(res) self.assertEqual(len(new_recurrences), 1) self.assertEqual(new_recurrences.base_event_id.start, new_date) self.assertEqual(len(new_recurrences.calendar_event_ids), self.recurrent_events_count) mock_patch.assert_called_once_with( self.recurrent_events[0].ms_organizer_event_id, { 'seriesMasterId': 'REC123', 'type': 'exception', 'start': { 'dateTime': pytz.utc.localize(new_date).isoformat(), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': pytz.utc.localize(new_date + timedelta(hours=1)).isoformat(), 'timeZone': 'Europe/London' }, 'isAllDay': False }, token=mock_get_token(self.organizer_user), timeout=ANY, ) # events (except the base one) of the old recurrence should have been removed for e_id in expected_deleted_event_ids: mock_delete.assert_any_call( e_id, token=mock_get_token(self.organizer_user), timeout=ANY, ) @patch.object(MicrosoftCalendarService, 'delete') @patch.object(MicrosoftCalendarService, 'insert') @patch.object(MicrosoftCalendarService, 'patch') def test_update_all_events_of_recurrence_from_odoo_attendee_calendar( self, mock_patch, mock_insert, mock_delete ): """ Update all events start date from a recurrence from the attendee calendar. """ # arrange new_date = datetime(2021, 9, 25, 10, 0, 0) existing_recurrences = self.env["calendar.recurrence"].search([]) expected_deleted_event_ids = [ r.ms_organizer_event_id for i, r in enumerate(self.recurrent_events) if i in range(1, self.recurrent_events_count) ] # act res = self.recurrent_events[0].with_user(self.attendee_user).write({ "recurrence_update": "all_events", "start": new_date.strftime("%Y-%m-%d %H:%M:%S"), }) self.call_post_commit_hooks() self.recurrent_events.invalidate_cache() # assert new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences self.assertTrue(res) self.assertEqual(len(new_recurrences), 1) self.assertEqual(new_recurrences.base_event_id.start, new_date) self.assertEqual(len(new_recurrences.calendar_event_ids), self.recurrent_events_count) mock_patch.assert_called_once_with( self.recurrent_events[0].ms_organizer_event_id, { 'seriesMasterId': 'REC123', 'type': 'exception', 'start': { 'dateTime': pytz.utc.localize(new_date).isoformat(), 'timeZone': 'Europe/London' }, 'end': { 'dateTime': pytz.utc.localize(new_date + timedelta(hours=1)).isoformat(), 'timeZone': 'Europe/London' }, 'isAllDay': False }, token=mock_get_token(self.organizer_user), timeout=ANY, ) # events (except the base one) of the old recurrence should have been removed for e_id in expected_deleted_event_ids: mock_delete.assert_any_call( e_id, token=mock_get_token(self.organizer_user), timeout=ANY, ) # ------------------------------------------------------------------------------- # Update from Outlook to Odoo # ------------------------------------------------------------------------------- @patch.object(MicrosoftCalendarService, 'get_events') def test_update_simple_event_from_outlook_organizer_calendar(self, mock_get_events): """ Update a simple event from Outlook organizer calendar. """ # arrange new_name = "update simple event" mock_get_events.return_value = ( MicrosoftEvent([dict( self.simple_event_from_outlook_organizer, subject=new_name, type="exception", lastModifiedDateTime=_modified_date_in_the_future(self.simple_event) )]), None ) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert self.assertEqual(self.simple_event.name, new_name) self.assertEqual(self.simple_event.follow_recurrence, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_simple_event_from_outlook_attendee_calendar(self, mock_get_events): """ Update a simple event from Outlook attendee calendar. """ # arrange new_name = "update simple event" mock_get_events.return_value = ( MicrosoftEvent([dict( dict(self.simple_event_from_outlook_organizer, id=789), # same iCalUId but different id subject=new_name, type="exception", lastModifiedDateTime=_modified_date_in_the_future(self.simple_event) )]), None ) # act self.attendee_user.with_user(self.attendee_user).sudo()._sync_microsoft_calendar() # assert self.assertEqual(self.simple_event.name, new_name) self.assertEqual(self.simple_event.follow_recurrence, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_name_of_one_event_of_recurrence_from_outlook_organizer_calendar(self, mock_get_events): """ Update one event name from a recurrence from Outlook organizer calendar. """ # arrange new_name = "another event name" from_event_index = 2 events = self.recurrent_event_from_outlook_organizer events[from_event_index] = dict( events[from_event_index], subject=new_name, type="exception", lastModifiedDateTime=_modified_date_in_the_future(self.simple_event) ) ms_event_id = events[from_event_index]['id'] mock_get_events.return_value = (MicrosoftEvent(events), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert updated_event = self.env["calendar.event"].search([('ms_organizer_event_id', '=', ms_event_id)]) self.assertEqual(updated_event.name, new_name) self.assertEqual(updated_event.follow_recurrence, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_one_event_of_recurrence_from_outlook_organizer_calendar(self, mock_get_events): """ Update one event start date from a recurrence from Outlook organizer calendar. """ # arrange new_date = datetime(2021, 9, 25, 10, 0, 0) from_event_index = 3 events = self.recurrent_event_from_outlook_organizer events[from_event_index] = dict( events[from_event_index], start={'dateTime': new_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC'}, type="exception", lastModifiedDateTime=_modified_date_in_the_future(self.recurrent_base_event) ) ms_event_id = events[from_event_index]['id'] mock_get_events.return_value = (MicrosoftEvent(events), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert updated_event = self.env["calendar.event"].search([('ms_organizer_event_id', '=', ms_event_id)]) self.assertEqual(updated_event.start, new_date) self.assertEqual(updated_event.follow_recurrence, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_one_event_of_recurrence_from_outlook_organizer_calendar_with_overlap( self, mock_get_events ): """ Update one event start date from a recurrence from Outlook organizer calendar, with event overlap. """ # arrange new_date = datetime(2021, 9, 23, 10, 0, 0) from_event_index = 3 events = self.recurrent_event_from_outlook_organizer events[from_event_index] = dict( events[from_event_index], start={'dateTime': new_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC'}, type="exception", lastModifiedDateTime=_modified_date_in_the_future(self.recurrent_base_event) ) ms_event_id = events[from_event_index]['id'] mock_get_events.return_value = (MicrosoftEvent(events), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert updated_event = self.env["calendar.event"].search([('ms_organizer_event_id', '=', ms_event_id)]) self.assertEqual(updated_event.start, new_date) self.assertEqual(updated_event.follow_recurrence, False) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_name_of_one_event_and_future_of_recurrence_from_outlook_organizer_calendar(self, mock_get_events): """ Update one event name and future events from a recurrence from Outlook organizer calendar. """ # arrange new_name = "another event name" from_event_index = 3 events = self.recurrent_event_from_outlook_organizer for i in range(from_event_index, len(events)): events[i] = dict( events[i], subject=f"{new_name}_{i}", type="exception", lastModifiedDateTime=_modified_date_in_the_future(self.recurrent_base_event) ) ms_event_ids = { events[i]['id']: events[i]['subject'] for i in range(from_event_index, len(events)) } mock_get_events.return_value = (MicrosoftEvent(events), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert updated_events = self.env["calendar.event"].search([ ('ms_organizer_event_id', 'in', tuple(ms_event_ids.keys())) ]) for e in updated_events: self.assertEqual(e.name, ms_event_ids[e.ms_organizer_event_id]) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_one_event_and_future_of_recurrence_from_outlook_organizer_calendar(self, mock_get_events): """ Update one event start date and future events from a recurrence from Outlook organizer calendar. When a time field is modified on an event and the future events of the recurrence, the recurrence is splitted: - the first one is still the same than the existing one, but stops at the first modified event, - the second one containing newly created events but based on the old events which have been deleted. """ # ----------- ARRANGE -------------- existing_events = self.env["calendar.event"].search([]) existing_recurrences = self.env["calendar.recurrence"].search([]) # event index from where the current recurrence will be splitted/modified from_event_index = 3 # number of events in both recurrences old_recurrence_event_count = from_event_index - 1 new_recurrence_event_count = len(self.recurrent_event_from_outlook_organizer) - from_event_index # dates for the new recurrences (shift event dates of 1 day in the past) new_rec_first_event_start_date = self.start_date + timedelta( days=self.recurrent_event_interval * old_recurrence_event_count - 1 ) new_rec_first_event_end_date = new_rec_first_event_start_date + timedelta(hours=1) new_rec_end_date = new_rec_first_event_end_date + timedelta( days=self.recurrent_event_interval * new_recurrence_event_count - 1 ) # prepare first recurrence data in received Outlook events events = self.recurrent_event_from_outlook_organizer[0:from_event_index] events[0]['lastModifiedDateTime'] = _modified_date_in_the_future(self.recurrent_base_event) events[0]['recurrence']['range']['endDate'] = ( self.recurrence_end_date - timedelta(days=self.recurrent_event_interval * new_recurrence_event_count) ).strftime("%Y-%m-%d") # prepare second recurrence data in received Outlook events events += [ dict( self.recurrent_event_from_outlook_organizer[0], start={ 'dateTime': new_rec_first_event_start_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, end={ 'dateTime': new_rec_first_event_end_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, id='REC123_new', iCalUId='REC456_new', recurrence=dict( self.recurrent_event_from_outlook_organizer[0]['recurrence'], range={ 'startDate': new_rec_first_event_start_date.strftime("%Y-%m-%d"), 'endDate': new_rec_end_date.strftime("%Y-%m-%d"), 'numberOfOccurrences': 0, 'recurrenceTimeZone': 'Romance Standard Time', 'type': 'endDate' } ) ) ] # ... and the recurrent events events += [ dict( self.recurrent_event_from_outlook_organizer[1], start={ 'dateTime': ( new_rec_first_event_start_date + timedelta(days=i * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, end={ 'dateTime': ( new_rec_first_event_end_date + timedelta(days=i * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, id=f'REC123_new_{i+1}', iCalUId=f'REC456_new_{i+1}', seriesMasterId='REC123_new', ) for i in range(0, new_recurrence_event_count) ] mock_get_events.return_value = (MicrosoftEvent(events), None) # ----------- ACT -------------- self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # ----------- ASSERT -------------- new_events = self.env["calendar.event"].search([]) - existing_events new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences # old recurrence self.assertEqual(len(self.recurrence.calendar_event_ids), 2) self.assertEqual( self.recurrence.until, self.recurrence_end_date.date() - timedelta(days=self.recurrent_event_interval * new_recurrence_event_count) ) # new recurrence self.assertEqual(len(new_recurrences), 1) self.assertEqual(len(new_events), new_recurrence_event_count) self.assertEqual(new_recurrences.ms_organizer_event_id, "REC123_new") self.assertEqual(new_recurrences.ms_universal_event_id, "REC456_new") for i, e in enumerate(sorted(new_events, key=lambda e: e.id)): self.assert_odoo_event(e, { "start": new_rec_first_event_start_date + timedelta(days=i * self.recurrent_event_interval), "stop": new_rec_first_event_end_date + timedelta(days=i * self.recurrent_event_interval), "microsoft_id": combine_ids(f'REC123_new_{i+1}', f'REC456_new_{i+1}'), "recurrence_id": new_recurrences, "follow_recurrence": True, }) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_one_event_and_future_of_recurrence_from_outlook_organizer_calendar_with_overlap( self, mock_get_events ): """ Update one event start date and future events from a recurrence from Outlook organizer calendar, overlapping an existing event. """ # ----------- ARRANGE -------------- existing_events = self.env["calendar.event"].search([]) existing_recurrences = self.env["calendar.recurrence"].search([]) # event index from where the current recurrence will be splitted/modified from_event_index = 3 # number of events in both recurrences old_recurrence_event_count = from_event_index - 1 new_recurrence_event_count = len(self.recurrent_event_from_outlook_organizer) - from_event_index # dates for the new recurrences (shift event dates of (recurrent_event_interval + 1) days in the past # to overlap an event. new_rec_first_event_start_date = self.start_date + timedelta( days=self.recurrent_event_interval * (old_recurrence_event_count - 1) - 1 ) new_rec_first_event_end_date = new_rec_first_event_start_date + timedelta(hours=1) new_rec_end_date = new_rec_first_event_end_date + timedelta( days=self.recurrent_event_interval * (new_recurrence_event_count - 1) - 1 ) # prepare first recurrence data in received Outlook events events = self.recurrent_event_from_outlook_organizer[0:from_event_index] events[0]['lastModifiedDateTime'] = _modified_date_in_the_future(self.recurrent_base_event) events[0]['recurrence']['range']['endDate'] = ( self.recurrence_end_date - timedelta(days=self.recurrent_event_interval * new_recurrence_event_count) ).strftime("%Y-%m-%d") # prepare second recurrence data in received Outlook events events += [ dict( self.recurrent_event_from_outlook_organizer[0], start={ 'dateTime': new_rec_first_event_start_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, end={ 'dateTime': new_rec_first_event_end_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, id='REC123_new', iCalUId='REC456_new', recurrence=dict( self.recurrent_event_from_outlook_organizer[0]['recurrence'], range={ 'startDate': new_rec_first_event_start_date.strftime("%Y-%m-%d"), 'endDate': new_rec_end_date.strftime("%Y-%m-%d"), 'numberOfOccurrences': 0, 'recurrenceTimeZone': 'Romance Standard Time', 'type': 'endDate' } ) ) ] # ... and the recurrent events events += [ dict( self.recurrent_event_from_outlook_organizer[1], start={ 'dateTime': ( new_rec_first_event_start_date + timedelta(days=i * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, end={ 'dateTime': ( new_rec_first_event_end_date + timedelta(days=i * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, id=f'REC123_new_{i+1}', iCalUId=f'REC456_new_{i+1}', seriesMasterId='REC123_new', ) for i in range(0, new_recurrence_event_count) ] mock_get_events.return_value = (MicrosoftEvent(events), None) # ----------- ACT -------------- self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # ----------- ASSERT -------------- new_events = self.env["calendar.event"].search([]) - existing_events new_recurrences = self.env["calendar.recurrence"].search([]) - existing_recurrences # old recurrence self.assertEqual(len(self.recurrence.calendar_event_ids), 2) self.assertEqual( self.recurrence.until, self.recurrence_end_date.date() - timedelta(days=self.recurrent_event_interval * new_recurrence_event_count) ) # new recurrence self.assertEqual(len(new_recurrences), 1) self.assertEqual(len(new_events), new_recurrence_event_count) self.assertEqual(new_recurrences.ms_organizer_event_id, "REC123_new") self.assertEqual(new_recurrences.ms_universal_event_id, "REC456_new") for i, e in enumerate(sorted(new_events, key=lambda e: e.id)): self.assert_odoo_event(e, { "start": new_rec_first_event_start_date + timedelta(days=i * self.recurrent_event_interval), "stop": new_rec_first_event_end_date + timedelta(days=i * self.recurrent_event_interval), "microsoft_id": combine_ids(f'REC123_new_{i+1}', f'REC456_new_{i+1}'), "recurrence_id": new_recurrences, "follow_recurrence": True, }) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_name_of_all_events_of_recurrence_from_outlook_organizer_calendar(self, mock_get_events): """ Update all event names of a recurrence from Outlook organizer calendar. """ # arrange new_name = "another event name" events = self.recurrent_event_from_outlook_organizer for i, e in enumerate(events): events[i] = dict( e, subject=f"{new_name}_{i}", lastModifiedDateTime=_modified_date_in_the_future(self.recurrent_base_event) ) ms_events_to_update = { events[i]['id']: events[i]['subject'] for i in range(1, len(events)) } mock_get_events.return_value = (MicrosoftEvent(events), None) # act self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # assert updated_events = self.env["calendar.event"].search([ ('ms_organizer_event_id', 'in', tuple(ms_events_to_update.keys())) ]) for e in updated_events: self.assertEqual(e.name, ms_events_to_update[e.ms_organizer_event_id]) self.assertEqual(e.follow_recurrence, True) def _prepare_outlook_events_for_all_events_start_date_update(self, nb_of_events): """ Utility method to avoid repeating data preparation for all tests about updating the start date of all events of a recurrence """ new_start_date = datetime(2021, 9, 21, 10, 0, 0) new_end_date = new_start_date + timedelta(hours=1) # prepare recurrence based on self.recurrent_event_from_outlook_organizer[0] which is the Outlook recurrence events = [dict( self.recurrent_event_from_outlook_organizer[0], start={ 'dateTime': new_start_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC' }, end={ 'dateTime': new_end_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC', }, recurrence=dict( self.recurrent_event_from_outlook_organizer[0]['recurrence'], range={ 'startDate': new_start_date.strftime("%Y-%m-%d"), 'endDate': ( new_end_date + timedelta(days=self.recurrent_event_interval * nb_of_events) ).strftime("%Y-%m-%d"), 'numberOfOccurrences': 0, 'recurrenceTimeZone': 'Romance Standard Time', 'type': 'endDate' } ), lastModifiedDateTime=_modified_date_in_the_future(self.recurrent_base_event) )] # prepare all events based on self.recurrent_event_from_outlook_organizer[1] which is the first Outlook event events += nb_of_events * [self.recurrent_event_from_outlook_organizer[1]] for i in range(1, nb_of_events + 1): events[i] = dict( events[i], id=f'REC123_EVENT_{i}', iCalUId=f'REC456_EVENT_{i}', start={ 'dateTime': ( new_start_date + timedelta(days=(i - 1) * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC', }, end={ 'dateTime': ( new_end_date + timedelta(days=(i - 1) * self.recurrent_event_interval) ).strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC', }, lastModifiedDateTime=_modified_date_in_the_future(self.recurrent_base_event) ) return events @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_all_events_of_recurrence_from_outlook_organizer_calendar(self, mock_get_events): """ Update all event start date of a recurrence from Outlook organizer calendar. """ # ----------- ARRANGE ----------- events = self._prepare_outlook_events_for_all_events_start_date_update(self.recurrent_events_count) ms_events_to_update = { events[i]['id']: events[i]['start'] for i in range(1, self.recurrent_events_count + 1) } mock_get_events.return_value = (MicrosoftEvent(events), None) # ----------- ACT ----------- self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # ----------- ASSERT ----------- updated_events = self.env["calendar.event"].search([ ('ms_organizer_event_id', 'in', tuple(ms_events_to_update.keys())) ]) for e in updated_events: self.assertEqual( e.start.strftime("%Y-%m-%dT%H:%M:%S.0000000"), ms_events_to_update[e.ms_organizer_event_id]["dateTime"] ) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_all_events_of_recurrence_with_more_events(self, mock_get_events): """ Update all event start date of a recurrence from Outlook organizer calendar, where more events have been added (the end date is later in the year) """ # ----------- ARRANGE ----------- nb_of_events = self.recurrent_events_count + 2 events = self._prepare_outlook_events_for_all_events_start_date_update(nb_of_events) ms_events_to_update = { events[i]['id']: events[i]['start'] for i in range(1, nb_of_events + 1) } mock_get_events.return_value = (MicrosoftEvent(events), None) # ----------- ACT ----------- self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # ----------- ASSERT ----------- updated_events = self.env["calendar.event"].search([ ('ms_organizer_event_id', 'in', tuple(ms_events_to_update.keys())) ]) for e in updated_events: self.assertEqual( e.start.strftime("%Y-%m-%dT%H:%M:%S.0000000"), ms_events_to_update[e.ms_organizer_event_id]["dateTime"] ) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_all_events_of_recurrence_with_less_events(self, mock_get_events): """ Update all event start date of a recurrence from Outlook organizer calendar, where some events have been removed (the end date is earlier in the year) """ # ----------- ARRANGE ----------- nb_of_events = self.recurrent_events_count - 2 events = self._prepare_outlook_events_for_all_events_start_date_update(nb_of_events) ms_events_to_update = { events[i]['id']: events[i]['start'] for i in range(1, nb_of_events + 1) } mock_get_events.return_value = (MicrosoftEvent(events), None) # ----------- ACT ----------- self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # ----------- ASSERT ----------- updated_events = self.env["calendar.event"].search([ ('ms_organizer_event_id', 'in', tuple(ms_events_to_update.keys())) ]) for e in updated_events: self.assertEqual( e.start.strftime("%Y-%m-%dT%H:%M:%S.0000000"), ms_events_to_update[e.ms_organizer_event_id]["dateTime"] ) @patch.object(MicrosoftCalendarService, 'get_events') def test_update_start_of_all_events_of_recurrence_with_exceptions(self, mock_get_events): """ Update all event start date of a recurrence from Outlook organizer calendar, where an event does not follow the recurrence anymore (it became an exception) """ # ----------- ARRANGE ----------- nb_of_events = self.recurrent_events_count - 2 events = self._prepare_outlook_events_for_all_events_start_date_update(nb_of_events) new_start_date = parse(events[2]['start']['dateTime']) + timedelta(days=1) new_end_date = parse(events[2]['end']['dateTime']) + timedelta(days=1) events[2] = dict( events[2], start={ 'dateTime': new_start_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC', }, end={ 'dateTime': new_end_date.strftime("%Y-%m-%dT%H:%M:%S.0000000"), 'timeZone': 'UTC', }, type="exception", ) ms_events_to_update = { events[i]['id']: events[i]['start'] for i in range(1, nb_of_events + 1) } mock_get_events.return_value = (MicrosoftEvent(events), None) # ----------- ACT ----------- self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() # ----------- ASSERT ----------- updated_events = self.env["calendar.event"].search([ ('ms_organizer_event_id', 'in', tuple(ms_events_to_update.keys())) ]) for e in updated_events: self.assertEqual( e.start.strftime("%Y-%m-%dT%H:%M:%S.0000000"), ms_events_to_update[e.ms_organizer_event_id]["dateTime"] )
41.56795
52,916
7,766
py
PYTHON
15.0
# -*- coding: utf-8 -*- from unittest.mock import patch, ANY from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_calendar.models.res_users import User from odoo.addons.microsoft_calendar.utils.event_id_storage import combine_ids from odoo.addons.microsoft_calendar.tests.common import TestCommon, mock_get_token, _modified_date_in_the_future, patch_api from odoo.tests import users import json @patch.object(User, '_get_microsoft_calendar_token', mock_get_token) class TestAnswerEvents(TestCommon): @patch_api def setUp(self): super().setUp() # a simple event self.simple_event = self.env["calendar.event"].search([("name", "=", "simple_event")]) if not self.simple_event: self.simple_event = self.env["calendar.event"].with_user(self.organizer_user).create( dict( self.simple_event_values, microsoft_id=combine_ids("123", "456"), ) ) @patch.object(MicrosoftCalendarService, 'patch') def test_attendee_accepts_event_from_odoo_calendar(self, mock_patch): attendee = self.env["calendar.attendee"].search([ ('event_id', '=', self.simple_event.id), ('partner_id', '=', self.attendee_user.partner_id.id) ]) attendee.with_user(self.attendee_user).do_accept() self.call_post_commit_hooks() self.simple_event.invalidate_cache() mock_patch.assert_called_once_with( self.simple_event.ms_organizer_event_id, { "attendees": [{ 'emailAddress': {'address': attendee.email or '', 'name': attendee.display_name or ''}, 'status': {'response': 'accepted'} }] }, token=mock_get_token(self.organizer_user), timeout=ANY, ) @patch.object(MicrosoftCalendarService, 'patch') def test_attendee_declines_event_from_odoo_calendar(self, mock_patch): attendee = self.env["calendar.attendee"].search([ ('event_id', '=', self.simple_event.id), ('partner_id', '=', self.attendee_user.partner_id.id) ]) attendee.with_user(self.attendee_user).do_decline() self.call_post_commit_hooks() self.simple_event.invalidate_cache() mock_patch.assert_called_once_with( self.simple_event.ms_organizer_event_id, { "attendees": [{ 'emailAddress': {'address': attendee.email or '', 'name': attendee.display_name or ''}, 'status': {'response': 'declined'} }] }, token=mock_get_token(self.organizer_user), timeout=ANY, ) @patch.object(MicrosoftCalendarService, 'get_events') def test_attendee_accepts_event_from_outlook_calendar(self, mock_get_events): """ In his Outlook calendar, the attendee accepts the event and sync with his odoo calendar. """ mock_get_events.return_value = ( MicrosoftEvent([dict( self.simple_event_from_outlook_organizer, attendees=[{ 'type': 'required', 'status': {'response': 'accepted', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': self.attendee_user.display_name, 'address': self.attendee_user.email} }], lastModifiedDateTime=_modified_date_in_the_future(self.simple_event) )]), None ) self.attendee_user.with_user(self.attendee_user).sudo()._sync_microsoft_calendar() attendee = self.env["calendar.attendee"].search([ ('event_id', '=', self.simple_event.id), ('partner_id', '=', self.attendee_user.partner_id.id) ]) self.assertEqual(attendee.state, "accepted") @patch.object(MicrosoftCalendarService, 'get_events') def test_attendee_accepts_event_from_outlook_calendar_synced_by_organizer(self, mock_get_events): """ In his Outlook calendar, the attendee accepts the event and the organizer syncs his odoo calendar. """ mock_get_events.return_value = ( MicrosoftEvent([dict( self.simple_event_from_outlook_organizer, attendees=[{ 'type': 'required', 'status': {'response': 'accepted', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': self.attendee_user.display_name, 'address': self.attendee_user.email} }], lastModifiedDateTime=_modified_date_in_the_future(self.simple_event) )]), None ) self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() attendee = self.env["calendar.attendee"].search([ ('event_id', '=', self.simple_event.id), ('partner_id', '=', self.attendee_user.partner_id.id) ]) self.assertEqual(attendee.state, "accepted") def test_attendee_declines_event_from_outlook_calendar(self): """ In his Outlook calendar, the attendee declines the event leading to automatically delete this event (that's the way Outlook handles it ...) LIMITATION: But, as there is no way to get the iCalUId to identify the corresponding Odoo event, there is no way to update the attendee status to "declined". """ @patch.object(MicrosoftCalendarService, 'get_events') def test_attendee_declines_event_from_outlook_calendar_synced_by_organizer(self, mock_get_events): """ In his Outlook calendar, the attendee declines the event leading to automatically delete this event (that's the way Outlook handles it ...) """ mock_get_events.return_value = ( MicrosoftEvent([dict( self.simple_event_from_outlook_organizer, attendees=[{ 'type': 'required', 'status': {'response': 'declined', 'time': '0001-01-01T00:00:00Z'}, 'emailAddress': {'name': self.attendee_user.display_name, 'address': self.attendee_user.email} }], lastModifiedDateTime=_modified_date_in_the_future(self.simple_event) )]), None ) self.organizer_user.with_user(self.organizer_user).sudo()._sync_microsoft_calendar() attendee = self.env["calendar.attendee"].search([ ('event_id', '=', self.simple_event.id), ('partner_id', '=', self.attendee_user.partner_id.id) ]) self.assertEqual(attendee.state, "declined") @users('admin') def test_sync_data_with_stopped_sync(self): self.authenticate(self.env.user.login, self.env.user.login) self.env['ir.config_parameter'].sudo().set_param( 'microsoft_calendar_client_id', 'test_microsoft_calendar_client_id' ) self.env.user.sudo().microsoft_calendar_rtoken = 'test_microsoft_calendar_rtoken' self.env.user.stop_microsoft_synchronization() payload = { 'params': { 'model': 'calendar.event' } } # Sending the request to the sync_data response = self.url_open( '/microsoft_calendar/sync_data', data=json.dumps(payload), headers={'Content-Type': 'application/json'} ).json() # the status must be sync_stopped self.assertEqual(response['result']['status'], 'sync_stopped')
42.67033
7,766
2,015
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.addons.microsoft_calendar.models.microsoft_sync import microsoft_calendar_token class ResetMicrosoftAccount(models.TransientModel): _name = 'microsoft.calendar.account.reset' _description = 'Microsoft Calendar Account Reset' user_id = fields.Many2one('res.users', required=True) delete_policy = fields.Selection( [('dont_delete', "Leave them untouched"), ('delete_microsoft', "Delete from the current Microsoft Calendar account"), ('delete_odoo', "Delete from Odoo"), ('delete_both', "Delete from both"), ], string="User's Existing Events", required=True, default='dont_delete', help="This will only affect events for which the user is the owner") sync_policy = fields.Selection([ ('new', "Synchronize only new events"), ('all', "Synchronize all existing events"), ], string="Next Synchronization", required=True, default='new') def reset_account(self): microsoft = self.env["calendar.event"]._get_microsoft_service() events = self.env['calendar.event'].search([ ('user_id', '=', self.user_id.id), ('ms_universal_event_id', '!=', False)]) if self.delete_policy in ('delete_microsoft', 'delete_both'): with microsoft_calendar_token(self.user_id) as token: for event in events: microsoft.delete(event.ms_universal_event_id, token=token) if self.delete_policy in ('delete_odoo', 'delete_both'): events.microsoft_id = False events.unlink() if self.sync_policy == 'all': events.write({ 'microsoft_id': False, 'need_sync_m': True, }) self.user_id._set_microsoft_auth_tokens(False, False, 0) self.user_id.write({ 'microsoft_calendar_sync_token': False, })
40.3
2,015
284
py
PYTHON
15.0
IDS_SEPARATOR = ':' def combine_ids(ms_id, ms_uid): if not ms_id: return False return ms_id + IDS_SEPARATOR + (ms_uid if ms_uid else '') def split_ids(value): ids = value.split(IDS_SEPARATOR) return tuple(ids) if len(ids) > 1 and ids[1] else (ids[0], False)
28.4
284
10,073
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.api import model from typing import Iterator, Mapping from collections import abc from odoo.addons.microsoft_calendar.utils.event_id_storage import combine_ids class MicrosoftEvent(abc.Set): """ This helper class holds the values of a Microsoft event. Inspired by Odoo recordset, one instance can be a single Microsoft event or a (immutable) set of Microsoft events. All usual set operations are supported (union, intersection, etc). :param iterable: iterable of MicrosoftCalendar instances or iterable of dictionnaries """ def __init__(self, iterable=()): self._events = {} for item in iterable: if isinstance(item, self.__class__): self._events[item.id] = item._events[item.id] elif isinstance(item, Mapping): self._events[item.get('id')] = item else: raise ValueError("Only %s or iterable of dict are supported" % self.__class__.__name__) def __iter__(self) -> Iterator['MicrosoftEvent']: return iter(MicrosoftEvent([vals]) for vals in self._events.values()) def __contains__(self, microsoft_event): return microsoft_event.id in self._events def __len__(self): return len(self._events) def __bool__(self): return bool(self._events) def __getattr__(self, name): # ensure_one try: event, = self._events.keys() except ValueError: raise ValueError("Expected singleton: %s" % self) event_id = list(self._events.keys())[0] return self._events[event_id].get(name) def __repr__(self): return '%s%s' % (self.__class__.__name__, self.ids) @property def ids(self): """ Use 'id' to return an event identifier which is specific to a calendar """ return tuple(e.id for e in self) def microsoft_ids(self): return tuple(e.id for e in self) @property def uids(self): """ Use 'iCalUid' to return an identifier which is unique accross all calendars """ return tuple(e.iCalUId for e in self) def odoo_id(self, env): return self._odoo_id def _meta_odoo_id(self, microsoft_guid): """Returns the Odoo id stored in the Microsoft Event metadata. This id might not actually exists in the database. """ return None @property def odoo_ids(self): """ Get the list of Odoo event ids already mapped with Outlook events (self) """ return tuple(e._odoo_id for e in self if e._odoo_id) def _load_odoo_ids_from_db(self, env, force_model=None): """ Map Microsoft events to existing Odoo events: 1) extract unmapped events only, 2) match Odoo events and Outlook events which have both a ICalUId set, 3) match remaining events, Returns the list of mapped events """ mapped_events = [e.id for e in self if e._odoo_id] # avoid mapping events if they are already all mapped if len(self) == len(mapped_events): return self unmapped_events = self.filter(lambda e: e.id not in mapped_events) model_env = force_model if force_model is not None else self._get_model(env) odoo_events = model_env.with_context(active_test=False).search([ '|', ('ms_universal_event_id', "in", unmapped_events.uids), ('ms_organizer_event_id', "in", unmapped_events.ids) ]).with_env(env) # 1. try to match unmapped events with Odoo events using their iCalUId unmapped_events_with_uids = unmapped_events.filter(lambda e: e.iCalUId) odoo_events_with_uids = odoo_events.filtered(lambda e: e.ms_universal_event_id) mapping = {e.ms_universal_event_id: e.id for e in odoo_events_with_uids} for ms_event in unmapped_events_with_uids: odoo_id = mapping.get(ms_event.iCalUId) if odoo_id: ms_event._events[ms_event.id]['_odoo_id'] = odoo_id mapped_events.append(ms_event.id) # 2. try to match unmapped events with Odoo events using their id unmapped_events = self.filter(lambda e: e.id not in mapped_events) mapping = {e.ms_organizer_event_id: e for e in odoo_events} for ms_event in unmapped_events: odoo_event = mapping.get(ms_event.id) if odoo_event: ms_event._events[ms_event.id]['_odoo_id'] = odoo_event.id mapped_events.append(ms_event.id) # don't forget to also set the global event ID on the Odoo event to ease # and improve reliability of future mappings odoo_event.write({ 'microsoft_id': combine_ids(ms_event.id, ms_event.iCalUId), 'need_sync_m': False, }) return self.filter(lambda e: e.id in mapped_events) def owner_id(self, env): """ Indicates who is the owner of an event (i.e the organizer of the event). There are several possible cases: 1) the current Odoo user is the organizer of the event according to Outlook event, so return his id. 2) the current Odoo user is NOT the organizer and: 2.1) we are able to find a Odoo user using the Outlook event organizer email address and we use his id, 2.2) we are NOT able to find a Odoo user matching the organizer email address and we return False, meaning that no Odoo user will be able to modify this event. All modifications will be done from Outlook. """ if self.isOrganizer: return env.user.id if self.organizer.get('emailAddress') and self.organizer.get('emailAddress').get('address'): # Warning: In Microsoft: 1 email = 1 user; but in Odoo several users might have the same email user = env['res.users'].search([('email', '=', self.organizer.get('emailAddress').get('address'))], limit=1) return user.id if user else False return False def filter(self, func) -> 'MicrosoftEvent': return MicrosoftEvent(e for e in self if func(e)) def is_recurrence(self): return self.type == 'seriesMaster' def is_recurrent(self): return bool(self.seriesMasterId or self.is_recurrence()) def is_recurrent_not_master(self): return bool(self.seriesMasterId) def get_recurrence(self): if not self.recurrence: return {} pattern = self.recurrence['pattern'] range = self.recurrence['range'] end_type_dict = { 'endDate': 'end_date', 'noEnd': 'forever', 'numbered': 'count', } type_dict = { 'absoluteMonthly': 'monthly', 'relativeMonthly': 'monthly', 'absoluteYearly': 'yearly', 'relativeYearly': 'yearly', } index_dict = { 'first': '1', 'second': '2', 'third': '3', 'fourth': '4', 'last': '-1', } rrule_type = type_dict.get(pattern['type'], pattern['type']) interval = pattern['interval'] if rrule_type == 'yearly': interval *= 12 result = { 'rrule_type': rrule_type, 'end_type': end_type_dict.get(range['type'], False), 'interval': interval, 'count': range['numberOfOccurrences'], 'day': pattern['dayOfMonth'], 'byday': index_dict.get(pattern['index'], False), 'until': range['type'] == 'endDate' and range['endDate'], } month_by_dict = { 'absoluteMonthly': 'date', 'relativeMonthly': 'day', 'absoluteYearly': 'date', 'relativeYearly': 'day', } month_by = month_by_dict.get(pattern['type'], False) if month_by: result['month_by'] = month_by # daysOfWeek contains the full name of the day, the fields contain the first 3 letters (mon, tue, etc) week_days = [x[:3] for x in pattern.get('daysOfWeek', [])] for week_day in ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']: result[week_day] = week_day in week_days if week_days: result['weekday'] = week_days[0].upper() return result def is_cancelled(self): return bool(self.isCancelled) or self.is_removed() def is_removed(self): return self.__getattr__('@removed') and self.__getattr__('@removed').get('reason') == 'deleted' def is_recurrence_outlier(self): return self.type == "exception" def cancelled(self): return self.filter(lambda e: e.is_cancelled()) def match_with_odoo_events(self, env) -> 'MicrosoftEvent': """ Match Outlook events (self) with existing Odoo events, and return the list of matched events """ # first, try to match recurrences # Note that when a recurrence is removed, there is no field in Outlook data to identify # the item as a recurrence, so select all deleted items by default. recurrence_candidates = self.filter(lambda x: x.is_recurrence() or x.is_removed()) mapped_recurrences = recurrence_candidates._load_odoo_ids_from_db(env, force_model=env["calendar.recurrence"]) # then, try to match events events_candidates = (self - mapped_recurrences).filter(lambda x: not x.is_recurrence()) mapped_events = events_candidates._load_odoo_ids_from_db(env) return mapped_recurrences | mapped_events def _get_model(self, env): if all(e.is_recurrence() for e in self): return env['calendar.recurrence'] if all(not e.is_recurrence() for e in self): return env['calendar.event'] raise TypeError("Mixing Microsoft events and Microsoft recurrences")
39.042636
10,073
8,808
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import requests import json import logging from werkzeug import urls from odoo import fields from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_account.models.microsoft_service import TIMEOUT, RESOURCE_NOT_FOUND_STATUSES _logger = logging.getLogger(__name__) def requires_auth_token(func): def wrapped(self, *args, **kwargs): if not kwargs.get('token'): raise AttributeError("An authentication token is required") return func(self, *args, **kwargs) return wrapped class InvalidSyncToken(Exception): pass # In Outlook, an event can be: # - a 'singleInstance' event, # - a 'serie master' which contains all the information about an event reccurrence such as # - an 'occurrence' which is an event from a reccurrence (serie) that follows this reccurrence # - an 'exception' which is an event from a reccurrence (serie) but some differences with the reccurrence template (could be # the name, the day of occurrence, ...) # # All these kinds of events are identified by: # - a event ID (id) which is specific to an Outlook calendar. # - a global event ID (iCalUId) which is common to all Outlook calendars containing this event. # # - 'singleInstance' and 'serie master' events are retrieved through the end-point `/v1.0/me/calendarView/delta` which provides # the last modified/deleted items since the last sync (or all of these items at the first time). # - 'occurrence' and 'exception' events are retrieved through the end-point `/v1.0/me/events/{serieMaster.id}/instances`, # using the corresponding serie master ID. class MicrosoftCalendarService(): def __init__(self, microsoft_service): self.microsoft_service = microsoft_service @requires_auth_token def _get_events_from_paginated_url(self, url, token=None, params=None, timeout=TIMEOUT): """ Get a list of events from a paginated URL. Each page contains a link to the next page, so loop over all the pages to get all the events. """ headers = { 'Content-type': 'application/json', 'Authorization': 'Bearer %s' % token, 'Prefer': 'outlook.body-content-type="html", odata.maxpagesize=50' } if not params: params = { 'startDateTime': fields.Datetime.subtract(fields.Datetime.now(), years=2).strftime("%Y-%m-%dT00:00:00Z"), 'endDateTime': fields.Datetime.add(fields.Datetime.now(), years=2).strftime("%Y-%m-%dT00:00:00Z"), } # get the first page of events _, data, _ = self.microsoft_service._do_request( url, params, headers, method='GET', timeout=timeout ) # and then, loop on other pages to get all the events events = data.get('value', []) next_page_token = data.get('@odata.nextLink') while next_page_token: _, data, _ = self.microsoft_service._do_request( next_page_token, {}, headers, preuri='', method='GET', timeout=timeout ) next_page_token = data.get('@odata.nextLink') events += data.get('value', []) token_url = data.get('@odata.deltaLink') next_sync_token = urls.url_parse(token_url).decode_query().get('$deltatoken', False) if token_url else None return events, next_sync_token @requires_auth_token def _get_events_delta(self, sync_token=None, token=None, timeout=TIMEOUT): """ Get a set of events that have been added, deleted or updated in a time range. See: https://docs.microsoft.com/en-us/graph/api/event-delta?view=graph-rest-1.0&tabs=http """ url = "/v1.0/me/calendarView/delta" params = {'$deltatoken': sync_token} if sync_token else None try: events, next_sync_token = self._get_events_from_paginated_url( url, params=params, token=token, timeout=timeout) except requests.HTTPError as e: if e.response.status_code == 410 and 'fullSyncRequired' in str(e.response.content) and sync_token: # retry with a full sync return self._get_events_delta(token=token, timeout=timeout) raise e # event occurrences (from a recurrence) are retrieved separately to get all their info, # # and mainly the iCalUId attribute which is not provided by the 'get_delta' api end point events = [e for e in events if e.get('type') != 'occurrence'] return MicrosoftEvent(events), next_sync_token @requires_auth_token def _get_occurrence_details(self, serieMasterId, token=None, timeout=TIMEOUT): """ Get all occurrences details from a serie master. See: https://docs.microsoft.com/en-us/graph/api/event-list-instances?view=graph-rest-1.0&tabs=http """ url = f"/v1.0/me/events/{serieMasterId}/instances" events, _ = self._get_events_from_paginated_url(url, token=token, timeout=timeout) return MicrosoftEvent(events) @requires_auth_token def get_events(self, sync_token=None, token=None, timeout=TIMEOUT): """ Retrieve all the events that have changed (added/updated/removed) from Microsoft Outlook. This is done in 2 steps: 1) get main changed events (so single events and serie masters) 2) get occurrences linked to a serie masters (to retrieve all needed details such as iCalUId) """ events, next_sync_token = self._get_events_delta(sync_token=sync_token, token=token, timeout=timeout) # get occurences details for all serie masters for master in filter(lambda e: e.type == 'seriesMaster', events): events |= self._get_occurrence_details(master.id, token=token, timeout=timeout) return events, next_sync_token @requires_auth_token def insert(self, values, token=None, timeout=TIMEOUT): url = "/v1.0/me/calendar/events" headers = {'Content-type': 'application/json', 'Authorization': 'Bearer %s' % token} _dummy, data, _dummy = self.microsoft_service._do_request(url, json.dumps(values), headers, method='POST', timeout=timeout) return data['id'], data['iCalUId'] @requires_auth_token def patch(self, event_id, values, token=None, timeout=TIMEOUT): url = "/v1.0/me/calendar/events/%s" % event_id headers = {'Content-type': 'application/json', 'Authorization': 'Bearer %s' % token} try: status, _dummy, _dummy = self.microsoft_service._do_request(url, json.dumps(values), headers, method='PATCH', timeout=timeout) except requests.HTTPError: _logger.info("Microsoft event %s has not been updated", event_id) return False return status not in RESOURCE_NOT_FOUND_STATUSES @requires_auth_token def delete(self, event_id, token=None, timeout=TIMEOUT): url = "/v1.0/me/calendar/events/%s" % event_id headers = {'Authorization': 'Bearer %s' % token} params = {} try: status, _dummy, _dummy = self.microsoft_service._do_request(url, params, headers=headers, method='DELETE', timeout=timeout) except requests.HTTPError as e: # For some unknown reason Microsoft can also return a 403 response when the event is already cancelled. status = e.response.status_code if status in (410, 403): _logger.info("Microsoft event %s was already deleted", event_id) else: raise e return status not in RESOURCE_NOT_FOUND_STATUSES @requires_auth_token def answer(self, event_id, answer, values, token=None, timeout=TIMEOUT): url = "/v1.0/me/calendar/events/%s/%s" % (event_id, answer) headers = {'Content-type': 'application/json', 'Authorization': 'Bearer %s' % token} status, _dummy, _dummy = self.microsoft_service._do_request(url, json.dumps(values), headers, method='POST', timeout=timeout) return status not in RESOURCE_NOT_FOUND_STATUSES ##################################### ## MANAGE CONNEXION TO MICROSOFT ## ##################################### def is_authorized(self, user): return bool(user.sudo().microsoft_calendar_rtoken) def _get_calendar_scope(self): return 'offline_access openid Calendars.ReadWrite' def _microsoft_authentication_url(self, from_url='http://www.odoo.com'): return self.microsoft_service._get_authorize_uri(from_url, service='calendar', scope=self._get_calendar_scope()) def _can_authorize_microsoft(self, user): return user.has_group('base.group_erp_manager')
45.169231
8,808
1,890
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models from odoo.addons.microsoft_calendar.models.microsoft_sync import microsoft_calendar_token from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService class Attendee(models.Model): _name = 'calendar.attendee' _inherit = 'calendar.attendee' def _send_mail_to_attendees(self, mail_template, force_send=False): """ Override the super method If not synced with Microsoft Outlook, let Odoo in charge of sending emails Otherwise, Microsoft Outlook will send them """ with microsoft_calendar_token(self.env.user.sudo()) as token: if not token: super()._send_mail_to_attendees(mail_template, force_send) def do_tentative(self): # Synchronize event after state change res = super().do_tentative() self._microsoft_sync_event('tentativelyAccept') return res def do_accept(self): # Synchronize event after state change res = super().do_accept() self._microsoft_sync_event('accept') return res def do_decline(self): # Synchronize event after state change res = super().do_decline() self._microsoft_sync_event('decline') return res def _microsoft_sync_event(self, answer): params = {"comment": "", "sendResponse": True} # Microsoft prevent user to answer the meeting when they are the organizer linked_events = self.event_id._get_synced_events() for event in linked_events.filtered(lambda e: e.user_id != self.env.user): event._microsoft_patch( event._get_organizer(), event.ms_organizer_event_id, event._microsoft_values(["attendee_ids"]), )
37.058824
1,890
22,867
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from contextlib import contextmanager from functools import wraps import pytz from dateutil.parser import parse from odoo import api, fields, models, registry from odoo.tools import ormcache_context from odoo.exceptions import UserError from odoo.osv import expression from odoo.addons.microsoft_calendar.utils.microsoft_event import MicrosoftEvent from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService from odoo.addons.microsoft_calendar.utils.event_id_storage import IDS_SEPARATOR, combine_ids, split_ids from odoo.addons.microsoft_account.models.microsoft_service import TIMEOUT _logger = logging.getLogger(__name__) MAX_RECURRENT_EVENT = 720 # API requests are sent to Microsoft Calendar after the current transaction ends. # This ensures changes are sent to Microsoft only if they really happened in the Odoo database. # It is particularly important for event creation , otherwise the event might be created # twice in Microsoft if the first creation crashed in Odoo. def after_commit(func): @wraps(func) def wrapped(self, *args, **kwargs): dbname = self.env.cr.dbname context = self.env.context uid = self.env.uid if self.env.context.get('no_calendar_sync'): return @self.env.cr.postcommit.add def called_after(): db_registry = registry(dbname) with db_registry.cursor() as cr: env = api.Environment(cr, uid, context) try: func(self.with_env(env), *args, **kwargs) except Exception as e: _logger.warning("Could not sync record now: %s" % self) _logger.exception(e) return wrapped @contextmanager def microsoft_calendar_token(user): yield user._get_microsoft_calendar_token() class MicrosoftSync(models.AbstractModel): _name = 'microsoft.calendar.sync' _description = "Synchronize a record with Microsoft Calendar" microsoft_id = fields.Char('Microsoft Calendar Id', copy=False) ms_organizer_event_id = fields.Char( 'Organizer event Id', compute='_compute_organizer_event_id', inverse='_set_event_id', search='_search_organizer_event_id', ) ms_universal_event_id = fields.Char( 'Universal event Id', compute='_compute_universal_event_id', inverse='_set_event_id', search='_search_universal_event_id', ) # This field helps to know when a microsoft event need to be resynced need_sync_m = fields.Boolean(default=True, copy=False) active = fields.Boolean(default=True) def write(self, vals): if 'ms_universal_event_id' in vals: self._from_uids.clear_cache(self) fields_to_sync = [x for x in vals.keys() if x in self._get_microsoft_synced_fields()] if fields_to_sync and 'need_sync_m' not in vals and not self.env.user.microsoft_synchronization_stopped: vals['need_sync_m'] = True result = super().write(vals) for record in self.filtered(lambda e: e.need_sync_m and e.ms_organizer_event_id): if not vals.get('active', True): # We need to delete the event. Cancel is not sufficant. Errors may occurs record._microsoft_delete(record._get_organizer(), record.ms_organizer_event_id, timeout=3) elif fields_to_sync: values = record._microsoft_values(fields_to_sync) if not values: continue record._microsoft_patch(record._get_organizer(), record.ms_organizer_event_id, values, timeout=3) return result @api.model_create_multi def create(self, vals_list): if self.env.user.microsoft_synchronization_stopped: for vals in vals_list: vals.update({'need_sync_m': False}) records = super().create(vals_list) records_to_sync = records.filtered(lambda r: r.need_sync_m and r.active) for record in records_to_sync: record._microsoft_insert(record._microsoft_values(self._get_microsoft_synced_fields()), timeout=3) return records @api.depends('microsoft_id') def _compute_organizer_event_id(self): for event in self: event.ms_organizer_event_id = split_ids(event.microsoft_id)[0] if event.microsoft_id else False @api.depends('microsoft_id') def _compute_universal_event_id(self): for event in self: event.ms_universal_event_id = split_ids(event.microsoft_id)[1] if event.microsoft_id else False def _set_event_id(self): for event in self: event.microsoft_id = combine_ids(event.ms_organizer_event_id, event.ms_universal_event_id) def _search_event_id(self, operator, value, with_uid): def _domain(v): return ('microsoft_id', '=like', f'%{IDS_SEPARATOR}{v}' if with_uid else f'{v}%') if operator == '=' and not value: return ( ['|', ('microsoft_id', '=', False), ('microsoft_id', '=ilike', f'%{IDS_SEPARATOR}')] if with_uid else [('microsoft_id', '=', False)] ) elif operator == '!=' and not value: return ( [('microsoft_id', 'ilike', f'{IDS_SEPARATOR}_')] if with_uid else [('microsoft_id', '!=', False)] ) return ( ['|'] * (len(value) - 1) + [_domain(v) for v in value] if operator.lower() == 'in' else [_domain(value)] ) def _search_organizer_event_id(self, operator, value): return self._search_event_id(operator, value, with_uid=False) def _search_universal_event_id(self, operator, value): return self._search_event_id(operator, value, with_uid=True) @api.model def _get_microsoft_service(self): return MicrosoftCalendarService(self.env['microsoft.service']) def _get_synced_events(self): """ Get events already synced with Microsoft Outlook. """ return self.filtered(lambda e: e.ms_universal_event_id) def unlink(self): synced = self._get_synced_events() for ev in synced: ev._microsoft_delete(ev._get_organizer(), ev.ms_organizer_event_id) return super().unlink() def _write_from_microsoft(self, microsoft_event, vals): self.write(vals) @api.model def _create_from_microsoft(self, microsoft_event, vals_list): return self.create(vals_list) @api.model @ormcache_context('uids', keys=('active_test',)) def _from_uids(self, uids): if not uids: return self.browse() return self.search([('ms_universal_event_id', 'in', uids)]) def _sync_odoo2microsoft(self): if not self: return if self._active_name: records_to_sync = self.filtered(self._active_name) else: records_to_sync = self cancelled_records = self - records_to_sync records_to_sync._ensure_attendees_have_email() updated_records = records_to_sync._get_synced_events() new_records = records_to_sync - updated_records for record in cancelled_records._get_synced_events(): record._microsoft_delete(record._get_organizer(), record.ms_organizer_event_id) for record in new_records: values = record._microsoft_values(self._get_microsoft_synced_fields()) if isinstance(values, dict): record._microsoft_insert(values) else: for value in values: record._microsoft_insert(value) for record in updated_records.filtered('need_sync_m'): values = record._microsoft_values(self._get_microsoft_synced_fields()) if not values: continue record._microsoft_patch(record._get_organizer(), record.ms_organizer_event_id, values) def _cancel_microsoft(self): self.microsoft_id = False self.unlink() def _sync_recurrence_microsoft2odoo(self, microsoft_events, new_events=None): recurrent_masters = new_events.filter(lambda e: e.is_recurrence()) if new_events else [] recurrents = new_events.filter(lambda e: e.is_recurrent_not_master()) if new_events else [] default_values = {'need_sync_m': False} new_recurrence = self.env['calendar.recurrence'] updated_events = self.env['calendar.event'] # --- create new recurrences and associated events --- for recurrent_master in recurrent_masters: new_calendar_recurrence = dict( self.env['calendar.recurrence']._microsoft_to_odoo_values(recurrent_master, default_values, with_ids=True), need_sync_m=False ) to_create = recurrents.filter( lambda e: e.seriesMasterId == new_calendar_recurrence['ms_organizer_event_id'] ) recurrents -= to_create base_values = dict( self.env['calendar.event']._microsoft_to_odoo_values(recurrent_master, default_values, with_ids=True), need_sync_m=False ) to_create_values = [] if new_calendar_recurrence.get('end_type', False) in ['count', 'forever']: to_create = list(to_create)[:MAX_RECURRENT_EVENT] for recurrent_event in to_create: if recurrent_event.type == 'occurrence': value = self.env['calendar.event']._microsoft_to_odoo_recurrence_values(recurrent_event, base_values) else: value = self.env['calendar.event']._microsoft_to_odoo_values(recurrent_event, default_values) to_create_values += [dict(value, need_sync_m=False)] new_calendar_recurrence['calendar_event_ids'] = [(0, 0, to_create_value) for to_create_value in to_create_values] new_recurrence_odoo = self.env['calendar.recurrence'].create(new_calendar_recurrence) new_recurrence_odoo.base_event_id = new_recurrence_odoo.calendar_event_ids[0] if new_recurrence_odoo.calendar_event_ids else False new_recurrence |= new_recurrence_odoo # --- update events in existing recurrences --- # Important note: # To map existing recurrences with events to update, we must use the universal id # (also known as ICalUId in the Microsoft API), as 'seriesMasterId' attribute of events # is specific to the Microsoft user calendar. ms_recurrence_ids = list({x.seriesMasterId for x in recurrents}) ms_recurrence_uids = {r.id: r.iCalUId for r in microsoft_events if r.id in ms_recurrence_ids} recurrences = self.env['calendar.recurrence'].search([ ('ms_universal_event_id', 'in', ms_recurrence_uids.values()) ]) for recurrent_master_id in ms_recurrence_ids: recurrence_id = recurrences.filtered( lambda ev: ev.ms_universal_event_id == ms_recurrence_uids[recurrent_master_id] ) to_update = recurrents.filter(lambda e: e.seriesMasterId == recurrent_master_id) for recurrent_event in to_update: if recurrent_event.type == 'occurrence': value = self.env['calendar.event']._microsoft_to_odoo_recurrence_values( recurrent_event, {'need_sync_m': False} ) else: value = self.env['calendar.event']._microsoft_to_odoo_values(recurrent_event, default_values) existing_event = recurrence_id.calendar_event_ids.filtered( lambda e: e._is_matching_timeslot(value['start'], value['stop'], recurrent_event.isAllDay) ) if not existing_event: continue value.pop('start') value.pop('stop') existing_event._write_from_microsoft(recurrent_event, value) updated_events |= existing_event new_recurrence |= recurrence_id return new_recurrence, updated_events def _update_microsoft_recurrence(self, recurrence, events): """ Update Odoo events from Outlook recurrence and events. """ # get the list of events to update ... events_to_update = events.filter(lambda e: e.seriesMasterId == self.ms_organizer_event_id) if self.end_type in ['count', 'forever']: events_to_update = list(events_to_update)[:MAX_RECURRENT_EVENT] # ... and update them rec_values = {} update_events = self.env['calendar.event'] for e in events_to_update: if e.type == "exception": event_values = self.env['calendar.event']._microsoft_to_odoo_values(e) elif e.type == "occurrence": event_values = self.env['calendar.event']._microsoft_to_odoo_recurrence_values(e) else: event_values = None if event_values: # keep event values to update the recurrence later if any(f for f in ('start', 'stop') if f in event_values): rec_values[(self.id, event_values.get('start'), event_values.get('stop'))] = dict( event_values, need_sync_m=False ) odoo_event = self.env['calendar.event'].browse(e.odoo_id(self.env)).exists().with_context( no_mail_to_attendees=True, mail_create_nolog=True ) odoo_event.write(dict(event_values, need_sync_m=False)) update_events |= odoo_event # update the recurrence detached_events = self._apply_recurrence(rec_values) detached_events._cancel_microsoft() return update_events @api.model def _sync_microsoft2odoo(self, microsoft_events: MicrosoftEvent): """ Synchronize Microsoft recurrences in Odoo. Creates new recurrences, updates existing ones. :return: synchronized odoo """ existing = microsoft_events.match_with_odoo_events(self.env) cancelled = microsoft_events.cancelled() new = microsoft_events - existing - cancelled new_recurrence = new.filter(lambda e: e.is_recurrent()) # create new events and reccurrences odoo_values = [ dict(self._microsoft_to_odoo_values(e, with_ids=True), need_sync_m=False) for e in (new - new_recurrence) ] synced_events = self.with_context(dont_notify=True)._create_from_microsoft(new, odoo_values) synced_recurrences, updated_events = self._sync_recurrence_microsoft2odoo(existing, new_recurrence) synced_events |= updated_events # remove cancelled events and recurrences cancelled_recurrences = self.env['calendar.recurrence'].search([ '|', ('ms_universal_event_id', 'in', cancelled.uids), ('ms_organizer_event_id', 'in', cancelled.ids), ]) cancelled_events = self.browse([ e.odoo_id(self.env) for e in cancelled if e.id not in [r.ms_organizer_event_id for r in cancelled_recurrences] ]) cancelled_recurrences._cancel_microsoft() cancelled_events = cancelled_events.exists() cancelled_events._cancel_microsoft() synced_recurrences |= cancelled_recurrences synced_events |= cancelled_events | cancelled_recurrences.calendar_event_ids # update other events for mevent in (existing - cancelled).filter(lambda e: e.lastModifiedDateTime): # Last updated wins. # This could be dangerous if microsoft server time and odoo server time are different if mevent.is_recurrence(): odoo_event = self.env['calendar.recurrence'].browse(mevent.odoo_id(self.env)).exists() else: odoo_event = self.browse(mevent.odoo_id(self.env)).exists() if odoo_event: odoo_event_updated_time = pytz.utc.localize(odoo_event.write_date) ms_event_updated_time = parse(mevent.lastModifiedDateTime) if ms_event_updated_time >= odoo_event_updated_time: vals = dict(odoo_event._microsoft_to_odoo_values(mevent), need_sync_m=False) odoo_event._write_from_microsoft(mevent, vals) if odoo_event._name == 'calendar.recurrence': update_events = odoo_event._update_microsoft_recurrence(mevent, microsoft_events) synced_recurrences |= odoo_event synced_events |= update_events else: synced_events |= odoo_event return synced_events, synced_recurrences def _impersonate_user(self, user_id): """ Impersonate a user (mainly the event organizer) to be able to call the Outlook API with its token """ return user_id.with_user(user_id) @after_commit def _microsoft_delete(self, user_id, event_id, timeout=TIMEOUT): """ Once the event has been really removed from the Odoo database, remove it from the Outlook calendar. Note that all self attributes to use in this method must be provided as method parameters because 'self' won't exist when this method will be really called due to @after_commit decorator. """ microsoft_service = self._get_microsoft_service() with microsoft_calendar_token(self._impersonate_user(user_id).sudo()) as token: if token: microsoft_service.delete(event_id, token=token, timeout=timeout) @after_commit def _microsoft_patch(self, user_id, event_id, values, timeout=TIMEOUT): """ Once the event has been really modified in the Odoo database, modify it in the Outlook calendar. Note that all self attributes to use in this method must be provided as method parameters because 'self' may have been modified between the call of '_microsoft_patch' and its execution, due to @after_commit decorator. """ microsoft_service = self._get_microsoft_service() with microsoft_calendar_token(self._impersonate_user(user_id).sudo()) as token: if token: self._ensure_attendees_have_email() res = microsoft_service.patch(event_id, values, token=token, timeout=timeout) self.write({ 'need_sync_m': not res, }) @after_commit def _microsoft_insert(self, values, timeout=TIMEOUT): """ Once the event has been really added in the Odoo database, add it in the Outlook calendar. Note that all self attributes to use in this method must be provided as method parameters because 'self' may have been modified between the call of '_microsoft_insert' and its execution, due to @after_commit decorator. """ if not values: return microsoft_service = self._get_microsoft_service() with microsoft_calendar_token(self.env.user.sudo()) as token: if token: self._ensure_attendees_have_email() event_id, uid = microsoft_service.insert(values, token=token, timeout=timeout) self.write({ 'microsoft_id': combine_ids(event_id, uid), 'need_sync_m': False, }) def _microsoft_attendee_answer(self, answer, params, timeout=TIMEOUT): if not answer: return microsoft_service = self._get_microsoft_service() with microsoft_calendar_token(self.env.user.sudo()) as token: if token: self._ensure_attendees_have_email() microsoft_service.answer( self.ms_organizer_event_id, answer, params, token=token, timeout=timeout ) self.write({ 'need_sync_m': False, }) def _get_microsoft_records_to_sync(self, full_sync=False): """ Return records that should be synced from Odoo to Microsoft :param full_sync: If True, all events attended by the user are returned :return: events """ domain = self.with_context(full_sync_m=full_sync)._get_microsoft_sync_domain() return self.with_context(active_test=False).search(domain) @api.model def _microsoft_to_odoo_values( self, microsoft_event: MicrosoftEvent, default_reminders=(), default_values=None, with_ids=False ): """ Implements this method to return a dict of Odoo values corresponding to the Microsoft event given as parameter :return: dict of Odoo formatted values """ raise NotImplementedError() def _microsoft_values(self, fields_to_sync): """ Implements this method to return a dict with values formatted according to the Microsoft Calendar API :return: dict of Microsoft formatted values """ raise NotImplementedError() def _ensure_attendees_have_email(self): raise NotImplementedError() def _get_microsoft_sync_domain(self): """ Return a domain used to search records to synchronize. e.g. return a domain to synchronize records owned by the current user. """ raise NotImplementedError() def _get_microsoft_synced_fields(self): """ Return a set of field names. Changing one of these fields marks the record to be re-synchronized. """ raise NotImplementedError() @api.model def _restart_microsoft_sync(self): """ Turns on the microsoft synchronization for all the events of a given user. """ raise NotImplementedError() def _extend_microsoft_domain(self, domain): """ Extends the sync domain based on the full_sync_m context parameter. In case of full sync it shouldn't include already synced events. """ if self._context.get('full_sync_m', True): domain = expression.AND([domain, [('ms_universal_event_id', '=', False)]]) else: is_active_clause = (self._active_name, '=', True) if self._active_name else expression.TRUE_LEAF domain = expression.AND([domain, [ '|', '&', ('ms_universal_event_id', '=', False), is_active_clause, ('need_sync_m', '=', True), ]]) return domain
43.226843
22,867
22,994
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pytz from datetime import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from odoo import api, fields, models, _ from odoo.exceptions import UserError, ValidationError from odoo.tools import is_html_empty, email_normalize from odoo.addons.microsoft_calendar.utils.event_id_storage import combine_ids ATTENDEE_CONVERTER_O2M = { 'needsAction': 'notresponded', 'tentative': 'tentativelyaccepted', 'declined': 'declined', 'accepted': 'accepted' } ATTENDEE_CONVERTER_M2O = { 'none': 'needsAction', 'notResponded': 'needsAction', 'tentativelyAccepted': 'tentative', 'declined': 'declined', 'accepted': 'accepted', 'organizer': 'accepted', } MAX_RECURRENT_EVENT = 720 _logger = logging.getLogger(__name__) class Meeting(models.Model): _name = 'calendar.event' _inherit = ['calendar.event', 'microsoft.calendar.sync'] # contains organizer event id and universal event id separated by a ':' microsoft_id = fields.Char('Microsoft Calendar Event Id') microsoft_recurrence_master_id = fields.Char('Microsoft Recurrence Master Id') def _get_organizer(self): return self.user_id @api.model def _get_microsoft_synced_fields(self): return {'name', 'description', 'allday', 'start', 'date_end', 'stop', 'user_id', 'privacy', 'attendee_ids', 'alarm_ids', 'location', 'show_as', 'active'} @api.model def _restart_microsoft_sync(self): self.env['calendar.event'].search(self._get_microsoft_sync_domain()).write({ 'need_sync_m': True, }) @api.model_create_multi def create(self, vals_list): notify_context = self.env.context.get('dont_notify', False) # for a recurrent event, we do not create events separately but we directly # create the recurrency from the corresponding calendar.recurrence. # That's why, events from a recurrency have their `need_sync_m` attribute set to False. return super(Meeting, self.with_context(dont_notify=notify_context)).create([ dict(vals, need_sync_m=False) if vals.get('recurrence_id') or vals.get('recurrency') else vals for vals in vals_list ]) def _check_recurrence_overlapping(self, new_start): """ Outlook does not allow to modify time fields of an event if this event crosses or overlaps the recurrence. In this case a 400 error with the Outlook code "ErrorOccurrenceCrossingBoundary" is returned. That means that the update violates the following Outlook restriction on recurrence exceptions: an occurrence cannot be moved to or before the day of the previous occurrence, and cannot be moved to or after the day of the following occurrence. For example: E1 E2 E3 E4 cannot becomes E1 E3 E2 E4 """ before_count = len(self.recurrence_id.calendar_event_ids.filtered( lambda e: e.start.date() < self.start.date() and e != self )) after_count = len(self.recurrence_id.calendar_event_ids.filtered( lambda e: e.start.date() < parse(new_start).date() and e != self )) if before_count != after_count: raise UserError(_( "Outlook limitation: in a recurrence, an event cannot be moved to or before the day of the " "previous event, and cannot be moved to or after the day of the following event." )) def _is_matching_timeslot(self, start, stop, allday): """ Check if an event matches with the provided timeslot """ self.ensure_one() event_start, event_stop = self._range() if allday: event_start = datetime(event_start.year, event_start.month, event_start.day, 0, 0) event_stop = datetime(event_stop.year, event_stop.month, event_stop.day, 0, 0) return (event_start, event_stop) == (start, stop) def write(self, values): recurrence_update_setting = values.get('recurrence_update') # check a Outlook limitation in overlapping the actual recurrence if recurrence_update_setting == 'self_only' and 'start' in values: self._check_recurrence_overlapping(values['start']) # if a single event becomes the base event of a recurrency, it should be first # removed from the Outlook calendar. if 'recurrency' in values and values['recurrency']: for e in self.filtered(lambda e: not e.recurrency and not e.recurrence_id): e._microsoft_delete(e._get_organizer(), e.ms_organizer_event_id, timeout=3) e.microsoft_id = False notify_context = self.env.context.get('dont_notify', False) res = super(Meeting, self.with_context(dont_notify=notify_context)).write(values) if recurrence_update_setting in ('all_events',) and len(self) == 1 \ and values.keys() & self._get_microsoft_synced_fields(): self.recurrence_id.need_sync_m = True return res def _get_microsoft_sync_domain(self): # in case of full sync, limit to a range of 1y in past and 1y in the future by default ICP = self.env['ir.config_parameter'].sudo() day_range = int(ICP.get_param('microsoft_calendar.sync.range_days', default=365)) lower_bound = fields.Datetime.subtract(fields.Datetime.now(), days=day_range) upper_bound = fields.Datetime.add(fields.Datetime.now(), days=day_range) domain = [ ('partner_ids.user_ids', 'in', self.env.user.id), ('stop', '>', lower_bound), ('start', '<', upper_bound), # Do not sync events that follow the recurrence, they are already synced at recurrence creation '!', '&', '&', ('recurrency', '=', True), ('recurrence_id', '!=', False), ('follow_recurrence', '=', True) ] return self._extend_microsoft_domain(domain) @api.model def _microsoft_to_odoo_values(self, microsoft_event, default_reminders=(), default_values=None, with_ids=False): if microsoft_event.is_cancelled(): return {'active': False} sensitivity_o2m = { 'normal': 'public', 'private': 'private', 'confidential': 'confidential', } commands_attendee, commands_partner = self._odoo_attendee_commands_m(microsoft_event) timeZone_start = pytz.timezone(microsoft_event.start.get('timeZone')) timeZone_stop = pytz.timezone(microsoft_event.end.get('timeZone')) start = parse(microsoft_event.start.get('dateTime')).astimezone(timeZone_start).replace(tzinfo=None) if microsoft_event.isAllDay: stop = parse(microsoft_event.end.get('dateTime')).astimezone(timeZone_stop).replace(tzinfo=None) - relativedelta(days=1) else: stop = parse(microsoft_event.end.get('dateTime')).astimezone(timeZone_stop).replace(tzinfo=None) values = default_values or {} values.update({ 'name': microsoft_event.subject or _("(No title)"), 'description': microsoft_event.body and microsoft_event.body['content'], 'location': microsoft_event.location and microsoft_event.location.get('displayName') or False, 'user_id': microsoft_event.owner_id(self.env), 'privacy': sensitivity_o2m.get(microsoft_event.sensitivity, self.default_get(['privacy'])['privacy']), 'attendee_ids': commands_attendee, 'allday': microsoft_event.isAllDay, 'start': start, 'stop': stop, 'show_as': 'free' if microsoft_event.showAs == 'free' else 'busy', 'recurrency': microsoft_event.is_recurrent() }) if commands_partner: # Add partner_commands only if set from Microsoft. The write method on calendar_events will # override attendee commands if the partner_ids command is set but empty. values['partner_ids'] = commands_partner if microsoft_event.is_recurrent() and not microsoft_event.is_recurrence(): # Propagate the follow_recurrence according to the Outlook result values['follow_recurrence'] = not microsoft_event.is_recurrence_outlier() if with_ids: values['microsoft_id'] = combine_ids(microsoft_event.id, microsoft_event.iCalUId) if microsoft_event.is_recurrent(): values['microsoft_recurrence_master_id'] = microsoft_event.seriesMasterId alarm_commands = self._odoo_reminders_commands_m(microsoft_event) if alarm_commands: values['alarm_ids'] = alarm_commands return values @api.model def _microsoft_to_odoo_recurrence_values(self, microsoft_event, default_values=None): timeZone_start = pytz.timezone(microsoft_event.start.get('timeZone')) timeZone_stop = pytz.timezone(microsoft_event.end.get('timeZone')) start = parse(microsoft_event.start.get('dateTime')).astimezone(timeZone_start).replace(tzinfo=None) if microsoft_event.isAllDay: stop = parse(microsoft_event.end.get('dateTime')).astimezone(timeZone_stop).replace(tzinfo=None) - relativedelta(days=1) else: stop = parse(microsoft_event.end.get('dateTime')).astimezone(timeZone_stop).replace(tzinfo=None) values = default_values or {} values.update({ 'microsoft_id': combine_ids(microsoft_event.id, microsoft_event.iCalUId), 'microsoft_recurrence_master_id': microsoft_event.seriesMasterId, 'start': start, 'stop': stop, }) return values @api.model def _odoo_attendee_commands_m(self, microsoft_event): commands_attendee = [] commands_partner = [] microsoft_attendees = microsoft_event.attendees or [] emails = [ a.get('emailAddress').get('address') for a in microsoft_attendees if email_normalize(a.get('emailAddress').get('address')) ] existing_attendees = self.env['calendar.attendee'] if microsoft_event.match_with_odoo_events(self.env): existing_attendees = self.env['calendar.attendee'].search([ ('event_id', '=', microsoft_event.odoo_id(self.env)), ('email', 'in', emails)]) elif self.env.user.partner_id.email not in emails: commands_attendee += [(0, 0, {'state': 'accepted', 'partner_id': self.env.user.partner_id.id})] commands_partner += [(4, self.env.user.partner_id.id)] partners = self.env['mail.thread']._mail_find_partner_from_emails(emails, records=self, force_create=True) attendees_by_emails = {a.email: a for a in existing_attendees} for email, partner, attendee_info in zip(emails, partners, microsoft_attendees): state = ATTENDEE_CONVERTER_M2O.get(attendee_info.get('status').get('response'), 'needsAction') if email in attendees_by_emails: # Update existing attendees commands_attendee += [(1, attendees_by_emails[email].id, {'state': state})] elif partner: # Create new attendees commands_attendee += [(0, 0, {'state': state, 'partner_id': partner.id})] commands_partner += [(4, partner.id)] if attendee_info.get('emailAddress').get('name') and not partner.name: partner.name = attendee_info.get('emailAddress').get('name') for odoo_attendee in attendees_by_emails.values(): # Remove old attendees if odoo_attendee.email not in emails: commands_attendee += [(2, odoo_attendee.id)] commands_partner += [(3, odoo_attendee.partner_id.id)] return commands_attendee, commands_partner @api.model def _odoo_reminders_commands_m(self, microsoft_event): reminders_commands = [] if microsoft_event.isReminderOn: event_id = self.browse(microsoft_event.odoo_id(self.env)) alarm_type_label = _("Notification") minutes = microsoft_event.reminderMinutesBeforeStart or 0 alarm = self.env['calendar.alarm'].search([ ('alarm_type', '=', 'notification'), ('duration_minutes', '=', minutes) ], limit=1) if alarm and alarm not in event_id.alarm_ids: reminders_commands = [(4, alarm.id)] elif not alarm: if minutes == 0: interval = 'minutes' duration = minutes name = _("%s - At time of event", alarm_type_label) elif minutes % (60*24) == 0: interval = 'days' duration = minutes / 60 / 24 name = _( "%(reminder_type)s - %(duration)s Days", reminder_type=alarm_type_label, duration=duration, ) elif minutes % 60 == 0: interval = 'hours' duration = minutes / 60 name = _( "%(reminder_type)s - %(duration)s Hours", reminder_type=alarm_type_label, duration=duration, ) else: interval = 'minutes' duration = minutes name = _( "%(reminder_type)s - %(duration)s Minutes", reminder_type=alarm_type_label, duration=duration, ) reminders_commands = [(0, 0, {'duration': duration, 'interval': interval, 'name': name, 'alarm_type': 'notification'})] alarm_to_rm = event_id.alarm_ids.filtered(lambda a: a.alarm_type == 'notification' and a.id != alarm.id) if alarm_to_rm: reminders_commands += [(3, a.id) for a in alarm_to_rm] else: event_id = self.browse(microsoft_event.odoo_id(self.env)) alarm_to_rm = event_id.alarm_ids.filtered(lambda a: a.alarm_type == 'notification') if alarm_to_rm: reminders_commands = [(3, a.id) for a in alarm_to_rm] return reminders_commands def _get_attendee_status_o2m(self, attendee): if self.user_id and self.user_id == attendee.partner_id.user_id: return 'organizer' return ATTENDEE_CONVERTER_O2M.get(attendee.state, 'None') def _microsoft_values(self, fields_to_sync, initial_values={}): values = dict(initial_values) if not fields_to_sync: return values microsoft_guid = self.env['ir.config_parameter'].sudo().get_param('microsoft_calendar.microsoft_guid', False) if self.microsoft_recurrence_master_id and 'type' not in values: values['seriesMasterId'] = self.microsoft_recurrence_master_id values['type'] = 'exception' if 'name' in fields_to_sync: values['subject'] = self.name or '' if 'description' in fields_to_sync: values['body'] = { 'content': self.description if not is_html_empty(self.description) else '', 'contentType': "html", } if any(x in fields_to_sync for x in ['allday', 'start', 'date_end', 'stop']): if self.allday: start = {'dateTime': self.start_date.isoformat(), 'timeZone': 'Europe/London'} end = {'dateTime': (self.stop_date + relativedelta(days=1)).isoformat(), 'timeZone': 'Europe/London'} else: start = {'dateTime': pytz.utc.localize(self.start).isoformat(), 'timeZone': 'Europe/London'} end = {'dateTime': pytz.utc.localize(self.stop).isoformat(), 'timeZone': 'Europe/London'} values['start'] = start values['end'] = end values['isAllDay'] = self.allday if 'location' in fields_to_sync: values['location'] = {'displayName': self.location or ''} if 'alarm_ids' in fields_to_sync: alarm_id = self.alarm_ids.filtered(lambda a: a.alarm_type == 'notification')[:1] values['isReminderOn'] = bool(alarm_id) values['reminderMinutesBeforeStart'] = alarm_id.duration_minutes if 'user_id' in fields_to_sync: values['organizer'] = {'emailAddress': {'address': self.user_id.email or '', 'name': self.user_id.display_name or ''}} values['isOrganizer'] = self.user_id == self.env.user if 'attendee_ids' in fields_to_sync: attendees = self.attendee_ids.filtered(lambda att: att.partner_id not in self.user_id.partner_id) values['attendees'] = [ { 'emailAddress': {'address': attendee.email or '', 'name': attendee.display_name or ''}, 'status': {'response': self._get_attendee_status_o2m(attendee)} } for attendee in attendees] if 'privacy' in fields_to_sync or 'show_as' in fields_to_sync: values['showAs'] = self.show_as sensitivity_o2m = { 'public': 'normal', 'private': 'private', 'confidential': 'confidential', } values['sensitivity'] = sensitivity_o2m.get(self.privacy) if 'active' in fields_to_sync and not self.active: values['isCancelled'] = True if values.get('type') == 'seriesMaster': recurrence = self.recurrence_id pattern = { 'interval': recurrence.interval } if recurrence.rrule_type in ['daily', 'weekly']: pattern['type'] = recurrence.rrule_type else: prefix = 'absolute' if recurrence.month_by == 'date' else 'relative' pattern['type'] = recurrence.rrule_type and prefix + recurrence.rrule_type.capitalize() if recurrence.month_by == 'date': pattern['dayOfMonth'] = recurrence.day if recurrence.month_by == 'day' or recurrence.rrule_type == 'weekly': pattern['daysOfWeek'] = [ weekday_name for weekday_name, weekday in { 'monday': recurrence.mon, 'tuesday': recurrence.tue, 'wednesday': recurrence.wed, 'thursday': recurrence.thu, 'friday': recurrence.fri, 'saturday': recurrence.sat, 'sunday': recurrence.sun, }.items() if weekday] pattern['firstDayOfWeek'] = 'sunday' if recurrence.rrule_type == 'monthly' and recurrence.month_by == 'day': byday_selection = { '1': 'first', '2': 'second', '3': 'third', '4': 'fourth', '-1': 'last', } pattern['index'] = byday_selection[recurrence.byday] dtstart = recurrence.dtstart or fields.Datetime.now() rule_range = { 'startDate': (dtstart.date()).isoformat() } if recurrence.end_type == 'count': # e.g. stop after X occurence rule_range['numberOfOccurrences'] = min(recurrence.count, MAX_RECURRENT_EVENT) rule_range['type'] = 'numbered' elif recurrence.end_type == 'forever': rule_range['numberOfOccurrences'] = MAX_RECURRENT_EVENT rule_range['type'] = 'numbered' elif recurrence.end_type == 'end_date': # e.g. stop after 12/10/2020 rule_range['endDate'] = recurrence.until.isoformat() rule_range['type'] = 'endDate' values['recurrence'] = { 'pattern': pattern, 'range': rule_range } return values def _ensure_attendees_have_email(self): invalid_event_ids = self.env['calendar.event'].search_read( domain=[('id', 'in', self.ids), ('attendee_ids.partner_id.email', '=', False)], fields=['display_time', 'display_name'], order='start', ) if invalid_event_ids: list_length_limit = 50 total_invalid_events = len(invalid_event_ids) invalid_event_ids = invalid_event_ids[:list_length_limit] invalid_events = ['\t- %s: %s' % (event['display_time'], event['display_name']) for event in invalid_event_ids] invalid_events = '\n'.join(invalid_events) details = "(%d/%d)" % (list_length_limit, total_invalid_events) if list_length_limit < total_invalid_events else "(%d)" % total_invalid_events raise ValidationError(_("For a correct synchronization between Odoo and Outlook Calendar, " "all attendees must have an email address. However, some events do " "not respect this condition. As long as the events are incorrect, " "the calendars will not be synchronized." "\nEither update the events/attendees or archive these events %s:" "\n%s", details, invalid_events)) def _microsoft_values_occurence(self, initial_values={}): values = initial_values values['type'] = 'occurrence' if self.allday: start = {'dateTime': self.start_date.isoformat(), 'timeZone': 'Europe/London'} end = {'dateTime': (self.stop_date + relativedelta(days=1)).isoformat(), 'timeZone': 'Europe/London'} else: start = {'dateTime': pytz.utc.localize(self.start).isoformat(), 'timeZone': 'Europe/London'} end = {'dateTime': pytz.utc.localize(self.stop).isoformat(), 'timeZone': 'Europe/London'} values['start'] = start values['end'] = end values['isAllDay'] = self.allday return values def _cancel_microsoft(self): """ Cancel an Microsoft event. There are 2 cases: 1) the organizer is an Odoo user: he's the only one able to delete the Odoo event. Attendees can just decline. 2) the organizer is NOT an Odoo user: any attendee should remove the Odoo event. """ user = self.env.user records = self.filtered(lambda e: not e.user_id or e.user_id == user) super(Meeting, records)._cancel_microsoft() attendees = (self - records).attendee_ids.filtered(lambda a: a.partner_id == user.partner_id) attendees.do_decline()
47.410309
22,994
6,308
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import requests from odoo.addons.microsoft_calendar.models.microsoft_sync import microsoft_calendar_token from datetime import timedelta from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.loglevels import exception_to_unicode from odoo.addons.microsoft_account.models.microsoft_service import DEFAULT_MICROSOFT_TOKEN_ENDPOINT from odoo.addons.microsoft_calendar.utils.microsoft_calendar import InvalidSyncToken _logger = logging.getLogger(__name__) class User(models.Model): _inherit = 'res.users' microsoft_calendar_sync_token = fields.Char('Microsoft Next Sync Token', copy=False) microsoft_synchronization_stopped = fields.Boolean('Outlook Synchronization stopped', copy=False) @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['microsoft_synchronization_stopped'] @property def SELF_WRITEABLE_FIELDS(self): return super().SELF_WRITEABLE_FIELDS + ['microsoft_synchronization_stopped'] def _microsoft_calendar_authenticated(self): return bool(self.sudo().microsoft_calendar_rtoken) def _get_microsoft_calendar_token(self): self.ensure_one() if self.microsoft_calendar_rtoken and not self._is_microsoft_calendar_valid(): self._refresh_microsoft_calendar_token() return self.microsoft_calendar_token def _is_microsoft_calendar_valid(self): return self.microsoft_calendar_token_validity and self.microsoft_calendar_token_validity >= (fields.Datetime.now() + timedelta(minutes=1)) def _refresh_microsoft_calendar_token(self): self.ensure_one() get_param = self.env['ir.config_parameter'].sudo().get_param client_id = get_param('microsoft_calendar_client_id') client_secret = get_param('microsoft_calendar_client_secret') if not client_id or not client_secret: raise UserError(_("The account for the Outlook Calendar service is not configured.")) headers = {"content-type": "application/x-www-form-urlencoded"} data = { 'refresh_token': self.microsoft_calendar_rtoken, 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'refresh_token', } try: dummy, response, dummy = self.env['microsoft.service']._do_request( DEFAULT_MICROSOFT_TOKEN_ENDPOINT, params=data, headers=headers, method='POST', preuri='' ) ttl = response.get('expires_in') self.write({ 'microsoft_calendar_token': response.get('access_token'), 'microsoft_calendar_token_validity': fields.Datetime.now() + timedelta(seconds=ttl), }) except requests.HTTPError as error: if error.response.status_code in (400, 401): # invalid grant or invalid client # Delete refresh token and make sure it's commited self.env.cr.rollback() self.write({ 'microsoft_calendar_rtoken': False, 'microsoft_calendar_token': False, 'microsoft_calendar_token_validity': False, 'microsoft_calendar_sync_token': False, }) self.env.cr.commit() error_key = error.response.json().get("error", "nc") error_msg = _( "An error occurred while generating the token. Your authorization code may be invalid or has already expired [%s]. " "You should check your Client ID and secret on the Microsoft Azure portal or try to stop and restart your calendar synchronisation.", error_key) raise UserError(error_msg) def _sync_microsoft_calendar(self): self.ensure_one() if self.microsoft_synchronization_stopped: return False calendar_service = self.env["calendar.event"]._get_microsoft_service() full_sync = not bool(self.microsoft_calendar_sync_token) with microsoft_calendar_token(self) as token: try: events, next_sync_token = calendar_service.get_events(self.microsoft_calendar_sync_token, token=token) except InvalidSyncToken: events, next_sync_token = calendar_service.get_events(token=token) full_sync = True self.microsoft_calendar_sync_token = next_sync_token # Microsoft -> Odoo synced_events, synced_recurrences = self.env['calendar.event']._sync_microsoft2odoo(events) if events else (self.env['calendar.event'], self.env['calendar.recurrence']) # Odoo -> Microsoft recurrences = self.env['calendar.recurrence']._get_microsoft_records_to_sync(full_sync=full_sync) recurrences -= synced_recurrences recurrences._sync_odoo2microsoft() synced_events |= recurrences.calendar_event_ids events = self.env['calendar.event']._get_microsoft_records_to_sync(full_sync=full_sync) (events - synced_events)._sync_odoo2microsoft() return bool(events | synced_events) or bool(recurrences | synced_recurrences) @api.model def _sync_all_microsoft_calendar(self): """ Cron job """ users = self.env['res.users'].search([('microsoft_calendar_rtoken', '!=', False), ('microsoft_synchronization_stopped', '=', False)]) for user in users: _logger.info("Calendar Synchro - Starting synchronization for %s", user) try: user.with_user(user).sudo()._sync_microsoft_calendar() self.env.cr.commit() except Exception as e: _logger.exception("[%s] Calendar Synchro - Exception : %s !", user, exception_to_unicode(e)) self.env.cr.rollback() def stop_microsoft_synchronization(self): self.ensure_one() self.microsoft_synchronization_stopped = True def restart_microsoft_synchronization(self): self.ensure_one() self.microsoft_synchronization_stopped = False self.env['calendar.recurrence']._restart_microsoft_sync() self.env['calendar.event']._restart_microsoft_sync()
46.043796
6,308
486
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' cal_microsoft_client_id = fields.Char("Microsoft Client_id", config_parameter='microsoft_calendar_client_id', default='') cal_microsoft_client_secret = fields.Char("Microsoft Client_key", config_parameter='microsoft_calendar_client_secret', default='')
44.181818
486
8,657
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 RecurrenceRule(models.Model): _name = 'calendar.recurrence' _inherit = ['calendar.recurrence', 'microsoft.calendar.sync'] # Don't sync by default. Sync only when the recurrence is applied need_sync_m = fields.Boolean(default=False) microsoft_id = fields.Char('Microsoft Calendar Recurrence Id') def _compute_rrule(self): # Note: 'need_sync_m' is set to False to avoid syncing the updated recurrence with # Outlook, as this update may already come from Outlook. If not, this modification will # be already synced through the calendar.event.write() for recurrence in self: if recurrence.rrule != recurrence._rrule_serialize(): recurrence.write({'rrule': recurrence._rrule_serialize()}) def _inverse_rrule(self): # Note: 'need_sync_m' is set to False to avoid syncing the updated recurrence with # Outlook, as this update mainly comes from Outlook (the 'rrule' field is not directly # modified in Odoo but computed from other fields). for recurrence in self.filtered('rrule'): values = self._rrule_parse(recurrence.rrule, recurrence.dtstart) recurrence.write(dict(values, need_sync_m=False)) def _apply_recurrence(self, specific_values_creation=None, no_send_edit=False, generic_values_creation=None): events = self.filtered('need_sync_m').calendar_event_ids detached_events = super()._apply_recurrence(specific_values_creation, no_send_edit, generic_values_creation) # If a synced event becomes a recurrence, the event needs to be deleted from # Microsoft since it's now the recurrence which is synced. vals = [] for event in events._get_synced_events(): if event.active and event.ms_universal_event_id and not event.recurrence_id.ms_universal_event_id: vals += [{ 'name': event.name, 'microsoft_id': event.microsoft_id, 'start': event.start, 'stop': event.stop, 'active': False, 'need_sync_m': True, }] event._microsoft_delete(event.user_id, event.ms_organizer_event_id) event.ms_universal_event_id = False self.env['calendar.event'].create(vals) self.calendar_event_ids.need_sync_m = False return detached_events def _write_events(self, values, dtstart=None): # If only some events are updated, sync those events. # If all events are updated, sync the recurrence instead. values['need_sync_m'] = bool(dtstart) or values.get("need_sync_m", True) return super()._write_events(values, dtstart=dtstart) def _get_organizer(self): return self.base_event_id.user_id def _get_rrule(self, dtstart=None): if not dtstart and self.dtstart: dtstart = self.dtstart return super()._get_rrule(dtstart) def _get_microsoft_synced_fields(self): return {'rrule'} | self.env['calendar.event']._get_microsoft_synced_fields() @api.model def _restart_microsoft_sync(self): self.env['calendar.recurrence'].search(self._get_microsoft_sync_domain()).write({ 'need_sync_m': True, }) def _has_base_event_time_fields_changed(self, new): """ Indicates if at least one time field of the base event has changed, based on provided `new` values. Note: for all day event comparison, hours/minutes are ignored. """ def _convert(value, to_convert): return value.date() if to_convert else value old = self.base_event_id and self.base_event_id.read(['start', 'stop', 'allday'])[0] return old and ( old['allday'] != new['allday'] or any( _convert(new[f], new['allday']) != _convert(old[f], old['allday']) for f in ('start', 'stop') ) ) def _write_from_microsoft(self, microsoft_event, vals): current_rrule = self.rrule # event_tz is written on event in Microsoft but on recurrence in Odoo vals['event_tz'] = microsoft_event.start.get('timeZone') super()._write_from_microsoft(microsoft_event, vals) new_event_values = self.env["calendar.event"]._microsoft_to_odoo_values(microsoft_event) if self._has_base_event_time_fields_changed(new_event_values): # we need to recreate the recurrence, time_fields were modified. base_event_id = self.base_event_id # We archive the old events to recompute the recurrence. These events are already deleted on Microsoft side. # We can't call _cancel because events without user_id would not be deleted (self.calendar_event_ids - base_event_id).microsoft_id = False (self.calendar_event_ids - base_event_id).unlink() base_event_id.with_context(dont_notify=True).write(dict( new_event_values, microsoft_id=False, need_sync_m=False )) if self.rrule == current_rrule: # if the rrule has changed, it will be recalculated below # There is no detached event now self.with_context(dont_notify=True)._apply_recurrence() else: time_fields = ( self.env["calendar.event"]._get_time_fields() | self.env["calendar.event"]._get_recurrent_fields() ) # We avoid to write time_fields because they are not shared between events. self._write_events(dict({ field: value for field, value in new_event_values.items() if field not in time_fields }, need_sync_m=False) ) # We apply the rrule check after the time_field check because the microsoft ids are generated according # to base_event start datetime. if self.rrule != current_rrule: detached_events = self._apply_recurrence() detached_events.microsoft_id = False detached_events.unlink() def _get_microsoft_sync_domain(self): # Empty rrule may exists in historical data. It is not a desired behavior but it could have been created with # older versions of the module. When synced, these recurrence may come back from Microsoft after database cleaning # and trigger errors as the records are not properly populated. # We also prevent sync of other user recurrent events. domain = [('calendar_event_ids.user_id', '=', self.env.user.id), ('rrule', '!=', False)] return self._extend_microsoft_domain(domain) def _cancel_microsoft(self): self.calendar_event_ids._cancel_microsoft() super()._cancel_microsoft() @api.model def _microsoft_to_odoo_values(self, microsoft_recurrence, default_reminders=(), default_values=None, with_ids=False): recurrence = microsoft_recurrence.get_recurrence() if with_ids: recurrence = { **recurrence, 'ms_organizer_event_id': microsoft_recurrence.id, 'ms_universal_event_id': microsoft_recurrence.iCalUId, } return recurrence def _microsoft_values(self, fields_to_sync): """ Get values to update the whole Outlook event recurrence. (done through the first event of the Outlook recurrence). """ return self.base_event_id._microsoft_values(fields_to_sync, initial_values={'type': 'seriesMaster'}) def _ensure_attendees_have_email(self): self.calendar_event_ids.filtered(lambda e: e.active)._ensure_attendees_have_email() def _split_from(self, event, recurrence_values=None): """ When a recurrence is splitted, the base event of the new recurrence already exist and may be already synced with Outlook. In this case, we need to be removed this event on Outlook side to avoid duplicates while posting the new recurrence. """ new_recurrence = super()._split_from(event, recurrence_values) if new_recurrence and new_recurrence.base_event_id.microsoft_id: new_recurrence.base_event_id._microsoft_delete( new_recurrence.base_event_id._get_organizer(), new_recurrence.base_event_id.ms_organizer_event_id ) return new_recurrence
46.794595
8,657
2,490
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 class MicrosoftCalendarController(http.Controller): @http.route('/microsoft_calendar/sync_data', type='json', auth='user') def sync_data(self, model, **kw): """ This route/function is called when we want to synchronize Odoo calendar with Microsoft Calendar. Function return a dictionary with the status : need_config_from_admin, need_auth, need_refresh, sync_stopped, success if not calendar_event The dictionary may contains an url, to allow Odoo Client to redirect user on this URL for authorization for example """ if model == 'calendar.event': MicrosoftCal = request.env["calendar.event"]._get_microsoft_service() # Checking that admin have already configured Microsoft API for microsoft synchronization ! client_id = request.env['ir.config_parameter'].sudo().get_param('microsoft_calendar_client_id') if not client_id or client_id == '': action_id = '' if MicrosoftCal._can_authorize_microsoft(request.env.user): action_id = request.env.ref('base_setup.action_general_configuration').id return { "status": "need_config_from_admin", "url": '', "action": action_id } # Checking that user have already accepted Odoo to access his calendar ! if not MicrosoftCal.is_authorized(request.env.user): url = MicrosoftCal._microsoft_authentication_url(from_url=kw.get('fromurl')) return { "status": "need_auth", "url": url } # If App authorized, and user access accepted, We launch the synchronization need_refresh = request.env.user.sudo()._sync_microsoft_calendar() # If synchronization has been stopped if not need_refresh and request.env.user.microsoft_synchronization_stopped: return { "status": "sync_stopped", "url": '' } return { "status": "need_refresh" if need_refresh else "no_new_event_from_microsoft", "url": '' } return {"status": "success"}
44.464286
2,490
1,364
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Sweden - Accounting", "version": "1.0", "author": "XCLUDE, Odoo SA", "category": "Accounting/Localizations/Account Charts", 'description': """ Swedish Accounting ------------------ This is the base module to manage the accounting chart for Sweden in Odoo. It also includes the invoice OCR payment reference handling. """, "depends": ["account", "base_vat"], "data": [ 'data/account.account.tag.csv', "data/account_chart_template_before_accounts.xml", "data/account.account.template-K3.csv", "data/account.account.template-K2.csv", "data/account.account.template.csv", "data/account_chart_template_after_accounts.xml", "data/account_tax_group_data.xml", "data/account_tax_report_data.xml", "data/account_tax_template.xml", "data/account_fiscal_position_template.xml", "data/account_fiscal_position_account_template.xml", "data/account_fiscal_position_tax_template.xml", "data/account_chart_template_configuration.xml", "views/partner_view.xml", "views/account_journal_view.xml", 'data/menuitem_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
35.894737
1,364
3,225
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 from stdnum import luhn class AccountMove(models.Model): _inherit = 'account.move' def _get_invoice_reference_se_ocr2(self, reference): self.ensure_one() return reference + luhn.calc_check_digit(reference) def _get_invoice_reference_se_ocr3(self, reference): self.ensure_one() reference = reference + str(len(reference) + 2)[:1] return reference + luhn.calc_check_digit(reference) def _get_invoice_reference_se_ocr4(self, reference): self.ensure_one() ocr_length = self.journal_id.l10n_se_invoice_ocr_length if len(reference) + 1 > ocr_length: raise UserError(_("OCR Reference Number length is greater than allowed. Allowed length in invoice journal setting is %s.") % str(ocr_length)) reference = reference.rjust(ocr_length - 1, '0') return reference + luhn.calc_check_digit(reference) def _get_invoice_reference_se_ocr2_invoice(self): self.ensure_one() return self._get_invoice_reference_se_ocr2(str(self.id)) def _get_invoice_reference_se_ocr3_invoice(self): self.ensure_one() return self._get_invoice_reference_se_ocr3(str(self.id)) def _get_invoice_reference_se_ocr4_invoice(self): self.ensure_one() return self._get_invoice_reference_se_ocr4(str(self.id)) def _get_invoice_reference_se_ocr2_partner(self): self.ensure_one() return self._get_invoice_reference_se_ocr2(self.partner_id.ref if str(self.partner_id.ref).isdecimal() else str(self.partner_id.id)) def _get_invoice_reference_se_ocr3_partner(self): self.ensure_one() return self._get_invoice_reference_se_ocr3(self.partner_id.ref if str(self.partner_id.ref).isdecimal() else str(self.partner_id.id)) def _get_invoice_reference_se_ocr4_partner(self): self.ensure_one() return self._get_invoice_reference_se_ocr4(self.partner_id.ref if str(self.partner_id.ref).isdecimal() else str(self.partner_id.id)) @api.onchange('partner_id') def _onchange_partner_id(self): """ If Vendor Bill and Vendor OCR is set, add it. """ if self.partner_id and self.move_type == 'in_invoice' and self.partner_id.l10n_se_default_vendor_payment_ref: self.payment_reference = self.partner_id.l10n_se_default_vendor_payment_ref return super(AccountMove, self)._onchange_partner_id() @api.onchange('payment_reference') def _onchange_payment_reference(self): """ If Vendor Bill and Payment Reference is changed check validation. """ if self.partner_id and self.move_type == 'in_invoice' and self.partner_id.l10n_se_check_vendor_ocr: reference = self.payment_reference try: luhn.validate(reference) except: return {'warning': {'title': _('Warning'), 'message': _('Vendor require OCR Number as payment reference. Payment reference isn\'t a valid OCR Number.')}} return super(AccountMove, self)._onchange_payment_reference()
44.178082
3,225
1,008
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api, _ from odoo.exceptions import ValidationError class AccountJournal(models.Model): _inherit = 'account.journal' invoice_reference_model = fields.Selection(selection_add=[('se_ocr2', 'Sweden OCR Level 1 & 2'), ('se_ocr3', 'Sweden OCR Level 3'), ('se_ocr4', 'Sweden OCR Level 4')], ondelete={'se_ocr2': 'set default', 'se_ocr3': 'set default', 'se_ocr4': 'set default'}) l10n_se_invoice_ocr_length = fields.Integer(string='OCR Number Length', help="Total length of OCR Reference Number including checksum.", default=6) @api.constrains('l10n_se_invoice_ocr_length') def _check_l10n_se_invoice_ocr_length(self): for journal in self: if journal.l10n_se_invoice_ocr_length < 6: raise ValidationError(_('OCR Reference Number length need to be greater than 5. Please correct settings under invoice journal settings.'))
56
1,008
678
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 import re class ResCompany(models.Model): _inherit = 'res.company' org_number = fields.Char(compute='_compute_org_number') @api.depends('vat') def _compute_org_number(self): for company in self: if company.account_fiscal_country_id.code == "SE" and company.vat: org_number = re.sub(r'\D', '', company.vat)[:-2] org_number = org_number[:6] + '-' + org_number[6:] company.org_number = org_number else: company.org_number = ''
30.818182
678
1,043
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api, _ from stdnum import luhn class ResPartner(models.Model): _inherit = 'res.partner' l10n_se_check_vendor_ocr = fields.Boolean(string='Check Vendor OCR', help='This Vendor uses OCR Number on their Vendor Bills.') l10n_se_default_vendor_payment_ref = fields.Char(string='Default Vendor Payment Ref', help='If set, the vendor uses the same Default Payment Reference or OCR Number on all their Vendor Bills.') @api.onchange('l10n_se_default_vendor_payment_ref') def onchange_l10n_se_default_vendor_payment_ref(self): if not self.l10n_se_default_vendor_payment_ref == "" and self.l10n_se_check_vendor_ocr: reference = self.l10n_se_default_vendor_payment_ref try: luhn.validate(reference) except: return {'warning': {'title': _('Warning'), 'message': _('Default vendor OCR number isn\'t a valid OCR number.')}}
49.666667
1,043
713
py
PYTHON
15.0
{ 'name': "Password Policy", "summary": "Implement basic password policy configuration & check", 'category': 'Hidden/Tools', 'depends': ['base_setup', 'web'], 'data': [ 'data/defaults.xml', 'views/res_users.xml', 'views/res_config_settings_views.xml', ], 'assets': { 'web.assets_backend': [ 'auth_password_policy/static/src/js/password_field.js', 'auth_password_policy/static/src/js/change_password.js', ], 'web.assets_common': [ 'auth_password_policy/static/src/js/password_gauge.js', 'auth_password_policy/static/src/css/password_field.css', ], }, 'license': 'LGPL-3', }
32.409091
713
1,060
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models, _ from odoo.exceptions import UserError class ResUsers(models.Model): _inherit = 'res.users' @api.model def get_password_policy(self): params = self.env['ir.config_parameter'].sudo() return { 'minlength': int(params.get_param('auth_password_policy.minlength', default=0)), } def _set_password(self): self._check_password_policy(self.mapped('password')) super(ResUsers, self)._set_password() def _check_password_policy(self, passwords): failures = [] params = self.env['ir.config_parameter'].sudo() minlength = int(params.get_param('auth_password_policy.minlength', default=0)) for password in passwords: if not password: continue if len(password) < minlength: failures.append(_(u"Passwords must have at least %d characters, got %d.") % (minlength, len(password))) if failures: raise UserError(u'\n\n '.join(failures))
32.121212
1,060
896
py
PYTHON
15.0
from odoo import api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' minlength = fields.Integer("Minimum Password Length", help="Minimum number of characters passwords must contain, set to 0 to disable.") @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res['minlength'] = int(self.env['ir.config_parameter'].sudo().get_param('auth_password_policy.minlength', default=0)) return res @api.model def set_values(self): self.env['ir.config_parameter'].sudo().set_param('auth_password_policy.minlength', self.minlength) super(ResConfigSettings, self).set_values() @api.onchange('minlength') def _on_change_mins(self): """ Password lower bounds must be naturals """ self.minlength = max(0, self.minlength or 0)
33.185185
896
576
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Ogone Payment Acquirer', 'version': '2.0', 'category': 'Accounting/Payment Acquirers', 'sequence': 360, 'summary': 'Payment Acquirer: Ogone Implementation', 'description': """Ogone Payment Acquirer""", 'depends': ['payment'], 'data': [ 'views/payment_views.xml', 'views/payment_ogone_templates.xml', 'data/payment_acquirer_data.xml', ], 'application': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
30.315789
576
652
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 OgoneCommon(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.ogone = cls._prepare_acquirer('ogone', update_values={ 'ogone_pspid': 'dummy', 'ogone_userid': 'dummy', 'ogone_password': 'dummy', 'ogone_shakey_in': 'dummy', 'ogone_shakey_out': 'dummy', }) cls.acquirer = cls.ogone cls.currency = cls.currency_euro
31.047619
652
4,427
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from freezegun import freeze_time from odoo.fields import Command from odoo.tests import tagged from odoo.tools import mute_logger from odoo.addons.payment import utils as payment_utils from .common import OgoneCommon from ..controllers.main import OgoneController @tagged('post_install', '-at_install') class OgoneTest(OgoneCommon): def test_incompatibility_with_validation_operation(self): acquirers = self.env['payment.acquirer']._get_compatible_acquirers( self.company.id, self.partner.id, is_validation=True ) self.assertNotIn(self.ogone, acquirers) @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior def test_reference_is_singularized(self): """ Test singularization of reference prefixes. """ reference = self.env['payment.transaction']._compute_reference(self.ogone.provider) self.assertEqual( reference, 'tx-20111102120021', "transaction reference was not correctly singularized" ) @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior def test_reference_is_stripped_at_max_length(self): """ Test stripping of reference prefixes of length > 40 chars. """ reference = self.env['payment.transaction']._compute_reference( self.ogone.provider, prefix='this is a reference of more than 40 characters to annoy ogone', ) self.assertEqual(reference, 'this is a reference of mo-20111102120021') self.assertEqual(len(reference), 40) @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior def test_reference_is_computed_based_on_document_name(self): """ Test computation of reference prefixes based on the provided invoice. """ invoice = self.env['account.move'].create({}) reference = self.env['payment.transaction']._compute_reference( self.ogone.provider, invoice_ids=[Command.set([invoice.id])] ) self.assertEqual(reference, 'MISC/2011/11/0001-20111102120021') @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior def test_redirect_form_values(self): """ Test the values of the redirect form inputs for online payments. """ return_url = self._build_url(OgoneController._return_url) expected_values = { 'PSPID': self.ogone.ogone_pspid, 'ORDERID': self.reference, 'AMOUNT': str(payment_utils.to_minor_currency_units(self.amount, None, 2)), 'CURRENCY': self.currency.name, 'LANGUAGE': self.partner.lang, 'EMAIL': self.partner.email, 'OWNERZIP': self.partner.zip, 'OWNERADDRESS': payment_utils.format_partner_address( self.partner.street, self.partner.street2 ), 'OWNERCTY': self.partner.country_id.code, 'OWNERTOWN': self.partner.city, 'OWNERTELNO': self.partner.phone, 'OPERATION': 'SAL', # direct sale 'USERID': self.ogone.ogone_userid, 'ACCEPTURL': return_url, 'DECLINEURL': return_url, 'EXCEPTIONURL': return_url, 'CANCELURL': return_url, 'ALIAS': None, 'ALIASUSAGE': None, } expected_values['SHASIGN'] = self.ogone._ogone_generate_signature( expected_values, incoming=False ).upper() tx = self.create_transaction(flow='redirect') self.assertEqual(tx.tokenize, False) with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx._get_processing_values() form_info = self._extract_values_from_html_form(processing_values['redirect_form_html']) self.assertEqual(form_info['action'], 'https://ogone.test.v-psp.com/ncol/test/orderstandard_utf8.asp') inputs = form_info['inputs'] self.assertEqual(len(expected_values), len(inputs)) for rendering_key, value in expected_values.items(): form_key = rendering_key.replace('_', '.') self.assertEqual( inputs[form_key], value, f"received value {inputs[form_key]} for input {form_key} (expected {value})" )
45.173469
4,427
10,481
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint import uuid from lxml import etree, objectify from werkzeug import urls from odoo import _, api, models from odoo.exceptions import UserError, ValidationError from . import const from odoo.addons.payment import utils as payment_utils from odoo.addons.payment_ogone.controllers.main import OgoneController _logger = logging.getLogger(__name__) class PaymentTransaction(models.Model): _inherit = 'payment.transaction' @api.model def _compute_reference(self, provider, prefix=None, separator='-', **kwargs): """ Override of payment to ensure that Ogone requirements for references are satisfied. Ogone requirements for references are as follows: - References must be unique at provider level for a given merchant account. This is satisfied by singularizing the prefix with the current datetime. If two transactions are created simultaneously, `_compute_reference` ensures the uniqueness of references by suffixing a sequence number. :param str provider: The provider of the acquirer handling the transaction :param str prefix: The custom prefix used to compute the full reference :param str separator: The custom separator used to separate the prefix from the suffix :return: The unique reference for the transaction :rtype: str """ if provider != 'ogone': return super()._compute_reference(provider, prefix=prefix, **kwargs) if not prefix: # If no prefix is provided, it could mean that a module has passed a kwarg intended for # the `_compute_reference_prefix` method, as it is only called if the prefix is empty. # We call it manually here because singularizing the prefix would generate a default # value if it was empty, hence preventing the method from ever being called and the # transaction from received a reference named after the related document. prefix = self.sudo()._compute_reference_prefix(provider, separator, **kwargs) or None prefix = payment_utils.singularize_reference_prefix(prefix=prefix, max_length=40) return super()._compute_reference(provider, prefix=prefix, **kwargs) def _get_specific_rendering_values(self, processing_values): """ Override of payment to return Ogone-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.acquirer_id.provider != 'ogone': return res return_url = urls.url_join(self.acquirer_id.get_base_url(), OgoneController._return_url) rendering_values = { 'PSPID': self.acquirer_id.ogone_pspid, 'ORDERID': self.reference, 'AMOUNT': payment_utils.to_minor_currency_units(self.amount, None, 2), 'CURRENCY': self.currency_id.name, 'LANGUAGE': self.partner_lang or 'en_US', 'EMAIL': self.partner_email or '', 'OWNERADDRESS': self.partner_address or '', 'OWNERZIP': self.partner_zip or '', 'OWNERTOWN': self.partner_city or '', 'OWNERCTY': self.partner_country_id.code or '', 'OWNERTELNO': self.partner_phone or '', 'OPERATION': 'SAL', # direct sale 'USERID': self.acquirer_id.ogone_userid, 'ACCEPTURL': return_url, 'DECLINEURL': return_url, 'EXCEPTIONURL': return_url, 'CANCELURL': return_url, } if self.tokenize: rendering_values.update({ 'ALIAS': f'ODOO-ALIAS-{uuid.uuid4().hex}', 'ALIASUSAGE': _("Storing your payment details is necessary for future use."), }) rendering_values.update({ 'SHASIGN': self.acquirer_id._ogone_generate_signature( rendering_values, incoming=False ).upper(), 'api_url': self.acquirer_id._ogone_get_api_url('hosted_payment_page'), }) return rendering_values def _send_payment_request(self): """ Override of payment to send a payment request to Ogone. Note: self.ensure_one() :return: None :raise: UserError if the transaction is not linked to a token """ super()._send_payment_request() if self.provider != 'ogone': return if not self.token_id: raise UserError("Ogone: " + _("The transaction is not linked to a token.")) # Make the payment request base_url = self.acquirer_id.get_base_url() data = { # DirectLink parameters 'PSPID': self.acquirer_id.ogone_pspid, 'ORDERID': self.reference, 'USERID': self.acquirer_id.ogone_userid, 'PSWD': self.acquirer_id.ogone_password, 'AMOUNT': payment_utils.to_minor_currency_units(self.amount, None, 2), 'CURRENCY': self.currency_id.name, 'CN': self.partner_name or '', # Cardholder Name 'EMAIL': self.partner_email or '', 'OWNERADDRESS': self.partner_address or '', 'OWNERZIP': self.partner_zip or '', 'OWNERTOWN': self.partner_city or '', 'OWNERCTY': self.partner_country_id.code or '', 'OWNERTELNO': self.partner_phone or '', 'OPERATION': 'SAL', # direct sale # Alias Manager parameters 'ALIAS': self.token_id.acquirer_ref, 'ALIASPERSISTEDAFTERUSE': 'Y', 'ECI': 9, # Recurring (from eCommerce) } data['SHASIGN'] = self.acquirer_id._ogone_generate_signature(data, incoming=False) _logger.info( "making payment request:\n%s", pprint.pformat({k: v for k, v in data.items() if k != 'PSWD'}) ) # Log the payment request data without the password response_content = self.acquirer_id._ogone_make_request(data) try: tree = objectify.fromstring(response_content) except etree.XMLSyntaxError: raise ValidationError("Ogone: " + "Received badly structured response from the API.") # Handle the feedback data _logger.info( "received payment request response as an etree:\n%s", etree.tostring(tree, pretty_print=True, encoding='utf-8') ) feedback_data = {'ORDERID': tree.get('orderID'), 'tree': tree} _logger.info("entering _handle_feedback_data with data:\n%s", pprint.pformat(feedback_data)) self._handle_feedback_data('ogone', feedback_data) @api.model def _get_tx_from_feedback_data(self, provider, data): """ Override of payment to find the transaction based on Ogone 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 the data match no transaction """ tx = super()._get_tx_from_feedback_data(provider, data) if provider != 'ogone': return tx reference = data.get('ORDERID') tx = self.search([('reference', '=', reference), ('provider', '=', 'ogone')]) if not tx: raise ValidationError( "Ogone: " + _("No transaction found matching reference %s.", reference) ) return tx def _process_feedback_data(self, data): """ Override of payment to process the transaction based on Ogone data. Note: self.ensure_one() :param dict data: The feedback data sent by the provider :return: None """ super()._process_feedback_data(data) if self.provider != 'ogone': return if 'tree' in data: data = data['tree'] self.acquirer_reference = data.get('PAYID') payment_status = int(data.get('STATUS', '0')) if payment_status in const.PAYMENT_STATUS_MAPPING['pending']: self._set_pending() elif payment_status in const.PAYMENT_STATUS_MAPPING['done']: has_token_data = 'ALIAS' in data if self.tokenize and has_token_data: self._ogone_tokenize_from_feedback_data(data) self._set_done() elif payment_status in const.PAYMENT_STATUS_MAPPING['cancel']: self._set_canceled() elif payment_status in const.PAYMENT_STATUS_MAPPING['declined']: if data.get("NCERRORPLUS"): reason = data.get("NCERRORPLUS") elif data.get("NCERROR"): reason = "Error code: %s" % data.get("NCERROR") else: reason = "Unknown reason" _logger.info("the payment has been declined: %s.", reason) self._set_error( "Ogone: " + _("The payment has been declined: %s", reason) ) else: # Classify unknown payment statuses as `error` tx state _logger.info("received data with invalid payment status: %s", payment_status) self._set_error( "Ogone: " + _("Received data with invalid payment status: %s", payment_status) ) def _ogone_tokenize_from_feedback_data(self, data): """ Create a token from feedback data. :param dict data: The feedback data sent by the provider :return: None """ token_name = data.get('CARDNO') or payment_utils.build_token_name() token = self.env['payment.token'].create({ 'acquirer_id': self.acquirer_id.id, 'name': token_name, # Already padded with 'X's 'partner_id': self.partner_id.id, 'acquirer_ref': data['ALIAS'], 'verified': True, # The payment is authorized, so the payment method is valid }) self.write({ 'token_id': token.id, 'tokenize': False, }) _logger.info( "created token with id %s for partner with id %s", token.id, self.partner_id.id )
43.309917
10,481
923
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, models from odoo.exceptions import UserError class PaymentToken(models.Model): _inherit = 'payment.token' def _handle_reactivation_request(self): """ Override of payment to raise an error informing that Ogone tokens cannot be restored. More specifically, permanents tokens are never deleted in Ogone's backend but we don't distinguish them from temporary tokens which are archived at creation time. So we simply block the reactivation of every token. Note: self.ensure_one() :return: None :raise: UserError if the token is managed by Ogone """ super()._handle_reactivation_request() if self.provider != 'ogone': return raise UserError(_("Saved payment methods cannot be restored once they have been archived."))
35.5
923
428
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['ogone'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]} return res
30.571429
428
5,566
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from hashlib import new as hashnew import requests from odoo import _, api, fields, models from odoo.exceptions import ValidationError from .const import VALID_KEYS _logger = logging.getLogger(__name__) class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection( selection_add=[('ogone', "Ogone")], ondelete={'ogone': 'set default'}) ogone_pspid = fields.Char( string="PSPID", help="The ID solely used to identify the account with Ogone", required_if_provider='ogone') ogone_userid = fields.Char( string="API User ID", help="The ID solely used to identify the API user with Ogone", required_if_provider='ogone') ogone_password = fields.Char( string="API User Password", required_if_provider='ogone', groups='base.group_system') ogone_shakey_in = fields.Char( string="SHA Key IN", required_if_provider='ogone', groups='base.group_system') ogone_shakey_out = fields.Char( string="SHA Key OUT", required_if_provider='ogone', groups='base.group_system') @api.model def _get_compatible_acquirers(self, *args, is_validation=False, **kwargs): """ Override of payment to unlist Ogone acquirers for validation operations. """ acquirers = super()._get_compatible_acquirers(*args, is_validation=is_validation, **kwargs) if is_validation: acquirers = acquirers.filtered(lambda a: a.provider != 'ogone') return acquirers def _ogone_get_api_url(self, api_key): """ Return the appropriate URL of the requested API for the acquirer state. Note: self.ensure_one() :param str api_key: The API whose URL to get: 'hosted_payment_page' or 'directlink' :return: The API URL :rtype: str """ self.ensure_one() if self.state == 'enabled': api_urls = { 'hosted_payment_page': 'https://secure.ogone.com/ncol/prod/orderstandard_utf8.asp', 'directlink': 'https://secure.ogone.com/ncol/prod/orderdirect_utf8.asp', } else: # 'test' api_urls = { 'hosted_payment_page': 'https://ogone.test.v-psp.com/ncol/test/orderstandard_utf8.asp', 'directlink': 'https://ogone.test.v-psp.com/ncol/test/orderdirect_utf8.asp', } return api_urls.get(api_key) def _ogone_generate_signature(self, values, incoming=True, format_keys=False): """ Generate the signature for incoming or outgoing communications. :param dict values: The values used to generate the signature :param bool incoming: Whether the signature must be generated for an incoming (Ogone to Odoo) or outgoing (Odoo to Ogone) communication. :param bool format_keys: Whether the keys must be formatted as uppercase, dot-separated strings to comply with Ogone APIs. This must be used when the keys are formatted as underscore-separated strings to be compliant with QWeb's `t-att-value`. :return: The signature :rtype: str """ def _filter_key(_key): return not incoming or _key in VALID_KEYS key = self.ogone_shakey_out if incoming else self.ogone_shakey_in # Swapped for Ogone's POV if format_keys: formatted_items = [(k.upper().replace('_', '.'), v) for k, v in values.items()] else: formatted_items = [(k.upper(), v) for k, v in values.items()] sorted_items = sorted(formatted_items) signing_string = ''.join(f'{k}={v}{key}' for k, v in sorted_items if _filter_key(k) and v) signing_string = signing_string.encode() hash_function = self.env['ir.config_parameter'].sudo().get_param('payment_ogone.hash_function') if not hash_function or hash_function.lower() not in ['sha1', 'sha256', 'sha512']: hash_function = 'sha1' shasign = hashnew(hash_function) shasign.update(signing_string) return shasign.hexdigest() def _ogone_make_request(self, payload=None, method='POST'): """ Make a request to one of Ogone APIs. Note: self.ensure_one() :param dict payload: The payload of the request :param str method: The HTTP method of the request :return The content of the response :rtype: bytes :raise: ValidationError if an HTTP error occurs """ self.ensure_one() url = self._ogone_get_api_url('directlink') try: response = requests.request(method, url, data=payload, timeout=60) response.raise_for_status() except requests.exceptions.ConnectionError: _logger.exception("unable to reach endpoint at %s", url) raise ValidationError("Ogone: " + _("Could not establish the connection to the API.")) except requests.exceptions.HTTPError: _logger.exception("invalid API request at %s with data %s", url, payload) raise ValidationError("Ogone: " + _("The communication with the API failed.")) return response.content def _get_default_payment_method_id(self): self.ensure_one() if self.provider != 'ogone': return super()._get_default_payment_method_id() return self.env.ref('payment_ogone.payment_method_ogone').id
43.147287
5,566
1,698
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # See https://epayments-support.ingenico.com/en/integration-solutions/integrations/directlink#directlink_integration_guides_request_a_new_order # See https://epayments-support.ingenico.com/en/integration-solutions/integrations/directlink#directlink_integration_guides_order_response VALID_KEYS = [ 'AAVADDRESS', 'AAVCHECK', 'AAVMAIL', 'AAVNAME', 'AAVPHONE', 'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT', 'BIC', 'BIN', 'BRAND', 'CARDNO', 'CCCTY', 'CN', 'COLLECTOR_BIC', 'COLLECTOR_IBAN', 'COMPLUS', 'CREATION_STATUS', 'CREDITDEBIT', 'CURRENCY', 'CVCCHECK', 'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY', 'DCC_EXCHRATE', 'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR', 'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOURS', 'DEVICEID', 'DIGESTCARDNO', 'ECI', 'ED', 'EMAIL', 'ENCCARDNO', 'FXAMOUNT', 'FXCURRENCY', 'IP', 'IPCTY', 'MANDATEID', 'MOBILEMODE', 'NBREMAILUSAGE', 'NBRIPUSAGE', 'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR', 'ORDERID', 'PAYID', 'PAYIDSUB', 'PAYMENT_REFERENCE', 'PM', 'SCO_CATEGORY', 'SCORING', 'SEQUENCETYPE', 'SIGNDATE', 'STATUS', 'SUBBRAND', 'SUBSCRIPTION_ID', 'TICKET', 'TRXDATE', 'VC', ] # See https://epayments-support.ingenico.com/en/get-started/transaction-status-full/ PAYMENT_STATUS_MAPPING = { 'pending': (41, 46, 50, 51, 52, 55, 56, 81, 82, 91, 92, 99), # 46 = 3DS 'done': (5, 8, 9), 'cancel': (1,), 'declined': (2,), }
21.769231
1,698
3,683
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint import re import werkzeug from odoo import _, http from odoo.exceptions import ValidationError from odoo.http import request _logger = logging.getLogger(__name__) class OgoneController(http.Controller): _return_url = '/payment/ogone/return' _backward_compatibility_urls = [ '/payment/ogone/accept', '/payment/ogone/test/accept', '/payment/ogone/decline', '/payment/ogone/test/decline', '/payment/ogone/exception', '/payment/ogone/test/exception', '/payment/ogone/cancel', '/payment/ogone/test/cancel', '/payment/ogone/validate/accept', '/payment/ogone/validate/decline', '/payment/ogone/validate/exception', ] # Facilitates the migration of users who registered the URLs in Ogone's backend prior to 14.3 @http.route( [_return_url] + _backward_compatibility_urls, type='http', auth='public', methods=['GET', 'POST'], csrf=False ) # 'GET' or 'POST' depending on the configuration in Ogone backend def ogone_return_from_redirect(self, **feedback_data): """ Process the data returned by Ogone after redirection to the Hosted Payment Page. This route can also accept S2S notifications from Ogone if it is configured as a webhook in Ogone's backend. :param dict feedback_data: The feedback data """ # Check the source and integrity of the data data = self._homogenize_data(feedback_data) self._verify_signature(feedback_data, data) # Handle the feedback data _logger.info("entering _handle_feedback_data with data:\n%s", pprint.pformat(data)) request.env['payment.transaction'].sudo()._handle_feedback_data('ogone', data) return request.redirect('/payment/status') def _homogenize_data(self, data): """ Format keys to follow an homogenized convention inspired by Ogone Directlink API. The keys received from Ogone APIs have inconsistent formatting and must be homogenized to allow re-using the same methods. We reformat them to follow a unified nomenclature inspired by DirectLink's order direct endpoint. Formatting steps: 1) Uppercase key strings: 'Something' -> 'SOMETHING', 'something' -> 'SOMETHING' 2) Remove the prefix: 'CARD.SOMETHING' -> 'SOMETHING', 'ALIAS.SOMETHING' -> 'SOMETHING' """ return {re.sub(r'.*\.', '', k.upper()): v for k, v in data.items()} def _verify_signature(self, sign_data, data): """ Check that the signature computed from the feedback matches the received one. :param dict sign_data: The original feedback data used to compute the signature :param dict sign_data: The formatted feedback data used to find the tx and received sig :return: None :raise: ValidationError if the signatures don't match """ acquirer_sudo = request.env['payment.transaction'].sudo()._get_tx_from_feedback_data( 'ogone', data ).acquirer_id # Find the acquirer based on the transaction received_signature = data.get('SHASIGN') expected_signature = acquirer_sudo._ogone_generate_signature(sign_data) if received_signature != expected_signature.upper(): raise ValidationError( "Ogone: " + _( "Received data with invalid signature. expected: %(exp)s ; received: %(rec)s ; " "data:\n%(data)s", exp=expected_signature, rec=received_signature, data=pprint.pformat(sign_data) ) )
44.914634
3,683
1,915
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Sales Timesheet', 'category': 'Hidden', 'summary': 'Sell based on timesheets', 'description': """ Allows to sell timesheets in your sales order ============================================= This module set the right product on all timesheet lines according to the order/contract you work on. This allows to have real delivered quantities in sales orders. """, 'depends': ['sale_project', 'hr_timesheet'], 'data': [ 'data/sale_service_data.xml', 'security/ir.model.access.csv', 'security/sale_timesheet_security.xml', 'views/account_invoice_views.xml', 'views/sale_order_views.xml', 'views/product_views.xml', 'views/project_task_views.xml', 'views/project_update_templates.xml', 'views/hr_timesheet_views.xml', 'views/res_config_settings_views.xml', 'views/sale_timesheet_portal_templates.xml', 'views/project_sharing_views.xml', 'report/project_profitability_report_analysis_views.xml', 'data/sale_timesheet_filters.xml', 'wizard/project_create_sale_order_views.xml', 'wizard/project_create_invoice_views.xml', 'wizard/sale_make_invoice_advance_views.xml', ], 'demo': [ 'data/sale_service_demo.xml', ], 'auto_install': True, 'uninstall_hook': 'uninstall_hook', 'assets': { 'web.assets_frontend': [ 'sale_timesheet/static/src/scss/sale_timesheet_portal.scss', ], 'web.assets_backend': [ 'sale_timesheet/static/src/js/so_line_one2many.js', ], 'web.assets_tests': [ 'sale_timesheet/static/tests/**/*', ], 'web.assets_qweb': [ 'sale_timesheet/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
34.196429
1,915
1,661
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestProjectBillingMulticompany(TestCommonSaleTimesheet): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) Project = cls.env['project.project'].with_context(tracking_disable=True) cls.project_non_billable = Project.create({ 'name': "Non Billable Project", 'allow_timesheets': True, 'allow_billable': True, 'company_id': cls.env.company.id, }) def test_makeBillable_multiCompany(self): wizard = self.env['project.create.sale.order'].with_context(allowed_company_ids=[self.company_data_2['company'].id, self.env.company.id], company_id=self.company_data_2['company'].id, active_id=self.project_non_billable.id, active_model='project.project').create({ 'line_ids': [(0, 0, { 'product_id': self.product_delivery_timesheet3.id, # product creates new Timesheet in new Project 'price_unit': self.product_delivery_timesheet3.list_price })], 'partner_id': self.partner_a.id, }) action = wizard.action_create_sale_order() sale_order = self.env['sale.order'].browse(action['res_id']) self.assertEqual(sale_order.company_id.id, self.project_non_billable.company_id.id, "The company on the sale order should be the same as the one on the project")
47.457143
1,661
44,236
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, timedelta from odoo.fields import Date from odoo.tools import float_is_zero from odoo.exceptions import UserError from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestSaleTimesheet(TestCommonSaleTimesheet): """ This test suite provide tests for the 3 main flows of selling services: - Selling services based on ordered quantities - Selling timesheet based on delivered quantities - Selling milestones, based on manual delivered quantities For that, we check the task/project created, the invoiced amounts, the delivered quantities changes, ... """ def test_timesheet_order(self): """ Test timesheet invoicing with 'invoice on order' timetracked products 1. create SO with 2 ordered product and confirm 2. create invoice 3. log timesheet 4. add new SO line (ordered service) 5. create new invoice """ # create SO and confirm it sale_order = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) so_line_ordered_project_only = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet4.name, 'product_id': self.product_order_timesheet4.id, 'product_uom_qty': 10, 'product_uom': self.product_order_timesheet4.uom_id.id, 'price_unit': self.product_order_timesheet4.list_price, 'order_id': sale_order.id, }) so_line_ordered_global_project = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet2.name, 'product_id': self.product_order_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_order_timesheet2.uom_id.id, 'price_unit': self.product_order_timesheet2.list_price, 'order_id': sale_order.id, }) so_line_ordered_project_only.product_id_change() so_line_ordered_global_project.product_id_change() sale_order.action_confirm() task_serv2 = self.env['project.task'].search([('sale_line_id', '=', so_line_ordered_global_project.id)]) project_serv1 = self.env['project.project'].search([('sale_line_id', '=', so_line_ordered_project_only.id)]) self.assertEqual(sale_order.tasks_count, 1, "One task should have been created on SO confirmation") self.assertEqual(len(sale_order.project_ids), 2, "One project should have been created by the SO, when confirmed + the one from SO line 2 'task in global project'") self.assertEqual(sale_order.analytic_account_id, project_serv1.analytic_account_id, "The created project should be linked to the analytic account of the SO") # create invoice invoice1 = sale_order._create_invoices()[0] # let's log some timesheets (on the project created by so_line_ordered_project_only) timesheet1 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 10.5, 'employee_id': self.employee_user.id, }) self.assertEqual(so_line_ordered_global_project.qty_delivered, 10.5, 'Timesheet directly on project does not increase delivered quantity on so line') self.assertEqual(sale_order.invoice_status, 'invoiced', 'Sale Timesheet: "invoice on order" timesheets should not modify the invoice_status of the so') self.assertEqual(timesheet1.timesheet_invoice_type, 'billable_fixed', "Timesheets linked to SO line with ordered product shoulbe be billable fixed") self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice, since we are in ordered quantity") timesheet2 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 39.5, 'employee_id': self.employee_user.id, }) self.assertEqual(so_line_ordered_global_project.qty_delivered, 50, 'Sale Timesheet: timesheet does not increase delivered quantity on so line') self.assertEqual(sale_order.invoice_status, 'invoiced', 'Sale Timesheet: "invoice on order" timesheets should not modify the invoice_status of the so') self.assertEqual(timesheet2.timesheet_invoice_type, 'billable_fixed', "Timesheets linked to SO line with ordered product shoulbe be billable fixed") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet should not be linked to the invoice, since we are in ordered quantity") timesheet3 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'unit_amount': 10, 'employee_id': self.employee_user.id, }) self.assertEqual(so_line_ordered_project_only.qty_delivered, 0.0, 'Timesheet directly on project does not increase delivered quantity on so line') self.assertEqual(timesheet3.timesheet_invoice_type, 'non_billable', "Timesheets without SO should be be 'non-billable'") self.assertFalse(timesheet3.timesheet_invoice_id, "The timesheet should not be linked to the invoice, since we are in ordered quantity") # log timesheet on task in global project (higher than the initial ordrered qty) timesheet4 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 5, 'employee_id': self.employee_user.id, }) self.assertEqual(sale_order.invoice_status, 'upselling', 'Sale Timesheet: "invoice on order" timesheets should not modify the invoice_status of the so') self.assertFalse(timesheet4.timesheet_invoice_id, "The timesheet should not be linked to the invoice, since we are in ordered quantity") # add so line with produdct "create task in new project". so_line_ordered_task_in_project = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet3.name, 'product_id': self.product_order_timesheet3.id, 'product_uom_qty': 3, 'product_uom': self.product_order_timesheet3.uom_id.id, 'price_unit': self.product_order_timesheet3.list_price, 'order_id': sale_order.id, }) self.assertEqual(sale_order.invoice_status, 'to invoice', 'Sale Timesheet: Adding a new service line (so line) should put the SO in "to invocie" state.') self.assertEqual(sale_order.tasks_count, 2, "Two tasks (1 per SO line) should have been created on SO confirmation") self.assertEqual(len(sale_order.project_ids), 2, "No new project should have been created by the SO, when selling 'new task in new project' product, since it reuse the one from 'project only'.") # get first invoice line of sale line linked to timesheet1 invoice_line_1 = so_line_ordered_global_project.invoice_lines.filtered(lambda line: line.move_id == invoice1) self.assertEqual(so_line_ordered_global_project.product_uom_qty, invoice_line_1.quantity, "The invoice (ordered) quantity should not change when creating timesheet") # timesheet can be modified timesheet1.write({'unit_amount': 12}) self.assertEqual(so_line_ordered_global_project.product_uom_qty, invoice_line_1.quantity, "The invoice (ordered) quantity should not change when modifying timesheet") # create second invoice invoice2 = sale_order._create_invoices()[0] self.assertEqual(len(sale_order.invoice_ids), 2, "A second invoice should have been created from the SO") self.assertTrue(float_is_zero(invoice2.amount_total - so_line_ordered_task_in_project.price_unit * 3, precision_digits=2), 'Sale: invoice generation on timesheets product is wrong') self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet2 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet3.timesheet_invoice_id, "The timesheet3 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet4.timesheet_invoice_id, "The timesheet4 should not be linked to the invoice, since we are in ordered quantity") # validate the first invoice invoice1.action_post() self.assertEqual(so_line_ordered_global_project.product_uom_qty, invoice_line_1.quantity, "The invoice (ordered) quantity should not change when modifying timesheet") self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet2 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet3.timesheet_invoice_id, "The timesheet3 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet4.timesheet_invoice_id, "The timesheet4 should not be linked to the invoice, since we are in ordered quantity") # timesheet can still be modified timesheet1.write({'unit_amount': 13}) def test_timesheet_delivery(self): """ Test timesheet invoicing with 'invoice on delivery' timetracked products 1. Create SO and confirm it 2. log timesheet 3. create invoice 4. log other timesheet 5. create a second invoice 6. add new SO line (delivered service) """ # create SO and confirm it sale_order = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) so_line_deliver_global_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': sale_order.id, }) so_line_deliver_task_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 20, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': sale_order.id, }) so_line_deliver_global_project.product_id_change() so_line_deliver_task_project.product_id_change() # confirm SO sale_order.action_confirm() task_serv1 = self.env['project.task'].search([('sale_line_id', '=', so_line_deliver_global_project.id)]) task_serv2 = self.env['project.task'].search([('sale_line_id', '=', so_line_deliver_task_project.id)]) project_serv2 = self.env['project.project'].search([('sale_line_id', '=', so_line_deliver_task_project.id)]) self.assertEqual(task_serv1.project_id, self.project_global, "Sale Timesheet: task should be created in global project") self.assertTrue(task_serv1, "Sale Timesheet: on SO confirmation, a task should have been created in global project") self.assertTrue(task_serv2, "Sale Timesheet: on SO confirmation, a task should have been created in a new project") self.assertEqual(sale_order.invoice_status, 'no', 'Sale Timesheet: "invoice on delivery" should not need to be invoiced on so confirmation') self.assertEqual(sale_order.analytic_account_id, task_serv2.project_id.analytic_account_id, "SO should have create a project") self.assertEqual(sale_order.tasks_count, 2, "Two tasks (1 per SO line) should have been created on SO confirmation") self.assertEqual(len(sale_order.project_ids), 2, "One project should have been created by the SO, when confirmed + the one from SO line 1 'task in global project'") self.assertEqual(sale_order.analytic_account_id, project_serv2.analytic_account_id, "The created project should be linked to the analytic account of the SO") # let's log some timesheets timesheet1 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv1.project_id.id, # global project 'task_id': task_serv1.id, 'unit_amount': 10.5, 'employee_id': self.employee_manager.id, }) self.assertEqual(so_line_deliver_global_project.invoice_status, 'to invoice', 'Sale Timesheet: "invoice on delivery" timesheets should set the so line in "to invoice" status when logged') self.assertEqual(so_line_deliver_task_project.invoice_status, 'no', 'Sale Timesheet: so line invoice status should not change when no timesheet linked to the line') self.assertEqual(sale_order.invoice_status, 'to invoice', 'Sale Timesheet: "invoice on delivery" timesheets should set the so in "to invoice" status when logged') self.assertEqual(timesheet1.timesheet_invoice_type, 'billable_time', "Timesheets linked to SO line with delivered product shoulbe be billable time") self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice yet") # invoice SO invoice1 = sale_order._create_invoices() self.assertTrue(float_is_zero(invoice1.amount_total - so_line_deliver_global_project.price_unit * 10.5, precision_digits=2), 'Sale: invoice generation on timesheets product is wrong') self.assertEqual(timesheet1.timesheet_invoice_id, invoice1, "The timesheet1 should not be linked to the invoice 1, as we are in delivered quantity (even if invoice is in draft") with self.assertRaises(UserError): # We can not modify timesheet linked to invoice (even draft ones) timesheet1.write({'unit_amount': 42}) # log some timesheets again timesheet2 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv1.project_id.id, # global project 'task_id': task_serv1.id, 'unit_amount': 39.5, 'employee_id': self.employee_user.id, }) self.assertEqual(so_line_deliver_global_project.invoice_status, 'to invoice', 'Sale Timesheet: "invoice on delivery" timesheets should set the so line in "to invoice" status when logged') self.assertEqual(so_line_deliver_task_project.invoice_status, 'no', 'Sale Timesheet: so line invoice status should not change when no timesheet linked to the line') self.assertEqual(sale_order.invoice_status, 'to invoice', 'Sale Timesheet: "invoice on delivery" timesheets should not modify the invoice_status of the so') self.assertEqual(timesheet2.timesheet_invoice_type, 'billable_time', "Timesheets linked to SO line with delivered product shoulbe be billable time") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet2 should not be linked to the invoice yet") # create a second invoice invoice2 = sale_order._create_invoices()[0] self.assertEqual(len(sale_order.invoice_ids), 2, "A second invoice should have been created from the SO") self.assertEqual(so_line_deliver_global_project.invoice_status, 'invoiced', 'Sale Timesheet: "invoice on delivery" timesheets should set the so line in "to invoice" status when logged') self.assertEqual(sale_order.invoice_status, 'no', 'Sale Timesheet: "invoice on delivery" timesheets should be invoiced completely by now') self.assertEqual(timesheet2.timesheet_invoice_id, invoice2, "The timesheet2 should not be linked to the invoice 2") with self.assertRaises(UserError): # We can not modify timesheet linked to invoice (even draft ones) timesheet2.write({'unit_amount': 42}) # add a line on SO so_line_deliver_only_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet4.name, 'product_id': self.product_delivery_timesheet4.id, 'product_uom_qty': 5, 'product_uom': self.product_delivery_timesheet4.uom_id.id, 'price_unit': self.product_delivery_timesheet4.list_price, 'order_id': sale_order.id, }) self.assertEqual(len(sale_order.project_ids), 2, "No new project should have been created by the SO, when selling 'project only' product, since it reuse the one from 'new task in new project'.") # let's log some timesheets on the project timesheet3 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': project_serv2.id, 'unit_amount': 7, 'employee_id': self.employee_user.id, }) self.assertTrue(float_is_zero(so_line_deliver_only_project.qty_delivered, precision_digits=2), "Timesheeting on project should not incremented the delivered quantity on the SO line") self.assertEqual(sale_order.invoice_status, 'to invoice', 'Sale Timesheet: "invoice on delivery" timesheets should have quantity to invoice') self.assertEqual(timesheet3.timesheet_invoice_type, 'billable_time', "Timesheets with an amount > 0 should be 'billable time'") self.assertFalse(timesheet3.timesheet_invoice_id, "The timesheet3 should not be linked to the invoice yet") # let's log some timesheets on the task (new task/new project) timesheet4 = self.env['account.analytic.line'].create({ 'name': 'Test Line 4', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 7, 'employee_id': self.employee_user.id, }) self.assertFalse(timesheet4.timesheet_invoice_id, "The timesheet4 should not be linked to the invoice yet") # modify a non invoiced timesheet timesheet4.write({'unit_amount': 42}) self.assertFalse(timesheet4.timesheet_invoice_id, "The timesheet4 should not still be linked to the invoice") # validate the second invoice invoice2.action_post() self.assertEqual(timesheet1.timesheet_invoice_id, invoice1, "The timesheet1 should not be linked to the invoice 1, even after validation") self.assertEqual(timesheet2.timesheet_invoice_id, invoice2, "The timesheet2 should not be linked to the invoice 1, even after validation") self.assertFalse(timesheet3.timesheet_invoice_id, "The timesheet3 should not be linked to the invoice, since we are in ordered quantity") self.assertFalse(timesheet4.timesheet_invoice_id, "The timesheet4 should not be linked to the invoice, since we are in ordered quantity") def test_timesheet_manual(self): """ Test timesheet invoicing with 'invoice on delivery' timetracked products """ # create SO and confirm it sale_order = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) so_line_manual_global_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_manual2.name, 'product_id': self.product_delivery_manual2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_manual2.uom_id.id, 'price_unit': self.product_delivery_manual2.list_price, 'order_id': sale_order.id, }) so_line_manual_only_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_manual4.name, 'product_id': self.product_delivery_manual4.id, 'product_uom_qty': 20, 'product_uom': self.product_delivery_manual4.uom_id.id, 'price_unit': self.product_delivery_manual4.list_price, 'order_id': sale_order.id, }) # confirm SO sale_order.action_confirm() self.assertTrue(sale_order.project_ids, "Sales Order should have create a project") self.assertEqual(sale_order.invoice_status, 'no', 'Sale Timesheet: manually product should not need to be invoiced on so confirmation') project_serv2 = so_line_manual_only_project.project_id self.assertTrue(project_serv2, "A second project is created when selling 'project only' after SO confirmation.") self.assertEqual(sale_order.analytic_account_id, project_serv2.analytic_account_id, "The created project should be linked to the analytic account of the SO") # let's log some timesheets (on task and project) timesheet1 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': self.project_global.id, # global project 'task_id': so_line_manual_global_project.task_id.id, 'unit_amount': 6, 'employee_id': self.employee_manager.id, }) timesheet2 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': self.project_global.id, # global project 'unit_amount': 3, 'employee_id': self.employee_manager.id, }) self.assertEqual(len(sale_order.project_ids), 2, "One project should have been created by the SO, when confirmed + the one coming from SO line 1 'task in global project'.") self.assertEqual(so_line_manual_global_project.task_id.sale_line_id, so_line_manual_global_project, "Task from a milestone product should be linked to its SO line too") self.assertEqual(timesheet1.timesheet_invoice_type, 'billable_fixed', "Milestone timesheet goes in billable fixed category") self.assertTrue(float_is_zero(so_line_manual_global_project.qty_delivered, precision_digits=2), "Milestone Timesheeting should not incremented the delivered quantity on the SO line") self.assertEqual(so_line_manual_global_project.qty_to_invoice, 0.0, "Manual service should not be affected by timesheet on their created task.") self.assertEqual(so_line_manual_only_project.qty_to_invoice, 0.0, "Manual service should not be affected by timesheet on their created project.") self.assertEqual(sale_order.invoice_status, 'no', 'Sale Timesheet: "invoice on delivery" should not need to be invoiced on so confirmation') self.assertEqual(timesheet1.timesheet_invoice_type, 'billable_fixed', "Timesheets linked to SO line with ordered product shoulbe be billable fixed since it is a milestone") self.assertEqual(timesheet2.timesheet_invoice_type, 'non_billable', "Timesheets without SO should be be 'non-billable'") self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet2 should not be linked to the invoice") # invoice SO sale_order.order_line.write({'qty_delivered': 5}) invoice1 = sale_order._create_invoices() for invoice_line in invoice1.invoice_line_ids: self.assertEqual(invoice_line.quantity, 5, "The invoiced quantity should be 5, as manually set on SO lines") self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice, since timesheets are used for time tracking in milestone") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet2 should not be linked to the invoice, since timesheets are used for time tracking in milestone") # validate the invoice invoice1.action_post() self.assertFalse(timesheet1.timesheet_invoice_id, "The timesheet1 should not be linked to the invoice, even after invoice validation") self.assertFalse(timesheet2.timesheet_invoice_id, "The timesheet2 should not be linked to the invoice, even after invoice validation") def test_timesheet_invoice(self): """ Test to create invoices for the sale order with timesheets 1) create sale order 2) try to create an invoice for the timesheets 10 days before 3) create invoice for the timesheets 6 days before 4) create invoice for the timesheets 4 days before 5) create invoice for the timesheets from today """ today = Date.context_today(self.env.user) sale_order = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) # Section Line so_line_ordered_project_only = self.env['sale.order.line'].create({ 'name': "Section Name", 'order_id': sale_order.id, 'display_type': 'line_section', }) so_line_deliver_global_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': sale_order.id, }) so_line_deliver_task_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 20, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': sale_order.id, }) so_line_deliver_global_project.product_id_change() so_line_deliver_task_project.product_id_change() # confirm SO sale_order.action_confirm() task_serv1 = self.env['project.task'].search([('sale_line_id', '=', so_line_deliver_global_project.id)]) task_serv2 = self.env['project.task'].search([('sale_line_id', '=', so_line_deliver_task_project.id)]) project_serv2 = self.env['project.project'].search([('sale_line_id', '=', so_line_deliver_task_project.id)]) timesheet1 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv1.project_id.id, 'task_id': task_serv1.id, 'unit_amount': 10, 'employee_id': self.employee_manager.id, 'date': today - timedelta(days=6) }) timesheet2 = self.env['account.analytic.line'].create({ 'name': 'Test Line 2', 'project_id': task_serv1.project_id.id, 'task_id': task_serv1.id, 'unit_amount': 20, 'employee_id': self.employee_manager.id, 'date': today - timedelta(days=1) }) timesheet3 = self.env['account.analytic.line'].create({ 'name': 'Test Line 3', 'project_id': task_serv1.project_id.id, 'task_id': task_serv1.id, 'unit_amount': 10, 'employee_id': self.employee_manager.id, 'date': today - timedelta(days=5) }) timesheet4 = self.env['account.analytic.line'].create({ 'name': 'Test Line 4', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 30, 'employee_id': self.employee_manager.id }) self.assertEqual(so_line_deliver_global_project.invoice_status, 'to invoice') self.assertEqual(so_line_deliver_task_project.invoice_status, 'to invoice') self.assertEqual(sale_order.invoice_status, 'to invoice') # Context for sale.advance.payment.inv wizard self.context = { 'active_model': 'sale.order', 'active_ids': [sale_order.id], 'active_id': sale_order.id, 'default_journal_id': self.company_data['default_journal_sale'].id } # invoice SO wizard = self.env['sale.advance.payment.inv'].with_context(self.context).create({ 'advance_payment_method': 'delivered', 'date_start_invoice_timesheet': today - timedelta(days=16), 'date_end_invoice_timesheet': today - timedelta(days=10) }) self.assertTrue(wizard.invoicing_timesheet_enabled, 'The "date_start_invoice_timesheet" and "date_end_invoice_timesheet" field should be visible in the wizard because a product in sale order has service_policy to "Timesheet on Task"') with self.assertRaises(UserError): wizard.create_invoices() self.assertFalse(sale_order.invoice_ids, 'Normally, no invoice will be created because the timesheet logged is after the period defined in date_start_invoice_timesheet and date_end_invoice_timesheet field') wizard.write({ 'date_start_invoice_timesheet': today - timedelta(days=10), 'date_end_invoice_timesheet': today - timedelta(days=6) }) wizard.create_invoices() self.assertTrue(sale_order.invoice_ids, 'One invoice should be created because the timesheet logged is between the period defined in wizard') self.assertTrue(all(line.invoice_status == "to invoice" for line in sale_order.order_line if line.qty_delivered != line.qty_invoiced), "All lines that still have some quantity to be invoiced should have an invoice status of 'to invoice', regardless if they were considered for previous invoicing, but didn't belong to the timesheet domain") invoice = sale_order.invoice_ids[0] self.assertEqual(so_line_deliver_global_project.qty_invoiced, timesheet1.unit_amount) # validate invoice invoice.action_post() wizard.write({ 'date_start_invoice_timesheet': today - timedelta(days=16), 'date_end_invoice_timesheet': today - timedelta(days=4) }) wizard.create_invoices() self.assertEqual(len(sale_order.invoice_ids), 2) invoice2 = sale_order.invoice_ids[-1] self.assertEqual(so_line_deliver_global_project.qty_invoiced, timesheet1.unit_amount + timesheet3.unit_amount, "The last invoice done should have the quantity of the timesheet 3, because the date this timesheet is the only one before the 'date_end_invoice_timesheet' field in the wizard.") wizard.write({ 'date_start_invoice_timesheet': today - timedelta(days=4), 'date_end_invoice_timesheet': today }) wizard.create_invoices() self.assertEqual(len(sale_order.invoice_ids), 3) invoice3 = sale_order.invoice_ids[-1] # Check if all timesheets have been invoiced self.assertEqual(so_line_deliver_global_project.qty_invoiced, timesheet1.unit_amount + timesheet2.unit_amount + timesheet3.unit_amount) self.assertTrue(so_line_deliver_task_project.invoice_lines) self.assertEqual(so_line_deliver_task_project.qty_invoiced, timesheet4.unit_amount) def test_transfert_project(self): """ Transfert task with timesheet to another project. """ Timesheet = self.env['account.analytic.line'] Task = self.env['project.task'] today = Date.context_today(self.env.user) task = Task.with_context(default_project_id=self.project_template.id).create({ 'name': 'first task', 'partner_id': self.partner_b.id, 'planned_hours': 10, 'sale_line_id': self.so.order_line[0].id }) Timesheet.create({ 'project_id': self.project_template.id, 'task_id': task.id, 'name': 'my first timesheet', 'unit_amount': 4, }) timesheet_count1 = Timesheet.search_count([('project_id', '=', self.project_global.id)]) timesheet_count2 = Timesheet.search_count([('project_id', '=', self.project_template.id)]) self.assertEqual(timesheet_count1, 0, "No timesheet in project_global") self.assertEqual(timesheet_count2, 1, "One timesheet in project_template") self.assertEqual(len(task.timesheet_ids), 1, "The timesheet should be linked to task") # change project of task, as the timesheet is not yet invoiced, the timesheet will change his project task.write({ 'project_id': self.project_global.id }) timesheet_count1 = Timesheet.search_count([('project_id', '=', self.project_global.id)]) timesheet_count2 = Timesheet.search_count([('project_id', '=', self.project_template.id)]) self.assertEqual(timesheet_count1, 1, "One timesheet in project_global") self.assertEqual(timesheet_count2, 0, "No timesheet in project_template") self.assertEqual(len(task.timesheet_ids), 1, "The timesheet still should be linked to task") # Create an invoice context = { 'active_model': 'sale.order', 'active_ids': [self.so.id], 'active_id': self.so.id, 'default_journal_id': self.company_data['default_journal_sale'].id } wizard = self.env['sale.advance.payment.inv'].with_context(context).create({ 'advance_payment_method': 'delivered', 'date_start_invoice_timesheet': today - timedelta(days=4), 'date_end_invoice_timesheet': today, }) wizard.create_invoices() Timesheet.create({ 'project_id': self.project_global.id, 'task_id': task.id, 'name': 'my second timesheet', 'unit_amount': 6, }) self.assertEqual(Timesheet.search_count([('project_id', '=', self.project_global.id)]), 2, "2 timesheets in project_global") # change project of task, the timesheet not yet invoiced will change its project. The timesheet already invoiced will not change his project. task.write({ 'project_id': self.project_template.id }) timesheet_count1 = Timesheet.search_count([('project_id', '=', self.project_global.id)]) timesheet_count2 = Timesheet.search_count([('project_id', '=', self.project_template.id)]) self.assertEqual(timesheet_count1, 1, "Still one timesheet in project_global") self.assertEqual(timesheet_count2, 1, "One timesheet in project_template") self.assertEqual(len(task.timesheet_ids), 2, "The 2 timesheets still should be linked to task") def test_change_customer_and_SOL_after_invoiced_timesheet(self): sale_order1 = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) sale_order2 = self.env['sale.order'].create({ 'partner_id': self.partner_b.id, 'partner_invoice_id': self.partner_b.id, 'partner_shipping_id': self.partner_b.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) so1_product_global_project_so_line = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': sale_order1.id, }) so2_product_global_project_so_line = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 20, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': sale_order2.id, }) sale_order1.action_confirm() sale_order2.action_confirm() task_so1 = self.env['project.task'].search([('sale_line_id', '=', so1_product_global_project_so_line.id)]) task_so2 = self.env['project.task'].search([('sale_line_id', '=', so2_product_global_project_so_line.id)]) self.assertEqual(self.partner_a, task_so1.partner_id, "The Customer of the first task should be equal to partner_a.") self.assertEqual(self.partner_b, task_so2.partner_id, "The Customer of the second task should be equal to partner_b.") self.assertEqual(sale_order1.partner_id, task_so1.partner_id, "The Customer of the first task should be equal to the Customer of the first Sales Order.") self.assertEqual(sale_order2.partner_id, task_so2.partner_id, "The Customer of the second task should be equal to the Customer of the second Sales Order.") task_so1_timesheet1 = self.env['account.analytic.line'].create({ 'name': 'Test Line1', 'project_id': task_so1.project_id.id, 'task_id': task_so1.id, 'unit_amount': 5, 'employee_id': self.employee_user.id, }) invoice = sale_order1._create_invoices() invoice.action_post() self.assertEqual(self.partner_a, task_so1_timesheet1.partner_id, "The Task's Timesheet entry should have the same partner than on the task 1 and Sales Order 1.") task_so1_timesheet2 = self.env['account.analytic.line'].create({ 'name': 'Test Line2', 'project_id': task_so1.project_id.id, 'task_id': task_so1.id, 'unit_amount': 3, 'employee_id': self.employee_user.id, }) task_so1.write({ 'partner_id': self.partner_b.id, 'sale_line_id': so2_product_global_project_so_line.id, }) self.assertEqual(self.partner_a, task_so1_timesheet1.partner_id, "The Task's first Timesheet entry should not have changed as it was already invoiced (its partner should still be partner_a).") self.assertEqual(self.partner_b, task_so1_timesheet2.partner_id, "The Task's second Timesheet entry should have its partner changed, as it was not invoiced and the Task's partner/customer changed.") self.assertEqual(so1_product_global_project_so_line, task_so1_timesheet1.so_line, "The Task's first Timesheet entry should not have changed as it was already invoiced (its so_line should still be equal to the first Sales Order line).") self.assertEqual(so2_product_global_project_so_line, task_so1_timesheet2.so_line, "The Task's second Timesheet entry should have it's so_line changed, as the Sales Order Item of the Task changed, and this entry was not invoiced.") def test_timesheet_upsell(self): """ Test timesheet upselling and email """ sale_order = self.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'user_id': self.user_employee_company_B.id, }) # create SO and confirm it uom_days = self.env.ref('uom.product_uom_day') sale_order_line = self.env['sale.order.line'].create({ 'order_id': sale_order.id, 'name': self.product_order_timesheet3.name, 'product_id': self.product_order_timesheet3.id, 'product_uom_qty': 1, 'product_uom': uom_days.id, 'price_unit': self.product_order_timesheet3.list_price, }) sale_order.action_confirm() task = sale_order_line.task_id # let's log some timesheets self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 8, 'employee_id': self.employee_manager.id, }) sale_order._create_invoices() last_message_id = self.env['mail.message'].search([('model', '=', 'sale.order'), ('res_id', '=', sale_order.id)], limit=1).id or 0 self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 5, 'employee_id': self.employee_user.id, }) self.assertEqual(sale_order.invoice_status, 'upselling', 'Sale Timesheet: "invoice on delivery" timesheets should not modify the invoice_status of the so') message_sent = self.env['mail.message'].search([ ('id', '>', last_message_id), ('subject', 'like', 'Upsell'), ('model', '=', 'sale.order'), ('res_id', '=', sale_order.id), ]) self.assertEqual(len(message_sent), 1, 'Sale Timesheet: An email should always be sent to the saleperson when the state of the sale order change to upselling') self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 5, 'employee_id': self.employee_user.id, }) message_sent = self.env['mail.message'].search([ ('id', '>', last_message_id), ('subject', 'like', 'Upsell'), ('model', '=', 'sale.order'), ('res_id', '=', sale_order.id), ]) self.assertEqual(len(message_sent), 1, 'Sale Timesheet: An email should only be sent to the saleperson when the state of the sale order change to upselling') def test_unlink_timesheet(self): sale_order = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'pricelist_id': self.company_data['default_pricelist'].id, }) so_line = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': sale_order.id, }) sale_order.action_confirm() task = so_line.task_id # let's log some timesheets analytic_line = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 50, 'employee_id': self.employee_manager.id, }) move = sale_order._create_invoices() self.assertEqual(analytic_line.timesheet_invoice_id, move, "The timesheet should be linked to move") move.with_context(check_move_validity=False).line_ids[0].unlink() self.assertFalse(analytic_line.timesheet_invoice_id,"The timesheet should have been unlinked from move")
57.449351
44,236
6,102
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tools import float_is_zero, float_compare from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet class TestCommonReporting(TestCommonSaleTimesheet): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # expense product cls.product_expense = cls.env['product.product'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'name': "Expense service", 'standard_price': 10, 'list_price': 20, 'type': 'service', 'invoice_policy': 'delivery', 'expense_policy': 'sales_price', 'default_code': 'EXP', 'service_type': 'manual', 'taxes_id': False, 'property_account_income_id': cls.company_data['default_account_revenue'].id, }) # create Analytic Accounts cls.analytic_account_1 = cls.env['account.analytic.account'].create({ 'name': 'Test AA 1', 'code': 'AA1', 'company_id': cls.company_data['company'].id, 'partner_id': cls.partner_a.id }) cls.analytic_account_2 = cls.env['account.analytic.account'].create({ 'name': 'Test AA 2', 'code': 'AA2', 'company_id': cls.company_data['company'].id, 'partner_id': cls.partner_a.id }) cls.analytic_account_3 = cls.env['account.analytic.account'].create({ 'name': 'Test AA 3', 'code': 'AA3', 'company_id': cls.company_data['company'].id, 'partner_id': cls.partner_a.id }) # Sale orders each will create project and a task in a global project (one SO is 'delivered', the other is 'ordered') # and a third one using fixed_price (which is 'delivered') cls.sale_order_1 = cls.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, 'analytic_account_id': cls.analytic_account_1.id, }) cls.so_line_deliver_project = cls.env['sale.order.line'].create({ 'name': cls.product_delivery_timesheet3.name, 'product_id': cls.product_delivery_timesheet3.id, 'product_uom_qty': 5, 'product_uom': cls.product_delivery_timesheet3.uom_id.id, 'price_unit': cls.product_delivery_timesheet3.list_price, 'order_id': cls.sale_order_1.id, }) cls.so_line_deliver_task = cls.env['sale.order.line'].create({ 'name': cls.product_delivery_timesheet2.name, 'product_id': cls.product_delivery_timesheet2.id, 'product_uom_qty': 7, 'product_uom': cls.product_delivery_timesheet2.uom_id.id, 'price_unit': cls.product_delivery_timesheet2.list_price, 'order_id': cls.sale_order_1.id, }) cls.sale_order_2 = cls.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, 'analytic_account_id': cls.analytic_account_2.id, }) cls.so_line_order_project = cls.env['sale.order.line'].create({ 'name': cls.product_order_timesheet3.name, 'product_id': cls.product_order_timesheet3.id, 'product_uom_qty': 5, 'product_uom': cls.product_order_timesheet3.uom_id.id, 'price_unit': cls.product_order_timesheet3.list_price, 'order_id': cls.sale_order_2.id, }) cls.so_line_order_task = cls.env['sale.order.line'].create({ 'name': cls.product_order_timesheet2.name, 'product_id': cls.product_order_timesheet2.id, 'product_uom_qty': 7, 'product_uom': cls.product_order_timesheet2.uom_id.id, 'price_unit': cls.product_order_timesheet2.list_price, 'order_id': cls.sale_order_2.id, }) cls.sale_order_3 = cls.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, 'analytic_account_id': cls.analytic_account_3.id, }) cls.so_line_deliver_manual_project = cls.env['sale.order.line'].create({ 'name': cls.product_delivery_manual3.name, 'product_id': cls.product_delivery_manual3.id, 'product_uom_qty': 11, 'product_uom': cls.product_delivery_manual3.uom_id.id, 'price_unit': cls.product_delivery_manual3.list_price, 'order_id': cls.sale_order_3.id, }) def _log_timesheet_user(self, project, unit_amount, task=False): """ Utility method to log timesheet """ Timesheet = self.env['account.analytic.line'] return Timesheet.create({ 'name': 'timesheet employee on project_so_1 only', 'account_id': project.analytic_account_id.id, 'project_id': project.id, 'employee_id': self.employee_user.id, 'unit_amount': unit_amount, 'task_id': task.id if task else False, }) def _log_timesheet_manager(self, project, unit_amount, task=False): """ Utility method to log timesheet """ Timesheet = self.env['account.analytic.line'] return Timesheet.create({ 'name': 'timesheet employee on project_so_1 only', 'account_id': project.analytic_account_id.id, 'project_id': project.id, 'employee_id': self.employee_manager.id, 'unit_amount': unit_amount, 'task_id': task.id if task else False, })
46.227273
6,102
41,581
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet from odoo.exceptions import UserError, ValidationError from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestSaleService(TestCommonSaleTimesheet): """ This test suite provide checks for miscellaneous small things. """ @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.sale_order = cls.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, }) def test_sale_service(self): """ Test task creation when confirming a sale_order with the corresponding product """ sale_order_line = self.env['sale.order.line'].create({ 'order_id': self.sale_order.id, 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price }) self.sale_order.order_line._compute_product_updatable() self.assertTrue(sale_order_line.product_updatable) self.sale_order.action_confirm() self.sale_order.order_line._compute_product_updatable() self.sale_order.action_confirm() self.sale_order.order_line._compute_product_updatable() self.assertFalse(sale_order_line.product_updatable) self.assertEqual(self.sale_order.invoice_status, 'no', 'Sale Service: there should be nothing to invoice after validation') # check task creation project = self.project_global task = project.task_ids.filtered(lambda t: t.name == '%s: %s' % (self.sale_order.name, self.product_delivery_timesheet2.name)) self.assertTrue(task, 'Sale Service: task is not created, or it badly named') self.assertEqual(task.partner_id, self.sale_order.partner_id, 'Sale Service: customer should be the same on task and on SO') self.assertEqual(task.email_from, self.sale_order.partner_id.email, 'Sale Service: Task Email should be the same as the SO customer Email') # log timesheet on task self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': project.id, 'task_id': task.id, 'unit_amount': 50, 'employee_id': self.employee_manager.id, }) self.assertEqual(self.sale_order.invoice_status, 'to invoice', 'Sale Service: there should be sale_ordermething to invoice after registering timesheets') self.sale_order._create_invoices() self.assertTrue(sale_order_line.product_uom_qty == sale_order_line.qty_delivered == sale_order_line.qty_invoiced, 'Sale Service: line should be invoiced completely') self.assertEqual(self.sale_order.invoice_status, 'invoiced', 'Sale Service: SO should be invoiced') self.assertEqual(self.sale_order.tasks_count, 1, "A task should have been created on SO confirmation.") # Add a line on the confirmed SO, and it should generate a new task directly product_service_task = self.env['product.product'].create({ 'name': "Delivered Service", 'standard_price': 30, 'list_price': 90, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': self.env.ref('uom.product_uom_hour').id, 'uom_po_id': self.env.ref('uom.product_uom_hour').id, 'default_code': 'SERV-DELI', 'service_type': 'timesheet', 'service_tracking': 'task_global_project', 'project_id': project.id }) self.env['sale.order.line'].create({ 'name': product_service_task.name, 'product_id': product_service_task.id, 'product_uom_qty': 10, 'product_uom': product_service_task.uom_id.id, 'price_unit': product_service_task.list_price, 'order_id': self.sale_order.id, }) self.assertEqual(self.sale_order.tasks_count, 2, "Adding a new service line on a confirmer SO should create a new task.") # delete timesheets before deleting the task, so as to trigger the error # about linked sales order lines and not the one about linked timesheets task.timesheet_ids.unlink() # not possible to delete a task linked to a SOL with self.assertRaises(ValidationError): task.unlink() def test_timesheet_uom(self): """ Test timesheet invoicing and uom conversion """ # create SO and confirm it uom_days = self.env.ref('uom.product_uom_day') sale_order_line = self.env['sale.order.line'].create({ 'order_id': self.sale_order.id, 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 5, 'product_uom': uom_days.id, 'price_unit': self.product_delivery_timesheet3.list_price }) self.sale_order.action_confirm() task = self.env['project.task'].search([('sale_line_id', '=', sale_order_line.id)]) # let's log some timesheets self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 16, 'employee_id': self.employee_manager.id, }) self.assertEqual(sale_order_line.qty_delivered, 2, 'Sale: uom conversion of timesheets is wrong') self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 24, 'employee_id': self.employee_user.id, }) self.sale_order._create_invoices() self.assertEqual(self.sale_order.invoice_status, 'invoiced', 'Sale Timesheet: "invoice on delivery" timesheets should not modify the invoice_status of the so') def test_task_so_line_assignation(self): # create SO line and confirm it so_line_deliver_global_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 10, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': self.sale_order.id, }) so_line_deliver_global_project.product_id_change() self.sale_order.action_confirm() task_serv2 = self.env['project.task'].search([('sale_line_id', '=', so_line_deliver_global_project.id)]) # let's log some timesheets (on the project created by so_line_ordered_project_only) timesheets = self.env['account.analytic.line'] timesheets |= self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 4, 'employee_id': self.employee_user.id, }) timesheets |= self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 1, 'employee_id': self.employee_manager.id, }) self.assertTrue(all([billing_type == 'billable_time' for billing_type in timesheets.mapped('timesheet_invoice_type')]), "All timesheets linked to the task should be on 'billable time'") self.assertEqual(so_line_deliver_global_project.qty_to_invoice, 5, "Quantity to invoice should have been increased when logging timesheet on delivered quantities task") # invoice SO, and validate invoice invoice = self.sale_order._create_invoices()[0] invoice.action_post() # make task non billable task_serv2.write({'sale_line_id': False}) self.assertTrue(all([billing_type == 'billable_time' for billing_type in timesheets.mapped('timesheet_invoice_type')]), "billable type of timesheet should not change when tranfering task into another project") self.assertEqual(task_serv2.timesheet_ids.mapped('so_line'), so_line_deliver_global_project, "Old invoiced timesheet are not modified when changing the task SO line") # try to update timesheets, catch error 'You cannot modify invoiced timesheet' with self.assertRaises(UserError): timesheets.write({'so_line': False}) def test_delivered_quantity(self): # create SO line and confirm it so_line_deliver_new_task_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 10, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': self.sale_order.id, }) so_line_deliver_new_task_project.product_id_change() self.sale_order.action_confirm() task_serv2 = self.env['project.task'].search([('sale_line_id', '=', so_line_deliver_new_task_project.id)]) # add a timesheet timesheet1 = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 4, 'employee_id': self.employee_user.id, }) self.assertEqual(so_line_deliver_new_task_project.qty_delivered, timesheet1.unit_amount, 'Delivered quantity should be the same then its only related timesheet.') # remove the only timesheet timesheet1.unlink() self.assertEqual(so_line_deliver_new_task_project.qty_delivered, 0.0, 'Delivered quantity should be reset to zero, since there is no more timesheet.') # log 2 new timesheets timesheet2 = self.env['account.analytic.line'].create({ 'name': 'Test Line 2', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 4, 'employee_id': self.employee_user.id, }) timesheet3 = self.env['account.analytic.line'].create({ 'name': 'Test Line 3', 'project_id': task_serv2.project_id.id, 'task_id': task_serv2.id, 'unit_amount': 2, 'employee_id': self.employee_user.id, }) self.assertEqual(so_line_deliver_new_task_project.qty_delivered, timesheet2.unit_amount + timesheet3.unit_amount, 'Delivered quantity should be the sum of the 2 timesheets unit amounts.') # remove timesheet2 timesheet2.unlink() self.assertEqual(so_line_deliver_new_task_project.qty_delivered, timesheet3.unit_amount, 'Delivered quantity should be reset to the sum of remaining timesheets unit amounts.') def test_sale_create_task(self): """ Check that confirming SO create correctly a task, and reconfirming it does not create a second one. Also check changing the ordered quantity of a SO line that have created a task should update the planned hours of this task. """ so_line1 = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 7, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': self.sale_order.id, }) # confirm SO self.sale_order.action_confirm() self.assertTrue(so_line1.task_id, "SO confirmation should create a task and link it to SOL") self.assertTrue(so_line1.project_id, "SO confirmation should create a project and link it to SOL") self.assertEqual(self.sale_order.tasks_count, 1, "The SO should have only one task") self.assertEqual(so_line1.task_id.sale_line_id, so_line1, "The created task is also linked to its origin sale line, for invoicing purpose.") self.assertFalse(so_line1.task_id.user_ids, "The created task should be unassigned") self.assertEqual(so_line1.product_uom_qty, so_line1.task_id.planned_hours, "The planned hours should be the same as the ordered quantity of the native SO line") so_line1.write({'product_uom_qty': 20}) self.assertEqual(so_line1.product_uom_qty, so_line1.task_id.planned_hours, "The planned hours should have changed when updating the ordered quantity of the native SO line") # cancel SO self.sale_order.action_cancel() self.assertTrue(so_line1.task_id, "SO cancellation should keep the task") self.assertTrue(so_line1.project_id, "SO cancellation should create a project") self.assertEqual(self.sale_order.tasks_count, 1, "The SO should still have only one task") self.assertEqual(so_line1.task_id.sale_line_id, so_line1, "The created task is also linked to its origin sale line, for invoicing purpose.") so_line1.write({'product_uom_qty': 30}) self.assertEqual(so_line1.product_uom_qty, so_line1.task_id.planned_hours, "The planned hours should have changed when updating the ordered quantity, even after SO cancellation") # reconfirm SO self.sale_order.action_draft() self.sale_order.action_confirm() self.assertTrue(so_line1.task_id, "SO reconfirmation should not have create another task") self.assertTrue(so_line1.project_id, "SO reconfirmation should bit have create another project") self.assertEqual(self.sale_order.tasks_count, 1, "The SO should still have only one task") self.assertEqual(so_line1.task_id.sale_line_id, so_line1, "The created task is also linked to its origin sale line, for invoicing purpose.") self.sale_order.action_done() with self.assertRaises(UserError): so_line1.write({'product_uom_qty': 20}) def test_sale_create_project(self): """ A SO with multiple product that should create project (with and without template) like ; Line 1 : Service 1 create project with Template A ===> project created with template A Line 2 : Service 2 create project no template ==> empty project created Line 3 : Service 3 create project with Template A ===> Don't create any project because line 1 has already created a project with template A Line 4 : Service 4 create project no template ==> Don't create any project because line 2 has already created an empty project Line 5 : Service 5 create project with Template B ===> project created with template B """ # second project template and its associated product project_template2 = self.env['project.project'].create({ 'name': 'Second Project TEMPLATE for services', 'allow_timesheets': True, 'active': False, # this template is archived }) Stage = self.env['project.task.type'].with_context(default_project_id=project_template2.id) stage1_tmpl2 = Stage.create({ 'name': 'Stage 1', 'sequence': 1 }) stage2_tmpl2 = Stage.create({ 'name': 'Stage 2', 'sequence': 2 }) product_deli_ts_tmpl = self.env['product.product'].create({ 'name': "Service delivered, create project only based on template B", 'standard_price': 17, 'list_price': 34, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': self.env.ref('uom.product_uom_hour').id, 'uom_po_id': self.env.ref('uom.product_uom_hour').id, 'default_code': 'SERV-DELI4', 'service_type': 'timesheet', 'service_tracking': 'project_only', 'project_template_id': project_template2.id, 'project_id': False, 'taxes_id': False, 'property_account_income_id': self.account_sale.id, }) # create 5 so lines so_line1 = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet5.name, 'product_id': self.product_delivery_timesheet5.id, 'product_uom_qty': 11, 'product_uom': self.product_delivery_timesheet5.uom_id.id, 'price_unit': self.product_delivery_timesheet5.list_price, 'order_id': self.sale_order.id, }) so_line2 = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet4.name, 'product_id': self.product_order_timesheet4.id, 'product_uom_qty': 10, 'product_uom': self.product_order_timesheet4.uom_id.id, 'price_unit': self.product_order_timesheet4.list_price, 'order_id': self.sale_order.id, }) so_line3 = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet5.name, 'product_id': self.product_delivery_timesheet5.id, 'product_uom_qty': 5, 'product_uom': self.product_delivery_timesheet5.uom_id.id, 'price_unit': self.product_delivery_timesheet5.list_price, 'order_id': self.sale_order.id, }) so_line4 = self.env['sale.order.line'].create({ 'name': self.product_delivery_manual3.name, 'product_id': self.product_delivery_manual3.id, 'product_uom_qty': 4, 'product_uom': self.product_delivery_manual3.uom_id.id, 'price_unit': self.product_delivery_manual3.list_price, 'order_id': self.sale_order.id, }) so_line5 = self.env['sale.order.line'].create({ 'name': product_deli_ts_tmpl.name, 'product_id': product_deli_ts_tmpl.id, 'product_uom_qty': 8, 'product_uom': product_deli_ts_tmpl.uom_id.id, 'price_unit': product_deli_ts_tmpl.list_price, 'order_id': self.sale_order.id, }) # confirm SO self.sale_order.action_confirm() # check each line has or no generate something self.assertTrue(so_line1.project_id, "Line1 should have create a project based on template A") self.assertTrue(so_line2.project_id, "Line2 should have create an empty project") self.assertEqual(so_line3.project_id, so_line1.project_id, "Line3 should reuse project of line1") self.assertEqual(so_line4.project_id, so_line2.project_id, "Line4 should reuse project of line2") self.assertTrue(so_line4.task_id, "Line4 should have create a new task, even if no project created.") self.assertTrue(so_line5.project_id, "Line5 should have create a project based on template B") # check all generated project should be active, even if the template is not self.assertTrue(so_line1.project_id.active, "Project of Line1 should be active") self.assertTrue(so_line2.project_id.active, "Project of Line2 should be active") self.assertTrue(so_line5.project_id.active, "Project of Line5 should be active") # check generated stuff are correct self.assertTrue(so_line1.project_id in self.project_template_state.project_ids, "Stage 1 from template B should be part of project from so line 1") self.assertTrue(so_line1.project_id in self.project_template_state.project_ids, "Stage 1 from template B should be part of project from so line 1") self.assertTrue(so_line5.project_id in stage1_tmpl2.project_ids, "Stage 1 from template B should be part of project from so line 5") self.assertTrue(so_line5.project_id in stage2_tmpl2.project_ids, "Stage 2 from template B should be part of project from so line 5") self.assertTrue(so_line1.project_id.allow_timesheets, "Create project should allow timesheets") self.assertTrue(so_line2.project_id.allow_timesheets, "Create project should allow timesheets") self.assertTrue(so_line5.project_id.allow_timesheets, "Create project should allow timesheets") self.assertEqual(so_line4.task_id.project_id, so_line2.project_id, "Task created with line 4 should have the project based on template A of the SO.") self.assertEqual(so_line1.project_id.sale_line_id, so_line1, "SO line of project with template A should be the one that create it.") self.assertEqual(so_line2.project_id.sale_line_id, so_line2, "SO line of project should be the one that create it.") self.assertEqual(so_line5.project_id.sale_line_id, so_line5, "SO line of project with template B should be the one that create it.") def test_sale_task_in_project_with_project(self): """ This will test the new 'task_in_project' service tracking correctly creates tasks and projects when a project_id is configured on the parent sale_order (ref task #1915660). Setup: - Configure a project_id on the SO - SO line 1: a product with its delivery tracking set to 'task_in_project' - SO line 2: the same product as SO line 1 - SO line 3: a product with its delivery tracking set to 'project_only' - Confirm sale_order Expected result: - 2 tasks created on the project_id configured on the SO - 1 project created with the correct template for the 'project_only' product """ self.sale_order.write({'project_id': self.project_global.id}) self.sale_order._onchange_project_id() self.assertEqual(self.sale_order.analytic_account_id, self.analytic_account_sale, "Changing the project on the SO should set the analytic account accordingly.") so_line1 = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet3.name, 'product_id': self.product_order_timesheet3.id, 'product_uom_qty': 11, 'product_uom': self.product_order_timesheet3.uom_id.id, 'price_unit': self.product_order_timesheet3.list_price, 'order_id': self.sale_order.id, }) so_line2 = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet3.name, 'product_id': self.product_order_timesheet3.id, 'product_uom_qty': 10, 'product_uom': self.product_order_timesheet3.uom_id.id, 'price_unit': self.product_order_timesheet3.list_price, 'order_id': self.sale_order.id, }) so_line3 = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet4.name, 'product_id': self.product_order_timesheet4.id, 'product_uom_qty': 5, 'product_uom': self.product_order_timesheet4.uom_id.id, 'price_unit': self.product_order_timesheet4.list_price, 'order_id': self.sale_order.id, }) # temporary project_template_id for our checks self.product_order_timesheet4.write({ 'project_template_id': self.project_template.id }) self.sale_order.action_confirm() # remove it after the confirm because other tests don't like it self.product_order_timesheet4.write({ 'project_template_id': False }) self.assertTrue(so_line1.task_id, "so_line1 should create a task as its product's service_tracking is set as 'task_in_project'") self.assertEqual(so_line1.task_id.project_id, self.project_global, "The project on so_line1's task should be project_global as configured on its parent sale_order") self.assertTrue(so_line2.task_id, "so_line2 should create a task as its product's service_tracking is set as 'task_in_project'") self.assertEqual(so_line2.task_id.project_id, self.project_global, "The project on so_line2's task should be project_global as configured on its parent sale_order") self.assertFalse(so_line3.task_id.name, "so_line3 should not create a task as its product's service_tracking is set as 'project_only'") self.assertNotEqual(so_line3.project_id, self.project_template, "so_line3 should create a new project and not directly use the configured template") self.assertIn(self.project_template.name, so_line3.project_id.name, "The created project for so_line3 should use the configured template") def test_sale_task_in_project_without_project(self): """ This will test the new 'task_in_project' service tracking correctly creates tasks and projects when the parent sale_order does NOT have a configured project_id (ref task #1915660). Setup: - SO line 1: a product with its delivery tracking set to 'task_in_project' - Confirm sale_order Expected result: - 1 project created with the correct template for the 'task_in_project' because the SO does not have a configured project_id - 1 task created from this new project """ so_line1 = self.env['sale.order.line'].create({ 'name': self.product_order_timesheet3.name, 'product_id': self.product_order_timesheet3.id, 'product_uom_qty': 10, 'product_uom': self.product_order_timesheet3.uom_id.id, 'price_unit': self.product_order_timesheet3.list_price, 'order_id': self.sale_order.id, }) # temporary project_template_id for our checks self.product_order_timesheet3.write({ 'project_template_id': self.project_template.id }) self.sale_order.action_confirm() # remove it after the confirm because other tests don't like it self.product_order_timesheet3.write({ 'project_template_id': False }) self.assertTrue(so_line1.task_id, "so_line1 should create a task as its product's service_tracking is set as 'task_in_project'") self.assertNotEqual(so_line1.project_id, self.project_template, "so_line1 should create a new project and not directly use the configured template") self.assertIn(self.project_template.name, so_line1.project_id.name, "The created project for so_line1 should use the configured template") def test_billable_task_and_subtask(self): """ Test if subtasks and tasks are billed on the correct SO line """ # create SO line and confirm it so_line_deliver_new_task_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 10, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': self.sale_order.id, }) so_line_deliver_new_task_project_2 = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name + "(2)", 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 10, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': self.sale_order.id, }) so_line_deliver_new_task_project.product_id_change() so_line_deliver_new_task_project_2.product_id_change() self.sale_order.action_confirm() project = so_line_deliver_new_task_project.project_id task = so_line_deliver_new_task_project.task_id self.assertEqual(project.sale_line_id, so_line_deliver_new_task_project, "The created project should be linked to the so line") self.assertEqual(task.sale_line_id, so_line_deliver_new_task_project, "The created task should be linked to the so line") # create a new task and subtask subtask = self.env['project.task'].create({ 'parent_id': task.id, 'project_id': project.id, 'name': '%s: substask1' % (task.name,), }) task2 = self.env['project.task'].create({ 'project_id': project.id, 'name': '%s: substask1' % (task.name,) }) self.assertEqual(subtask.sale_line_id, task.sale_line_id, "By, default, a child task should have the same SO line as its mother") self.assertEqual(task2.sale_line_id, project.sale_line_id, "A new task in a billable project should have the same SO line as its project") self.assertEqual(task2.partner_id, so_line_deliver_new_task_project.order_partner_id, "A new task in a billable project should have the same SO line as its project") # moving subtask in another project subtask.write({'display_project_id': self.project_global.id}) self.assertEqual(subtask.sale_line_id, task.sale_line_id, "A child task should always have the same SO line as its mother, even when changing project") self.assertEqual(subtask.sale_line_id, so_line_deliver_new_task_project) # changing the SO line of the mother task task.write({'sale_line_id': so_line_deliver_new_task_project_2.id}) self.assertEqual(subtask.sale_line_id, so_line_deliver_new_task_project, "A child task is not impacted by the change of SO line of its mother") self.assertEqual(task.sale_line_id, so_line_deliver_new_task_project_2, "A mother task can have its SO line set manually") # changing the SO line of a subtask subtask.write({'sale_line_id': so_line_deliver_new_task_project_2.id}) self.assertEqual(subtask.sale_line_id, so_line_deliver_new_task_project_2, "A child can have its SO line set manually") def test_change_ordered_qty(self): """ Changing the ordered quantity of a SO line that have created a task should update the planned hours of this task """ sale_order_line = self.env['sale.order.line'].create({ 'order_id': self.sale_order.id, 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price }) self.sale_order.action_confirm() self.assertEqual(sale_order_line.product_uom_qty, sale_order_line.task_id.planned_hours, "The planned hours should be the same as the ordered quantity of the native SO line") sale_order_line.write({'product_uom_qty': 20}) self.assertEqual(sale_order_line.product_uom_qty, sale_order_line.task_id.planned_hours, "The planned hours should have changed when updating the ordered quantity of the native SO line") self.sale_order.action_cancel() sale_order_line.write({'product_uom_qty': 30}) self.assertEqual(sale_order_line.product_uom_qty, sale_order_line.task_id.planned_hours, "The planned hours should have changed when updating the ordered quantity, even after SO cancellation") self.sale_order.action_done() with self.assertRaises(UserError): sale_order_line.write({'product_uom_qty': 20}) def test_copy_billable_project_and_task(self): sale_order_line = self.env['sale.order.line'].create({ 'order_id': self.sale_order.id, 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 5, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price }) self.sale_order.action_confirm() task = self.env['project.task'].search([('sale_line_id', '=', sale_order_line.id)]) project = sale_order_line.project_id # copy the project project_copy = project.copy() self.assertFalse(project_copy.sale_line_id, "Duplicating project should erase its Sale line") self.assertFalse(project_copy.sale_order_id, "Duplicating project should erase its Sale order") self.assertEqual(len(project.tasks), len(project_copy.tasks), "Copied project must have the same number of tasks") self.assertFalse(project_copy.tasks.mapped('sale_line_id'), "The tasks of the duplicated project should not have a Sale Line set.") # copy the task task_copy = task.copy() self.assertEqual(task_copy.sale_line_id, task.sale_line_id, "Duplicating task should keep its Sale line") def test_remaining_hours_prepaid_services(self): """ Test if the remaining hours is correctly computed Test Case: ========= 1) Check the remaining hours in the SOL containing a prepaid service product, 2) Create task in project with pricing type is equal to "task rate" and has the customer in the SO and check if the remaining hours is equal to the remaining hours in the SOL, 3) Create timesheet in the task for this SOL and check if the remaining hours correctly decrease, 4) Change the SOL in the task and see if the remaining hours is correctly recomputed. 5) Create without storing the timesheet to check if remaining hours in SOL does not change. """ # 1) Check the remaining hours in the SOL containing a prepaid service product prepaid_service_sol = self.so.order_line.filtered(lambda sol: sol.product_id.service_policy == 'ordered_timesheet') self.assertEqual(len(prepaid_service_sol), 1, "It should only have one SOL with prepaid service product in this SO.") self.assertEqual(prepaid_service_sol.remaining_hours, prepaid_service_sol.product_uom_qty - prepaid_service_sol.qty_delivered, "The remaining hours of this SOL should be equal to the ordered quantity minus the delivered quantity.") # 2) Create task in project with pricing type is equal to "task rate" and has the customer in the SO # and check if the remaining hours is equal to the remaining hours in the SOL, task = self.env['project.task'].create({ 'name': 'Test task', 'project_id': self.project_task_rate.id, }) self.assertEqual(task.partner_id, self.project_task_rate.partner_id) self.assertEqual(task.partner_id, self.so.partner_id) self.assertEqual(task.remaining_hours_so, prepaid_service_sol.remaining_hours) # 3) Create timesheet in the task for this SOL and check if the remaining hours correctly decrease self.env['account.analytic.line'].create({ 'name': 'Test Timesheet', 'project_id': self.project_task_rate.id, 'task_id': task.id, 'unit_amount': 1, }) self.assertEqual(task.remaining_hours_so, 1, "Before the creation of a timesheet, the remaining hours was 2 hours, when we timesheet 1 hour, the remaining hours should be equal to 1 hour.") self.assertEqual(prepaid_service_sol.remaining_hours, task.remaining_hours_so, "The remaining hours on the SOL should also be equal to 1 hour.") # 4) Change the SOL in the task and see if the remaining hours is correctly recomputed. task.update({ 'sale_line_id': self.so.order_line[0].id, }) self.assertEqual(task.remaining_hours_so, False, "Since the SOL doesn't contain a prepaid service product, the remaining_hours_so should be equal to False.") self.assertEqual(prepaid_service_sol.remaining_hours, 2, "Since the timesheet on task has the same SOL than the one in the task, the remaining_hours should increase of 1 hour to be equal to 2 hours.") # 5) Create without storing the timesheet to check if remaining hours in SOL does not change timesheet = self.env['account.analytic.line'].new({ 'name': 'Test Timesheet', 'project_id': self.project_task_rate.id, 'task_id': task.id, 'unit_amount': 1, 'so_line': prepaid_service_sol.id, 'is_so_line_edited': True, }) self.assertEqual(timesheet.so_line, prepaid_service_sol, "The SOL should be the same than one containing the prepaid service product.") self.assertEqual(prepaid_service_sol.remaining_hours, 2, "The remaining hours should not change.") def test_several_uom_sol_to_planned_hours(self): planned_hours_for_uom = { 'day': 8.0, 'hour': 1.0, 'unit': 1.0, 'gram': 0.0, } Product = self.env['product.product'] product_vals = { 'type': 'service', 'service_type': 'timesheet', 'project_id': self.project_global.id, 'service_tracking': 'task_global_project', } SaleOrderLine = self.env['sale.order.line'] sol_vals = { 'product_uom_qty': 1, 'price_unit': 100, 'order_id': self.sale_order.id, } self.project_global.task_ids = False for uom_name in planned_hours_for_uom: uom_id = self.env.ref('uom.product_uom_%s' % uom_name) product_vals.update({ 'name': uom_name, 'uom_id': uom_id.id, 'uom_po_id': uom_id.id, }) product = Product.create(product_vals) sol_vals.update({ 'name': uom_name, 'product_id': product.id, 'product_uom': uom_id.id, }) SaleOrderLine.create(sol_vals) self.sale_order.action_confirm() tasks = self.project_global.task_ids for task in tasks: self.assertEqual(task.planned_hours, planned_hours_for_uom[task.sale_line_id.name]) project_updates_data = self.project_global._get_sold_items()['data'] for datum in project_updates_data: # A datum looks like this: {'name': 'day', 'value': '0.0 / 8.0 Hours',...} uom_in = datum['name'] # So the value looks like this: '0.0 / 8.0 Hours' # We extract the ordered quantity (second number in the string) and the displayed unit of measure values = datum['value'][6:].split(' ') qty = float(values[0]) uom_out = values[1] # All uom but grams should have been converted to company's project time unit company_time_uom = self.env.company.project_time_mode_id if uom_in == 'gram': self.assertEqual(qty, 1.0) self.assertEqual(uom_out, self.env.ref('uom.product_uom_gram').display_name) else: self.assertEqual(qty, planned_hours_for_uom[uom_in]) self.assertEqual(uom_out, company_time_uom.display_name) def test_add_product_analytic_account(self): """ When we have a project with an analytic account and we add a product to the task, the consequent invoice line should have the same analytic account as the project. """ # Ensure the SO has no analytic account to give to its SOLs self.assertFalse(self.sale_order.analytic_account_id) Product = self.env['product.product'] SaleOrderLine = self.env['sale.order.line'] # Create a SO with a service that creates a task product_create = Product.create({ 'name': 'Product that creates the task', 'type': 'service', 'service_type': 'timesheet', 'project_id': self.project_global.id, 'service_tracking': 'task_global_project', }) sale_order_line_create = SaleOrderLine.create({ 'order_id': self.sale_order.id, 'name': product_create.name, 'product_id': product_create.id, 'product_uom_qty': 5, 'product_uom': product_create.uom_id.id, 'price_unit': product_create.list_price, }) self.sale_order.action_confirm() # Add a SOL with a task_id to mimmic the "Add a product" flow on the task product_add = Product.create({'name': 'Product added on task'}) SaleOrderLine.create({ 'order_id': self.sale_order.id, 'name': product_add.name, 'product_id': product_add.id, 'product_uom_qty': 5, 'product_uom': product_add.uom_id.id, 'price_unit': product_add.list_price, 'task_id': sale_order_line_create.task_id.id, }) self.sale_order._create_invoices() # Check that the resulting invoice line and the project have the same analytic account invoice_line = self.sale_order.invoice_ids.line_ids.filtered(lambda line: line.product_id == product_add) self.assertEqual(invoice_line.analytic_account_id, self.project_global.analytic_account_id, "SOL's analytic account should be the same as the project's")
54.001299
41,581
118,570
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.osv import expression from odoo.tools import float_is_zero, float_compare from odoo.addons.sale_timesheet.tests.common_reporting import TestCommonReporting from odoo.tests import tagged, Form @tagged('-at_install', 'post_install') class TestReporting(TestCommonReporting): def test_profitability_report(self): # this test suppose everything is in the same currency as the current one currency = self.env.company.currency_id rounding = currency.rounding project_global_stat = self.env['project.profitability.report'].search([('project_id', '=', self.project_global.id)]).read()[0] self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") # confirm sales orders self.sale_order_1.action_confirm() self.sale_order_2.action_confirm() self.sale_order_3.action_confirm() self.env['project.profitability.report'].flush() project_so_1 = self.so_line_deliver_project.project_id project_so_2 = self.so_line_order_project.project_id project_so_3 = self.so_line_deliver_manual_project.project_id task_so_1 = self.so_line_deliver_project.task_id task_so_2 = self.so_line_order_project.task_id task_so_3 = self.so_line_deliver_manual_project.task_id task_in_global_1 = self.so_line_deliver_task.task_id task_in_global_2 = self.so_line_order_task.task_id # deliver project should not be impacted, as no timesheet are logged yet project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO1 should be 0.0") # order project should be to invoice, but nothing has been delivered yet project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], self.so_line_order_project.price_unit * self.so_line_order_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice should be the one from the SO line, as we are in ordered quantity") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # fixed price project should not be impacted, as no delivered quantity are logged yet project_so_3_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_3.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO3 should be 0.0") # global project now contain 3 tasks: 'deliver' ones which have no effect (no timesheet or delivered yet), and the 'order' one which should update the 'to invoice' amount project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the global project should be 0.0") self.assertEqual(float_compare(project_global_stat['amount_untaxed_to_invoice'], self.so_line_order_task.price_unit * self.so_line_order_task.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of global project should take the task in 'oredered qty' into account") self.assertTrue(float_is_zero(project_global_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") # logged some timesheets: on project only, then on tasks with different employees timesheet1 = self._log_timesheet_user(project_so_1, 2) timesheet2 = self._log_timesheet_user(project_so_2, 2) timesheet3 = self._log_timesheet_user(project_so_1, 3, task_so_1) timesheet4 = self._log_timesheet_user(project_so_2, 3, task_so_2) timesheet5 = self._log_timesheet_manager(project_so_1, 1, task_so_1) timesheet6 = self._log_timesheet_manager(project_so_2, 1, task_so_2) timesheet7 = self._log_timesheet_manager(self.project_global, 3, task_in_global_1) timesheet8 = self._log_timesheet_manager(self.project_global, 3, task_in_global_2) timesheet9 = self._log_timesheet_user(project_so_3, 4, task_so_3) self.env['project.profitability.report'].flush() # deliver project should now have cost and something to invoice project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_1_timesheet_cost = timesheet1.amount + timesheet3.amount + timesheet5.amount project_so_1_timesheet_sold_unit = timesheet1.unit_amount + timesheet3.unit_amount + timesheet5.unit_amount self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['amount_untaxed_to_invoice'], self.so_line_deliver_project.price_unit * project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The amount to invoice of the project from SO1 should only include timesheet linked to task") self.assertEqual(float_compare(project_so_1_stat['timesheet_unit_amount'], project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO1 should include all timesheet in project") self.assertEqual(float_compare(project_so_1_stat['timesheet_cost'], project_so_1_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO1 should include all timesheet") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the deliver project should be 0.0") # order project still have something to invoice but has costs now project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], self.so_line_order_project.price_unit * self.so_line_order_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice should be the one from the SO line, as we are in ordered quantity") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # fixed price project should ow have cost and nothing to invoice as no delivered quantity are logged yet project_so_3_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_3.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_3_timesheet_cost = timesheet9.amount project_so_3_timesheet_sold_unit = timesheet9.unit_amount self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['timesheet_unit_amount'], project_so_3_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO3") self.assertEqual(float_compare(project_so_3_stat['timesheet_cost'], project_so_3_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO3") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO3 should be 0.0") # global project should have more to invoice, and should now have costs project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_global_timesheet_cost = timesheet7.amount + timesheet8.amount project_global_timesheet_unit = timesheet7.unit_amount + timesheet8.unit_amount project_global_to_invoice = (self.so_line_order_task.price_unit * self.so_line_order_task.product_uom_qty) + (self.so_line_deliver_task.price_unit * timesheet7.unit_amount) self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the global project should be 0.0") self.assertEqual(float_compare(project_global_stat['amount_untaxed_to_invoice'], project_global_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of global project should take the task in 'oredered qty' and the delivered timesheets into account") self.assertEqual(float_compare(project_global_stat['timesheet_unit_amount'], project_global_timesheet_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the global project should include all timesheet") self.assertEqual(float_compare(project_global_stat['timesheet_cost'], project_global_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the global project should include all timesheet") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") self.so_line_deliver_manual_project.write({'qty_delivered': 7.0}) self.env['project.profitability.report'].flush() # deliver project should now have cost and something to invoice project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_1_timesheet_cost = timesheet1.amount + timesheet3.amount + timesheet5.amount project_so_1_timesheet_sold_unit = timesheet1.unit_amount + timesheet3.unit_amount + timesheet5.unit_amount self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['amount_untaxed_to_invoice'], self.so_line_deliver_project.price_unit * project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The amount to invoice of the project from SO1 should only include timesheet linked to task") self.assertEqual(float_compare(project_so_1_stat['timesheet_unit_amount'], project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO1 should include all timesheet in project") self.assertEqual(float_compare(project_so_1_stat['timesheet_cost'], project_so_1_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO1 should include all timesheet") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the deliver project should be 0.0") # order project still have something to invoice but has costs now project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], self.so_line_order_project.price_unit * self.so_line_order_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice should be the one from the SO line, as we are in ordered quantity") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # fixed price project should ow have cost and something to invoice as some delivered quantity are logged in project_so_3_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_3.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_3_timesheet_cost = timesheet9.amount project_so_3_timesheet_sold_unit = timesheet9.unit_amount self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['amount_untaxed_to_invoice'], self.so_line_deliver_manual_project.price_unit * self.so_line_deliver_manual_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['timesheet_unit_amount'], project_so_3_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO3") self.assertEqual(float_compare(project_so_3_stat['timesheet_cost'], project_so_3_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO3") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO3 should be 0.0") # global project should have more to invoice, and should now have costs project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_global_timesheet_cost = timesheet7.amount + timesheet8.amount project_global_timesheet_unit = timesheet7.unit_amount + timesheet8.unit_amount project_global_to_invoice = (self.so_line_order_task.price_unit * self.so_line_order_task.product_uom_qty) + (self.so_line_deliver_task.price_unit * timesheet7.unit_amount) self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the global project should be 0.0") self.assertEqual(float_compare(project_global_stat['amount_untaxed_to_invoice'], project_global_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of global project should take the task in 'oredered qty' and the delivered timesheets into account") self.assertEqual(float_compare(project_global_stat['timesheet_unit_amount'], project_global_timesheet_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the global project should include all timesheet") self.assertEqual(float_compare(project_global_stat['timesheet_cost'], project_global_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the global project should include all timesheet") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") InvoiceWizard = self.env['sale.advance.payment.inv'].with_context(mail_notrack=True) # invoice the Sales Order SO1 (based on delivered qty) context = { "active_model": 'sale.order', "active_ids": [self.sale_order_1.id], "active_id": self.sale_order_1.id, 'open_invoices': True, } payment = InvoiceWizard.create({ 'advance_payment_method': 'delivered', }) action_invoice = payment.with_context(context).create_invoices() invoice_id = action_invoice['res_id'] invoice_1 = self.env['account.move'].browse(invoice_id) invoice_1.action_post() self.env['project.profitability.report'].flush() # deliver project should now have cost and something invoiced project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_1_timesheet_cost = timesheet1.amount + timesheet3.amount + timesheet5.amount project_so_1_timesheet_sold_unit = timesheet1.unit_amount + timesheet3.unit_amount + timesheet5.unit_amount self.assertEqual(float_compare(project_so_1_stat['amount_untaxed_invoiced'], self.so_line_deliver_project.price_unit * project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The invoiced amount of the project from SO1 should only include timesheet linked to task") self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['timesheet_unit_amount'], project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO1 should include all timesheet in project") self.assertEqual(float_compare(project_so_1_stat['timesheet_cost'], project_so_1_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO1 should include all timesheet") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the deliver project should be 0.0") # order project has still nothing invoiced project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], self.so_line_order_project.price_unit * self.so_line_order_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice should be the one from the SO line, as we are in ordered quantity") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # fixed price project has still nothing invoice project_so_3_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_3.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_3_timesheet_cost = timesheet9.amount project_so_3_timesheet_sold_unit = timesheet9.unit_amount self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['amount_untaxed_to_invoice'], self.so_line_deliver_manual_project.price_unit * self.so_line_deliver_manual_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['timesheet_unit_amount'], project_so_3_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO3") self.assertEqual(float_compare(project_so_3_stat['timesheet_cost'], project_so_3_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO3") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO3 should be 0.0") # global project should have more to invoice, and should now have costs project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_global_timesheet_cost = timesheet7.amount + timesheet8.amount project_global_timesheet_unit = timesheet7.unit_amount + timesheet8.unit_amount project_global_to_invoice = self.so_line_order_task.price_unit * self.so_line_order_task.product_uom_qty project_global_invoiced = self.so_line_deliver_task.price_unit * timesheet7.unit_amount self.assertEqual(float_compare(project_global_stat['amount_untaxed_invoiced'], project_global_invoiced, precision_rounding=rounding), 0, "The invoiced amount of the global project should be 0.0") self.assertEqual(float_compare(project_global_stat['amount_untaxed_to_invoice'], project_global_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of global project should take the task in 'oredered qty' and the delivered timesheets into account") self.assertEqual(float_compare(project_global_stat['timesheet_unit_amount'], project_global_timesheet_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the global project should include all timesheet") self.assertEqual(float_compare(project_global_stat['timesheet_cost'], project_global_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the global project should include all timesheet") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") # invoice the Sales Order SO2 context = { "active_model": 'sale.order', "active_ids": [self.sale_order_2.id], "active_id": self.sale_order_2.id, 'open_invoices': True, } payment = InvoiceWizard.create({ 'advance_payment_method': 'delivered', }) action_invoice = payment.with_context(context).create_invoices() invoice_id = action_invoice['res_id'] invoice_2 = self.env['account.move'].browse(invoice_id) invoice_2.action_post() self.env['project.profitability.report'].flush() # deliver project should not be impacted by the invoice of the other SO project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_1_timesheet_cost = timesheet1.amount + timesheet3.amount + timesheet5.amount project_so_1_timesheet_sold_unit = timesheet1.unit_amount + timesheet3.unit_amount + timesheet5.unit_amount self.assertEqual(float_compare(project_so_1_stat['amount_untaxed_invoiced'], self.so_line_deliver_project.price_unit * project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The invoiced amount of the project from SO1 should only include timesheet linked to task") self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['timesheet_unit_amount'], project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO1 should include all timesheet in project") self.assertEqual(float_compare(project_so_1_stat['timesheet_cost'], project_so_1_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO1 should include all timesheet") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the deliver project should be 0.0") # order project is now totally invoiced, as we are in ordered qty project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], self.so_line_order_project.price_unit * self.so_line_order_project.product_uom_qty, precision_rounding=rounding), 0, "The invoiced amount should be the one from the SO line, as we are in ordered quantity") self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice should be the one 0.0, as all ordered quantity is invoiced") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # fixed price project has still nothing invoice project_so_3_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_3.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_3_timesheet_cost = timesheet9.amount project_so_3_timesheet_sold_unit = timesheet9.unit_amount self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['amount_untaxed_to_invoice'], self.so_line_deliver_manual_project.price_unit * self.so_line_deliver_manual_project.qty_to_invoice, precision_rounding=rounding), 0, "The amount to invoice of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['timesheet_unit_amount'], project_so_3_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO3") self.assertEqual(float_compare(project_so_3_stat['timesheet_cost'], project_so_3_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO3") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO3 should be 0.0") # global project should be totally invoiced project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_global_timesheet_cost = timesheet7.amount + timesheet8.amount project_global_timesheet_unit = timesheet7.unit_amount + timesheet8.unit_amount project_global_invoiced = self.so_line_order_task.price_unit * self.so_line_order_task.product_uom_qty + self.so_line_deliver_task.price_unit * timesheet7.unit_amount self.assertEqual(float_compare(project_global_stat['amount_untaxed_invoiced'], project_global_invoiced, precision_rounding=rounding), 0, "The invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of global project should take the task in 'oredered qty' and the delivered timesheets into account") self.assertEqual(float_compare(project_global_stat['timesheet_unit_amount'], project_global_timesheet_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the global project should include all timesheet") self.assertEqual(float_compare(project_global_stat['timesheet_cost'], project_global_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the global project should include all timesheet") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") # invoice the Sales Order SO3 context = { "active_model": 'sale.order', "active_ids": [self.sale_order_3.id], "active_id": self.sale_order_3.id, 'open_invoices': True, } payment = InvoiceWizard.create({ 'advance_payment_method': 'delivered', }) action_invoice = payment.with_context(context).create_invoices() invoice_id = action_invoice['res_id'] invoice_3 = self.env['account.move'].browse(invoice_id) invoice_3.action_post() self.env['project.profitability.report'].flush() # deliver project should not be impacted by the invoice of the other SO project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_1_timesheet_cost = timesheet1.amount + timesheet3.amount + timesheet5.amount project_so_1_timesheet_sold_unit = timesheet1.unit_amount + timesheet3.unit_amount + timesheet5.unit_amount self.assertEqual(float_compare(project_so_1_stat['amount_untaxed_invoiced'], self.so_line_deliver_project.price_unit * project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The invoiced amount of the project from SO1 should only include timesheet linked to task") self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['timesheet_unit_amount'], project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO1 should include all timesheet in project") self.assertEqual(float_compare(project_so_1_stat['timesheet_cost'], project_so_1_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO1 should include all timesheet") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the deliver project should be 0.0") # order project should not be impacted by the invoice of the other SO project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], self.so_line_order_project.price_unit * self.so_line_order_project.product_uom_qty, precision_rounding=rounding), 0, "The invoiced amount should be the one from the SO line, as we are in ordered quantity") self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice should be the one 0.0, as all ordered quantity is invoiced") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # fixed price project is now partially invoiced, as we are in delivered qty project_so_3_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_3.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_3_timesheet_cost = timesheet9.amount project_so_3_timesheet_sold_unit = timesheet9.unit_amount self.assertEqual(float_compare(project_so_3_stat['amount_untaxed_invoiced'], self.so_line_deliver_manual_project.price_unit * self.so_line_deliver_manual_project.qty_delivered, precision_rounding=rounding), 0, "The invoiced amount of the project from SO3 should be the delivered quantity * the unit price") self.assertTrue(float_is_zero(project_so_3_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO3 should be 0.0") self.assertEqual(float_compare(project_so_3_stat['timesheet_unit_amount'], project_so_3_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO3") self.assertEqual(float_compare(project_so_3_stat['timesheet_cost'], project_so_3_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO3") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO3 should be 0.0") self.assertTrue(float_is_zero(project_so_3_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO3 should be 0.0") # global project should be totally invoiced project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_global_timesheet_cost = timesheet7.amount + timesheet8.amount project_global_timesheet_unit = timesheet7.unit_amount + timesheet8.unit_amount project_global_invoiced = self.so_line_order_task.price_unit * self.so_line_order_task.product_uom_qty + self.so_line_deliver_task.price_unit * timesheet7.unit_amount self.assertEqual(float_compare(project_global_stat['amount_untaxed_invoiced'], project_global_invoiced, precision_rounding=rounding), 0, "The invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of global project should take the task in 'oredered qty' and the delivered timesheets into account") self.assertEqual(float_compare(project_global_stat['timesheet_unit_amount'], project_global_timesheet_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the global project should include all timesheet") self.assertEqual(float_compare(project_global_stat['timesheet_cost'], project_global_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the global project should include all timesheet") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") # simulate the auto creation of the SO line for expense, like we confirm a vendor bill. so_line_expense = self.env['sale.order.line'].create({ 'name': self.product_expense.name, 'product_id': self.product_expense.id, 'product_uom_qty': 0.0, 'product_uom': self.product_expense.uom_id.id, 'price_unit': self.product_expense.list_price, # reinvoice at sales price 'order_id': self.sale_order_1.id, 'is_expense': True, }) # add expense AAL: 20% margin when reinvoicing AnalyticLine = self.env['account.analytic.line'] expense1 = AnalyticLine.create({ 'name': 'expense on project_so_1', 'account_id': project_so_1.analytic_account_id.id, 'so_line': so_line_expense.id, 'employee_id': self.employee_user.id, 'unit_amount': 4, 'amount': 4 * self.product_expense.list_price * -1, 'product_id': self.product_expense.id, 'product_uom_id': self.product_expense.uom_id.id, }) expense2 = AnalyticLine.create({ 'name': 'expense on global project', 'account_id': self.project_global.analytic_account_id.id, 'employee_id': self.employee_user.id, 'unit_amount': 2, 'amount': 2 * self.product_expense.list_price * -1, 'product_id': self.product_expense.id, 'product_uom_id': self.product_expense.uom_id.id, }) self.env['project.profitability.report'].flush() # deliver project should now have expense cost, and expense to reinvoice as there is a still open sales order linked to the AA1 project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_1_timesheet_cost = timesheet1.amount + timesheet3.amount + timesheet5.amount project_so_1_timesheet_sold_unit = timesheet1.unit_amount + timesheet3.unit_amount + timesheet5.unit_amount self.assertEqual(float_compare(project_so_1_stat['amount_untaxed_invoiced'], self.so_line_deliver_project.price_unit * project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The invoiced amount of the project from SO1 should only include timesheet linked to task") self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['timesheet_unit_amount'], project_so_1_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO1 should include all timesheet in project") self.assertEqual(float_compare(project_so_1_stat['timesheet_cost'], project_so_1_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO1 should include all timesheet") self.assertEqual(float_compare(project_so_1_stat['expense_amount_untaxed_to_invoice'], -1 * expense1.amount, precision_rounding=rounding), 0, "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['expense_cost'], expense1.amount, precision_rounding=rounding), 0, "The expense cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the deliver project should be 0.0") # order project is not impacted by the expenses project_so_2_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], self.so_line_order_project.price_unit * self.so_line_order_project.product_uom_qty, precision_rounding=rounding), 0, "The invoiced amount should be the one from the SO line, as we are in ordered quantity") self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice should be the one 0.0, as all ordered quantity is invoiced") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # global project should have an expense, but not reinvoiceable project_global_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] project_global_timesheet_cost = timesheet7.amount + timesheet8.amount project_global_timesheet_unit = timesheet7.unit_amount + timesheet8.unit_amount project_global_invoiced = self.so_line_order_task.price_unit * self.so_line_order_task.product_uom_qty + self.so_line_deliver_task.price_unit * timesheet7.unit_amount self.assertEqual(float_compare(project_global_stat['amount_untaxed_invoiced'], project_global_invoiced, precision_rounding=rounding), 0, "The invoiced amount of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of global project should take the task in 'oredered qty' and the delivered timesheets into account") self.assertEqual(float_compare(project_global_stat['timesheet_unit_amount'], project_global_timesheet_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the global project should include all timesheet") self.assertEqual(float_compare(project_global_stat['timesheet_cost'], project_global_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the global project should include all timesheet") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_global_stat['expense_cost'], expense2.amount, precision_rounding=rounding), 0, "The expense cost of the global project should be 0.0") self.assertTrue(float_is_zero(project_global_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the global project should be 0.0") def test_reversed_downpayment(self): # this test suppose everything is in the same currency as the current one currency = self.env.company.currency_id rounding = currency.rounding self.sale_order_2.action_confirm() context = { 'active_model': 'sale.order', 'active_ids': self.sale_order_2.ids, 'active_id': self.sale_order_2.id, 'default_journal_id': self.company_data['default_journal_sale'].id, 'open_invoices': True, } # Let's do an invoice for a deposit of 100 downpayment = self.env['sale.advance.payment.inv'].with_context(context).create({ 'advance_payment_method': 'percentage', 'amount': 10, }) action_invoice = downpayment.create_invoices() invoice_id = action_invoice['res_id'] invoice_downpayment = self.env['account.move'].browse(invoice_id) invoice_downpayment.action_post() posted_invoice_res_ids = [invoice_id] downpayment2 = self.env['sale.advance.payment.inv'].with_context(context).create({ 'advance_payment_method': 'percentage', 'amount': 25, }) action_invoice = downpayment2.create_invoices() invoice_downpayment2 = self.env['account.move'].search(expression.AND([action_invoice['domain'], [('id', 'not in', posted_invoice_res_ids)]])) invoice_downpayment2.action_post() posted_invoice_res_ids += invoice_downpayment2.ids milestone_to_invoice = self.so_line_order_project.price_unit * self.so_line_order_project.qty_to_invoice timesheets_to_invoice = self.so_line_order_task.price_unit * self.so_line_order_task.qty_to_invoice total_product_price = milestone_to_invoice + timesheets_to_invoice credit_note_wizard = self.env['account.move.reversal'].with_context({ 'active_ids': invoice_downpayment2.ids, 'active_id': invoice_downpayment2.id, 'active_model': 'account.move' }).create({ 'refund_method': 'refund', 'reason': 'reason test create', 'journal_id': invoice_downpayment2.journal_id.id, }) action_moves = credit_note_wizard.reverse_moves() credit_id = action_moves['res_id'] invoice_credit = self.env['account.move'].browse(credit_id) invoice_credit.action_post() posted_invoice_res_ids += invoice_credit.ids project_so_2 = self.so_line_order_project.project_id task_so_2 = self.so_line_order_project.task_id task_in_global_2 = self.so_line_order_task.task_id self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], 0.1 * total_product_price, precision_rounding=rounding), 0, "The invoiced amount is the amount of downpayments not reversed") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], milestone_to_invoice - 0.1 * total_product_price, precision_rounding=rounding), 0, "The amount to invoice is the milestone product minus the downpayment not reversed") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO2 is 0") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO2 is 0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # logged some timesheets: on project only, then on tasks with different employees timesheet2 = self._log_timesheet_user(project_so_2, 2) timesheet4 = self._log_timesheet_user(project_so_2, 3, task_so_2) timesheet6 = self._log_timesheet_manager(project_so_2, 2, task_so_2) timesheet8 = self._log_timesheet_manager(self.project_global, 3, task_in_global_2) # simulate the auto creation of the SO line for expense, like we confirm a vendor bill. so_line_expense = self.env['sale.order.line'].create({ 'name': self.product_expense.name, 'product_id': self.product_expense.id, 'product_uom_qty': 0.0, 'product_uom': self.product_expense.uom_id.id, 'price_unit': self.product_expense.list_price, # reinvoice at sales price 'order_id': self.sale_order_2.id, 'is_expense': True, }) expense1 = self.env['account.analytic.line'].create({ 'name': 'expense on project_so_2', 'account_id': project_so_2.analytic_account_id.id, 'so_line': so_line_expense.id, 'employee_id': self.employee_user.id, 'unit_amount': 4, 'amount': 4 * self.product_expense.list_price * -1, 'product_id': self.product_expense.id, 'product_uom_id': self.product_expense.uom_id.id, }) self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] project_so_2_timesheet_cost = timesheet2.amount + timesheet4.amount + timesheet6.amount project_so_2_timesheet_sold_unit = timesheet2.unit_amount + timesheet4.unit_amount + timesheet6.unit_amount self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], 0.1 * total_product_price, precision_rounding=rounding), 0, "The invoiced amount of the project from SO2 should only include downpayment not reversed") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], milestone_to_invoice - 0.1 * total_product_price, precision_rounding=rounding), 0, "The amount to invoice of the project from SO2 should include the milestone to invoice minus the downpayment") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet in project") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['expense_amount_untaxed_to_invoice'], -expense1.amount, precision_rounding=rounding), 0, "The expense cost to reinvoice of the project from SO2 should be the expense amount") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['expense_cost'], expense1.amount, precision_rounding=rounding), 0, "The expense cost of the project from SO1 should be expense amount") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # invoice the Sales Order SO2 context = { "active_model": 'sale.order', "active_ids": self.sale_order_2.ids, "active_id": self.sale_order_2.id, 'open_invoices': True, 'mail_notrack': True, } payment = self.env['sale.advance.payment.inv'].with_context(mail_notrack=True).create({ 'advance_payment_method': 'delivered', }) action_invoice = payment.with_context(context).create_invoices() invoice_payment = self.env['account.move'].search(expression.AND([action_invoice['domain'], [('id', 'not in', posted_invoice_res_ids)]])) invoice_payment.action_post() self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], milestone_to_invoice, precision_rounding=rounding), 0, "The invoiced amount of the project from SO2 should only include timesheet linked to task") self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet in project") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense to invoice amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['expense_amount_untaxed_invoiced'], -1 * expense1.amount, precision_rounding=rounding), 0, "The expense cost reinvoiced of the project from SO2 should be the expense amount") self.assertEqual(float_compare(project_so_2_stat['expense_cost'], expense1.amount, precision_rounding=rounding), 0, "The expense cost of the project from SO2 should be the expense amount") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") credit_note_wizard = self.env['account.move.reversal'].with_context({ 'active_ids': invoice_payment.ids, 'active_id': invoice_payment.id, 'active_model': 'account.move' }).create({ 'refund_method': 'refund', 'reason': 'reason test create', 'journal_id': invoice_payment.journal_id.id, }) action_moves = credit_note_wizard.reverse_moves() credit_id = action_moves['res_id'] invoice_credit = self.env['account.move'].browse(credit_id) invoice_credit.action_post() self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], 0.1 * total_product_price, precision_rounding=rounding), 0, "The invoiced amount of the project from SO2 should only include downpayment not reversed") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], milestone_to_invoice - 0.1 * total_product_price, precision_rounding=rounding), 0, "The amount to invoice of the project from SO2 should include the milestone to invoice minus the downpayment") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet in project") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertEqual(float_compare(project_so_2_stat['expense_amount_untaxed_to_invoice'], -expense1.amount, precision_rounding=rounding), 0, "The expense cost to reinvoice of the project from SO2 should be the expense amount") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['expense_cost'], expense1.amount, precision_rounding=rounding), 0, "The expense cost of the project from SO1 should be expense amount") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") def test_milestone_no_tracking(self): # this test suppose everything is in the same currency as the current one currency = self.env.company.currency_id rounding = currency.rounding so_line_deliver_no_task = self.env['sale.order.line'].create({ 'name': self.product_delivery_manual1.name, 'product_id': self.product_delivery_manual1.id, 'product_uom_qty': 50, 'product_uom': self.product_delivery_manual1.uom_id.id, 'price_unit': self.product_delivery_manual1.list_price, 'order_id': self.sale_order_2.id, }) so_line_deliver_no_task.write({'qty_delivered': 1.0}) self.sale_order_2.action_confirm() milestone_to_invoice = self.so_line_order_project.price_unit * self.so_line_order_project.qty_to_invoice milestone_no_task = so_line_deliver_no_task.price_unit * so_line_deliver_no_task.qty_to_invoice self.env['project.profitability.report'].flush() project_so_2 = self.so_line_order_project.project_id project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], milestone_to_invoice + milestone_no_task, precision_rounding=rounding), 0, "The amount to invoice of the project from SO2 should include the milestone to invoice") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") task_using_milestone_not_tracked = self.env['project.task'].create({ 'name': 'Task with milestone not tracked', 'project_id': project_so_2.id, 'partner_id': project_so_2.partner_id.id, 'sale_line_id': so_line_deliver_no_task.id, }) self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should be 0.0") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], milestone_to_invoice + milestone_no_task, precision_rounding=rounding), 0, "The amount to invoice of the project from SO2 should include the milestone to invoice linked to the project or project's task") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") timesheet = self._log_timesheet_user(project_so_2, 3, task_using_milestone_not_tracked) self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] project_so_2_timesheet_cost = timesheet.amount project_so_2_timesheet_sold_unit = timesheet.unit_amount self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO2 should only include downpayment not reversed") self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_to_invoice'], milestone_to_invoice + milestone_no_task, precision_rounding=rounding), 0, "The amount to invoice of the project from SO2 should include the milestone to invoice minus the downpayment") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet in project") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") # invoice the Sales Order SO2 context = { "active_model": 'sale.order', "active_ids": self.sale_order_2.ids, "active_id": self.sale_order_2.id, 'open_invoices': True, 'mail_notrack': True, } payment = self.env['sale.advance.payment.inv'].with_context(mail_notrack=True).create({ 'advance_payment_method': 'delivered', }) action_invoice = payment.with_context(context).create_invoices() invoice_payment = self.env['account.move'].browse(action_invoice['res_id']) invoice_payment.action_post() self.env['project.profitability.report'].flush() project_so_2_stat = self.env['project.profitability.report'].read_group( [('project_id', 'in', project_so_2.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'] )[0] self.assertEqual(float_compare(project_so_2_stat['amount_untaxed_invoiced'], milestone_to_invoice + milestone_no_task, precision_rounding=rounding), 0, "The invoiced amount of the project from SO2 should include the milestone invoiced") self.assertTrue(float_is_zero(project_so_2_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO2 should include the milestone to invoice") self.assertEqual(float_compare(project_so_2_stat['timesheet_unit_amount'], project_so_2_timesheet_sold_unit, precision_rounding=rounding), 0, "The timesheet unit amount of the project from SO2 should include all timesheet in project") self.assertEqual(float_compare(project_so_2_stat['timesheet_cost'], project_so_2_timesheet_cost, precision_rounding=rounding), 0, "The timesheet cost of the project from SO2 should include all timesheet") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO2 should be 0.0") self.assertTrue(float_is_zero(project_so_2_stat['other_revenues'], precision_rounding=rounding), "The other revenues of the project from SO2 should be 0.0") def test_profitability_credit_note_bill(self): """Test whether the profitability is zeroed by credit note on a vendor bill.""" ProjectProfitabilityReport = self.env['project.profitability.report'] analytic_account = self.project_global.analytic_account_id product = self.env['product.product'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'name': "Product", 'standard_price': 100.0, 'list_price': 100.0, 'taxes_id': False, }) test_bill = self.env['account.move'].create({ 'move_type': 'in_invoice', 'currency_id': self.env.user.company_id.currency_id, 'partner_id': self.partner_a, 'invoice_date': '2021-01-01', 'invoice_line_ids': [(0, 0, { 'quantity': 1, 'product_id': product.id, 'price_unit': 100.0, 'analytic_account_id': analytic_account.id, })] }) test_bill.action_post() ProjectProfitabilityReport.flush() project_stat= ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_cost'], test_bill.amount_total_signed, msg="The expense cost of the project should be equal to the the invoice line price, before credit note.") self.assertAlmostEqual(project_stat['other_revenues'], 0, msg="The other revenues of the project should be zero, before credit note") credit_note_wizard = self.env['account.move.reversal'].with_context({ 'active_model': 'account.move', 'active_ids': test_bill.ids, 'active_id': test_bill.id, }).create({ 'refund_method': 'cancel', 'reason': 'no reason', 'journal_id': self.company_data['default_journal_purchase'].id }) credit_note_wizard.reverse_moves() ProjectProfitabilityReport.flush() project_stat= ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_cost'], 0, msg="The expense cost of the project should be zero, as it is balanced by credit note.") self.assertAlmostEqual(project_stat['other_revenues'], 0, msg="The other revenues (credit note) of the project should be zero (not taken into account), after credit note.") def test_profitability_credit_note_invoice(self): """Test whether the profitability doesn't change with customer invoice or its credit note.""" ProjectProfitabilityReport = self.env['project.profitability.report'] analytic_account = self.project_global.analytic_account_id product = self.env['product.product'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'name': "Product", 'standard_price': 100.0, 'list_price': 100.0, 'taxes_id': False, }) test_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'currency_id': self.env.user.company_id.currency_id, 'partner_id': self.partner_a, 'invoice_date': '2021-01-01', 'invoice_line_ids': [(0, 0, { 'quantity': 1, 'product_id': product.id, 'price_unit': 100.0, 'analytic_account_id': analytic_account.id, })] }) test_invoice.action_post() ProjectProfitabilityReport.flush() project_stat= ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_cost'], 0, msg="The expense cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['other_revenues'], test_invoice.amount_total_signed, msg="The other revenues of the project should be equal to the the invoice line price, after credit note.") credit_note_wizard = self.env['account.move.reversal'].with_context({ 'active_model': 'account.move', 'active_ids': test_invoice.ids, 'active_id': test_invoice.id, }).create({ 'refund_method': 'cancel', 'reason': 'no reason', 'journal_id': self.company_data['default_journal_sale'].id }) credit_note_wizard.reverse_moves() ProjectProfitabilityReport.flush() project_stat= ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_cost'], 0, msg="The expense costs (credit note) of the project should be zero (not taken into account), after credit note.") self.assertAlmostEqual(project_stat['other_revenues'], 0, msg="The other revenues of the project should be zero, as it is balanced by credit note.") def test_project_profitability_report(self): """ Test profitability report for a project with a task and a SO with a service and a product added linked to the task.""" # create Analytic Accounts self.analytic_account_1 = self.env['account.analytic.account'].create({ 'name': 'Test AA 1', 'code': 'AA1', 'company_id': self.company_data['company'].id, 'partner_id': self.partner_a.id }) self.sale_order_1 = self.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, 'analytic_account_id': self.analytic_account_1.id, }) self.so_line_deliver_project = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet3.name, 'product_id': self.product_delivery_timesheet3.id, 'product_uom': self.product_delivery_timesheet3.uom_id.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'order_id': self.sale_order_1.id, }) self.so_line_deliver_task = self.env['sale.order.line'].create({ 'name': self.product_delivery_timesheet2.name, 'product_id': self.product_delivery_timesheet2.id, 'product_uom': self.product_delivery_timesheet2.uom_id.id, 'price_unit': self.product_delivery_timesheet2.list_price, 'order_id': self.sale_order_1.id, }) # this test suppose everything is in the same currency as the current one currency = self.env.company.currency_id rounding = currency.rounding # confirm sales orders self.sale_order_1.action_confirm() self.env['project.profitability.report'].flush() project_so_1 = self.so_line_deliver_project.project_id task_so_1 = self.so_line_deliver_project.task_id self.product_material = self.env['product.product'].create({ 'name': 'My Material Product', 'sale_ok': True, 'invoice_policy': 'order', 'lst_price': 5, }) self.env['sale.order.line'].create({ 'order_id': self.sale_order_1.id, 'name': self.product_material.name, 'product_id': self.product_material.id, 'product_uom_qty': 5, 'product_uom': self.product_material.uom_id.id, 'price_unit': self.product_material.list_price, 'task_id': task_so_1.id, }) InvoiceWizard = self.env['sale.advance.payment.inv'].with_context(mail_notrack=True) # invoice the Sales Order SO1 (based on delivered qty) context = { "active_model": 'sale.order', "active_ids": [self.sale_order_1.id], "active_id": self.sale_order_1.id, 'open_invoices': True, } payment = InvoiceWizard.create({ 'advance_payment_method': 'delivered', }) action_invoice = payment.with_context(context).create_invoices() invoice_id = action_invoice['res_id'] invoice_1 = self.env['account.move'].browse(invoice_id) invoice_1.action_post() project_so_1_stat = self.env['project.profitability.report'].read_group([('project_id', 'in', project_so_1.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_invoiced'], precision_rounding=rounding), "The invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['amount_untaxed_to_invoice'], precision_rounding=rounding), "The amount to invoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['timesheet_unit_amount'], precision_rounding=rounding), "The timesheet unit amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['timesheet_cost'], precision_rounding=rounding), "The timesheet cost of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_to_invoice'], precision_rounding=rounding), "The expense cost to reinvoice of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_amount_untaxed_invoiced'], precision_rounding=rounding), "The expense invoiced amount of the project from SO1 should be 0.0") self.assertTrue(float_is_zero(project_so_1_stat['expense_cost'], precision_rounding=rounding), "The expense cost of the project from SO1 should be 0.0") self.assertEqual(float_compare(project_so_1_stat['other_revenues'], invoice_1.amount_untaxed, precision_rounding=rounding), 0, "The other revenues of the project from SO1 should be the same as the untaxed amount in invoice") def test_profitability_partial_refund_invoice(self): ProjectProfitabilityReport = self.env['project.profitability.report'] analytic_account = self.project_global.analytic_account_id product = self.env['product.product'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'name': "Product", 'standard_price': 100.0, 'list_price': 100.0, 'taxes_id': False, }) test_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'currency_id': self.env.user.company_id.currency_id, 'partner_id': self.partner_a, 'invoice_date': '2021-01-01', 'invoice_line_ids': [(0, 0, { 'quantity': 2, 'product_id': product.id, 'price_unit': 100.0, 'analytic_account_id': analytic_account.id, })] }) test_invoice.action_post() ProjectProfitabilityReport.flush() project_stat = ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_cost'], 0, msg="The expense cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['other_revenues'], test_invoice.amount_total_signed, msg="The other revenues of the project should be equal to the the invoice line price, after credit note.") refund_note_wizard = self.env['account.move.reversal'].with_context({ 'active_model': 'account.move', 'active_ids': test_invoice.ids, 'active_id': test_invoice.id, }).create({ 'refund_method': 'refund', 'reason': 'no reason', 'journal_id': self.company_data['default_journal_sale'].id }) refund = self.env['account.move'].browse(refund_note_wizard.reverse_moves()["res_id"]) move_form = Form(refund) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 1 refund = move_form.save() refund.action_post() ProjectProfitabilityReport.flush() project_stat = ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_cost'], 0, msg="The expense costs (credit note) of the project should be zero (not taken into account), after credit note.") self.assertAlmostEqual(project_stat['other_revenues'], test_invoice.amount_total_signed + refund.amount_total_signed, msg="The other revenues of the project should be zero, as it is balanced by credit note.") def test_profitability_partial_refund_vendor_bill(self): ProjectProfitabilityReport = self.env['project.profitability.report'] analytic_account = self.project_global.analytic_account_id product = self.env['product.product'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'name': "Product", 'standard_price': 100.0, 'list_price': 100.0, 'taxes_id': False, }) test_invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'currency_id': self.env.user.company_id.currency_id, 'partner_id': self.partner_a, 'invoice_date': '2021-01-01', 'invoice_line_ids': [(0, 0, { 'quantity': 2, 'product_id': product.id, 'price_unit': 100.0, 'analytic_account_id': analytic_account.id, })] }) test_invoice.action_post() ProjectProfitabilityReport.flush() project_stat = ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['expense_cost'], test_invoice.amount_total_signed, msg="The expense cost of the project should be zero, before credit note.") self.assertAlmostEqual(project_stat['other_revenues'], 0, msg="The other revenues of the project should be equal to the the invoice line price, after credit note.") refund_note_wizard = self.env['account.move.reversal'].with_context({ 'active_model': 'account.move', 'active_ids': test_invoice.ids, 'active_id': test_invoice.id, }).create({ 'refund_method': 'refund', 'reason': 'no reason', 'journal_id': self.company_data['default_journal_purchase'].id }) refund = self.env['account.move'].browse(refund_note_wizard.reverse_moves()["res_id"]) move_form = Form(refund) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 1 refund = move_form.save() refund.action_post() ProjectProfitabilityReport.flush() project_stat = ProjectProfitabilityReport.read_group([('project_id', 'in', self.project_global.ids)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'timesheet_unit_amount', 'timesheet_cost', 'expense_cost', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues'], ['project_id'])[0] self.assertAlmostEqual(project_stat['amount_untaxed_invoiced'], 0, msg="The invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['amount_untaxed_to_invoice'], 0, msg="The amount to invoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_unit_amount'], 0, msg="The timesheet unit amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['timesheet_cost'], 0, msg="The timesheet cost of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_to_invoice'], 0, msg="The expense cost to reinvoice of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_amount_untaxed_invoiced'], 0, msg="The expense invoiced amount of the project should be zero, after credit note.") self.assertAlmostEqual(project_stat['expense_cost'], test_invoice.amount_total_signed + refund.amount_total_signed, msg="The expense costs (credit note) of the project should be zero (not taken into account), after credit note.") self.assertAlmostEqual(project_stat['other_revenues'], 0, msg="The other revenues of the project should be zero, as it is balanced by credit note.")
102.658009
118,570
21,760
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet from odoo.fields import Date from odoo.tests import Form, tagged @tagged('-at_install', 'post_install') class TestReInvoice(TestCommonSaleTimesheet): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # patch expense products to make them services creating task/project service_values = { 'type': 'service', 'service_type': 'timesheet', 'service_tracking': 'task_in_project' } cls.company_data['product_order_cost'].write(service_values) cls.company_data['product_delivery_cost'].write(service_values) cls.company_data['product_order_sales_price'].write(service_values) cls.company_data['product_delivery_sales_price'].write(service_values) cls.company_data['product_order_no'].write(service_values) # create AA, SO and invoices cls.analytic_account = cls.env['account.analytic.account'].create({ 'name': 'Test AA', 'code': 'TESTSALE_TIMESHEET_REINVOICE', 'company_id': cls.company_data['company'].id, 'partner_id': cls.partner_a.id }) cls.sale_order = cls.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, 'analytic_account_id': cls.analytic_account.id, 'pricelist_id': cls.company_data['default_pricelist'].id, }) cls.Invoice = cls.env['account.move'].with_context( default_move_type='in_invoice', default_invoice_date=cls.sale_order.date_order, mail_notrack=True, mail_create_nolog=True, ) def test_at_cost(self): """ Test vendor bill at cost for product based on ordered and delivered quantities. """ # create SO line and confirm SO (with only one line) sale_order_line1 = self.env['sale.order.line'].create({ 'name': self.company_data['product_order_cost'].name, 'product_id': self.company_data['product_order_cost'].id, 'product_uom_qty': 2, 'product_uom': self.company_data['product_order_cost'].uom_id.id, 'price_unit': self.company_data['product_order_cost'].list_price, 'order_id': self.sale_order.id, }) sale_order_line1.product_id_change() sale_order_line2 = self.env['sale.order.line'].create({ 'name': self.company_data['product_delivery_cost'].name, 'product_id': self.company_data['product_delivery_cost'].id, 'product_uom_qty': 4, 'product_uom': self.company_data['product_delivery_cost'].uom_id.id, 'price_unit': self.company_data['product_delivery_cost'].list_price, 'order_id': self.sale_order.id, }) sale_order_line2.product_id_change() self.sale_order.onchange_partner_id() self.sale_order._compute_tax_id() self.sale_order.action_confirm() self.assertEqual(sale_order_line1.qty_delivered_method, 'timesheet', "Delivered quantity of 'service' SO line should be computed by timesheet amount") self.assertEqual(sale_order_line2.qty_delivered_method, 'timesheet', "Delivered quantity of 'service' SO line should be computed by timesheet amount") # let's log some timesheets (on the project created by sale_order_line1) task_sol1 = sale_order_line1.task_id self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_sol1.project_id.id, 'task_id': task_sol1.id, 'unit_amount': 1, 'employee_id': self.employee_user.id, 'company_id': self.company_data['company'].id, }) move_form = Form(self.Invoice) move_form.partner_id = self.partner_a with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_order_cost'] line_form.quantity = 3.0 line_form.analytic_account_id = self.analytic_account with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_delivery_cost'] line_form.quantity = 3.0 line_form.analytic_account_id = self.analytic_account invoice_a = move_form.save() invoice_a.action_post() sale_order_line3 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol.product_id == self.company_data['product_order_cost']) sale_order_line4 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol.product_id == self.company_data['product_delivery_cost']) self.assertTrue(sale_order_line3, "A new sale line should have been created with ordered product") self.assertTrue(sale_order_line4, "A new sale line should have been created with delivered product") self.assertEqual(len(self.sale_order.order_line), 4, "There should be 4 lines on the SO (2 vendor bill lines created)") self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 2, "There should be 4 lines on the SO (2 vendor bill lines created)") self.assertEqual(sale_order_line1.qty_delivered, 1, "Exising SO line 1 should not be impacted by reinvoicing product at cost") self.assertEqual(sale_order_line2.qty_delivered, 0, "Exising SO line 2 should not be impacted by reinvoicing product at cost") self.assertFalse(sale_order_line3.task_id, "Adding a new expense SO line should not create a task (sol3)") self.assertFalse(sale_order_line4.task_id, "Adding a new expense SO line should not create a task (sol4)") self.assertEqual(len(self.sale_order.project_ids), 1, "SO create only one project with its service line. Adding new expense SO line should not impact that") self.assertEqual((sale_order_line3.price_unit, sale_order_line3.qty_delivered, sale_order_line3.product_uom_qty, sale_order_line3.qty_invoiced), (self.company_data['product_order_cost'].standard_price, 3.0, 0, 0), 'Sale line is wrong after confirming vendor invoice') self.assertEqual((sale_order_line4.price_unit, sale_order_line4.qty_delivered, sale_order_line4.product_uom_qty, sale_order_line4.qty_invoiced), (self.company_data['product_delivery_cost'].standard_price, 3.0, 0, 0), 'Sale line is wrong after confirming vendor invoice') self.assertEqual(sale_order_line3.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line should be computed by analytic amount") self.assertEqual(sale_order_line4.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line should be computed by analytic amount") # create second invoice lines and validate it move_form = Form(self.Invoice) move_form.partner_id = self.partner_a with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_order_cost'] line_form.quantity = 2.0 line_form.analytic_account_id = self.analytic_account with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_delivery_cost'] line_form.quantity = 2.0 line_form.analytic_account_id = self.analytic_account invoice_b = move_form.save() invoice_b.action_post() sale_order_line5 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol != sale_order_line3 and sol.product_id == self.company_data['product_order_cost']) sale_order_line6 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol != sale_order_line4 and sol.product_id == self.company_data['product_delivery_cost']) self.assertTrue(sale_order_line5, "A new sale line should have been created with ordered product") self.assertTrue(sale_order_line6, "A new sale line should have been created with delivered product") self.assertEqual(len(self.sale_order.order_line), 6, "There should be still 4 lines on the SO, no new created") self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 4, "There should be still 2 expenses lines on the SO") self.assertEqual((sale_order_line5.price_unit, sale_order_line5.qty_delivered, sale_order_line5.product_uom_qty, sale_order_line5.qty_invoiced), (self.company_data['product_order_cost'].standard_price, 2.0, 0, 0), 'Sale line 5 is wrong after confirming 2e vendor invoice') self.assertEqual((sale_order_line6.price_unit, sale_order_line6.qty_delivered, sale_order_line6.product_uom_qty, sale_order_line6.qty_invoiced), (self.company_data['product_delivery_cost'].standard_price, 2.0, 0, 0), 'Sale line 6 is wrong after confirming 2e vendor invoice') def test_sales_price(self): """ Test invoicing vendor bill at sales price for products based on delivered and ordered quantities. Check no existing SO line is incremented, but when invoicing a second time, increment only the delivered so line. """ # create SO line and confirm SO (with only one line) sale_order_line1 = self.env['sale.order.line'].create({ 'name': self.company_data['product_delivery_sales_price'].name, 'product_id': self.company_data['product_delivery_sales_price'].id, 'product_uom_qty': 2, 'qty_delivered': 1, 'product_uom': self.company_data['product_delivery_sales_price'].uom_id.id, 'price_unit': self.company_data['product_delivery_sales_price'].list_price, 'order_id': self.sale_order.id, }) sale_order_line1.product_id_change() sale_order_line2 = self.env['sale.order.line'].create({ 'name': self.company_data['product_order_sales_price'].name, 'product_id': self.company_data['product_order_sales_price'].id, 'product_uom_qty': 3, 'qty_delivered': 1, 'product_uom': self.company_data['product_order_sales_price'].uom_id.id, 'price_unit': self.company_data['product_order_sales_price'].list_price, 'order_id': self.sale_order.id, }) sale_order_line2.product_id_change() self.sale_order._compute_tax_id() self.sale_order.action_confirm() # let's log some timesheets (on the project created by sale_order_line1) task_sol1 = sale_order_line1.task_id self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_sol1.project_id.id, 'task_id': task_sol1.id, 'unit_amount': 1, 'employee_id': self.employee_user.id, }) # create invoice lines and validate it move_form = Form(self.Invoice) move_form.partner_id = self.partner_a with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_delivery_sales_price'] line_form.quantity = 3.0 line_form.analytic_account_id = self.analytic_account with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_order_sales_price'] line_form.quantity = 3.0 line_form.analytic_account_id = self.analytic_account invoice_a = move_form.save() invoice_a.action_post() sale_order_line3 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol.product_id == self.company_data['product_delivery_sales_price']) sale_order_line4 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol.product_id == self.company_data['product_order_sales_price']) self.assertTrue(sale_order_line3, "A new sale line should have been created with ordered product") self.assertTrue(sale_order_line4, "A new sale line should have been created with delivered product") self.assertEqual(len(self.sale_order.order_line), 4, "There should be 4 lines on the SO (2 vendor bill lines created)") self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 2, "There should be 4 lines on the SO (2 vendor bill lines created)") self.assertEqual(sale_order_line1.qty_delivered, 1, "Exising SO line 1 should not be impacted by reinvoicing product at cost") self.assertEqual(sale_order_line2.qty_delivered, 0, "Exising SO line 2 should not be impacted by reinvoicing product at cost") self.assertFalse(sale_order_line3.task_id, "Adding a new expense SO line should not create a task (sol3)") self.assertFalse(sale_order_line4.task_id, "Adding a new expense SO line should not create a task (sol4)") self.assertEqual(len(self.sale_order.project_ids), 1, "SO create only one project with its service line. Adding new expense SO line should not impact that") self.assertEqual((sale_order_line3.price_unit, sale_order_line3.qty_delivered, sale_order_line3.product_uom_qty, sale_order_line3.qty_invoiced), (self.company_data['product_delivery_sales_price'].list_price, 3.0, 0, 0), 'Sale line is wrong after confirming vendor invoice') self.assertEqual((sale_order_line4.price_unit, sale_order_line4.qty_delivered, sale_order_line4.product_uom_qty, sale_order_line4.qty_invoiced), (self.company_data['product_order_sales_price'].list_price, 3.0, 0, 0), 'Sale line is wrong after confirming vendor invoice') self.assertEqual(sale_order_line3.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line 3 should be computed by analytic amount") self.assertEqual(sale_order_line4.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line 4 should be computed by analytic amount") # create second invoice lines and validate it move_form = Form(self.Invoice) move_form.partner_id = self.partner_a with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_delivery_sales_price'] line_form.quantity = 2.0 line_form.analytic_account_id = self.analytic_account with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_order_sales_price'] line_form.quantity = 2.0 line_form.analytic_account_id = self.analytic_account invoice_b = move_form.save() invoice_b.action_post() sale_order_line5 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol != sale_order_line3 and sol.product_id == self.company_data['product_delivery_sales_price']) sale_order_line6 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol != sale_order_line4 and sol.product_id == self.company_data['product_order_sales_price']) self.assertFalse(sale_order_line5, "No new sale line should have been created with delivered product !!") self.assertTrue(sale_order_line6, "A new sale line should have been created with ordered product") self.assertEqual(len(self.sale_order.order_line), 5, "There should be 5 lines on the SO, 1 new created and 1 incremented") self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 3, "There should be 3 expenses lines on the SO") self.assertEqual((sale_order_line6.price_unit, sale_order_line6.qty_delivered, sale_order_line4.product_uom_qty, sale_order_line6.qty_invoiced), (self.company_data['product_order_sales_price'].list_price, 2.0, 0, 0), 'Sale line is wrong after confirming 2e vendor invoice') def test_no_expense(self): """ Test invoicing vendor bill with no policy. Check nothing happen. """ # confirm SO sale_order_line = self.env['sale.order.line'].create({ 'name': self.company_data['product_order_no'].name, 'product_id': self.company_data['product_order_no'].id, 'product_uom_qty': 2, 'qty_delivered': 1, 'product_uom': self.company_data['product_order_no'].uom_id.id, 'price_unit': self.company_data['product_order_no'].list_price, 'order_id': self.sale_order.id, }) self.sale_order._compute_tax_id() self.sale_order.action_confirm() # create invoice lines and validate it move_form = Form(self.Invoice) move_form.partner_id = self.partner_a with move_form.line_ids.new() as line_form: line_form.product_id = self.company_data['product_order_no'] line_form.quantity = 3.0 line_form.analytic_account_id = self.analytic_account invoice_a = move_form.save() invoice_a.action_post() # let's log some timesheets (on the project created by sale_order_line1) task_sol1 = sale_order_line.task_id self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task_sol1.project_id.id, 'task_id': task_sol1.id, 'unit_amount': 1, 'employee_id': self.employee_user.id, }) self.assertEqual(len(self.sale_order.order_line), 1, "No SO line should have been created (or removed) when validating vendor bill") self.assertEqual(sale_order_line.qty_delivered, 1, "The delivered quantity of SO line should not have been incremented") self.assertTrue(invoice_a.mapped('line_ids.analytic_line_ids'), "Analytic lines should be generated") def test_reversed_invoice_reinvoice_with_period(self): """ Tests that when reversing an invoice of timesheet and selecting a time period, the qty to invoice is correctly found Business flow: Create a sale order and deliver some hours (invoiced = 0) Create an invoice Confirm (invoiced = 1) Add Credit Note Confirm (invoiced = 0) Go back to the SO Create an invoice Select a time period [1 week ago, 1 week in the future] Confirm -> Fails if there is nothing to invoice """ product = self.env['product.product'].create({ 'name': "Service delivered, create task in global project", 'standard_price': 30, 'list_price': 90, 'type': 'service', 'service_policy': 'delivered_timesheet', 'invoice_policy': 'delivery', 'default_code': 'SERV-DELI2', 'service_type': 'timesheet', 'service_tracking': 'task_global_project', 'project_id': self.project_global.id, 'taxes_id': False, 'property_account_income_id': self.account_sale.id, }) today = Date.context_today(self.env.user) # Creates a sales order for quantity 3 so_form = Form(self.env['sale.order']) so_form.partner_id = self.env['res.partner'].create({'name': 'Toto'}) with so_form.order_line.new() as line: line.product_id = product line.product_uom_qty = 3.0 sale_order = so_form.save() sale_order.action_confirm() # "Deliver" 1 of 3 task = sale_order.tasks_ids self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 1, 'employee_id': self.employee_user.id, 'company_id': self.company_data['company'].id, }) context = { "active_model": 'sale.order', "active_ids": [sale_order.id], "active_id": sale_order.id, 'open_invoices': True, } # Invoice the 1 wizard = self.env['sale.advance.payment.inv'].with_context(context).create({ 'advance_payment_method': 'delivered' }) invoice_dict = wizard.create_invoices() # Confirm the invoice invoice = self.env['account.move'].browse(invoice_dict['res_id']) invoice.action_post() # Refund the invoice wiz_context = { 'active_model': 'account.move', 'active_ids': [invoice.id], 'default_journal_id': self.company_data['default_journal_sale'].id } refund_invoice_wiz = self.env['account.move.reversal'].with_context(wiz_context).create({ 'reason': 'please reverse :c', 'refund_method': 'refund', 'date': today, }) refund_invoice = self.env['account.move'].browse(refund_invoice_wiz.reverse_moves()['res_id']) refund_invoice.action_post() # reversing with action_reverse and then action_post does not reset the invoice_status to 'to invoice' in tests # Recreate wizard to get the new invoices created wizard = self.env['sale.advance.payment.inv'].with_context(context).create({ 'advance_payment_method': 'delivered', 'date_start_invoice_timesheet': today - timedelta(days=7), 'date_end_invoice_timesheet': today + timedelta(days=7) }) # The actual test : wizard.create_invoices() # No exception should be raised, there is indeed something to be invoiced since it was reversed
57.263158
21,760
3,704
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from .common import TestCommonSaleTimesheet @tagged('-at_install', 'post_install') class TestEditSoLineTimesheet(TestCommonSaleTimesheet): def setUp(self): super().setUp() self.task_rate_task = self.env['project.task'].create({ 'name': 'Task', 'project_id': self.project_task_rate.id, 'sale_line_id': self.so.order_line[0].id, }) def test_sol_no_change_if_edited(self): """ Check if a sol manually edited, does not change with a change of sol in the task. Test Case: ========= 1) create some timesheets on this task, 2) edit a SOL of a timesheet in this task, 3) check if the edited SOL has the one selected and is not the one in the task, 4) change the sol on the task, 5) check if the timesheet in which the sol has manually edited, does not change but the another ones are the case. """ # 1) create some timesheets on this task timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': self.project_task_rate.id, 'task_id': self.task_rate_task.id, 'unit_amount': 5, 'employee_id': self.employee_manager.id }) timesheet._compute_so_line() edited_timesheet = timesheet.copy() self.assertTrue(timesheet.so_line == edited_timesheet.so_line == self.task_rate_task.sale_line_id, "SOL in timesheet should be the same than the one in the task.") self.assertEqual(timesheet.unit_amount + edited_timesheet.unit_amount, self.task_rate_task.sale_line_id.qty_delivered, "The quantity timesheeted should be increased the quantity delivered in the linked SOL.") # 2) edit a SOL of a timesheet in this task # Remark, we simulate the action done in the task form view edited_timesheet.write({ "is_so_line_edited": True, "so_line": self.so.order_line[1].id, }) self.so.order_line._compute_qty_delivered() # 3) check if the edited SOL has the one selected and is not the one in the task self.assertNotEqual(edited_timesheet.so_line, self.task_rate_task.sale_line_id, "SOL in timesheet should be different than the one in the task.") self.assertEqual(edited_timesheet.so_line, self.so.order_line[1], "SOL in timesheet is the one selected when we manually edit in the timesheet") self.assertEqual(self.task_rate_task.sale_line_id.qty_delivered, timesheet.unit_amount, "The quantity delivered should be the quantity defined in the first timesheet of the task since the so_line in the second timesheet has manually been changed.") # 4) change the sol on the task self.task_rate_task.update({ 'sale_line_id': self.so.order_line[-1].id, }) timesheet._compute_so_line() edited_timesheet._compute_so_line() self.so.order_line._compute_qty_delivered() # 5) check if the timesheet in which the sol has manually edited, does not change but the another ones are the case. self.assertEqual(timesheet.so_line, self.task_rate_task.sale_line_id, "SOL in timesheet should be the same than the one in the task.") self.assertNotEqual(edited_timesheet.so_line, self.task_rate_task.sale_line_id, "SOL in timesheet which is manually edited should be different than the one in the task.") self.assertEqual(edited_timesheet.so_line, self.so.order_line[1], "SOL in timesheet should still be the same")
55.283582
3,704
5,885
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet from odoo.tests import tagged from odoo.exceptions import UserError @tagged('post_install', '-at_install') class TestAccruedTimeSheetSaleOrders(TestCommonSaleTimesheet): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.sale_order = cls.env['sale.order'].create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, 'pricelist_id': cls.company_data['default_pricelist'].id, 'date_order': '2020-01-01', }) so_line_deliver_global_project = cls.env['sale.order.line'].create({ 'name': cls.product_delivery_timesheet2.name, 'product_id': cls.product_delivery_timesheet2.id, 'product_uom_qty': 50, 'product_uom': cls.product_delivery_timesheet2.uom_id.id, 'price_unit': cls.product_delivery_timesheet2.list_price, 'order_id': cls.sale_order.id, }) cls.sale_order.action_confirm() cls.task = cls.env['project.task'].search([('sale_line_id', '=', so_line_deliver_global_project.id)]) cls.account_revenue = cls.company_data['default_account_revenue'] def _log_hours(self, unit_amount, date): self.env['account.analytic.line'].create({ 'name': 'Test Line', 'project_id': self.task.project_id.id, 'task_id': self.task.id, 'unit_amount': unit_amount, 'employee_id': self.employee_manager.id, 'date': date, }) def test_timesheet_accrued_entries(self): # log 10 hours on 2020-01-02 self._log_hours(10, '2020-01-02') # log 10 hours on 2020-01-05 self._log_hours(10, '2020-01-05') wizard = self.env['account.accrued.orders.wizard'].with_context({ 'active_model': 'sale.order', 'active_ids': self.sale_order.ids, }).create({ 'account_id': self.company_data['default_account_expense'].id, 'date': '2020-01-01', }) # nothing to invoice on 2020-01-01 with self.assertRaises(UserError): wizard.create_entries() # 10 hours to invoice on 2020-01-03 wizard.date = fields.Date.to_date('2020-01-03') self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_revenue.id, 'debit': 900, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 900}, # move lines {'account_id': self.account_revenue.id, 'debit': 0, 'credit': 900}, {'account_id': wizard.account_id.id, 'debit': 900, 'credit': 0}, ]) # 20 hours to invoice on 2020-01-07 wizard.date = fields.Date.to_date('2020-01-07') self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_revenue.id, 'debit': 1800, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 1800}, # move lines {'account_id': self.account_revenue.id, 'debit': 0, 'credit': 1800}, {'account_id': wizard.account_id.id, 'debit': 1800, 'credit': 0}, ]) def test_timesheet_invoiced_accrued_entries(self): # log 10 hours on 2020-01-02 self._log_hours(10, '2020-01-02') # invoice on 2020-01-04 inv = self.sale_order._create_invoices() inv.invoice_date = fields.Date.to_date('2020-01-04') inv.action_post() # log 10 hours on 2020-01-06 self._log_hours(10, '2020-01-06') # invoice on 2020-01-08 inv = self.sale_order._create_invoices() inv.invoice_date = fields.Date.to_date('2020-01-08') inv.action_post() wizard = self.env['account.accrued.orders.wizard'].with_context({ 'active_model': 'sale.order', 'active_ids': self.sale_order.ids, }).create({ 'account_id': self.company_data['default_account_expense'].id, 'date': '2020-01-02', }) self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_revenue.id, 'debit': 900, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 900}, # move lines {'account_id': self.account_revenue.id, 'debit': 0, 'credit': 900}, {'account_id': wizard.account_id.id, 'debit': 900, 'credit': 0}, ]) # nothing to invoice on 2020-01-05 wizard.date = fields.Date.to_date('2020-01-05') with self.assertRaises(UserError): wizard.create_entries() # 20 hours to invoice on 2020-01-07 wizard.date = fields.Date.to_date('2020-01-07') self.assertRecordValues(self.env['account.move'].search(wizard.create_entries()['domain']).line_ids, [ # reverse move lines {'account_id': self.account_revenue.id, 'debit': 900, 'credit': 0}, {'account_id': wizard.account_id.id, 'debit': 0, 'credit': 900}, # move lines {'account_id': self.account_revenue.id, 'debit': 0, 'credit': 900}, {'account_id': wizard.account_id.id, 'debit': 900, 'credit': 0}, ]) # nothing to invoice on 2020-01-05 wizard.date = fields.Date.to_date('2020-01-09') with self.assertRaises(UserError): wizard.create_entries()
43.272059
5,885
13,311
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from .common import TestCommonSaleTimesheet @tagged('-at_install', 'post_install') class TestSoLineDeterminedInTimesheet(TestCommonSaleTimesheet): def test_sol_determined_when_project_is_task_rate(self): """ Test the sol give to the timesheet when the pricing type in the project is task rate Test Case: ========= 1) Create Task in project with pricing_type='task_rate', 2) Compute the SOL for the task and check if we have the one containing the prepaid service product, 3) Create timesheet and check if the SOL in this timesheet is the one in the task, 4) Since the remaining hours of the prepaid service is equals to 0 hour, when we create a new task, the SOL in this one should be equal to False 5) Change the SOL in the task and see if the SOL in the timesheet also changes. """ # 1) Create Task in project with pricing_type='task_rate' task = self.env['project.task'].create({ 'name': 'Task', 'project_id': self.project_task_rate.id, }) # 2) Compute the SOL for the task and check if we have the one containing the prepaid service product # task._compute_sale_line() self.assertEqual(task.sale_line_id, self.so.order_line[-1], "The SOL in the task should be the one containing the prepaid service product.") self.assertTrue(all(sol.qty_delivered == 0 for sol in self.so.order_line), "The quantity delivered should be equal to 0 because we have no timesheet for each SOL containing in the SO.") # 3) Create timesheet and check if the SOL in this timesheet is the one in the task timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 2, 'employee_id': self.employee_manager.id, 'project_id': self.project_task_rate.id, 'task_id': task.id, }) self.assertEqual(timesheet.so_line, task.sale_line_id, "The SOL in the timesheet should be the same than the one in the task.") self.assertEqual(self.so.order_line[-1].qty_delivered, 2, "The quantity delivered should be equal to 2.") self.assertEqual(task.remaining_hours_so, 0, "The remaining hours on the SOL containing the prepaid service product should be equals to 0.") # 4) Since the remaining hours of the prepaid service product is equals to 0 hour, when we create a new task, the SOL in this one should be equals to False task2 = self.env['project.task'].create({ 'name': 'Task 2', 'project_id': self.project_task_rate.id, }) self.assertFalse(task2.sale_line_id, "The SOL in this task should be equal to False") # 5) Change the SOL in the task and see if the SOL in the timesheet also changes. task.update({'sale_line_id': self.so.order_line[0].id}) self.assertEqual(timesheet.so_line, task.sale_line_id, "The SOL in the timesheet should also change and be the same than the one in the task.") def test_sol_determined_when_project_is_project_rate(self): """ Test the sol give to the timesheet when the pricing type in the project is project rate Test Case: ========= 1) Define a SO and SOL in the project, 2) Create task and check if the SOL is the one defined in the project, 3) Create timesheet in the task and check if the SOL in the timesheet is the one in the task, 4) Change the SOL in the task and check if the SOL in the timesheet has also changed. """ # 1) Define a SO and SOL in the project self.project_project_rate = self.project_task_rate.copy({ 'name': 'Project with pricing_type="project_rate"', 'sale_line_id': self.so.order_line[0].id, }) # 2) Create task and check if the SOL is the one defined in the project task = self.env['project.task'].create({ 'name': 'Task', 'project_id': self.project_project_rate.id, }) self.assertEqual(task.sale_line_id, self.so.order_line[0], "The SOL in the task should be the one containing the prepaid service product.") self.assertTrue(all(sol.qty_delivered == 0 for sol in self.so.order_line), "The quantity delivered should be equal to 0 because we have no timesheet for each SOL containing in the SO.") # 3) Create timesheet in the task and check if the SOL in the timesheet is the one in the task timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 1, 'employee_id': self.employee_manager.id, 'project_id': self.project_project_rate.id, 'task_id': task.id, }) self.assertTrue(timesheet.so_line == task.sale_line_id == self.so.order_line[0], "The SOL in the timesheet should be the same than the one in the task.") self.assertEqual(self.so.order_line[0].qty_delivered, 1, "The quantity delivered should be equal to 1.") # 4) Change the SOL in the task and check if the SOL in the timesheet has also changed task.update({'sale_line_id': self.so.order_line[1].id}) self.assertTrue(timesheet.so_line == task.sale_line_id == self.so.order_line[1], "The SOL in the timesheet should also change and be the same than the one in the task.") def test_sol_determined_when_project_is_employee_rate(self): """ Test the sol give to the timesheet when the pricing type in the project is employee rate Test Case: ========= 1) Define a SO, SOL mapping for an employee in the project, 2) Create task and check if the SOL is the one defined in the project, 3) Create timesheet in the task and check if the SOL in the timesheet is the one in the task, 4) Create timesheet in the task for the employee defined in the mapping and check if the SOL in this timesheet is the one defined in the mapping, 5) Change the SOL in the task and check if only the SOL in the timesheet which does not concerne about the mapping changes, 6) Change the SOL in the mapping and check if the timesheet conserne by the mapping has its SOL has been changed too. """ # 1) Define a SO, SOL and mapping for an employee in the project, self.project_employee_rate = self.project_task_rate.copy({ 'name': 'Project with pricing_type="employee_rate"', 'sale_line_id': self.so.order_line[0].id, 'sale_line_employee_ids': [(0, 0, { 'employee_id': self.employee_user.id, 'sale_line_id': self.so.order_line[1].id, })] }) mapping = self.project_employee_rate.sale_line_employee_ids # 2) Create task and check if the SOL is the one defined in the project, task = self.env['project.task'].create({ 'name': 'Task', 'project_id': self.project_employee_rate.id, }) self.assertEqual(task.sale_line_id, self.so.order_line[0], "The SOL in the task should be the one containing the prepaid service product.") self.assertTrue(all(sol.qty_delivered == 0 for sol in self.so.order_line), "The quantity delivered should be equal to 0 because we have no timesheet for each SOL containing in the SO.") # 3) Create timesheet in the task and check if the SOL in the timesheet is the one in the task, timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 1, 'employee_id': self.employee_manager.id, 'project_id': self.project_employee_rate.id, 'task_id': task.id, }) self.assertTrue(timesheet.so_line == task.sale_line_id == self.so.order_line[0], "The SOL in the timesheet should be the same than the one in the task.") self.assertEqual(self.so.order_line[0].qty_delivered, 1, "The quantity delivered should be equal to 1 for all SOLs in the SO.") # 4) Create timesheet in the task for the employee defined in the mapping and check if the SOL in this timesheet is the one defined in the # mapping, employee_user_timesheet = timesheet.copy({ 'name': 'Test Line Employee User', 'employee_id': self.employee_user.id, 'unit_amount': 2, }) employee_user_timesheet._compute_so_line() self.assertTrue(employee_user_timesheet.so_line == self.project_employee_rate.sale_line_employee_ids[0].sale_line_id == self.so.order_line[1], "The SOL in the timesheet should be the one defined in the mapping for the employee user.") self.assertEqual(self.so.order_line[1].qty_delivered, 2, "The quantity delivered for this SOL should be equal to 2 hours.") # 5) Change the SOL in the task and check if only the SOL in the timesheet which does not concerne about the mapping changes, task.update({'sale_line_id': self.so.order_line[2].id}) self.assertTrue(timesheet.so_line == task.sale_line_id == self.so.order_line[2], "The SOL in the timesheet should also change and be the same than the one in the task.") self.assertNotEqual(timesheet.so_line, employee_user_timesheet.so_line, "The SOL in the timesheet done by the employee user should not be the same than the one in the other timesheet in the task.") # 6) Change the SOL in the mapping and check if the timesheet conserne by the mapping has its SOL has been changed too. mapping.update({'sale_line_id': self.so.order_line[-1].id}) self.assertTrue(employee_user_timesheet.so_line == mapping.sale_line_id == self.so.order_line[-1], "The SOL in the timesheet done by the employee user should be the one defined in the mapping.") self.assertNotEqual(timesheet.so_line, employee_user_timesheet.so_line, "The other timesheet should not have the SOL defined in the mapping.") def test_no_so_line_if_project_non_billable(self): """ Test if the timesheet created in task in non billable project does not have a SOL Test Case: ========= 1) Create task in a non billable project, 2) Check if there is no SOL in task, 3) Create timesheet in the task and check if it does not contain any SOL. """ # 1) Create task in a non billable project, task = self.env['project.task'].create({ 'name': 'Test Task', 'project_id': self.project_non_billable.id, 'partner_id': self.partner_a.id, }) # 2) Check if there is no SOL in task, self.assertFalse(task.sale_line_id, 'No SOL should be linked in this task because the project is non billable.') # 3) Create timesheet in the task and check if it does not contain any SOL. timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 1, 'employee_id': self.employee_manager.id, 'project_id': task.project_id.id, 'task_id': task.id, }) self.assertFalse(timesheet.so_line, 'No SOL should be linked in this timesheet because the project is non billable.') def test_tranfer_project(self): """ Test if the SOL in timesheet is erased if the task of this timesheet changes the project from a billable project to a non billable project Test Case: ========= 1) Create task in project_task_rate, 2) Check if the task has the SOL which contain the prepaid service product, 3) Create timesheet in this task, 4) Check if the timesheet contains the same SOL than the task, 5) Move the task in a non billable project, 6) Check if the task and timesheet has no SOL. """ # 1) Create task in project_task_rate, task = self.env['project.task'].create({ 'name': 'Test Task', 'project_id': self.project_task_rate.id, }) # 2) Check if the task has the SOL which contain the prepaid service product, self.assertEqual(task.sale_line_id, self.so.order_line[-1], 'The SOL with prepaid service product should be linked to the task.') # 3) Create timesheet in this task, timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 1, 'employee_id': self.employee_manager.id, 'project_id': task.project_id.id, 'task_id': task.id, }) # 4) Check if the timesheet contains the same SOL than the task, self.assertEqual(timesheet.so_line, task.sale_line_id, 'The timesheet should have the same SOL than the task.') # 5) Move the task in a non billable project, task.write({'project_id': self.project_non_billable.id}) # 6) Check if the task and timesheet has no SOL. self.assertFalse(timesheet.so_line, 'No SOL should be linked to the timesheet because the project is non billable')
59.16
13,311
7,658
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from .common import TestCommonSaleTimesheet @tagged('-at_install', 'post_install') class TestProjectPricingType(TestCommonSaleTimesheet): def test_pricing_type(self): """ Test the _compute_pricing_type when the user add a sales order item or some employee mappings in the project Test Case: ========= 1) Take a project non billable and check if the pricing_type is equal to False 2) Set allow_billable to True and check if the pricing_type is equal to task_rate (if no SOL and no mappings) 3) Set a customer and a SOL in the project and check if the pricing_type is equal to fixed_rate (project rate) 4) Set a employee mapping and check if the pricing_type is equal to employee_rate """ # 1) Take a project non billable and check if the pricing_type is equal to False project = self.project_non_billable self.assertFalse(project.allow_billable, 'The allow_billable should be false if the project is non billable.') self.assertFalse(project.pricing_type, 'The pricing type of this project should be equal to False since it is non billable.') self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'task_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'fixed_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'employee_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('=', False))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'task_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'fixed_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'employee_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('!=', False))) # 2) Set allow_billable to True and check if the pricing_type is equal to task_rate (if no SOL and no mappings) project.write({ 'allow_billable': True, }) self.assertTrue(project.allow_billable, 'The allow_billable should be updated and equal to True.') self.assertFalse(project.sale_order_id, 'The sales order should be unset.') self.assertFalse(project.sale_line_id, 'The sales order item should be unset.') self.assertFalse(project.sale_line_employee_ids, 'The employee mappings should be empty.') self.assertEqual(project.pricing_type, 'task_rate', 'The pricing type should be equal to task_rate.') self.assertTrue(project.filtered_domain(project._search_pricing_type('=', 'task_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'fixed_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'employee_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', False))) self.assertFalse(project.filtered_domain(project._search_pricing_type('!=', 'task_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'fixed_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'employee_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', False))) # 3) Set a customer and a SOL in the project and check if the pricing_type is equal to fixed_rate (project rate) project.write({ 'partner_id': self.partner_b.id, 'sale_line_id': self.so.order_line[0].id, }) self.assertEqual(project.sale_order_id, self.so, 'The sales order should be equal to the one set in the project.') self.assertEqual(project.sale_line_id, self.so.order_line[0], 'The sales order item should be the one chosen.') self.assertEqual(project.pricing_type, 'fixed_rate', 'The pricing type should be equal to fixed_rate since the project has a sales order item.') self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'task_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('=', 'fixed_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'employee_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', False))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'task_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('!=', 'fixed_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'employee_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', False))) # 4) Set a employee mapping and check if the pricing_type is equal to employee_rate project.write({ 'sale_line_employee_ids': [(0, 0, { 'employee_id': self.employee_user.id, 'sale_line_id': self.so.order_line[1].id, })] }) self.assertEqual(len(project.sale_line_employee_ids), 1, 'The project should have an employee mapping.') self.assertEqual(project.pricing_type, 'employee_rate', 'The pricing type should be equal to employee_rate since the project has an employee mapping.') self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'task_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'fixed_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('=', 'employee_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', False))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'task_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'fixed_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('!=', 'employee_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', False))) # Even if the project has no sales order item, since it has an employee mapping, the pricing type must be equal to employee_rate. project.write({ 'sale_line_id': False, }) self.assertFalse(project.sale_order_id, 'The sales order of the project should be empty.') self.assertFalse(project.sale_line_id, 'The sales order item of the project should be empty.') self.assertEqual(project.pricing_type, 'employee_rate', 'The pricing type should always be equal to employee_rate.') self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'task_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', 'fixed_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('=', 'employee_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('=', False))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'task_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', 'fixed_rate'))) self.assertFalse(project.filtered_domain(project._search_pricing_type('!=', 'employee_rate'))) self.assertTrue(project.filtered_domain(project._search_pricing_type('!=', False)))
72.933333
7,658
2,277
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from freezegun import freeze_time from odoo.tests import tagged from odoo.tools import format_amount from odoo.addons.project.tests.test_project_update_flow import TestProjectUpdate @tagged('-at_install', 'post_install') class TestProjectUpdateSaleTimesheet(TestProjectUpdate): def test_project_update_description_profitability(self): self.project_pigs.allow_billable = True template_values = self.env['project.update']._get_template_values(self.project_pigs) # Store the formatted amount in the same currency as the project to guarantee the same unit comparison_amount = format_amount(self.env, 0.0, self.project_pigs.currency_id) self.assertEqual(template_values['profitability']['costs'], comparison_amount, "Project costs used in the template should be well defined") self.assertEqual(template_values['profitability']['revenues'], comparison_amount, "Project revenues used in the template should be well defined") self.assertEqual(template_values['profitability']['margin'], 0, "Margin used in the template should be well defined") self.assertEqual(template_values['profitability']['margin_formatted'], comparison_amount, "Margin formatted used in the template should be well defined") self.assertEqual(template_values['profitability']['margin_percentage'], "0", "Margin percentage used in the template should be well defined") def test_project_update_panel_profitability_no_billable(self): panel_data = self.project_pigs.get_panel_data() self.assertEqual(panel_data['profitability_items']['allow_billable'], False, "Project should not be billable by default") try: self.project_pigs.action_view_timesheet() except Exception as e: raise AssertionError("Error raised unexpectedly while calling the action defined in profitalities action panel data ! Exception : " + e.args[0]) try: self.project_pigs.action_view_timesheet() except Exception as e: raise AssertionError("Error raised unexpectedly while calling the action defined in profitalities action panel data ! Exception : " + e.args[0])
63.25
2,277
15,168
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.sale.tests.common import TestSaleCommon class TestCommonSaleTimesheet(TestSaleCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.user_employee_company_B = mail_new_test_user( cls.env, name='Gregor Clegane Employee', login='gregor', email='gregor@example.com', notification_type='email', groups='base.group_user', company_id=cls.company_data_2['company'].id, company_ids=[cls.company_data_2['company'].id], ) cls.user_manager_company_B = mail_new_test_user( cls.env, name='Cersei Lannister Manager', login='cersei', email='cersei@example.com', notification_type='email', groups='base.group_user', company_id=cls.company_data_2['company'].id, company_ids=[cls.company_data_2['company'].id, cls.env.company.id], ) cls.employee_user = cls.env['hr.employee'].create({ 'name': 'Employee User', 'timesheet_cost': 15, }) cls.employee_manager = cls.env['hr.employee'].create({ 'name': 'Employee Manager', 'timesheet_cost': 45, }) cls.employee_company_B = cls.env['hr.employee'].create({ 'name': 'Gregor Clegane', 'user_id': cls.user_employee_company_B.id, 'timesheet_cost': 15, }) cls.manager_company_B = cls.env['hr.employee'].create({ 'name': 'Cersei Lannister', 'user_id': cls.user_manager_company_B.id, 'timesheet_cost': 45, }) # Account and project cls.account_sale = cls.company_data['default_account_revenue'] cls.analytic_account_sale = cls.env['account.analytic.account'].create({ 'name': 'Project for selling timesheet - AA', 'code': 'AA-2030', 'company_id': cls.company_data['company'].id, }) cls.analytic_account_sale_company_B = cls.env['account.analytic.account'].create({ 'name': 'Project for selling timesheet Company B - AA', 'code': 'AA-2030', 'company_id': cls.company_data_2['company'].id, }) # Create projects Project = cls.env['project.project'].with_context(tracking_disable=True) cls.project_global = Project.create({ 'name': 'Project for selling timesheets', 'allow_timesheets': True, 'analytic_account_id': cls.analytic_account_sale.id, 'allow_billable': True, }) cls.project_template = Project.create({ 'name': 'Project TEMPLATE for services', 'allow_timesheets': True, }) cls.project_template_state = cls.env['project.task.type'].create({ 'name': 'Only stage in project template', 'sequence': 1, 'project_ids': [(4, cls.project_template.id)] }) # Projects: at least one per billable type cls.project_task_rate = Project.create({ 'name': 'Project with pricing_type="task_rate"', 'allow_timesheets': True, 'allow_billable': True, 'partner_id': cls.partner_b.id, 'analytic_account_id': cls.analytic_account_sale.id, }) cls.project_subtask = Project.create({ 'name': "Sub Task Project (non billable)", 'allow_timesheets': True, 'allow_billable': False, 'partner_id': False, }) cls.project_non_billable = Project.create({ 'name': "Non Billable Project", 'allow_timesheets': True, 'allow_billable': False, 'partner_id': False, }) # Create service products uom_hour = cls.env.ref('uom.product_uom_hour') # -- ordered quantities (ordered, timesheet) cls.product_order_timesheet1 = cls.env['product.product'].create({ 'name': "Service Ordered, create no task", 'standard_price': 11, 'list_price': 13, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED1', 'service_type': 'timesheet', 'service_tracking': 'no', 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_order_timesheet2 = cls.env['product.product'].create({ 'name': "Service Ordered, create task in global project", 'standard_price': 30, 'list_price': 90, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED2', 'service_type': 'timesheet', 'service_tracking': 'task_global_project', 'project_id': cls.project_global.id, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_order_timesheet3 = cls.env['product.product'].create({ 'name': "Service Ordered, create task in new project", 'standard_price': 10, 'list_price': 20, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED3', 'service_type': 'timesheet', 'service_tracking': 'task_in_project', 'project_id': False, # will create a project 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_order_timesheet4 = cls.env['product.product'].create({ 'name': "Service Ordered, create project only", 'standard_price': 15, 'list_price': 30, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED4', 'service_type': 'timesheet', 'service_tracking': 'project_only', 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_order_timesheet5 = cls.env['product.product'].create({ 'name': "Service Ordered, create project only based on template", 'standard_price': 17, 'list_price': 34, 'type': 'service', 'invoice_policy': 'order', 'uom_id': cls.env.ref('uom.product_uom_hour').id, 'uom_po_id': cls.env.ref('uom.product_uom_hour').id, 'default_code': 'SERV-ORDERED4', 'service_type': 'timesheet', 'service_tracking': 'project_only', 'project_id': False, 'project_template_id': cls.project_template.id, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) # -- timesheet on tasks (delivered, timesheet) cls.product_delivery_timesheet1 = cls.env['product.product'].create({ 'name': "Service delivered, create no task", 'standard_price': 11, 'list_price': 13, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI1', 'service_type': 'timesheet', 'service_tracking': 'no', 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_timesheet2 = cls.env['product.product'].create({ 'name': "Service delivered, create task in global project", 'standard_price': 30, 'list_price': 90, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI2', 'service_type': 'timesheet', 'service_tracking': 'task_global_project', 'project_id': cls.project_global.id, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_timesheet3 = cls.env['product.product'].create({ 'name': "Service delivered, create task in new project", 'standard_price': 10, 'list_price': 20, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI3', 'service_type': 'timesheet', 'service_tracking': 'task_in_project', 'project_id': False, # will create a project 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_timesheet4 = cls.env['product.product'].create({ 'name': "Service delivered, create project only", 'standard_price': 15, 'list_price': 30, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI4', 'service_type': 'timesheet', 'service_tracking': 'project_only', 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_timesheet5 = cls.env['product.product'].create({ 'name': "Service delivered, create project only based on template", 'standard_price': 17, 'list_price': 34, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': cls.env.ref('uom.product_uom_hour').id, 'uom_po_id': cls.env.ref('uom.product_uom_hour').id, 'default_code': 'SERV-DELI5', 'service_type': 'timesheet', 'service_tracking': 'project_only', 'project_template_id': cls.project_template.id, 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) # -- milestones (delivered, manual) cls.product_delivery_manual1 = cls.env['product.product'].create({ 'name': "Service delivered, create no task", 'standard_price': 11, 'list_price': 13, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI1', 'service_type': 'manual', 'service_tracking': 'no', 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_manual2 = cls.env['product.product'].create({ 'name': "Service delivered, create task in global project", 'standard_price': 30, 'list_price': 90, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI2', 'service_type': 'manual', 'service_tracking': 'task_global_project', 'project_id': cls.project_global.id, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_manual3 = cls.env['product.product'].create({ 'name': "Service delivered, create task in new project", 'standard_price': 10, 'list_price': 20, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI3', 'service_type': 'manual', 'service_tracking': 'task_in_project', 'project_id': False, # will create a project 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_manual4 = cls.env['product.product'].create({ 'name': "Service delivered, create project only", 'standard_price': 15, 'list_price': 30, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-DELI4', 'service_type': 'manual', 'service_tracking': 'project_only', 'project_id': False, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) cls.product_delivery_manual5 = cls.env['product.product'].create({ 'name': "Service delivered, create project only with template", 'standard_price': 17, 'list_price': 34, 'type': 'service', 'invoice_policy': 'delivery', 'uom_id': cls.env.ref('uom.product_uom_hour').id, 'uom_po_id': cls.env.ref('uom.product_uom_hour').id, 'default_code': 'SERV-DELI4', 'service_type': 'manual', 'service_tracking': 'project_only', 'project_id': False, 'project_template_id': cls.project_template.id, 'taxes_id': False, 'property_account_income_id': cls.account_sale.id, }) def setUp(self): super().setUp() self.so = self.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({ 'partner_id': self.partner_b.id, 'partner_invoice_id': self.partner_b.id, 'partner_shipping_id': self.partner_b.id, }) self.env['sale.order.line'].create([{ 'order_id': self.so.id, 'name': self.product_delivery_timesheet1.name, 'product_id': self.product_delivery_timesheet1.id, 'product_uom_qty': 10, 'price_unit': self.product_delivery_timesheet1.list_price }, { 'order_id': self.so.id, 'product_id': self.product_delivery_timesheet2.id, 'product_uom_qty': 5, }, { 'order_id': self.so.id, 'product_id': self.product_delivery_timesheet3.id, 'product_uom_qty': 5, }, { 'order_id': self.so.id, 'product_id': self.product_order_timesheet1.id, 'product_uom_qty': 2, }]) self.so.action_confirm()
40.884097
15,168
26,915
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_timesheet.tests.common import TestCommonSaleTimesheet from odoo.fields import Command from odoo.tests import tagged from odoo.tests.common import Form @tagged('post_install', '-at_install') class TestProjectBilling(TestCommonSaleTimesheet): """ This test suite provide checks for miscellaneous small things. """ @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # set up cls.employee_tde = cls.env['hr.employee'].create({ 'name': 'Employee TDE', 'timesheet_cost': 42, }) cls.partner_2 = cls.env['res.partner'].create({ 'name': 'Customer from the South', 'email': 'customer.usd@south.com', 'property_account_payable_id': cls.company_data['default_account_payable'].id, 'property_account_receivable_id': cls.company_data['default_account_receivable'].id, }) # Sale Order 1, no project/task created, used to timesheet at employee rate SaleOrder = cls.env['sale.order'].with_context(tracking_disable=True) SaleOrderLine = cls.env['sale.order.line'].with_context(tracking_disable=True) cls.sale_order_1 = SaleOrder.create({ 'partner_id': cls.partner_a.id, 'partner_invoice_id': cls.partner_a.id, 'partner_shipping_id': cls.partner_a.id, }) cls.so1_line_order_no_task = SaleOrderLine.create({ 'name': cls.product_order_timesheet1.name, 'product_id': cls.product_order_timesheet1.id, 'product_uom_qty': 10, 'product_uom': cls.product_order_timesheet1.uom_id.id, 'price_unit': cls.product_order_timesheet1.list_price, 'order_id': cls.sale_order_1.id, }) cls.so1_line_deliver_no_task = SaleOrderLine.create({ 'name': cls.product_delivery_timesheet1.name, 'product_id': cls.product_delivery_timesheet1.id, 'product_uom_qty': 10, 'product_uom': cls.product_delivery_timesheet1.uom_id.id, 'price_unit': cls.product_delivery_timesheet1.list_price, 'order_id': cls.sale_order_1.id, }) # Sale Order 2, creates 2 project billed at task rate cls.sale_order_2 = SaleOrder.create({ 'partner_id': cls.partner_2.id, 'partner_invoice_id': cls.partner_2.id, 'partner_shipping_id': cls.partner_2.id, }) cls.so2_line_deliver_project_task = SaleOrderLine.create({ 'order_id': cls.sale_order_2.id, 'name': cls.product_delivery_timesheet3.name, 'product_id': cls.product_delivery_timesheet3.id, 'product_uom_qty': 5, 'product_uom': cls.product_delivery_timesheet3.uom_id.id, 'price_unit': cls.product_delivery_timesheet3.list_price }) cls.so2_line_deliver_project_template = SaleOrderLine.create({ 'order_id': cls.sale_order_2.id, 'name': cls.product_delivery_timesheet5.name, 'product_id': cls.product_delivery_timesheet5.id, 'product_uom_qty': 7, 'product_uom': cls.product_delivery_timesheet5.uom_id.id, 'price_unit': cls.product_delivery_timesheet5.list_price }) cls.sale_order_2.action_confirm() cls.project_project_rate = cls.project_task_rate.copy({ 'name': 'Project with pricing_type="project_rate"', 'sale_order_id': cls.sale_order_1.id, 'sale_line_id': cls.so1_line_order_no_task.id, }) # FIXME: [XBO] since the both projects have a SOL than the pricing_type should not be task_rate ! cls.project_task_rate = cls.env['project.project'].search([('sale_line_id', '=', cls.so2_line_deliver_project_task.id)], limit=1) cls.project_task_rate2 = cls.env['project.project'].search([('sale_line_id', '=', cls.so2_line_deliver_project_template.id)], limit=1) cls.project_employee_rate = cls.project_task_rate.copy({ 'name': 'Project with pricing_type="employee_rate"', 'partner_id': cls.sale_order_1.partner_id.id, }) cls.project_employee_rate_manager = cls.env['project.sale.line.employee.map'].create({ 'project_id': cls.project_employee_rate.id, 'sale_line_id': cls.so1_line_order_no_task.id, 'employee_id': cls.employee_manager.id, }) cls.project_employee_rate_user = cls.env['project.sale.line.employee.map'].create({ 'project_id': cls.project_employee_rate.id, 'sale_line_id': cls.so1_line_deliver_no_task.id, 'employee_id': cls.employee_user.id, }) cls.project_task_rate = cls.env['project.project'].search([('sale_line_id', '=', cls.so2_line_deliver_project_task.id)], limit=1) cls.project_task_rate2 = cls.env['project.project'].search([('sale_line_id', '=', cls.so2_line_deliver_project_template.id)], limit=1) def test_make_billable_at_task_rate(self): """ Starting from a non billable project, make it billable at task rate """ Timesheet = self.env['account.analytic.line'] Task = self.env['project.task'] # set a customer on the project self.project_non_billable.write({ 'partner_id': self.partner_2.id, 'timesheet_product_id': self.product_delivery_timesheet3, }) # create a task and 2 timesheets task = Task.with_context(default_project_id=self.project_non_billable.id).create({ 'name': 'first task', 'partner_id': self.project_non_billable.partner_id.id, 'planned_hours': 10, }) timesheet1 = Timesheet.create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 3, 'employee_id': self.employee_manager.id, }) timesheet2 = Timesheet.create({ 'name': 'Test Line tde', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 2, 'employee_id': self.employee_tde.id, }) # Change project to billable at task rate self.project_non_billable.write({ 'allow_billable': True, }) # create wizard wizard = self.env['project.create.sale.order'].with_context(active_id=self.project_non_billable.id, active_model='project.project').create({ 'line_ids': [ Command.create({'product_id': self.product_delivery_timesheet3.id, 'price_unit': self.product_delivery_timesheet3.lst_price}), ], }) self.assertEqual(wizard.partner_id, self.project_non_billable.partner_id, "The wizard should have the same partner as the project") self.assertEqual(len(wizard.line_ids), 1, "The wizard should have one line") self.assertEqual(wizard.line_ids.product_id, self.product_delivery_timesheet3, "The wizard should have one line with right product") # create the SO from the project action = wizard.action_create_sale_order() sale_order = self.env['sale.order'].browse(action['res_id']) self.assertEqual(sale_order.partner_id, self.project_non_billable.partner_id, "The customer of the SO should be the same as the project") self.assertEqual(len(sale_order.order_line), 1, "The SO should have 1 line") self.assertEqual(sale_order.order_line.product_id, wizard.line_ids.product_id, "The product of the only SOL should be the selected on the wizard") self.assertEqual(sale_order.order_line.project_id, self.project_non_billable, "SOL should be linked to the project") self.assertTrue(sale_order.order_line.task_id, "The SOL creates a task as they were no task already present in the project (system limitation)") self.assertEqual(sale_order.order_line.task_id.project_id, self.project_non_billable, "The created task should be in the project") self.assertEqual(sale_order.order_line.qty_delivered, timesheet1.unit_amount + timesheet2.unit_amount, "The create SOL should have an delivered quantity equals to the sum of tasks'timesheets") self.assertEqual(self.project_non_billable.pricing_type, 'fixed_rate', 'The pricing type of the project should be project rate since we linked a SO in the project.') def test_make_billable_at_employee_rate(self): """ Starting from a non billable project, make it billable at employee rate """ Timesheet = self.env['account.analytic.line'] Task = self.env['project.task'] # set a customer on the project self.project_non_billable.write({ 'partner_id': self.partner_2.id }) # create a task and 2 timesheets task = Task.with_context(default_project_id=self.project_non_billable.id).create({ 'name': 'first task', 'partner_id': self.project_non_billable.partner_id.id, 'planned_hours': 10, }) timesheet1 = Timesheet.create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 3, 'employee_id': self.employee_manager.id, }) timesheet2 = Timesheet.create({ 'name': 'Test Line tde', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 2, 'employee_id': self.employee_user.id, }) # Change project to billable at employee rate self.project_non_billable.write({ 'allow_billable': True, }) # create wizard wizard = self.env['project.create.sale.order'].with_context(active_id=self.project_non_billable.id, active_model='project.project').create({ 'partner_id': self.partner_2.id, 'line_ids': [ (0, 0, {'product_id': self.product_delivery_timesheet1.id, 'price_unit': 15, 'employee_id': self.employee_tde.id}), # product creates no T (0, 0, {'product_id': self.product_delivery_timesheet1.id, 'price_unit': 15, 'employee_id': self.employee_manager.id}), # product creates no T (same product than previous one) (0, 0, {'product_id': self.product_delivery_timesheet3.id, 'price_unit': self.product_delivery_timesheet3.list_price, 'employee_id': self.employee_user.id}), # product creates new T in new P ] }) self.assertEqual(wizard.partner_id, self.project_non_billable.partner_id, "The wizard should have the same partner as the project") self.assertEqual(wizard.project_id, self.project_non_billable, "The wizard'project should be the non billable project") # create the SO from the project action = wizard.action_create_sale_order() sale_order = self.env['sale.order'].browse(action['res_id']) self.assertEqual(sale_order.partner_id, self.project_non_billable.partner_id, "The customer of the SO should be the same as the project") self.assertEqual(len(sale_order.order_line), 2, "The SO should have 2 lines, as in wizard map there were 2 time the same product with the same price (for 2 different employees)") self.assertEqual(len(self.project_non_billable.sale_line_employee_ids), 3, "The project have 3 lines in its map") self.assertEqual(self.project_non_billable.pricing_type, 'employee_rate', 'The pricing type of the project should be employee rate since we have some mappings in this project.') self.assertEqual(self.project_non_billable.sale_line_id, sale_order.order_line[0], "The wizard sets sale line fallbakc on project as the first of the list") self.assertEqual(task.sale_line_id, sale_order.order_line[0], "The wizard sets sale line fallback on tasks") self.assertEqual(task.partner_id, wizard.partner_id, "The wizard sets the customer on tasks to make SOL line field visible") line1 = sale_order.order_line.filtered(lambda sol: sol.product_id == self.product_delivery_timesheet1) line2 = sale_order.order_line.filtered(lambda sol: sol.product_id == self.product_delivery_timesheet3) self.assertTrue(line1, "Sale line 1 with product 1 should exists") self.assertTrue(line2, "Sale line 2 with product 3 should exists") self.assertFalse(line1.project_id, "Sale line 1 should be linked to the 'non billable' project") self.assertEqual(line2.project_id, self.project_non_billable, "Sale line 3 should be linked to the 'non billable' project") self.assertEqual(line1.price_unit, 15, "The unit price of SOL 1 should be 15") self.assertEqual(line1.product_uom_qty, 3, "The ordered qty of SOL 1 should be 3") self.assertEqual(line2.product_uom_qty, 2, "The ordered qty of SOL 2 should be 2") self.assertEqual(self.project_non_billable.sale_line_employee_ids.mapped('sale_line_id'), sale_order.order_line, "The SO lines of the map should be the same of the sales order") self.assertEqual(timesheet1.so_line, line1, "Timesheet1 should be linked to sale line 1, as employee manager create the timesheet") self.assertEqual(timesheet2.so_line, line2, "Timesheet2 should be linked to sale line 2, as employee tde create the timesheet") self.assertEqual(timesheet1.unit_amount, line1.qty_delivered, "Sale line 1 should have a delivered qty equals to the sum of its linked timesheets") self.assertEqual(timesheet2.unit_amount, line2.qty_delivered, "Sale line 2 should have a delivered qty equals to the sum of its linked timesheets") def test_billing_employee_rate(self): """ Check task and subtask creation, and timesheeting in a project billed at 'employee rate'. Then move the task into a 'task rate' project. """ Task = self.env['project.task'].with_context(tracking_disable=True) Timesheet = self.env['account.analytic.line'] # create a task task = Task.with_context(default_project_id=self.project_employee_rate.id).create({ 'name': 'first task', 'partner_id': self.partner_a.id, }) self.assertTrue(task.allow_billable, "Task in project 'employee rate' should be billable") self.assertEqual(task.pricing_type, 'employee_rate', "Task in project 'employee rate' should be billed at employee rate") self.assertEqual(task.sale_line_id, self.project_employee_rate.sale_line_id, "Task created in a project billed on 'employee rate' should be linked to the SOL defined in the project.") self.assertEqual(task.partner_id, task.project_id.partner_id, "Task created in a project billed on 'employee rate' should have the same customer as the one from the project") task.write({'sale_line_id': False}) # remove the SOL to check if the timesheet has no SOL when there is no SOL in the task # log timesheet on task timesheet1 = Timesheet.create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 50, 'employee_id': self.employee_manager.id, }) self.assertFalse(timesheet1.so_line, "The timesheet should be not linked to the project of the map entry since no SOL in the linked task.") task.write({ 'sale_line_id': self.project_employee_rate_user.sale_line_id.id }) self.assertEqual(self.project_employee_rate_manager.sale_line_id, timesheet1.so_line, "The timesheet should be linked to the SOL associated to the Employee manager in the map") self.assertEqual(self.project_employee_rate_manager.project_id, timesheet1.project_id, "The timesheet should be linked to the project of the map entry") # create a subtask subtask = Task.with_context(default_project_id=self.project_subtask.id).create({ 'name': 'first subtask task', 'parent_id': task.id, }) self.assertFalse(subtask.allow_billable, "Subtask in non billable project should be non billable too") self.assertFalse(subtask.project_id.allow_billable, "The subtask project is non billable even if the subtask is") self.assertEqual(subtask.partner_id, subtask.parent_id.partner_id, "Subtask should have the same customer as the one from their mother") # log timesheet on subtask timesheet2 = Timesheet.create({ 'name': 'Test Line on subtask', 'project_id': subtask.project_id.id, 'task_id': subtask.id, 'unit_amount': 50, 'employee_id': self.employee_user.id, }) self.assertEqual(subtask.project_id, timesheet2.project_id, "The timesheet is in the subtask project") self.assertNotEqual(self.project_employee_rate_user.project_id, timesheet2.project_id, "The timesheet should not be linked to the billing project for the map") self.assertFalse(timesheet2.so_line, "The timesheet should not be linked to SOL as the task is in a non billable project") # move task into task rate project task.write({ 'project_id': self.project_task_rate.id, }) self.assertTrue(task.allow_billable, "Task in project 'task rate' should be billed at task rate") self.assertEqual(task.sale_line_id, self.so1_line_deliver_no_task, "The task should keep the same SOL since the partner_id has not changed when the project of the task has changed.") self.assertEqual(task.partner_id, self.partner_a, "Task created in a project billed on 'employee rate' should have the same customer when it has been created.") # move subtask into task rate project subtask.write({ 'display_project_id': self.project_task_rate2.id, }) self.assertTrue(subtask.allow_billable, "Subtask should keep the billable type from its parent, even when they are moved into another project") self.assertEqual(subtask.sale_line_id, task.sale_line_id, "Subtask should keep the same sale order line than their mother, even when they are moved into another project") # create a second task in employee rate project task2 = Task.with_context(default_project_id=self.project_employee_rate.id).create({ 'name': 'first task', 'partner_id': self.partner_a.id, 'sale_line_id': False }) # log timesheet on task in 'employee rate' project without any fallback (no map, no SOL on task, no SOL on project) timesheet3 = Timesheet.create({ 'name': 'Test Line', 'project_id': task2.project_id.id, 'task_id': task2.id, 'unit_amount': 3, 'employee_id': self.employee_tde.id, }) self.assertFalse(timesheet3.so_line, "The timesheet should not be linked to SOL as there is no fallback at all (no map, no SOL on task, no SOL on project)") # log timesheet on task in 'employee rate' project (no map, no SOL on task, but SOL on project) timesheet4 = Timesheet.create({ 'name': 'Test Line ', 'project_id': task2.project_id.id, 'task_id': task2.id, 'unit_amount': 4, 'employee_id': self.employee_tde.id, }) self.assertFalse(timesheet4.so_line, "The timesheet should not be linked to SOL, as no entry for TDE in project map") def test_billing_task_rate(self): """ Check task and subtask creation, and timesheeting in a project billed at 'task rate'. Then move the task into a 'employee rate' project then, 'non billable'. """ Task = self.env['project.task'].with_context(tracking_disable=True) Timesheet = self.env['account.analytic.line'] # create a task task = Task.with_context(default_project_id=self.project_task_rate.id).create({ 'name': 'first task', }) self.assertEqual(task.sale_line_id, self.so2_line_deliver_project_task, "Task created in a project billed on 'task rate' should be linked to a SOL containing a prepaid service product and the remaining hours of this SOL should be greater than 0.") self.assertEqual(task.partner_id, task.project_id.partner_id, "Task created in a project billed on 'task rate' should have the same customer as the one from the project") # log timesheet on task timesheet1 = Timesheet.create({ 'name': 'Test Line', 'project_id': task.project_id.id, 'task_id': task.id, 'unit_amount': 50, 'employee_id': self.employee_manager.id, }) self.assertEqual(task.sale_line_id, timesheet1.so_line, "The timesheet should be linked to the SOL associated to the task since the pricing type of the project is task rate.") # create a subtask subtask = Task.with_context(default_project_id=self.project_task_rate.id).create({ 'name': 'first subtask task', 'parent_id': task.id, 'display_project_id': self.project_subtask.id, }) self.assertEqual(subtask.partner_id, subtask.parent_id.partner_id, "Subtask should have the same customer as the one from their mother") # log timesheet on subtask timesheet2 = Timesheet.create({ 'name': 'Test Line on subtask', 'project_id': subtask.display_project_id.id, 'task_id': subtask.id, 'unit_amount': 50, 'employee_id': self.employee_user.id, }) self.assertEqual(subtask.display_project_id, timesheet2.project_id, "The timesheet is in the subtask project") self.assertFalse(timesheet2.so_line, "The timesheet should not be linked to SOL as it's a non billable project") # move task and subtask into task rate project task.write({ 'project_id': self.project_employee_rate.id, }) subtask.write({ 'display_project_id': self.project_employee_rate.id, }) self.assertEqual(task.sale_line_id, self.project_task_rate.sale_line_id, "Task moved in a employee rate billable project should keep its SOL because the partner_id has not changed too.") self.assertEqual(task.partner_id, self.project_task_rate.partner_id, "Task created in a project billed on 'employee rate' should have the same customer as the one from its initial project.") self.assertEqual(subtask.sale_line_id, subtask.parent_id.sale_line_id, "Subtask moved in a employee rate billable project should have the SOL of its parent since it keep its partner_id and this partner is different than the one in the destination project.") self.assertEqual(subtask.partner_id, subtask.parent_id.partner_id, "Subtask moved in a project billed on 'employee rate' should keep its initial customer, that is the one of its parent.") def test_customer_change_in_project(self): """ Test when the user change the customer in a project Test Case: ========= 1) Take project with pricing_type="fixed_rate", change the existing customer to another and check if the SO and SOL are equal to False. 2) Take project with pricing_type="employee_rate", change the existing customer to another and check if the SO and SOL are equal to False. 2.1) Check if the SOL in mapping is also equal to False """ # 1) Take project with pricing_type="fixed_rate", change the existing customer to another and check if the SO and SOL are equal to False. self.project_project_rate.write({ 'partner_id': self.partner_2.id, }) self.assertFalse(self.project_project_rate.sale_order_id, "The SO in the project should be False because the previous SO customer does not match the actual customer of the project.") self.assertFalse(self.project_project_rate.sale_line_id, "The SOL in the project should be False because the previous SOL customer does not match the actual customer of the project.") self.assertEqual(self.project_project_rate.pricing_type, 'task_rate', 'Since there is no SO and SOL in the project, the pricing type should be task rate.') # 2) Take project with pricing_type="employee_rate", change the existing customer to another and check if the SO and SOL are equal to False. self.project_employee_rate.write({ 'partner_id': self.partner_2.id, }) self.assertFalse(self.project_employee_rate.sale_order_id, "The SO in the project should be False because the previous SO customer does not match the actual customer of the project.") self.assertFalse(self.project_employee_rate.sale_line_id, "The SOL in the project should be False because the previous SOL customer does not match the actual customer of the project.") # 2.1) Check if the SOL in mapping is also equal to False self.assertFalse(self.project_employee_rate_manager.sale_line_id, "The SOL in the mapping should be False because the actual customer in the project has not this SOL.") self.assertFalse(self.project_employee_rate_user.sale_line_id, "The SOL in the mapping should be False because the actual customer in the project has not this SOL.") self.assertEqual(self.project_employee_rate.pricing_type, 'employee_rate', 'Since the mappings have not been removed, the pricing type should remain the same, that is employee rate.') def test_project_form_view(self): """ Test if in the form view, the partner is correctly computed when the user adds a mapping Test Case: ========= 1) Use the Form class to create a project with a form view 2) Define a billable project 3) Create an employee mapping in this project 4) Check if the partner_id and pricing_type fields have been changed """ with Form(self.env['project.project'].with_context({'tracking_disable': True})) as project_form: project_form.name = 'Test Billable Project' project_form.allow_billable = True with project_form.sale_line_employee_ids.new() as mapping_form: mapping_form.employee_id = self.employee_manager mapping_form.sale_line_id = self.so.order_line[:1] self.assertEqual(project_form.partner_id, self.so.partner_id, 'The partner should be the one defined the SO linked to the SOL defined in the mapping.') project = project_form.save() self.assertEqual(project.pricing_type, 'employee_rate', 'Since there is a mapping in this project, the pricing type should be employee rate.')
59.024123
26,915
1,081
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. # -*- coding: utf-8 -*- from odoo.tests import HttpCase, tagged @tagged('-at_install', 'post_install') class TestUi(HttpCase): @classmethod def setUpClass(cls): super().setUpClass() service_category_id = cls.env['product.category'].create({ 'name': 'Services', 'parent_id': cls.env.ref('product.product_category_1').id, }).id uom_hour_id = cls.env.ref('uom.product_uom_hour').id cls.prepaid_service_product = cls.env['product.product'].create({ 'name': 'Service Product (Prepaid Hours)', 'categ_id': service_category_id, 'type': 'service', 'list_price': 250.00, 'standard_price': 190.00, 'uom_id': uom_hour_id, 'uom_po_id': uom_hour_id, 'service_policy': 'ordered_timesheet', 'service_tracking': 'no', }) def test_ui(self): self.start_tour('/web', 'sale_timesheet_tour', login='admin', timeout=100)
32.757576
1,081
5,956
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import Command from .common import TestCommonSaleTimesheet from odoo.tests import tagged @tagged('post_install', '-at_install') class TestProject(TestCommonSaleTimesheet): def setUp(self): super().setUp() self.project_global.write({ 'sale_line_id': self.so.order_line[0].id, }) def test_fetch_sale_order_items(self): """ Test _fetch_sale_order_items and _get_sale_order_items methods This test will check we have the SOLs linked to the project and its tasks. Test Case: ========= 1) No SOLs and SO should be found on a non billable project 2) Sol linked to the project should be fetched 3) SOL linked to the project and its task should be fetched 4) remove the SOL linked to the project and check the SOL linked to the task is fetched 5) Add an additional domain in the tasks to check if we can fetch with an additional filter for instance, only the SOLs linked to the folded tasks. 6) Set allàw_billable=False and check no SOL is found since the project is not billable. """ self.assertFalse(self.project_non_billable._fetch_sale_order_items()) self.assertFalse(self.project_non_billable._get_sale_order_items()) self.assertFalse(self.project_non_billable._get_sale_orders()) sale_item = self.so.order_line[0] self.project_global.invalidate_cache() expected_task_sale_order_items = self.project_global.tasks.sale_line_id expected_sale_order_items = sale_item | expected_task_sale_order_items self.assertEqual(self.project_global._fetch_sale_order_items(), expected_sale_order_items) self.assertEqual(self.project_global._get_sale_order_items(), expected_sale_order_items) self.assertEqual(self.project_global._get_sale_orders(), self.so) task = self.env['project.task'].create({ 'name': 'Task with SOL', 'project_id': self.project_global.id, 'sale_line_id': self.so.order_line[1].id, }) self.assertEqual(task.project_id, self.project_global) self.assertEqual(task.sale_line_id, self.so.order_line[1]) self.assertEqual(task.sale_order_id, self.so) sale_lines = self.project_global._get_sale_order_items() self.assertEqual(sale_lines, task.sale_line_id + self.project_global.sale_line_id, 'The Sales Order Items found should be the one linked to the project and the one of project task.') self.assertEqual(self.project_global._get_sale_orders(), self.so, 'The Sales Order fetched should be the one of the both sale_lines fetched.') self.project_global.write({ 'sale_line_id': False, }) self.project_global.invalidate_cache() expected_task_sale_order_items |= task.sale_line_id self.assertEqual(self.project_global._get_sale_order_items(), expected_task_sale_order_items) self.assertEqual(self.project_global._get_sale_orders(), self.so) new_stage = self.env['project.task.type'].create({ 'name': 'New', 'sequence': 1, 'project_ids': [Command.set(self.project_global.ids)], }) done_stage = self.env['project.task.type'].create({ 'name': 'Done', 'sequence': 2, 'project_ids': [Command.set(self.project_global.ids)], 'fold': True, 'is_closed': True, }) task.write({ 'stage_id': done_stage.id, }) self.env['project.task.type'].flush() self.assertFalse(self.project_global._fetch_sale_order_items({'project.task': [('stage_id.fold', '=', False)]})) self.assertEqual(self.project_global._fetch_sale_order_items({'project.task': [('stage_id.fold', '=', True)]}), task.sale_line_id) task2 = self.env['project.task'].create({ 'name': 'Task 2', 'project_id': self.project_global.id, 'sale_line_id': sale_item.id, 'stage_id': new_stage.id, }) self.assertEqual(self.project_global._fetch_sale_order_items({'project.task': [('stage_id.fold', '=', False)]}), task2.sale_line_id) self.assertEqual(self.project_global._fetch_sale_order_items({'project.task': [('stage_id.fold', '=', True)]}), task.sale_line_id) self.project_global.allow_billable = False self.assertFalse(self.project_global._get_sale_order_items()) self.assertFalse(self.project_global._get_sale_orders()) def test_compute_cost_in_employee_mappings(self): self.assertFalse(self.project_global.sale_line_employee_ids) employee_mapping = self.env['project.sale.line.employee.map'] \ .with_context(default_project_id=self.project_global.id) \ .create({ 'employee_id': self.employee_manager.id, 'sale_line_id': self.project_global.sale_line_id.id, }) self.assertFalse(employee_mapping.is_cost_changed) self.assertEqual(employee_mapping.cost, self.employee_manager.timesheet_cost) employee_mapping.cost = 5 self.assertTrue(employee_mapping.is_cost_changed) self.assertEqual(employee_mapping.cost, 5) self.employee_manager.timesheet_cost = 80 self.assertTrue(employee_mapping.is_cost_changed) self.assertEqual(employee_mapping.cost, 5) employee_mapping.employee_id = self.employee_user self.assertTrue(employee_mapping.is_cost_changed) self.assertEqual(employee_mapping.cost, 5) employee_mapping.cost = self.employee_user.timesheet_cost employee_mapping.employee_id = self.employee_company_B self.assertEqual(employee_mapping.cost, self.employee_company_B.timesheet_cost)
47.64
5,955
6,715
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from .common import TestCommonSaleTimesheet @tagged('-at_install', 'post_install') class TestUpsellWarning(TestCommonSaleTimesheet): def test_display_upsell_warning(self): """ Test to display an upsell warning We display an upsell warning in SO when this following condition is satisfy in its SOL: (qty_delivered / product_uom_qty) >= product_id.service_upsell_threshold Test Case: ========= 1) Configure the upsell warning in prepaid service product 2) Create SO with a SOL containing this updated product, 3) Create Project and Task, 4) Timesheet in the task to satisfy the condition for the SOL to display an upsell warning, 5) Check if the SO has an 'sale.mail_act_sale_upsell' activity. """ # 1) Configure the upsell warning in prepaid service product self.product_order_timesheet1.write({ 'service_upsell_threshold': 0.5, }) # 2) Create SO with a SOL containing this updated product so = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, }) self.env['sale.order.line'].create({ 'order_id': so.id, 'name': self.product_order_timesheet1.name, 'product_id': self.product_order_timesheet1.id, 'product_uom_qty': 10, 'price_unit': self.product_order_timesheet1.list_price, }) so.action_confirm() # 3) Create Project and Task project = self.env['project.project'].create({ 'name': 'Project', 'allow_timesheets': True, 'allow_billable': True, 'partner_id': self.partner_a.id, 'analytic_account_id': self.analytic_account_sale.id, }) task = self.env['project.task'].create({ 'name': 'Task Test', 'project_id': project.id, }) task._compute_sale_line() # 4) Timesheet in the task to satisfy the condition for the SOL to display an upsell warning timesheet = self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 5, 'employee_id': self.employee_manager.id, 'project_id': project.id, 'task_id': task.id, }) timesheet._compute_so_line() so.order_line._compute_qty_delivered() so.order_line._compute_invoice_status() so._get_invoice_status() # Normally this method is called at the end of _get_invoice_status and other compute method. Here, we simulate for invoice_status field so._compute_field_value(so._fields['invoice_status']) self.assertEqual(len(so.activity_search(['sale.mail_act_sale_upsell'])), 0, 'No upsell warning should appear in the SO.') timesheet.write({ 'unit_amount': 6, }) timesheet._compute_so_line() so.order_line._compute_qty_delivered() so.order_line._compute_invoice_status() so._get_invoice_status() # Normally this method is called at the end of _get_invoice_status and other compute method. Here, we simulate for invoice_status field so._compute_field_value(so._fields['invoice_status']) # 5) Check if the SO has an 'sale.mail_act_sale_upsell' activity. self.assertEqual(len(so.activity_search(['sale.mail_act_sale_upsell'])), 1, 'A upsell warning should appear in the SO.') def test_display_upsell_warning_when_invoiced(self): """ Test to display an upsell warning when threshold value (10000%) exceed while creating invoice. We display an upsell warning in SO when this following condition is satisfy in its SOL: (qty_delivered / product_uom_qty) >= product_id.service_upsell_threshold Test Case: ========= 1) Configure the upsell warning in prepaid service product 2) Create SO with a SOL containing this updated product, 3) Create Project and Task, 4) Timesheet in the task to satisfy the condition for the SOL to display an upsell warning, 5) Create Invoice of the SO, 6) Check if the SO has an 'sale.mail_act_sale_upsell' activity. """ # 1) Configure the upsell warning in prepaid service product with 100 (10000%) self.product_order_timesheet1.write({ 'service_upsell_threshold': 100, }) # 2) Create SO with a SOL containing this updated product so = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'partner_invoice_id': self.partner_a.id, 'partner_shipping_id': self.partner_a.id, }) self.env['sale.order.line'].create({ 'order_id': so.id, 'name': self.product_order_timesheet1.name, 'product_id': self.product_order_timesheet1.id, 'product_uom_qty': 1, 'price_unit': self.product_order_timesheet1.list_price, }) so.action_confirm() # 3) Create Project and Task project = self.env['project.project'].create({ 'name': 'Project', 'allow_timesheets': True, 'allow_billable': True, 'partner_id': self.partner_a.id, 'analytic_account_id': self.analytic_account_sale.id, }) task = self.env['project.task'].create({ 'name': 'Task Test', 'project_id': project.id, 'sale_line_id': so.order_line.id }) # 4) Timesheet in the task to satisfy the condition for the SOL to display an upsell warning self.env['account.analytic.line'].create({ 'name': 'Test Line', 'unit_amount': 50, 'employee_id': self.employee_manager.id, 'project_id': project.id, 'task_id': task.id, }) so.order_line._compute_qty_delivered() # 5) Create Invoice of the SO so._create_invoices() # Normally this method is called at the end of _get_invoice_status and other compute method. Here, we simulate for invoice_status field so._compute_field_value(so._fields['invoice_status']) # 6) Check if the SO has an 'sale.mail_act_sale_upsell' activity. self.assertEqual(len(so.activity_search(['sale.mail_act_sale_upsell'])), 0, 'No upsell warning should appear in the SO.')
42.770701
6,715
2,716
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 ProjectCreateInvoice(models.TransientModel): _name = 'project.create.invoice' _description = "Create Invoice from project" @api.model def default_get(self, fields): result = super(ProjectCreateInvoice, self).default_get(fields) active_model = self._context.get('active_model') if active_model != 'project.project': raise UserError(_('You can only apply this action from a project.')) active_id = self._context.get('active_id') if 'project_id' in fields and active_id: result['project_id'] = active_id return result project_id = fields.Many2one('project.project', "Project", help="Project to make billable", required=True) _candidate_orders = fields.Many2many('sale.order', compute='_compute_candidate_orders') sale_order_id = fields.Many2one( 'sale.order', string="Choose the Sales Order to invoice", required=True, domain="[('id', 'in', _candidate_orders)]" ) amount_to_invoice = fields.Monetary("Amount to invoice", compute='_compute_amount_to_invoice', currency_field='currency_id', help="Total amount to invoice on the sales order, including all items (services, storables, expenses, ...)") currency_id = fields.Many2one(related='sale_order_id.currency_id', readonly=True) @api.depends('project_id.tasks.sale_line_id.order_id.invoice_status') def _compute_candidate_orders(self): for p in self: p._candidate_orders = p.project_id\ .mapped('tasks.sale_line_id.order_id')\ .filtered(lambda so: so.invoice_status == 'to invoice') @api.depends('sale_order_id') def _compute_amount_to_invoice(self): for wizard in self: amount_untaxed = 0.0 amount_tax = 0.0 for line in wizard.sale_order_id.order_line.filtered(lambda sol: sol.invoice_status == 'to invoice'): amount_untaxed += line.price_reduce * line.qty_to_invoice amount_tax += line.price_tax wizard.amount_to_invoice = amount_untaxed + amount_tax def action_create_invoice(self): if not self.sale_order_id and self.sale_order_id.invoice_status != 'to invoice': raise UserError(_("The selected Sales Order should contain something to invoice.")) action = self.env["ir.actions.actions"]._for_xml_id("sale.action_view_sale_advance_payment_inv") action['context'] = { 'active_ids': self.sale_order_id.ids } return action
46.827586
2,716
14,089
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 ProjectCreateSalesOrder(models.TransientModel): _name = 'project.create.sale.order' _description = "Create SO from project" @api.model def default_get(self, fields): result = super(ProjectCreateSalesOrder, self).default_get(fields) active_model = self._context.get('active_model') if active_model != 'project.project': raise UserError(_("You can only apply this action from a project.")) active_id = self._context.get('active_id') if 'project_id' in fields and active_id: project = self.env['project.project'].browse(active_id) if project.sale_order_id: raise UserError(_("The project has already a sale order.")) result['project_id'] = active_id if not result.get('partner_id', False): result['partner_id'] = project.partner_id.id if project.pricing_type != 'task_rate' and not result.get('line_ids', False): if project.pricing_type == 'employee_rate': default_product = self.env.ref('sale_timesheet.time_product', False) result['line_ids'] = [ (0, 0, { 'employee_id': e.employee_id.id, 'product_id': e.timesheet_product_id.id or default_product.id, 'price_unit': e.price_unit if e.timesheet_product_id else default_product.lst_price }) for e in project.sale_line_employee_ids] employee_from_timesheet = project.task_ids.timesheet_ids.employee_id - project.sale_line_employee_ids.employee_id result['line_ids'] += [ (0, 0, { 'employee_id': e.id, 'product_id': default_product.id, 'price_unit': default_product.lst_price }) for e in employee_from_timesheet] return result project_id = fields.Many2one('project.project', "Project", domain=[('sale_line_id', '=', False)], help="Project for which we are creating a sales order", required=True) company_id = fields.Many2one(related='project_id.company_id') partner_id = fields.Many2one('res.partner', string="Customer", required=True, help="Customer of the sales order") commercial_partner_id = fields.Many2one(related='partner_id.commercial_partner_id') sale_order_id = fields.Many2one( 'sale.order', string="Sales Order", domain="['|', '|', ('partner_id', '=', partner_id), ('partner_id', 'child_of', commercial_partner_id), ('partner_id', 'parent_of', partner_id)]") line_ids = fields.One2many('project.create.sale.order.line', 'wizard_id', string='Lines') info_invoice = fields.Char(compute='_compute_info_invoice') @api.depends('sale_order_id') def _compute_info_invoice(self): for line in self: domain = self.env['sale.order.line']._timesheet_compute_delivered_quantity_domain() timesheet = self.env['account.analytic.line'].read_group(domain + [('task_id', 'in', line.project_id.tasks.ids), ('so_line', '=', False), ('timesheet_invoice_id', '=', False)], ['unit_amount'], ['task_id']) unit_amount = round(sum(t.get('unit_amount', 0) for t in timesheet), 2) if timesheet else 0 if not unit_amount: line.info_invoice = False continue company_uom = self.env.company.timesheet_encode_uom_id label = _("hours") if company_uom == self.env.ref('uom.product_uom_day'): label = _("days") line.info_invoice = _("%(amount)s %(label)s will be added to the new Sales Order.", amount=unit_amount, label=label) @api.onchange('partner_id') def _onchange_partner_id(self): self.sale_order_id = False def action_create_sale_order(self): # if project linked to SO line or at least on tasks with SO line, then we consider project as billable. if self.project_id.sale_line_id: raise UserError(_("The project is already linked to a sales order item.")) # at least one line if not self.line_ids: raise UserError(_("At least one line should be filled.")) if self.line_ids.employee_id: # all employee having timesheet should be in the wizard map timesheet_employees = self.env['account.analytic.line'].search([('task_id', 'in', self.project_id.tasks.ids)]).mapped('employee_id') map_employees = self.line_ids.mapped('employee_id') missing_meployees = timesheet_employees - map_employees if missing_meployees: raise UserError(_('The Sales Order cannot be created because you did not enter some employees that entered timesheets on this project. Please list all the relevant employees before creating the Sales Order.\nMissing employee(s): %s') % (', '.join(missing_meployees.mapped('name')))) # check here if timesheet already linked to SO line timesheet_with_so_line = self.env['account.analytic.line'].search_count([('task_id', 'in', self.project_id.tasks.ids), ('so_line', '!=', False)]) if timesheet_with_so_line: raise UserError(_('The sales order cannot be created because some timesheets of this project are already linked to another sales order.')) # create SO according to the chosen billable type sale_order = self._create_sale_order() view_form_id = self.env.ref('sale.view_order_form').id action = self.env["ir.actions.actions"]._for_xml_id("sale.action_orders") action.update({ 'views': [(view_form_id, 'form')], 'view_mode': 'form', 'name': sale_order.name, 'res_id': sale_order.id, }) return action def _create_sale_order(self): """ Private implementation of generating the sales order """ sale_order = self.env['sale.order'].create({ 'project_id': self.project_id.id, 'partner_id': self.partner_id.id, 'analytic_account_id': self.project_id.analytic_account_id.id, 'client_order_ref': self.project_id.name, 'company_id': self.project_id.company_id.id, }) sale_order.onchange_partner_id() sale_order.onchange_partner_shipping_id() # rewrite the user as the onchange_partner_id erases it sale_order.write({'user_id': self.project_id.user_id.id}) sale_order.onchange_user_id() # create the sale lines, the map (optional), and assign existing timesheet to sale lines self._make_billable(sale_order) # confirm SO sale_order.action_confirm() return sale_order def _make_billable(self, sale_order): if not self.line_ids.employee_id: # Then we configure the project with pricing type is equal to project rate self._make_billable_at_project_rate(sale_order) else: # Then we configure the project with pricing type is equal to employee rate self._make_billable_at_employee_rate(sale_order) def _make_billable_at_project_rate(self, sale_order): self.ensure_one() task_left = self.project_id.tasks.filtered(lambda task: not task.sale_line_id) for wizard_line in self.line_ids: task_ids = self.project_id.tasks.filtered(lambda task: not task.sale_line_id and task.timesheet_product_id == wizard_line.product_id) task_left -= task_ids # trying to simulate the SO line created a task, according to the product configuration # To avoid, generating a task when confirming the SO task_id = False if task_ids and wizard_line.product_id.service_tracking in ['task_in_project', 'task_global_project']: task_id = task_ids.ids[0] # create SO line sale_order_line = self.env['sale.order.line'].create({ 'order_id': sale_order.id, 'product_id': wizard_line.product_id.id, 'price_unit': wizard_line.price_unit, 'project_id': self.project_id.id, # prevent to re-create a project on confirmation 'task_id': task_id, 'product_uom_qty': 0.0, }) # link the tasks to the SO line task_ids.write({ 'sale_line_id': sale_order_line.id, 'partner_id': sale_order.partner_id.id, 'email_from': sale_order.partner_id.email, }) # assign SOL to timesheets search_domain = [('task_id', 'in', task_ids.ids), ('so_line', '=', False)] self.env['account.analytic.line'].search(search_domain).write({ 'so_line': sale_order_line.id }) sale_order_line.with_context({'no_update_planned_hours': True}).write({ 'product_uom_qty': sale_order_line.qty_delivered }) self.project_id.write({ 'sale_order_id': sale_order.id, 'sale_line_id': sale_order_line.id, # we take the last sale_order_line created 'partner_id': self.partner_id.id, }) if task_left: task_left.sale_line_id = False def _make_billable_at_employee_rate(self, sale_order): # trying to simulate the SO line created a task, according to the product configuration # To avoid, generating a task when confirming the SO task_id = self.env['project.task'].search([('project_id', '=', self.project_id.id)], order='create_date DESC', limit=1).id project_id = self.project_id.id lines_already_present = dict([(l.employee_id.id, l) for l in self.project_id.sale_line_employee_ids]) non_billable_tasks = self.project_id.tasks.filtered(lambda task: not task.sale_line_id) map_entries = self.env['project.sale.line.employee.map'] EmployeeMap = self.env['project.sale.line.employee.map'].sudo() # create SO lines: create on SOL per product/price. So many employee can be linked to the same SOL map_product_price_sol = {} # (product_id, price) --> SOL for wizard_line in self.line_ids: map_key = (wizard_line.product_id.id, wizard_line.price_unit) if map_key not in map_product_price_sol: values = { 'order_id': sale_order.id, 'product_id': wizard_line.product_id.id, 'price_unit': wizard_line.price_unit, 'product_uom_qty': 0.0, } if wizard_line.product_id.service_tracking in ['task_in_project', 'task_global_project']: values['task_id'] = task_id if wizard_line.product_id.service_tracking in ['task_in_project', 'project_only']: values['project_id'] = project_id sale_order_line = self.env['sale.order.line'].create(values) map_product_price_sol[map_key] = sale_order_line if wizard_line.employee_id.id not in lines_already_present: map_entries |= EmployeeMap.create({ 'project_id': self.project_id.id, 'sale_line_id': map_product_price_sol[map_key].id, 'employee_id': wizard_line.employee_id.id, }) else: map_entries |= lines_already_present[wizard_line.employee_id.id] lines_already_present[wizard_line.employee_id.id].write({ 'sale_line_id': map_product_price_sol[map_key].id }) # link the project to the SO self.project_id.write({ 'sale_order_id': sale_order.id, 'sale_line_id': sale_order.order_line[0].id, 'partner_id': self.partner_id.id, }) non_billable_tasks.write({ 'partner_id': sale_order.partner_id.id, 'email_from': sale_order.partner_id.email, }) # assign SOL to timesheets for map_entry in map_entries: search_domain = [('employee_id', '=', map_entry.employee_id.id), ('so_line', '=', False), ('task_id', 'in', self.project_id.tasks.ids)] self.env['account.analytic.line'].search(search_domain).write({ 'so_line': map_entry.sale_line_id.id }) map_entry.sale_line_id.with_context({'no_update_planned_hours': True}).write({ 'product_uom_qty': map_entry.sale_line_id.qty_delivered }) return map_entries class ProjectCreateSalesOrderLine(models.TransientModel): _name = 'project.create.sale.order.line' _description = 'Create SO Line from project' _order = 'id,create_date' wizard_id = fields.Many2one('project.create.sale.order', required=True) product_id = fields.Many2one('product.product', domain=[('detailed_type', '=', 'service'), ('invoice_policy', '=', 'delivery'), ('service_type', '=', 'timesheet')], string="Service", help="Product of the sales order item. Must be a service invoiced based on timesheets on tasks.") price_unit = fields.Float("Unit Price", help="Unit price of the sales order item.") currency_id = fields.Many2one('res.currency', string="Currency") employee_id = fields.Many2one('hr.employee', string="Employee", help="Employee that has timesheets on the project.") _sql_constraints = [ ('unique_employee_per_wizard', 'UNIQUE(wizard_id, employee_id)', "An employee cannot be selected more than once in the mapping. Please remove duplicate(s) and try again."), ] @api.onchange('product_id') def _onchange_product_id(self): self.price_unit = self.product_id.lst_price or 0 self.currency_id = self.product_id.currency_id
51.608059
14,089
2,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 class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" @api.model def _default_invoicing_timesheet_enabled(self): if 'active_id' not in self._context and 'active_ids' not in self._context: return False sale_orders = self.env['sale.order'].browse(self._context.get('active_id') or self._context.get('active_ids')) order_lines = sale_orders.mapped('order_line').filtered(lambda sol: sol.invoice_status == 'to invoice') product_ids = order_lines.mapped('product_id').filtered(lambda p: p._is_delivered_timesheet()) return bool(product_ids) date_start_invoice_timesheet = fields.Date( string='Start Date', help="Only timesheets not yet invoiced (and validated, if applicable) from this period will be invoiced. If the period is not indicated, all timesheets not yet invoiced (and validated, if applicable) will be invoiced without distinction.") date_end_invoice_timesheet = fields.Date( string='End Date', help="Only timesheets not yet invoiced (and validated, if applicable) from this period will be invoiced. If the period is not indicated, all timesheets not yet invoiced (and validated, if applicable) will be invoiced without distinction.") invoicing_timesheet_enabled = fields.Boolean(default=_default_invoicing_timesheet_enabled) def create_invoices(self): """ Override method from sale/wizard/sale_make_invoice_advance.py When the user want to invoice the timesheets to the SO up to a specific period then we need to recompute the qty_to_invoice for each product_id in sale.order.line, before creating the invoice. """ sale_orders = self.env['sale.order'].browse( self._context.get('active_ids', []) ) if self.advance_payment_method == 'delivered' and self.invoicing_timesheet_enabled: if self.date_start_invoice_timesheet or self.date_end_invoice_timesheet: sale_orders.mapped('order_line')._recompute_qty_to_invoice(self.date_start_invoice_timesheet, self.date_end_invoice_timesheet) sale_orders.with_context( timesheet_start_date=self.date_start_invoice_timesheet, timesheet_end_date=self.date_end_invoice_timesheet )._create_invoices(final=self.deduct_down_payments) if self._context.get('open_invoices', False): return sale_orders.action_view_invoice() return {'type': 'ir.actions.act_window_close'} return super(SaleAdvancePaymentInv, self).create_invoices()
53.769231
2,796
6,590
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from odoo import api, fields, models, _ from odoo.osv import expression class AccountMove(models.Model): _inherit = "account.move" timesheet_ids = fields.One2many('account.analytic.line', 'timesheet_invoice_id', string='Timesheets', readonly=True, copy=False) timesheet_count = fields.Integer("Number of timesheets", compute='_compute_timesheet_count') timesheet_encode_uom_id = fields.Many2one('uom.uom', related='company_id.timesheet_encode_uom_id') timesheet_total_duration = fields.Integer("Timesheet Total Duration", compute='_compute_timesheet_total_duration', help="Total recorded duration, expressed in the encoding UoM, and rounded to the unit") @api.depends('timesheet_ids', 'company_id.timesheet_encode_uom_id') def _compute_timesheet_total_duration(self): if not self.user_has_groups('hr_timesheet.group_hr_timesheet_user'): self.timesheet_total_duration = 0 return group_data = self.env['account.analytic.line'].read_group([ ('timesheet_invoice_id', 'in', self.ids) ], ['timesheet_invoice_id', 'unit_amount'], ['timesheet_invoice_id']) timesheet_unit_amount_dict = defaultdict(float) timesheet_unit_amount_dict.update({data['timesheet_invoice_id'][0]: data['unit_amount'] for data in group_data}) for invoice in self: total_time = invoice.company_id.project_time_mode_id._compute_quantity(timesheet_unit_amount_dict[invoice.id], invoice.timesheet_encode_uom_id) invoice.timesheet_total_duration = round(total_time) @api.depends('timesheet_ids') def _compute_timesheet_count(self): timesheet_data = self.env['account.analytic.line'].read_group([('timesheet_invoice_id', 'in', self.ids)], ['timesheet_invoice_id'], ['timesheet_invoice_id']) mapped_data = dict([(t['timesheet_invoice_id'][0], t['timesheet_invoice_id_count']) for t in timesheet_data]) for invoice in self: invoice.timesheet_count = mapped_data.get(invoice.id, 0) def action_view_timesheet(self): self.ensure_one() return { 'type': 'ir.actions.act_window', 'name': _('Timesheets'), 'domain': [('project_id', '!=', False)], 'res_model': 'account.analytic.line', 'view_id': False, 'view_mode': 'tree,form', 'help': _(""" <p class="o_view_nocontent_smiling_face"> Record timesheets </p><p> You can register and track your workings hours by project every day. Every time spent on a project will become a cost and can be re-invoiced to customers if required. </p> """), 'limit': 80, 'context': { 'default_project_id': self.id, 'search_default_project_id': [self.id] } } def _link_timesheets_to_invoice(self, start_date=None, end_date=None): """ Search timesheets from given period and link this timesheets to the invoice When we create an invoice from a sale order, we need to link the timesheets in this sale order to the invoice. Then, we can know which timesheets are invoiced in the sale order. :param start_date: the start date of the period :param end_date: the end date of the period """ for line in self.filtered(lambda i: i.move_type == 'out_invoice' and i.state == 'draft').invoice_line_ids: sale_line_delivery = line.sale_line_ids.filtered(lambda sol: sol.product_id.invoice_policy == 'delivery' and sol.product_id.service_type == 'timesheet') if sale_line_delivery: domain = line._timesheet_domain_get_invoiced_lines(sale_line_delivery) if start_date: domain = expression.AND([domain, [('date', '>=', start_date)]]) if end_date: domain = expression.AND([domain, [('date', '<=', end_date)]]) timesheets = self.env['account.analytic.line'].sudo().search(domain) timesheets.write({'timesheet_invoice_id': line.move_id.id}) class AccountMoveLine(models.Model): _inherit = 'account.move.line' @api.model def _timesheet_domain_get_invoiced_lines(self, sale_line_delivery): """ Get the domain for the timesheet to link to the created invoice :param sale_line_delivery: recordset of sale.order.line to invoice :return a normalized domain """ return [ ('so_line', 'in', sale_line_delivery.ids), ('project_id', '!=', False), '|', '|', ('timesheet_invoice_id', '=', False), ('timesheet_invoice_id.state', '=', 'cancel'), ('timesheet_invoice_id.payment_state', '=', 'reversed') ] def unlink(self): move_line_read_group = self.env['account.move.line'].search_read([ ('move_id.move_type', '=', 'out_invoice'), ('move_id.state', '=', 'draft'), ('sale_line_ids.product_id.invoice_policy', '=', 'delivery'), ('sale_line_ids.product_id.service_type', '=', 'timesheet'), ('id', 'in', self.ids)], ['move_id', 'sale_line_ids']) sale_line_ids_per_move = defaultdict(lambda: self.env['sale.order.line']) for move_line in move_line_read_group: sale_line_ids_per_move[move_line['move_id'][0]] += self.env['sale.order.line'].browse(move_line['sale_line_ids']) timesheet_read_group = self.sudo().env['account.analytic.line'].read_group([ ('timesheet_invoice_id.move_type', '=', 'out_invoice'), ('timesheet_invoice_id.state', '=', 'draft'), ('timesheet_invoice_id', 'in', self.move_id.ids)], ['timesheet_invoice_id', 'so_line', 'ids:array_agg(id)'], ['timesheet_invoice_id', 'so_line'], lazy=False) timesheet_ids = [] for timesheet in timesheet_read_group: move_id = timesheet['timesheet_invoice_id'][0] if timesheet['so_line'][0] in sale_line_ids_per_move[move_id].ids: timesheet_ids += timesheet['ids'] self.sudo().env['account.analytic.line'].browse(timesheet_ids).write({'timesheet_invoice_id': False}) return super().unlink()
50.305344
6,590
15,429
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import math from collections import defaultdict from odoo import api, fields, models, _ from odoo.osv import expression from odoo.tools import float_compare, format_amount class SaleOrder(models.Model): _inherit = 'sale.order' timesheet_ids = fields.Many2many('account.analytic.line', compute='_compute_timesheet_ids', string='Timesheet activities associated to this sale') timesheet_count = fields.Float(string='Timesheet activities', compute='_compute_timesheet_ids', groups="hr_timesheet.group_hr_timesheet_user") # override domain project_id = fields.Many2one(domain="[('pricing_type', '!=', 'employee_rate'), ('analytic_account_id', '!=', False), ('company_id', '=', company_id)]") timesheet_encode_uom_id = fields.Many2one('uom.uom', related='company_id.timesheet_encode_uom_id') timesheet_total_duration = fields.Integer("Timesheet Total Duration", compute='_compute_timesheet_total_duration', help="Total recorded duration, expressed in the encoding UoM, and rounded to the unit") def _compute_timesheet_ids(self): timesheet_groups = self.env['account.analytic.line'].sudo().read_group( [('so_line', 'in', self.mapped('order_line').ids), ('project_id', '!=', False)], ['so_line', 'ids:array_agg(id)'], ['so_line']) timesheets_per_sol = {group['so_line'][0]: (group['ids'], group['so_line_count']) for group in timesheet_groups} for order in self: timesheet_ids = [] timesheet_count = 0 for sale_line_id in order.order_line.filtered('is_service').ids: list_timesheet_ids, count = timesheets_per_sol.get(sale_line_id, ([], 0)) timesheet_ids.extend(list_timesheet_ids) timesheet_count += count order.update({ 'timesheet_ids': self.env['account.analytic.line'].browse(timesheet_ids), 'timesheet_count': timesheet_count, }) @api.depends('company_id.project_time_mode_id', 'timesheet_ids', 'company_id.timesheet_encode_uom_id') def _compute_timesheet_total_duration(self): if not self.user_has_groups('hr_timesheet.group_hr_timesheet_user'): self.update({'timesheet_total_duration': 0}) return group_data = self.env['account.analytic.line'].sudo().read_group([ ('order_id', 'in', self.ids) ], ['order_id', 'unit_amount'], ['order_id']) timesheet_unit_amount_dict = defaultdict(float) timesheet_unit_amount_dict.update({data['order_id'][0]: data['unit_amount'] for data in group_data}) for sale_order in self: total_time = sale_order.company_id.project_time_mode_id._compute_quantity(timesheet_unit_amount_dict[sale_order.id], sale_order.timesheet_encode_uom_id) sale_order.timesheet_total_duration = round(total_time) def _compute_field_value(self, field): if field.name != 'invoice_status' or self.env.context.get('mail_activity_automation_skip'): return super()._compute_field_value(field) # Get SOs which their state is not equal to upselling or invoied and if at least a SOL has warning prepaid service upsell set to True and the warning has not already been displayed upsellable_orders = self.filtered(lambda so: so.state == 'sale' and so.invoice_status not in ('upselling', 'invoiced') and (so.user_id or so.partner_id.user_id) # salesperson needed to assign upsell activity ) super(SaleOrder, upsellable_orders.with_context(mail_activity_automation_skip=True))._compute_field_value(field) for order in upsellable_orders: upsellable_lines = order._get_prepaid_service_lines_to_upsell() if upsellable_lines: order._create_upsell_activity() # We want to display only one time the warning for each SOL upsellable_lines.write({'has_displayed_warning_upsell': True}) super(SaleOrder, self - upsellable_orders)._compute_field_value(field) def _get_prepaid_service_lines_to_upsell(self): """ Retrieve all sols which need to display an upsell activity warning in the SO These SOLs should contain a product which has: - type="service", - service_policy="ordered_timesheet", """ self.ensure_one() precision = self.env['decimal.precision'].precision_get('Product Unit of Measure') return self.order_line.filtered(lambda sol: sol.is_service and not sol.has_displayed_warning_upsell # we don't want to display many times the warning each time we timesheet on the SOL and sol.product_id.service_policy == 'ordered_timesheet' and float_compare( sol.qty_delivered, sol.product_uom_qty * (sol.product_id.service_upsell_threshold or 1.0), precision_digits=precision ) > 0 ) def action_view_timesheet(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("sale_timesheet.timesheet_action_from_sales_order") action['context'] = { 'search_default_billable_timesheet': True } # erase default filters if self.timesheet_count > 0: action['domain'] = [('so_line', 'in', self.order_line.ids)] else: action = {'type': 'ir.actions.act_window_close'} return action def _create_invoices(self, grouped=False, final=False, date=None): """Link timesheets to the created invoices. Date interval is injected in the context in sale_make_invoice_advance_inv wizard. """ moves = super()._create_invoices(grouped=grouped, final=final, date=date) moves._link_timesheets_to_invoice(self.env.context.get("timesheet_start_date"), self.env.context.get("timesheet_end_date")) return moves class SaleOrderLine(models.Model): _inherit = "sale.order.line" qty_delivered_method = fields.Selection(selection_add=[('timesheet', 'Timesheets')]) analytic_line_ids = fields.One2many(domain=[('project_id', '=', False)]) # only analytic lines, not timesheets (since this field determine if SO line came from expense) remaining_hours_available = fields.Boolean(compute='_compute_remaining_hours_available', compute_sudo=True) remaining_hours = fields.Float('Remaining Hours on SO', compute='_compute_remaining_hours', compute_sudo=True, store=True) has_displayed_warning_upsell = fields.Boolean('Has Displayed Warning Upsell') def name_get(self): res = super(SaleOrderLine, self).name_get() with_remaining_hours = self.env.context.get('with_remaining_hours') with_price_unit = self.env.context.get('with_price_unit') if with_remaining_hours or with_price_unit: names = dict(res) result = [] uom_hour = with_remaining_hours and self.env.ref('uom.product_uom_hour') uom_day = with_remaining_hours and self.env.ref('uom.product_uom_day') sols_by_so_dict = with_price_unit and defaultdict(lambda: self.env[self._name]) # key: (sale_order_id, product_id), value: sale order line for line in self: if with_remaining_hours: name = names.get(line.id) if line.remaining_hours_available: company = self.env.company encoding_uom = company.timesheet_encode_uom_id remaining_time = '' if encoding_uom == uom_hour: hours, minutes = divmod(abs(line.remaining_hours) * 60, 60) round_minutes = minutes / 30 minutes = math.ceil(round_minutes) if line.remaining_hours >= 0 else math.floor(round_minutes) if minutes > 1: minutes = 0 hours += 1 else: minutes = minutes * 30 remaining_time = ' ({sign}{hours:02.0f}:{minutes:02.0f})'.format( sign='-' if line.remaining_hours < 0 else '', hours=hours, minutes=minutes) elif encoding_uom == uom_day: remaining_days = company.project_time_mode_id._compute_quantity(line.remaining_hours, encoding_uom, round=False) remaining_time = ' ({qty:.02f} {unit})'.format( qty=remaining_days, unit=_('days') if abs(remaining_days) > 1 else _('day') ) name = '{name}{remaining_time}'.format( name=name, remaining_time=remaining_time ) if with_price_unit: names[line.id] = name if not with_price_unit: result.append((line.id, name)) if with_price_unit: sols_by_so_dict[line.order_id.id, line.product_id.id] += line if with_price_unit: for sols in sols_by_so_dict.values(): if len(sols) > 1: result += [( line.id, '%s - %s' % ( names.get(line.id), format_amount(self.env, line.price_unit, line.currency_id)) ) for line in sols] else: result.append((sols.id, names.get(sols.id))) return result return res @api.depends('product_id.service_policy') def _compute_remaining_hours_available(self): uom_hour = self.env.ref('uom.product_uom_hour') for line in self: is_ordered_timesheet = line.product_id.service_policy == 'ordered_timesheet' is_time_product = line.product_uom.category_id == uom_hour.category_id line.remaining_hours_available = is_ordered_timesheet and is_time_product @api.depends('qty_delivered', 'product_uom_qty', 'analytic_line_ids') def _compute_remaining_hours(self): uom_hour = self.env.ref('uom.product_uom_hour') for line in self: remaining_hours = None if line.remaining_hours_available: qty_left = line.product_uom_qty - line.qty_delivered remaining_hours = line.product_uom._compute_quantity(qty_left, uom_hour) line.remaining_hours = remaining_hours @api.depends('product_id') def _compute_qty_delivered_method(self): """ Sale Timesheet module compute delivered qty for product [('type', 'in', ['service']), ('service_type', '=', 'timesheet')] """ super(SaleOrderLine, self)._compute_qty_delivered_method() for line in self: if not line.is_expense and line.product_id.type == 'service' and line.product_id.service_type == 'timesheet': line.qty_delivered_method = 'timesheet' @api.depends('analytic_line_ids.project_id', 'project_id.pricing_type') def _compute_qty_delivered(self): super(SaleOrderLine, self)._compute_qty_delivered() lines_by_timesheet = self.filtered(lambda sol: sol.qty_delivered_method == 'timesheet') domain = lines_by_timesheet._timesheet_compute_delivered_quantity_domain() mapping = lines_by_timesheet.sudo()._get_delivered_quantity_by_analytic(domain) for line in lines_by_timesheet: line.qty_delivered = mapping.get(line.id or line._origin.id, 0.0) def _timesheet_compute_delivered_quantity_domain(self): """ Hook for validated timesheet in addionnal module """ domain = [('project_id', '!=', False)] if self._context.get('accrual_entry_date'): domain += [('date', '<=', self._context['accrual_entry_date'])] return domain ########################################### # Service : Project and task generation ########################################### def _convert_qty_company_hours(self, dest_company): company_time_uom_id = dest_company.project_time_mode_id planned_hours = 0.0 product_uom = self.product_uom if product_uom == self.env.ref('uom.product_uom_unit'): product_uom = self.env.ref('uom.product_uom_hour') if product_uom.category_id == company_time_uom_id.category_id: if product_uom != company_time_uom_id: planned_hours = product_uom._compute_quantity(self.product_uom_qty, company_time_uom_id) else: planned_hours = self.product_uom_qty return planned_hours def _timesheet_create_project(self): project = super()._timesheet_create_project() project.write({'allow_timesheets': True}) return project def _timesheet_create_project_prepare_values(self): """Generate project values""" values = super()._timesheet_create_project_prepare_values() values['allow_billable'] = True return values def _recompute_qty_to_invoice(self, start_date, end_date): """ Recompute the qty_to_invoice field for product containing timesheets Search the existed timesheets between the given period in parameter. Retrieve the unit_amount of this timesheet and then recompute the qty_to_invoice for each current product. :param start_date: the start date of the period :param end_date: the end date of the period """ lines_by_timesheet = self.filtered(lambda sol: sol.product_id and sol.product_id._is_delivered_timesheet()) domain = lines_by_timesheet._timesheet_compute_delivered_quantity_domain() refund_account_moves = self.order_id.invoice_ids.filtered(lambda am: am.state == 'posted' and am.move_type == 'out_refund').reversed_entry_id timesheet_domain = [ '|', ('timesheet_invoice_id', '=', False), ('timesheet_invoice_id.state', '=', 'cancel')] if refund_account_moves: credited_timesheet_domain = [('timesheet_invoice_id.state', '=', 'posted'), ('timesheet_invoice_id', 'in', refund_account_moves.ids)] timesheet_domain = expression.OR([timesheet_domain, credited_timesheet_domain]) domain = expression.AND([domain, timesheet_domain]) if start_date: domain = expression.AND([domain, [('date', '>=', start_date)]]) if end_date: domain = expression.AND([domain, [('date', '<=', end_date)]]) mapping = lines_by_timesheet.sudo()._get_delivered_quantity_by_analytic(domain) for line in lines_by_timesheet: qty_to_invoice = mapping.get(line.id, 0.0) if qty_to_invoice: line.qty_to_invoice = qty_to_invoice else: prev_inv_status = line.invoice_status line.qty_to_invoice = qty_to_invoice line.invoice_status = prev_inv_status
53.020619
15,429
4,106
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models from odoo.tools import float_utils, format_amount, formatLang class ProjectUpdate(models.Model): _inherit = 'project.update' @api.model def _get_template_values(self, project): template_values = super(ProjectUpdate, self)._get_template_values(project) services = self._get_services_values(project) profitability = self._get_profitability_values(project) show_sold = template_values['project'].allow_billable and len(services.get('data', [])) > 0 return { **template_values, 'show_sold': show_sold, 'show_profitability': bool(profitability), 'show_activities': template_values['show_activities'] or show_sold or bool(profitability), 'services': services, 'profitability': profitability, } @api.model def _get_project_sols(self, project): # TODO: remove me in master return @api.model def _get_services_values(self, project): if not project.allow_billable: return {} services = [] total_sold, total_effective, total_remaining = 0, 0, 0 sols = project._get_sale_order_lines() name_by_sol = dict(sols.name_get()) product_uom_unit = self.env.ref('uom.product_uom_unit') for sol in sols: #We only want to consider hours and days for this calculation is_unit = sol.product_uom == product_uom_unit if sol.product_uom.category_id == self.env.company.timesheet_encode_uom_id.category_id or is_unit: product_uom_qty = sol.product_uom._compute_quantity(sol.product_uom_qty, self.env.company.timesheet_encode_uom_id, raise_if_failure=False) qty_delivered = sol.product_uom._compute_quantity(sol.qty_delivered, self.env.company.timesheet_encode_uom_id, raise_if_failure=False) services.append({ 'name': name_by_sol[sol.id] if len(sols.order_id) > 1 else sol.name, 'sold_value': product_uom_qty, 'effective_value': qty_delivered, 'remaining_value': product_uom_qty - qty_delivered, 'unit': sol.product_uom.name if is_unit else self.env.company.timesheet_encode_uom_id.name, 'is_unit': is_unit, 'sol': sol, }) if sol.product_uom.category_id == self.env.company.timesheet_encode_uom_id.category_id: total_sold += product_uom_qty total_effective += qty_delivered total_remaining = total_sold - total_effective return { 'data': services, 'total_sold': total_sold, 'total_effective': total_effective, 'total_remaining': total_remaining, 'company_unit_name': self.env.company.timesheet_encode_uom_id.name, } @api.model def _get_profitability_values(self, project): costs_revenues = project.analytic_account_id and project.allow_billable if not (self.user_has_groups('project.group_project_manager') and costs_revenues): return {} profitability = project._get_profitability_common() return { 'analytic_account_id': project.analytic_account_id, 'costs': format_amount(self.env, -profitability['costs'], self.env.company.currency_id), 'revenues': format_amount(self.env, profitability['revenues'], self.env.company.currency_id), 'margin': profitability['margin'], 'margin_formatted': format_amount(self.env, profitability['margin'], self.env.company.currency_id), 'margin_percentage': formatLang(self.env, not float_utils.float_is_zero(profitability['costs'], precision_digits=2) and -(profitability['margin'] / profitability['costs']) * 100 or 0.0, digits=0), }
50.073171
4,106
10,074
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import threading from odoo import api, fields, models, _ from odoo.exceptions import ValidationError SERVICE_POLICY = [ # (service_policy, (invoice_policy, service_type), string) ('ordered_timesheet', ('order', 'timesheet'), 'Prepaid/Fixed Price'), ('delivered_timesheet', ('delivery', 'timesheet'), 'Based on Timesheets'), ('delivered_manual', ('delivery', 'manual'), 'Based on Milestones'), ] SERVICE_TO_GENERAL = {policy[0]: policy[1] for policy in SERVICE_POLICY} GENERAL_TO_SERVICE = {policy[1]: policy[0] for policy in SERVICE_POLICY} class ProductTemplate(models.Model): _inherit = 'product.template' service_policy = fields.Selection([ (policy[0], policy[2]) for policy in SERVICE_POLICY ], string="Service Invoicing Policy", compute='_compute_service_policy', inverse='_inverse_service_policy') service_type = fields.Selection(selection_add=[ ('timesheet', 'Timesheets on project (one fare per SO/Project)'), ], ondelete={'timesheet': 'set default'}) # override domain project_id = fields.Many2one(domain="[('company_id', '=', current_company_id), ('allow_billable', '=', True), ('pricing_type', '=', 'task_rate'), ('allow_timesheets', 'in', [service_policy == 'delivered_timesheet', True])]") project_template_id = fields.Many2one(domain="[('company_id', '=', current_company_id), ('allow_billable', '=', True), ('allow_timesheets', 'in', [service_policy == 'delivered_timesheet', True])]") service_upsell_threshold = fields.Float('Threshold', default=1, help="Percentage of time delivered compared to the prepaid amount that must be reached for the upselling opportunity activity to be triggered.") service_upsell_threshold_ratio = fields.Char(compute='_compute_service_upsell_threshold_ratio') @api.depends('uom_id') def _compute_service_upsell_threshold_ratio(self): product_uom_hour = self.env.ref('uom.product_uom_hour') for record in self: if not record.uom_id: record.service_upsell_threshold_ratio = False continue record.service_upsell_threshold_ratio = f"1 {record.uom_id.name} = {product_uom_hour.factor / record.uom_id.factor:.2f} Hours" def _compute_visible_expense_policy(self): visibility = self.user_has_groups('project.group_project_user') for product_template in self: if not product_template.visible_expense_policy: product_template.visible_expense_policy = visibility return super(ProductTemplate, self)._compute_visible_expense_policy() @api.depends('invoice_policy', 'service_type', 'type') def _compute_service_policy(self): for product in self: product.service_policy = GENERAL_TO_SERVICE.get((product.invoice_policy, product.service_type), False) if not product.service_policy and product.type == 'service': product.service_policy = 'ordered_timesheet' @api.onchange('service_policy') def _inverse_service_policy(self): for product in self: if product.service_policy: product.invoice_policy, product.service_type = SERVICE_TO_GENERAL.get(product.service_policy, (False, False)) @api.depends('service_tracking', 'service_policy', 'type') def _compute_product_tooltip(self): super()._compute_product_tooltip() for record in self.filtered(lambda record: record.type == 'service'): if record.service_policy == 'ordered_timesheet': pass elif record.service_policy == 'delivered_timesheet': if record.service_tracking == 'no': record.product_tooltip = _( "Invoice based on timesheets (delivered quantity) on projects or tasks " "you'll create later on." ) elif record.service_tracking == 'task_global_project': record.product_tooltip = _( "Invoice based on timesheets (delivered quantity), and create a task in " "an existing project to track the time spent." ) elif record.service_tracking == 'task_in_project': record.product_tooltip = _( "Invoice based on timesheets (delivered quantity), and create a project " "for the order with a task for each sales order line to track the time " "spent." ) elif record.service_tracking == 'project_only': record.product_tooltip = _( "Invoice based on timesheets (delivered quantity), and create an empty " "project for the order to track the time spent." ) elif record.service_policy == 'delivered_manual': if record.service_tracking == 'no': record.product_tooltip = _( "Sales order lines define milestones of the project to invoice by setting " "the delivered quantity." ) elif record.service_tracking == 'task_global_project': record.product_tooltip = _( "Sales order lines define milestones of the project to invoice by setting " "the delivered quantity. Create a task in an existing project to track the" " time spent." ) elif record.service_tracking == 'task_in_project': record.product_tooltip = _( "Sales order lines define milestones of the project to invoice by setting " "the delivered quantity. Create an empty project for the order to track " "the time spent." ) elif record.service_tracking == 'project_only': record.product_tooltip = _( "Sales order lines define milestones of the project to invoice by setting " "the delivered quantity. Create a project for the order with a task for " "each sales order line to track the time spent." ) @api.model def _get_onchange_service_policy_updates(self, service_tracking, service_policy, project_id, project_template_id): vals = {} if service_tracking != 'no' and service_policy == 'delivered_timesheet': if project_id and not project_id.allow_timesheets: vals['project_id'] = False elif project_template_id and not project_template_id.allow_timesheets: vals['project_template_id'] = False return vals @api.onchange('service_policy') def _onchange_service_policy(self): self._inverse_service_policy() vals = self._get_onchange_service_policy_updates(self.service_tracking, self.service_policy, self.project_id, self.project_template_id) if vals: self.update(vals) @api.ondelete(at_uninstall=False) def _unlink_except_master_data(self): time_product = self.env.ref('sale_timesheet.time_product') if time_product.product_tmpl_id in self: raise ValidationError(_('The %s product is required by the Timesheets app and cannot be archived nor deleted.') % time_product.name) def write(self, vals): # timesheet product can't be archived test_mode = getattr(threading.current_thread(), 'testing', False) or self.env.registry.in_test_mode() if not test_mode and 'active' in vals and not vals['active']: time_product = self.env.ref('sale_timesheet.time_product') if time_product.product_tmpl_id in self: raise ValidationError(_('The %s product is required by the Timesheets app and cannot be archived nor deleted.') % time_product.name) return super(ProductTemplate, self).write(vals) class ProductProduct(models.Model): _inherit = 'product.product' def _is_delivered_timesheet(self): """ Check if the product is a delivered timesheet """ self.ensure_one() return self.type == 'service' and self.service_policy == 'delivered_timesheet' @api.onchange('service_policy') def _onchange_service_policy(self): self.product_tmpl_id._inverse_service_policy() vals = self.product_tmpl_id._get_onchange_service_policy_updates(self.service_tracking, self.service_policy, self.project_id, self.project_template_id) if vals: self.update(vals) @api.ondelete(at_uninstall=False) def _unlink_except_master_data(self): time_product = self.env.ref('sale_timesheet.time_product') if time_product in self: raise ValidationError(_('The %s product is required by the Timesheets app and cannot be archived nor deleted.') % time_product.name) def write(self, vals): # timesheet product can't be archived test_mode = getattr(threading.current_thread(), 'testing', False) or self.env.registry.in_test_mode() if not test_mode and 'active' in vals and not vals['active']: time_product = self.env.ref('sale_timesheet.time_product') if time_product in self: raise ValidationError(_('The %s product is required by the Timesheets app and cannot be archived nor deleted.') % time_product.name) return super(ProductProduct, self).write(vals)
55.04918
10,074
332
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' invoice_policy = fields.Boolean(string="Invoice Policy", help="Timesheets taken when invoicing time spent")
33.2
332
3,753
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 ProjectProductEmployeeMap(models.Model): _name = 'project.sale.line.employee.map' _description = 'Project Sales line, employee mapping' project_id = fields.Many2one('project.project', "Project", required=True) employee_id = fields.Many2one('hr.employee', "Employee", required=True) sale_line_id = fields.Many2one('sale.order.line', "Sale Order Item", compute="_compute_sale_line_id", store=True, readonly=False, domain="""[ ('is_service', '=', True), ('is_expense', '=', False), ('state', 'in', ['sale', 'done']), ('order_partner_id', '=?', partner_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]""") company_id = fields.Many2one('res.company', string='Company', related='project_id.company_id') partner_id = fields.Many2one(related='project_id.partner_id') price_unit = fields.Float("Unit Price", compute='_compute_price_unit', store=True, readonly=True) currency_id = fields.Many2one('res.currency', string="Currency", compute='_compute_currency_id', store=True, readonly=False) cost = fields.Monetary(currency_field='cost_currency_id', compute='_compute_cost', store=True, readonly=False, help="This cost overrides the employee's default timesheet cost in employee's HR Settings") cost_currency_id = fields.Many2one('res.currency', string="Cost Currency", related='employee_id.currency_id', readonly=True) is_cost_changed = fields.Boolean('Is Cost Manually Changed', compute='_compute_is_cost_changed', store=True) _sql_constraints = [ ('uniqueness_employee', 'UNIQUE(project_id,employee_id)', 'An employee cannot be selected more than once in the mapping. Please remove duplicate(s) and try again.'), ] @api.depends('partner_id') def _compute_sale_line_id(self): self.filtered( lambda map_entry: map_entry.sale_line_id and map_entry.partner_id and map_entry.sale_line_id.order_partner_id.commercial_partner_id != map_entry.partner_id.commercial_partner_id ).update({'sale_line_id': False}) @api.depends('sale_line_id.price_unit') def _compute_price_unit(self): for line in self: if line.sale_line_id: line.price_unit = line.sale_line_id.price_unit else: line.price_unit = 0 @api.depends('sale_line_id.price_unit') def _compute_currency_id(self): for line in self: line.currency_id = line.sale_line_id.currency_id if line.sale_line_id else False @api.depends('employee_id.timesheet_cost') def _compute_cost(self): self.env.remove_to_compute(self._fields['is_cost_changed'], self) for map_entry in self: if not map_entry.is_cost_changed: map_entry.cost = map_entry.employee_id.timesheet_cost or 0.0 @api.depends('cost') def _compute_is_cost_changed(self): for map_entry in self: map_entry.is_cost_changed = map_entry.employee_id and map_entry.cost != map_entry.employee_id.timesheet_cost @api.model def create(self, values): res = super(ProjectProductEmployeeMap, self).create(values) res._update_project_timesheet() return res def write(self, values): res = super(ProjectProductEmployeeMap, self).write(values) self._update_project_timesheet() return res def _update_project_timesheet(self): self.filtered(lambda l: l.sale_line_id).project_id._update_timesheets_sale_line_id()
47.506329
3,753
29,190
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from collections import defaultdict from odoo import api, fields, models, _, _lt from odoo.osv import expression from odoo.exceptions import ValidationError, UserError from odoo.tools import format_amount, float_is_zero, formatLang # YTI PLEASE SPLIT ME class Project(models.Model): _inherit = 'project.project' @api.model def default_get(self, fields): """ Pre-fill timesheet product as "Time" data product when creating new project allowing billable tasks by default. """ result = super(Project, self).default_get(fields) if 'timesheet_product_id' in fields and result.get('allow_billable') and result.get('allow_timesheets') and not result.get('timesheet_product_id'): default_product = self.env.ref('sale_timesheet.time_product', False) if default_product: result['timesheet_product_id'] = default_product.id return result def _default_timesheet_product_id(self): return self.env.ref('sale_timesheet.time_product', False) pricing_type = fields.Selection([ ('task_rate', 'Task rate'), ('fixed_rate', 'Project rate'), ('employee_rate', 'Employee rate') ], string="Pricing", default="task_rate", compute='_compute_pricing_type', search='_search_pricing_type', help='The task rate is perfect if you would like to bill different services to different customers at different rates. The fixed rate is perfect if you bill a service at a fixed rate per hour or day worked regardless of the employee who performed it. The employee rate is preferable if your employees deliver the same service at a different rate. For instance, junior and senior consultants would deliver the same service (= consultancy), but at a different rate because of their level of seniority.') sale_line_employee_ids = fields.One2many('project.sale.line.employee.map', 'project_id', "Sale line/Employee map", copy=False, help="Employee/Sale Order Item Mapping:\n Defines to which sales order item an employee's timesheet entry will be linked." "By extension, it defines the rate at which an employee's time on the project is billed.") allow_billable = fields.Boolean("Billable", help="Invoice your time and material from tasks.") billable_percentage = fields.Integer( compute='_compute_billable_percentage', groups='hr_timesheet.group_hr_timesheet_approver', help="% of timesheets that are billable compared to the total number of timesheets linked to the AA of the project, rounded to the unit.") display_create_order = fields.Boolean(compute='_compute_display_create_order') timesheet_product_id = fields.Many2one( 'product.product', string='Timesheet Product', domain="""[ ('detailed_type', '=', 'service'), ('invoice_policy', '=', 'delivery'), ('service_type', '=', 'timesheet'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]""", help='Select a Service product with which you would like to bill your time spent on tasks.', compute="_compute_timesheet_product_id", store=True, readonly=False, default=_default_timesheet_product_id) warning_employee_rate = fields.Boolean(compute='_compute_warning_employee_rate', compute_sudo=True) partner_id = fields.Many2one(compute='_compute_partner_id', store=True, readonly=False) @api.depends('sale_line_id', 'sale_line_employee_ids', 'allow_billable') def _compute_pricing_type(self): billable_projects = self.filtered('allow_billable') for project in billable_projects: if project.sale_line_employee_ids: project.pricing_type = 'employee_rate' elif project.sale_line_id: project.pricing_type = 'fixed_rate' else: project.pricing_type = 'task_rate' (self - billable_projects).update({'pricing_type': False}) def _search_pricing_type(self, operator, value): """ Search method for pricing_type field. This method returns a domain based on the operator and the value given in parameter: - operator = '=': - value = 'task_rate': [('sale_line_employee_ids', '=', False), ('sale_line_id', '=', False), ('allow_billable', '=', True)] - value = 'fixed_rate': [('sale_line_employee_ids', '=', False), ('sale_line_id', '!=', False), ('allow_billable', '=', True)] - value = 'employee_rate': [('sale_line_employee_ids', '!=', False), ('allow_billable', '=', True)] - value is False: [('allow_billable', '=', False)] - operator = '!=': - value = 'task_rate': ['|', '|', ('sale_line_employee_ids', '!=', False), ('sale_line_id', '!=', False), ('allow_billable', '=', False)] - value = 'fixed_rate': ['|', '|', ('sale_line_employee_ids', '!=', False), ('sale_line_id', '=', False), ('allow_billable', '=', False)] - value = 'employee_rate': ['|', ('sale_line_employee_ids', '=', False), ('allow_billable', '=', False)] - value is False: [('allow_billable', '!=', False)] :param operator: the supported operator is either '=' or '!='. :param value: the value than the field should be is among these values into the following tuple: (False, 'task_rate', 'fixed_rate', 'employee_rate'). :returns: the domain to find the expected projects. """ if operator not in ('=', '!='): raise UserError(_('Operation not supported')) if not ((isinstance(value, bool) and value is False) or (isinstance(value, str) and value in ('task_rate', 'fixed_rate', 'employee_rate'))): raise UserError(_('Value does not exist in the pricing type')) if value is False: return [('allow_billable', operator, value)] sol_cond = ('sale_line_id', '!=', False) mapping_cond = ('sale_line_employee_ids', '!=', False) if value == 'task_rate': domain = [expression.NOT_OPERATOR, sol_cond, expression.NOT_OPERATOR, mapping_cond] elif value == 'fixed_rate': domain = [sol_cond, expression.NOT_OPERATOR, mapping_cond] else: # value == 'employee_rate' domain = [mapping_cond] domain = expression.AND([domain, [('allow_billable', '=', True)]]) domain = expression.normalize_domain(domain) if operator != '=': domain.insert(0, expression.NOT_OPERATOR) domain = expression.distribute_not(domain) return domain @api.depends('analytic_account_id', 'timesheet_ids') def _compute_billable_percentage(self): timesheets_read_group = self.env['account.analytic.line'].read_group([('project_id', 'in', self.ids)], ['project_id', 'so_line', 'unit_amount'], ['project_id', 'so_line'], lazy=False) timesheets_by_project = defaultdict(list) for res in timesheets_read_group: timesheets_by_project[res['project_id'][0]].append((res['unit_amount'], bool(res['so_line']))) for project in self: timesheet_total = timesheet_billable = 0.0 for unit_amount, is_billable_timesheet in timesheets_by_project[project.id]: timesheet_total += unit_amount if is_billable_timesheet: timesheet_billable += unit_amount billable_percentage = timesheet_billable / timesheet_total * 100 if timesheet_total > 0 else 0 project.billable_percentage = round(billable_percentage) @api.depends('partner_id', 'pricing_type') def _compute_display_create_order(self): for project in self: project.display_create_order = project.partner_id and project.pricing_type == 'task_rate' @api.depends('allow_timesheets', 'allow_billable') def _compute_timesheet_product_id(self): default_product = self.env.ref('sale_timesheet.time_product', False) for project in self: if not project.allow_timesheets or not project.allow_billable: project.timesheet_product_id = False elif not project.timesheet_product_id: project.timesheet_product_id = default_product @api.depends('pricing_type', 'allow_timesheets', 'allow_billable', 'sale_line_employee_ids', 'sale_line_employee_ids.employee_id') def _compute_warning_employee_rate(self): projects = self.filtered(lambda p: p.allow_billable and p.allow_timesheets and p.pricing_type == 'employee_rate') employees = self.env['account.analytic.line'].read_group([('task_id', 'in', projects.task_ids.ids)], ['employee_id', 'project_id'], ['employee_id', 'project_id'], ['employee_id', 'project_id'], lazy=False) dict_project_employee = defaultdict(list) for line in employees: dict_project_employee[line['project_id'][0]] += [line['employee_id'][0]] if line['employee_id'] else [] for project in projects: project.warning_employee_rate = any(x not in project.sale_line_employee_ids.employee_id.ids for x in dict_project_employee[project.id]) (self - projects).warning_employee_rate = False @api.depends('sale_line_employee_ids.sale_line_id', 'sale_line_id') def _compute_partner_id(self): for project in self: if project.partner_id: continue if project.allow_billable and project.allow_timesheets and project.pricing_type != 'task_rate': sol = project.sale_line_id or project.sale_line_employee_ids.sale_line_id[:1] project.partner_id = sol.order_partner_id @api.depends('partner_id') def _compute_sale_line_id(self): super()._compute_sale_line_id() for project in self.filtered(lambda p: not p.sale_line_id and p.partner_id and p.pricing_type == 'employee_rate'): # Give a SOL by default either the last SOL with service product and remaining_hours > 0 sol = self.env['sale.order.line'].search([ ('is_service', '=', True), ('order_partner_id', 'child_of', project.partner_id.commercial_partner_id.id), ('is_expense', '=', False), ('state', 'in', ['sale', 'done']), ('remaining_hours', '>', 0) ], limit=1) project.sale_line_id = sol or project.sale_line_employee_ids.sale_line_id[:1] # get the first SOL containing in the employee mappings if no sol found in the search @api.constrains('sale_line_id') def _check_sale_line_type(self): for project in self.filtered(lambda project: project.sale_line_id): if not project.sale_line_id.is_service: raise ValidationError(_("You cannot link a billable project to a sales order item that is not a service.")) if project.sale_line_id.is_expense: raise ValidationError(_("You cannot link a billable project to a sales order item that comes from an expense or a vendor bill.")) def write(self, values): res = super(Project, self).write(values) if 'allow_billable' in values and not values.get('allow_billable'): self.task_ids._get_timesheet().write({ 'so_line': False, }) return res def _update_timesheets_sale_line_id(self): for project in self.filtered(lambda p: p.allow_billable and p.allow_timesheets): timesheet_ids = project.sudo(False).mapped('timesheet_ids').filtered(lambda t: not t.is_so_line_edited and t._is_not_billed()) if not timesheet_ids: continue for employee_id in project.sale_line_employee_ids.filtered(lambda l: l.project_id == project).employee_id: sale_line_id = project.sale_line_employee_ids.filtered(lambda l: l.project_id == project and l.employee_id == employee_id).sale_line_id timesheet_ids.filtered(lambda t: t.employee_id == employee_id).sudo().so_line = sale_line_id def action_open_project_invoices(self): invoices = self.env['account.move'].search([ ('line_ids.analytic_account_id', '!=', False), ('line_ids.analytic_account_id', 'in', self.analytic_account_id.ids), ('move_type', '=', 'out_invoice') ]) action = { 'name': _('Invoices'), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'views': [[False, 'tree'], [False, 'form'], [False, 'kanban']], 'domain': [('id', 'in', invoices.ids)], 'context': { 'create': False, } } if len(invoices) == 1: action['views'] = [[False, 'form']] action['res_id'] = invoices.id return action def action_view_timesheet(self): self.ensure_one() return { 'type': 'ir.actions.act_window', 'name': _('Timesheets of %s', self.name), 'domain': [('project_id', '!=', False)], 'res_model': 'account.analytic.line', 'view_id': False, 'view_mode': 'tree,form', 'help': _(""" <p class="o_view_nocontent_smiling_face"> Record timesheets </p><p> You can register and track your workings hours by project every day. Every time spent on a project will become a cost and can be re-invoiced to customers if required. </p> """), 'limit': 80, 'context': { 'default_project_id': self.id, 'search_default_project_id': [self.id] } } def action_make_billable(self): return { "name": _("Create Sales Order"), "type": 'ir.actions.act_window', "res_model": 'project.create.sale.order', "views": [[False, "form"]], "target": 'new', "context": { 'active_id': self.id, 'active_model': 'project.project', 'default_product_id': self.timesheet_product_id.id, }, } def action_billable_time_button(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("hr_timesheet.timesheet_action_all") action.update({ 'context': { 'search_default_groupby_task': True, 'default_project_id': self.id, }, 'domain': [('project_id', '=', self.id)], 'view_mode': 'tree,kanban,pivot,graph,form', 'views': [ [self.env.ref('hr_timesheet.timesheet_view_tree_user').id, 'tree'], [self.env.ref('hr_timesheet.view_kanban_account_analytic_line').id, 'kanban'], [self.env.ref('hr_timesheet.view_hr_timesheet_line_pivot').id, 'pivot'], [self.env.ref('hr_timesheet.view_hr_timesheet_line_graph_all').id, 'graph'], [self.env.ref('hr_timesheet.timesheet_view_form_user').id, 'form'], ], }) return action def action_view_all_rating(self): return { 'name': _('Rating'), 'type': 'ir.actions.act_window', 'res_model': 'rating.rating', 'view_mode': 'kanban,list,graph,pivot,form', 'view_type': 'ir.actions.act_window', 'context': { 'search_default_rating_last_30_days': True, }, 'domain': [('consumed','=',True), ('parent_res_model','=','project.project'), ('parent_res_id', '=', self.id)], } # ---------------------------- # Project Updates # ---------------------------- def get_panel_data(self): panel_data = super(Project, self).get_panel_data() return { **panel_data, 'analytic_account_id': self.analytic_account_id.id, 'sold_items': self._get_sold_items(), 'profitability_items': self._get_profitability_items(), } def _get_sale_order_lines(self): sale_orders = self._get_sale_orders() return self.env['sale.order.line'].search([('order_id', 'in', sale_orders.ids), ('is_service', '=', True), ('is_downpayment', '=', False)], order='id asc') def _get_sold_items(self): timesheet_encode_uom = self.env.company.timesheet_encode_uom_id product_uom_unit = self.env.ref('uom.product_uom_unit') product_uom_hour = self.env.ref('uom.product_uom_hour') sols = self._get_sale_order_lines() number_sale_orders = len(sols.order_id) sold_items = { 'allow_billable': self.allow_billable, 'data': [], 'number_sols': len(sols), 'total_sold': 0, 'effective_sold': 0, 'company_unit_name': timesheet_encode_uom.name } for sol in sols: name = [x[1] for x in sol.name_get()] if number_sale_orders > 1 else sol.name product_uom_convert = sol.product_uom if product_uom_convert == product_uom_unit: product_uom_convert = product_uom_hour qty_delivered = product_uom_convert._compute_quantity(sol.qty_delivered, timesheet_encode_uom, raise_if_failure=False) product_uom_qty = product_uom_convert._compute_quantity(sol.product_uom_qty, timesheet_encode_uom, raise_if_failure=False) if product_uom_convert.category_id == timesheet_encode_uom.category_id: product_uom_convert = timesheet_encode_uom if qty_delivered > 0 or product_uom_qty > 0: sold_items['data'].append({ 'name': name, 'value': '%s / %s %s' % (formatLang(self.env, qty_delivered, 1), formatLang(self.env, product_uom_qty, 1), product_uom_convert.name), 'color': 'red' if qty_delivered > product_uom_qty else 'black' }) #We only want to consider hours and days for this calculation, and eventually units if the service policy is not based on milestones if sol.product_uom.category_id == timesheet_encode_uom.category_id or (sol.product_uom == product_uom_unit and sol.product_id.service_policy != 'delivered_manual'): sold_items['total_sold'] += product_uom_qty sold_items['effective_sold'] += qty_delivered remaining = sold_items['total_sold'] - sold_items['effective_sold'] sold_items['remaining'] = { 'value': remaining, 'color': 'red' if remaining < 0 else 'black', } return sold_items def _fetch_sale_order_item_ids(self, domain_per_model=None, limit=None, offset=None): if not self or not self.filtered('allow_billable'): return [] return super()._fetch_sale_order_item_ids(domain_per_model, limit, offset) def _get_sale_order_items_query(self, domain_per_model=None): billable_project_domain = [('allow_billable', '=', True)] if domain_per_model is None: domain_per_model = { 'project.project': billable_project_domain, 'project.task': billable_project_domain, } else: domain_per_model['project.project'] = expression.AND([ domain_per_model.get('project.project', []), billable_project_domain, ]) domain_per_model['project.task'] = expression.AND([ domain_per_model.get('project.task', []), billable_project_domain, ]) return super()._get_sale_order_items_query(domain_per_model) def _get_profitability_items(self): if not self.user_has_groups('project.group_project_manager'): return {'data': []} data = [] if self.allow_billable: profitability = self._get_profitability_common() margin_color = False if not float_is_zero(profitability['margin'], precision_digits=0): margin_color = profitability['margin'] > 0 and 'green' or 'red' data += [{ 'name': _("Revenues"), 'value': format_amount(self.env, profitability['revenues'], self.company_id.currency_id) }, { 'name': _("Costs"), 'value': format_amount(self.env, profitability['costs'], self.company_id.currency_id) }, { 'name': _("Margin"), 'color': margin_color, 'value': format_amount(self.env, profitability['margin'], self.company_id.currency_id) }] return { 'action': self.allow_billable and self.allow_timesheets and "action_view_timesheet", 'allow_billable': self.allow_billable, 'data': data, } def _get_profitability_common(self): self.ensure_one() result = { 'costs': 0.0, 'margin': 0.0, 'revenues': 0.0 } profitability = self.env['project.profitability.report'].read_group( [('project_id', '=', self.id)], ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced', 'expense_amount_untaxed_to_invoice', 'expense_amount_untaxed_invoiced', 'other_revenues', 'expense_cost', 'timesheet_cost', 'margin'], ['project_id'], limit=1) if profitability: profitability = profitability[0] result.update({ 'costs': profitability['timesheet_cost'] + profitability['expense_cost'], 'margin': profitability['margin'], 'revenues': (profitability['amount_untaxed_invoiced'] + profitability['amount_untaxed_to_invoice'] + profitability['expense_amount_untaxed_invoiced'] + profitability['expense_amount_untaxed_to_invoice'] + profitability['other_revenues']), }) return result def _get_sale_order_stat_button(self): so_button = super()._get_sale_order_stat_button() so_button['show'] &= self.allow_billable return so_button def _get_stat_buttons(self): buttons = super(Project, self)._get_stat_buttons() if self.user_has_groups('hr_timesheet.group_hr_timesheet_approver'): buttons.append({ 'icon': 'clock-o', 'text': _lt('Billable Time'), 'number': '%s %%' % (self.billable_percentage), 'action_type': 'object', 'action': 'action_billable_time_button', 'additional_context': json.dumps({ 'active_id': self.id, 'default_project_id': self.id }), 'show': self.allow_timesheets and bool(self.analytic_account_id), 'sequence': 9, }) return buttons class ProjectTask(models.Model): _inherit = "project.task" def _get_default_partner_id(self, project, parent): res = super()._get_default_partner_id(project, parent) if not res and project: # project in sudo if the current user is a portal user. related_project = project if not self.user_has_groups('!base.group_user,base.group_portal') else project.sudo() if related_project.pricing_type == 'employee_rate': return related_project.sale_line_employee_ids.sale_line_id.order_partner_id[:1] return res sale_order_id = fields.Many2one(domain="['|', '|', ('partner_id', '=', partner_id), ('partner_id', 'child_of', commercial_partner_id), ('partner_id', 'parent_of', partner_id)]") so_analytic_account_id = fields.Many2one(related='sale_order_id.analytic_account_id', string='Sale Order Analytic Account') pricing_type = fields.Selection(related="project_id.pricing_type") is_project_map_empty = fields.Boolean("Is Project map empty", compute='_compute_is_project_map_empty') has_multi_sol = fields.Boolean(compute='_compute_has_multi_sol', compute_sudo=True) allow_billable = fields.Boolean(related="project_id.allow_billable") timesheet_product_id = fields.Many2one(related="project_id.timesheet_product_id") remaining_hours_so = fields.Float('Remaining Hours on SO', compute='_compute_remaining_hours_so', compute_sudo=True) remaining_hours_available = fields.Boolean(related="sale_line_id.remaining_hours_available") @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS | { 'allow_billable', 'remaining_hours_available', 'remaining_hours_so', } @api.depends('sale_line_id', 'timesheet_ids', 'timesheet_ids.unit_amount') def _compute_remaining_hours_so(self): # TODO This is not yet perfectly working as timesheet.so_line stick to its old value although changed # in the task From View. timesheets = self.timesheet_ids.filtered(lambda t: t.task_id.sale_line_id in (t.so_line, t._origin.so_line) and t.so_line.remaining_hours_available) mapped_remaining_hours = {task._origin.id: task.sale_line_id and task.sale_line_id.remaining_hours or 0.0 for task in self} uom_hour = self.env.ref('uom.product_uom_hour') for timesheet in timesheets: delta = 0 if timesheet._origin.so_line == timesheet.task_id.sale_line_id: delta += timesheet._origin.unit_amount if timesheet.so_line == timesheet.task_id.sale_line_id: delta -= timesheet.unit_amount if delta: mapped_remaining_hours[timesheet.task_id._origin.id] += timesheet.product_uom_id._compute_quantity(delta, uom_hour) for task in self: task.remaining_hours_so = mapped_remaining_hours[task._origin.id] @api.depends('so_analytic_account_id.active') def _compute_analytic_account_active(self): super()._compute_analytic_account_active() for task in self: task.analytic_account_active = task.analytic_account_active or task.so_analytic_account_id.active @api.depends('allow_billable') def _compute_sale_order_id(self): billable_tasks = self.filtered('allow_billable') super(ProjectTask, billable_tasks)._compute_sale_order_id() (self - billable_tasks).sale_order_id = False @api.depends('commercial_partner_id', 'sale_line_id.order_partner_id.commercial_partner_id', 'parent_id.sale_line_id', 'project_id.sale_line_id', 'allow_billable') def _compute_sale_line(self): billable_tasks = self.filtered('allow_billable') (self - billable_tasks).update({'sale_line_id': False}) super(ProjectTask, billable_tasks)._compute_sale_line() for task in billable_tasks.filtered(lambda t: not t.sale_line_id): task.sale_line_id = task._get_last_sol_of_customer() @api.depends('project_id.sale_line_employee_ids') def _compute_is_project_map_empty(self): for task in self: task.is_project_map_empty = not bool(task.sudo().project_id.sale_line_employee_ids) @api.depends('timesheet_ids') def _compute_has_multi_sol(self): for task in self: task.has_multi_sol = task.timesheet_ids and task.timesheet_ids.so_line != task.sale_line_id def _get_last_sol_of_customer(self): # Get the last SOL made for the customer in the current task where we need to compute self.ensure_one() if not self.commercial_partner_id or not self.allow_billable: return False domain = [('company_id', '=', self.company_id.id), ('is_service', '=', True), ('order_partner_id', 'child_of', self.commercial_partner_id.id), ('is_expense', '=', False), ('state', 'in', ['sale', 'done']), ('remaining_hours', '>', 0)] if self.project_id.pricing_type != 'task_rate' and self.project_sale_order_id and self.commercial_partner_id == self.project_id.partner_id.commercial_partner_id: domain.append(('order_id', '=?', self.project_sale_order_id.id)) return self.env['sale.order.line'].search(domain, limit=1) def _get_timesheet(self): # return not invoiced timesheet and timesheet without so_line or so_line linked to task timesheet_ids = super(ProjectTask, self)._get_timesheet() return timesheet_ids.filtered(lambda t: t._is_not_billed()) def _get_action_view_so_ids(self): return list(set((self.sale_order_id + self.timesheet_ids.so_line.order_id).ids)) class ProjectTaskRecurrence(models.Model): _inherit = 'project.task.recurrence' @api.model def _get_recurring_fields(self): return ['so_analytic_account_id'] + super(ProjectTaskRecurrence, self)._get_recurring_fields()
51.939502
29,190
9,133
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import UserError, ValidationError from odoo import api, fields, models, _ from odoo.osv import expression class AccountAnalyticLine(models.Model): _inherit = 'account.analytic.line' def _default_sale_line_domain(self): domain = super(AccountAnalyticLine, self)._default_sale_line_domain() return expression.OR([domain, [('qty_delivered_method', '=', 'timesheet')]]) timesheet_invoice_type = fields.Selection([ ('billable_time', 'Billed on Timesheets'), ('billable_fixed', 'Billed at a Fixed price'), ('non_billable', 'Non Billable Tasks'), ('timesheet_revenues', 'Timesheet Revenues'), ('service_revenues', 'Service Revenues'), ('other_revenues', 'Other Revenues'), ('other_costs', 'Other Costs')], string="Billable Type", compute='_compute_timesheet_invoice_type', compute_sudo=True, store=True, readonly=True) commercial_partner_id = fields.Many2one('res.partner', compute="_compute_commercial_partner") timesheet_invoice_id = fields.Many2one('account.move', string="Invoice", readonly=True, copy=False, help="Invoice created from the timesheet") so_line = fields.Many2one(compute="_compute_so_line", store=True, readonly=False, domain="[('is_service', '=', True), ('is_expense', '=', False), ('state', 'in', ['sale', 'done']), ('order_partner_id', 'child_of', commercial_partner_id)]") # we needed to store it only in order to be able to groupby in the portal order_id = fields.Many2one(related='so_line.order_id', store=True, readonly=True) is_so_line_edited = fields.Boolean("Is Sales Order Item Manually Edited") @api.depends('project_id.commercial_partner_id', 'task_id.commercial_partner_id') def _compute_commercial_partner(self): for timesheet in self: timesheet.commercial_partner_id = timesheet.task_id.commercial_partner_id or timesheet.project_id.commercial_partner_id # When user edit Sale Order Item(so_line) for timesheet make is_so_line_edited field true @api.onchange('so_line') def _onchange_so_line(self): # TODO: [XBO] remove me in master return @api.depends('so_line.product_id', 'project_id', 'amount') def _compute_timesheet_invoice_type(self): for timesheet in self: if timesheet.project_id: # AAL will be set to False invoice_type = 'non_billable' if not timesheet.so_line else False if timesheet.so_line and timesheet.so_line.product_id.type == 'service': if timesheet.so_line.product_id.invoice_policy == 'delivery': if timesheet.so_line.product_id.service_type == 'timesheet': invoice_type = 'timesheet_revenues' if timesheet.amount > 0 else 'billable_time' else: invoice_type = 'billable_fixed' elif timesheet.so_line.product_id.invoice_policy == 'order': invoice_type = 'billable_fixed' timesheet.timesheet_invoice_type = invoice_type else: if timesheet.so_line and timesheet.so_line.product_id.type == 'service': timesheet.timesheet_invoice_type = 'service_revenues' else: timesheet.timesheet_invoice_type = 'other_revenues' if timesheet.amount >= 0 else 'other_costs' @api.depends('task_id.sale_line_id', 'project_id.sale_line_id', 'employee_id', 'project_id.allow_billable') def _compute_so_line(self): for timesheet in self.filtered(lambda t: not t.is_so_line_edited and t._is_not_billed()): # Get only the timesheets are not yet invoiced timesheet.so_line = timesheet.project_id.allow_billable and timesheet._timesheet_determine_sale_line() @api.depends('timesheet_invoice_id.state') def _compute_partner_id(self): super(AccountAnalyticLine, self.filtered(lambda t: t._is_not_billed()))._compute_partner_id() @api.depends('timesheet_invoice_id.state') def _compute_project_id(self): super(AccountAnalyticLine, self.filtered(lambda t: t._is_not_billed()))._compute_project_id() def _is_not_billed(self): self.ensure_one() return not self.timesheet_invoice_id or self.timesheet_invoice_id.state == 'cancel' def _check_timesheet_can_be_billed(self): return self.so_line in self.project_id.mapped('sale_line_employee_ids.sale_line_id') | self.task_id.sale_line_id | self.project_id.sale_line_id def write(self, values): # prevent to update invoiced timesheets if one line is of type delivery self._check_can_write(values) result = super(AccountAnalyticLine, self).write(values) return result def _check_can_write(self, values): if self.sudo().filtered(lambda aal: aal.so_line.product_id.invoice_policy == "delivery") and self.filtered(lambda t: t.timesheet_invoice_id and t.timesheet_invoice_id.state != 'cancel'): if any(field_name in values for field_name in ['unit_amount', 'employee_id', 'project_id', 'task_id', 'so_line', 'amount', 'date']): raise UserError(_('You cannot modify timesheets that are already invoiced.')) @api.model def _timesheet_preprocess(self, values): # TODO: remove me in master return super()._timesheet_preprocess(values) def _timesheet_determine_sale_line(self): """ Deduce the SO line associated to the timesheet line: 1/ timesheet on task rate: the so line will be the one from the task 2/ timesheet on employee rate task: find the SO line in the map of the project (even for subtask), or fallback on the SO line of the task, or fallback on the one on the project """ self.ensure_one() if not self.task_id: if self.project_id.pricing_type == 'employee_rate': map_entry = self._get_employee_mapping_entry() if map_entry: return map_entry.sale_line_id if self.project_id.sale_line_id: return self.project_id.sale_line_id if self.task_id.allow_billable and self.task_id.sale_line_id: if self.task_id.pricing_type in ('task_rate', 'fixed_rate'): return self.task_id.sale_line_id else: # then pricing_type = 'employee_rate' map_entry = self.project_id.sale_line_employee_ids.filtered( lambda map_entry: map_entry.employee_id == self.employee_id and map_entry.sale_line_id.order_partner_id.commercial_partner_id == self.task_id.commercial_partner_id ) if map_entry: return map_entry.sale_line_id return self.task_id.sale_line_id return False def _timesheet_get_portal_domain(self): """ Only the timesheets with a product invoiced on delivered quantity are concerned. since in ordered quantity, the timesheet quantity is not invoiced, thus there is no meaning of showing invoice with ordered quantity. """ domain = super(AccountAnalyticLine, self)._timesheet_get_portal_domain() return expression.AND([domain, [('timesheet_invoice_type', 'in', ['billable_time', 'non_billable', 'billable_fixed'])]]) @api.model def _timesheet_get_sale_domain(self, order_lines_ids, invoice_ids): if not invoice_ids: return [('so_line', 'in', order_lines_ids.ids)] return [ '|', '&', ('timesheet_invoice_id', 'in', invoice_ids.ids), # TODO : Master: Check if non_billable should be removed ? ('timesheet_invoice_type', 'in', ['billable_time', 'non_billable']), '&', ('timesheet_invoice_type', '=', 'billable_fixed'), ('so_line', 'in', order_lines_ids.ids) ] def _get_timesheets_to_merge(self): res = super(AccountAnalyticLine, self)._get_timesheets_to_merge() return res.filtered(lambda l: not l.timesheet_invoice_id or l.timesheet_invoice_id.state != 'posted') @api.ondelete(at_uninstall=False) def _unlink_except_invoiced(self): if any(line.timesheet_invoice_id and line.timesheet_invoice_id.state == 'posted' for line in self): raise UserError(_('You cannot remove a timesheet that has already been invoiced.')) def _get_employee_mapping_entry(self): self.ensure_one() return self.env['project.sale.line.employee.map'].search([('project_id', '=', self.project_id.id), ('employee_id', '=', self.employee_id.id)]) def _employee_timesheet_cost(self): if self.project_id.pricing_type == 'employee_rate': mapping_entry = self._get_employee_mapping_entry() if mapping_entry: return mapping_entry.cost return super()._employee_timesheet_cost()
53.409357
9,133
30,341
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 ProfitabilityAnalysis(models.Model): _name = "project.profitability.report" _description = "Project Profitability Report" _order = 'project_id, sale_line_id' _auto = False analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', readonly=True) project_id = fields.Many2one('project.project', string='Project', readonly=True) task_id = fields.Many2one('project.task', string='Task', readonly=True) currency_id = fields.Many2one('res.currency', string='Project Currency', readonly=True) company_id = fields.Many2one('res.company', string='Project Company', readonly=True) user_id = fields.Many2one('res.users', string='Project Manager', readonly=True) partner_id = fields.Many2one('res.partner', string='Customer', readonly=True) line_date = fields.Date("Date", readonly=True) # cost timesheet_unit_amount = fields.Float("Timesheet Duration", digits=(16, 2), readonly=True, group_operator="sum") timesheet_cost = fields.Float("Timesheet Cost", digits=(16, 2), readonly=True, group_operator="sum") expense_cost = fields.Float("Other Costs", digits=(16, 2), readonly=True, group_operator="sum") # sale revenue order_confirmation_date = fields.Datetime('Sales Order Confirmation Date', readonly=True) sale_line_id = fields.Many2one('sale.order.line', string='Sale Order Line', readonly=True) sale_order_id = fields.Many2one('sale.order', string='Sale Order', readonly=True) product_id = fields.Many2one('product.product', string='Product', readonly=True) amount_untaxed_to_invoice = fields.Float("Amount to Invoice", digits=(16, 2), readonly=True, group_operator="sum") amount_untaxed_invoiced = fields.Float("Amount Invoiced", digits=(16, 2), readonly=True, group_operator="sum") expense_amount_untaxed_to_invoice = fields.Float("Amount to Re-invoice", digits=(16, 2), readonly=True, group_operator="sum") expense_amount_untaxed_invoiced = fields.Float("Amount Re-invoiced", digits=(16, 2), readonly=True, group_operator="sum") other_revenues = fields.Float("Other Revenues", digits=(16, 2), readonly=True, group_operator="sum", help="All revenues that are not from timesheets and that are linked to the analytic account of the project.") margin = fields.Float("Margin", digits=(16, 2), readonly=True, group_operator="sum") _depends = { 'sale.order.line': [ 'order_id', 'invoice_status', 'price_reduce', 'product_id', 'qty_invoiced', 'untaxed_amount_invoiced', 'untaxed_amount_to_invoice', 'currency_id', 'company_id', 'is_downpayment', 'project_id', 'task_id', 'qty_delivered_method', ], 'sale.order': [ 'date_order', 'user_id', 'partner_id', 'currency_id', 'analytic_account_id', 'order_line', 'invoice_status', 'amount_untaxed', 'currency_rate', 'company_id', 'project_id', ], } def init(self): tools.drop_view_if_exists(self._cr, self._table) query = """ CREATE VIEW %s AS ( SELECT sub.id as id, sub.project_id as project_id, sub.task_id as task_id, sub.user_id as user_id, sub.sale_line_id as sale_line_id, sub.analytic_account_id as analytic_account_id, sub.partner_id as partner_id, sub.company_id as company_id, sub.currency_id as currency_id, sub.sale_order_id as sale_order_id, sub.order_confirmation_date as order_confirmation_date, sub.product_id as product_id, sub.sale_qty_delivered_method as sale_qty_delivered_method, sub.expense_amount_untaxed_to_invoice as expense_amount_untaxed_to_invoice, sub.expense_amount_untaxed_invoiced as expense_amount_untaxed_invoiced, sub.amount_untaxed_to_invoice as amount_untaxed_to_invoice, sub.amount_untaxed_invoiced as amount_untaxed_invoiced, sub.timesheet_unit_amount as timesheet_unit_amount, sub.timesheet_cost as timesheet_cost, sub.expense_cost as expense_cost, sub.other_revenues as other_revenues, sub.line_date as line_date, (sub.expense_amount_untaxed_to_invoice + sub.expense_amount_untaxed_invoiced + sub.amount_untaxed_to_invoice + sub.amount_untaxed_invoiced + sub.other_revenues + sub.timesheet_cost + sub.expense_cost) as margin FROM ( SELECT ROW_NUMBER() OVER (ORDER BY P.id, SOL.id) AS id, P.id AS project_id, P.user_id AS user_id, SOL.id AS sale_line_id, SOL.task_id AS task_id, P.analytic_account_id AS analytic_account_id, P.partner_id AS partner_id, C.id AS company_id, C.currency_id AS currency_id, S.id AS sale_order_id, S.date_order AS order_confirmation_date, SOL.product_id AS product_id, SOL.qty_delivered_method AS sale_qty_delivered_method, COST_SUMMARY.expense_amount_untaxed_to_invoice AS expense_amount_untaxed_to_invoice, COST_SUMMARY.expense_amount_untaxed_invoiced AS expense_amount_untaxed_invoiced, COST_SUMMARY.amount_untaxed_to_invoice AS amount_untaxed_to_invoice, COST_SUMMARY.amount_untaxed_invoiced AS amount_untaxed_invoiced, COST_SUMMARY.timesheet_unit_amount AS timesheet_unit_amount, COST_SUMMARY.timesheet_cost AS timesheet_cost, COST_SUMMARY.expense_cost AS expense_cost, COST_SUMMARY.other_revenues AS other_revenues, COST_SUMMARY.line_date::date AS line_date FROM project_project P JOIN res_company C ON C.id = P.company_id LEFT JOIN ( -- Each costs and revenues will be retrieved individually by sub-requests -- This is required to able to get the date SELECT project_id, analytic_account_id, sale_line_id, SUM(timesheet_unit_amount) AS timesheet_unit_amount, SUM(timesheet_cost) AS timesheet_cost, SUM(expense_cost) AS expense_cost, SUM(other_revenues) AS other_revenues, SUM(expense_amount_untaxed_to_invoice) AS expense_amount_untaxed_to_invoice, SUM(expense_amount_untaxed_invoiced) AS expense_amount_untaxed_invoiced, SUM(amount_untaxed_to_invoice) AS amount_untaxed_to_invoice, SUM(amount_untaxed_invoiced) AS amount_untaxed_invoiced, line_date AS line_date FROM ( -- Get the timesheet costs SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, TS.so_line AS sale_line_id, TS.unit_amount AS timesheet_unit_amount, TS.amount AS timesheet_cost, 0.0 AS other_revenues, 0.0 AS expense_cost, 0.0 AS expense_amount_untaxed_to_invoice, 0.0 AS expense_amount_untaxed_invoiced, 0.0 AS amount_untaxed_to_invoice, 0.0 AS amount_untaxed_invoiced, TS.date AS line_date FROM account_analytic_line TS, project_project P WHERE TS.project_id IS NOT NULL AND P.id = TS.project_id AND P.active = 't' AND P.allow_timesheets = 't' UNION ALL -- Get the other revenues (products that are not services) SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, AAL.so_line AS sale_line_id, 0.0 AS timesheet_unit_amount, 0.0 AS timesheet_cost, AAL.amount + COALESCE(AAL_RINV.amount, 0) AS other_revenues, 0.0 AS expense_cost, 0.0 AS expense_amount_untaxed_to_invoice, 0.0 AS expense_amount_untaxed_invoiced, 0.0 AS amount_untaxed_to_invoice, 0.0 AS amount_untaxed_invoiced, AAL.date AS line_date FROM project_project P JOIN account_analytic_account AA ON P.analytic_account_id = AA.id JOIN account_analytic_line AAL ON AAL.account_id = AA.id LEFT JOIN sale_order_line_invoice_rel SOINV ON SOINV.invoice_line_id = AAL.move_id LEFT JOIN sale_order_line SOL ON SOINV.order_line_id = SOL.id LEFT JOIN account_move_line AML ON AAL.move_id = AML.id AND AML.parent_state = 'posted' AND AML.exclude_from_invoice_tab = 'f' -- Check if it's not a Credit Note for a Vendor Bill LEFT JOIN account_move RBILL ON RBILL.id = AML.move_id LEFT JOIN account_move_line BILLL ON BILLL.move_id = RBILL.reversed_entry_id AND BILLL.parent_state = 'posted' AND BILLL.exclude_from_invoice_tab = 'f' AND BILLL.product_id = AML.product_id -- Check if it's not an Invoice reversed by a Credit Note LEFT JOIN account_move RINV ON RINV.reversed_entry_id = AML.move_id LEFT JOIN account_move_line RINVL ON RINVL.move_id = RINV.id AND RINVL.parent_state = 'posted' AND RINVL.exclude_from_invoice_tab = 'f' AND RINVL.product_id = AML.product_id LEFT JOIN account_analytic_line AAL_RINV ON RINVL.id = AAL_RINV.move_id WHERE AAL.amount > 0.0 AND AAL.project_id IS NULL AND P.active = 't' AND P.allow_timesheets = 't' AND BILLL.id IS NULL AND (SOL.id IS NULL OR (SOL.is_expense IS NOT TRUE AND SOL.is_downpayment IS NOT TRUE AND SOL.is_service IS NOT TRUE)) UNION ALL -- Get the expense costs from account analytic line SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, AAL.so_line AS sale_line_id, 0.0 AS timesheet_unit_amount, 0.0 AS timesheet_cost, 0.0 AS other_revenues, AAL.amount + COALESCE(AML_RBILLL.amount, 0) AS expense_cost, 0.0 AS expense_amount_untaxed_to_invoice, 0.0 AS expense_amount_untaxed_invoiced, 0.0 AS amount_untaxed_to_invoice, 0.0 AS amount_untaxed_invoiced, AAL.date AS line_date FROM project_project P JOIN account_analytic_account AA ON P.analytic_account_id = AA.id JOIN account_analytic_line AAL ON AAL.account_id = AA.id LEFT JOIN account_move_line AML ON AAL.move_id = AML.id AND AML.parent_state = 'posted' AND AML.exclude_from_invoice_tab = 'f' -- Check if it's not a Credit Note for an Invoice LEFT JOIN account_move RINV ON RINV.id = AML.move_id LEFT JOIN account_move_line INVL ON INVL.move_id = RINV.reversed_entry_id AND INVL.parent_state = 'posted' AND INVL.exclude_from_invoice_tab = 'f' AND INVL.product_id = AML.product_id -- Check if it's not a Bill reversed by a Credit Note LEFT JOIN account_move RBILL ON RBILL.reversed_entry_id = AML.move_id LEFT JOIN account_move_line RBILLL ON RBILLL.move_id = RBILL.id AND RBILLL.parent_state = 'posted' AND RBILLL.exclude_from_invoice_tab = 'f' AND RBILLL.product_id = AML.product_id LEFT JOIN account_analytic_line AML_RBILLL ON RBILLL.id = AML_RBILLL.move_id -- Check if the AAL is not related to a consumed downpayment (when the SOL is fully invoiced - with downpayment discounted.) LEFT JOIN sale_order_line_invoice_rel SOINVDOWN ON SOINVDOWN.invoice_line_id = AML.id LEFT JOIN sale_order_line SOLDOWN on SOINVDOWN.order_line_id = SOLDOWN.id AND SOLDOWN.is_downpayment = 't' WHERE AAL.amount < 0.0 AND AAL.project_id IS NULL AND INVL.id IS NULL AND SOLDOWN.id IS NULL AND P.active = 't' AND P.allow_timesheets = 't' UNION ALL -- Get the following values: expense amount untaxed to invoice/invoiced, amount untaxed to invoice/invoiced -- These values have to be computed from all the records retrieved just above but grouped by project and sale order line SELECT AMOUNT_UNTAXED.project_id AS project_id, AMOUNT_UNTAXED.analytic_account_id AS analytic_account_id, AMOUNT_UNTAXED.sale_line_id AS sale_line_id, 0.0 AS timesheet_unit_amount, 0.0 AS timesheet_cost, 0.0 AS other_revenues, 0.0 AS expense_cost, CASE WHEN SOL.qty_delivered_method = 'analytic' THEN (SOL.untaxed_amount_to_invoice / CASE COALESCE(S.currency_rate, 0) WHEN 0 THEN 1.0 ELSE S.currency_rate END) ELSE 0.0 END AS expense_amount_untaxed_to_invoice, CASE WHEN SOL.qty_delivered_method = 'analytic' AND SOL.invoice_status = 'invoiced' THEN CASE WHEN T.expense_policy = 'sales_price' THEN (SOL.untaxed_amount_invoiced / CASE COALESCE(S.currency_rate, 0) WHEN 0 THEN 1.0 ELSE S.currency_rate END) ELSE -AMOUNT_UNTAXED.expense_cost END ELSE 0.0 END AS expense_amount_untaxed_invoiced, CASE WHEN SOL.qty_delivered_method IN ('timesheet', 'manual', 'stock_move') AND SOL.is_service IS TRUE THEN (SOL.untaxed_amount_to_invoice / CASE COALESCE(S.currency_rate, 0) WHEN 0 THEN 1.0 ELSE S.currency_rate END) ELSE 0.0 END AS amount_untaxed_to_invoice, CASE WHEN SOL.qty_delivered_method IN ('timesheet', 'manual', 'stock_move') AND SOL.is_service IS TRUE THEN (SOL.untaxed_amount_invoiced / CASE COALESCE(S.currency_rate, 0) WHEN 0 THEN 1.0 ELSE S.currency_rate END) ELSE 0.0 END AS amount_untaxed_invoiced, S.date_order AS line_date FROM project_project P JOIN res_company C ON C.id = P.company_id LEFT JOIN ( -- Gets SOL linked to timesheets SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, AAL.so_line AS sale_line_id, 0.0 AS expense_cost FROM account_analytic_line AAL, project_project P WHERE AAL.project_id IS NOT NULL AND P.id = AAL.project_id AND P.active = 't' GROUP BY P.id, AAL.so_line UNION -- Service SOL linked to a project task AND not yet timesheeted SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, SOL.id AS sale_line_id, 0.0 AS expense_cost FROM sale_order_line SOL JOIN project_task T ON T.sale_line_id = SOL.id JOIN project_project P ON T.project_id = P.id LEFT JOIN account_analytic_line AAL ON AAL.task_id = T.id WHERE SOL.is_service = 't' AND AAL.id IS NULL -- not timesheeted AND P.active = 't' AND P.allow_timesheets = 't' GROUP BY P.id, SOL.id UNION -- Service SOL linked to project AND not yet timesheeted SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, SOL.id AS sale_line_id, 0.0 AS expense_cost FROM sale_order_line SOL JOIN project_project P ON P.sale_line_id = SOL.id LEFT JOIN account_analytic_line AAL ON AAL.project_id = P.id LEFT JOIN project_task T ON T.sale_line_id = SOL.id WHERE SOL.is_service = 't' AND AAL.id IS NULL -- not timesheeted AND (T.id IS NULL OR T.project_id != P.id) -- not linked to a task in this project AND P.active = 't' AND P.allow_timesheets = 't' GROUP BY P.id, SOL.id UNION -- Service SOL linked to analytic account AND not yet timesheeted SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, SOL.id AS sale_line_id, 0.0 AS expense_cost FROM sale_order_line SOL JOIN sale_order SO ON SO.id = SOL.order_id JOIN account_analytic_account AA ON AA.id = SO.analytic_account_id JOIN project_project P ON P.analytic_account_id = AA.id LEFT JOIN project_project PSOL ON PSOL.sale_line_id = SOL.id LEFT JOIN project_task TSOL ON TSOL.sale_line_id = SOL.id LEFT JOIN account_analytic_line AAL ON AAL.so_line = SOL.id WHERE SOL.is_service = 't' AND AAL.id IS NULL -- not timesheeted AND TSOL.id IS NULL -- not linked to a task AND PSOL.id IS NULL -- not linked to a project AND P.active = 't' AND P.allow_timesheets = 't' GROUP BY P.id, SOL.id UNION SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, AAL.so_line AS sale_line_id, 0.0 AS expense_cost FROM project_project P LEFT JOIN account_analytic_account AA ON P.analytic_account_id = AA.id LEFT JOIN account_analytic_line AAL ON AAL.account_id = AA.id WHERE AAL.amount > 0.0 AND AAL.project_id IS NULL AND P.active = 't' AND P.allow_timesheets = 't' GROUP BY P.id, AA.id, AAL.so_line UNION SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, AAL.so_line AS sale_line_id, SUM(AAL.amount) AS expense_cost FROM project_project P LEFT JOIN account_analytic_account AA ON P.analytic_account_id = AA.id LEFT JOIN account_analytic_line AAL ON AAL.account_id = AA.id WHERE AAL.amount < 0.0 AND AAL.project_id IS NULL AND P.active = 't' AND P.allow_timesheets = 't' GROUP BY P.id, AA.id, AAL.so_line UNION SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, SOLDOWN.id AS sale_line_id, 0.0 AS expense_cost FROM project_project P LEFT JOIN sale_order_line SOL ON P.sale_line_id = SOL.id LEFT JOIN sale_order SO ON SO.id = SOL.order_id OR SO.analytic_account_id = P.analytic_account_id LEFT JOIN sale_order_line SOLDOWN ON SOLDOWN.order_id = SO.id AND SOLDOWN.is_downpayment = 't' LEFT JOIN sale_order_line_invoice_rel SOINV ON SOINV.order_line_id = SOLDOWN.id LEFT JOIN account_move_line INVL ON SOINV.invoice_line_id = INVL.id AND INVL.parent_state = 'posted' AND INVL.exclude_from_invoice_tab = 'f' LEFT JOIN account_move RINV ON INVL.move_id = RINV.reversed_entry_id LEFT JOIN account_move_line RINVL ON RINV.id = RINVL.move_id AND RINVL.parent_state = 'posted' AND RINVL.exclude_from_invoice_tab = 'f' AND RINVL.product_id = SOLDOWN.product_id LEFT JOIN account_analytic_line ANLI ON ANLI.move_id = RINVL.id AND ANLI.amount < 0.0 WHERE ANLI.id IS NULL -- there are no credit note for this downpayment AND P.active = 't' AND P.allow_timesheets = 't' GROUP BY P.id, SOLDOWN.id UNION SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, SOL.id AS sale_line_id, 0.0 AS expense_cost FROM sale_order_line SOL INNER JOIN project_project P ON SOL.project_id = P.id WHERE P.active = 't' AND P.allow_timesheets = 't' UNION SELECT P.id AS project_id, P.analytic_account_id AS analytic_account_id, SOL.id AS sale_line_id, 0.0 AS expense_cost FROM sale_order_line SOL INNER JOIN project_task T ON SOL.task_id = T.id INNER JOIN project_project P ON P.id = T.project_id WHERE P.active = 't' AND P.allow_timesheets = 't' ) AMOUNT_UNTAXED ON AMOUNT_UNTAXED.project_id = P.id LEFT JOIN sale_order_line SOL ON AMOUNT_UNTAXED.sale_line_id = SOL.id LEFT JOIN sale_order S ON SOL.order_id = S.id LEFT JOIN product_product PP on (SOL.product_id = PP.id) LEFT JOIN product_template T on (PP.product_tmpl_id = T.id) WHERE P.active = 't' AND P.analytic_account_id IS NOT NULL ) SUB_COST_SUMMARY GROUP BY project_id, analytic_account_id, sale_line_id, line_date ) COST_SUMMARY ON COST_SUMMARY.project_id = P.id LEFT JOIN sale_order_line SOL ON COST_SUMMARY.sale_line_id = SOL.id LEFT JOIN sale_order S ON SOL.order_id = S.id WHERE P.active = 't' AND P.analytic_account_id IS NOT NULL ) AS sub ) """ % self._table self._cr.execute(query)
71.390588
30,341
4,370
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.exceptions import AccessError, MissingError from odoo.http import request from odoo.osv import expression from odoo.addons.account.controllers import portal from odoo.addons.hr_timesheet.controllers.portal import TimesheetCustomerPortal class PortalAccount(portal.PortalAccount): def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): values = super(PortalAccount, self)._invoice_get_page_view_values(invoice, access_token, **kwargs) domain = request.env['account.analytic.line']._timesheet_get_portal_domain() domain = expression.AND([ domain, request.env['account.analytic.line']._timesheet_get_sale_domain( invoice.mapped('line_ids.sale_line_ids'), request.env['account.move'].browse([invoice.id]) ) ]) values['timesheets'] = request.env['account.analytic.line'].sudo().search(domain) values['is_uom_day'] = request.env['account.analytic.line'].sudo()._is_timesheet_encode_uom_day() return values class SaleTimesheetCustomerPortal(TimesheetCustomerPortal): def _get_searchbar_inputs(self): searchbar_inputs = super()._get_searchbar_inputs() searchbar_inputs.update( so={'input': 'so', 'label': _('Search in Sales Order')}, sol={'input': 'sol', 'label': _('Search in Sales Order Item')}, invoice={'input': 'invoice', 'label': _('Search in Invoice')}) return searchbar_inputs def _get_searchbar_groupby(self): searchbar_groupby = super()._get_searchbar_groupby() searchbar_groupby.update( so={'input': 'so', 'label': _('Sales Order')}, sol={'input': 'sol', 'label': _('Sales Order Item')}, invoice={'input': 'invoice', 'label': _('Invoice')}) return searchbar_groupby def _get_search_domain(self, search_in, search): search_domain = super()._get_search_domain(search_in, search) if search_in in ('sol', 'all'): search_domain = expression.OR([search_domain, [('so_line', 'ilike', search)]]) if search_in in ('so', 'all'): search_domain = expression.OR([search_domain, [('so_line.order_id.name', 'ilike', search)]]) if search_in in ('invoice', 'all'): invoices = request.env['account.move'].sudo().search([('name', 'ilike', search)]) domain = request.env['account.analytic.line']._timesheet_get_sale_domain(invoices.mapped('invoice_line_ids.sale_line_ids'), invoices) search_domain = expression.OR([search_domain, domain]) return search_domain def _get_groupby_mapping(self): groupby_mapping = super()._get_groupby_mapping() groupby_mapping.update( sol='so_line', so='order_id', invoice='timesheet_invoice_id') return groupby_mapping def _get_searchbar_sortings(self): searchbar_sortings = super()._get_searchbar_sortings() searchbar_sortings.update( sol={'label': _('Sales Order Item'), 'order': 'so_line'}) return searchbar_sortings def _task_get_page_view_values(self, task, access_token, **kwargs): values = super()._task_get_page_view_values(task, access_token, **kwargs) values['so_accessible'] = False try: if task.sale_order_id and self._document_check_access('sale.order', task.sale_order_id.id): values['so_accessible'] = True except (AccessError, MissingError): pass values['invoices_accessible'] = [] for invoice in task.sale_order_id.invoice_ids: try: if self._document_check_access('account.move', invoice.id): values['invoices_accessible'].append(invoice.id) except (AccessError, MissingError): pass return values @http.route(['/my/timesheets', '/my/timesheets/page/<int:page>'], type='http', auth="user", website=True) def portal_my_timesheets(self, page=1, sortby=None, filterby=None, search=None, search_in='all', groupby='sol', **kw): return super().portal_my_timesheets(page, sortby, filterby, search, search_in, groupby, **kw)
46.989247
4,370
595
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Track Speakers SMS Marketing', 'category': 'Hidden', 'version': '1.0', 'description': """ SMS Marketing on event track speakers ===================================== Bridge module adding UX requirements to ease SMS marketing on event track speakers.. """, 'depends': [ 'mass_mailing', 'mass_mailing_sms', 'sms', 'website_event_track' ], 'data': [ ], 'auto_install': True, 'license': 'LGPL-3', }
22.884615
595
522
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_track_speakers(self): # Minimal override: set form view being the one mixing sms and mail (not prioritized one) action = super(Event, self).action_mass_mailing_track_speakers() action['view_id'] = self.env.ref('mass_mailing_sms.mailing_mailing_view_form_mixed').id return action
37.285714
522