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
11,173
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.exceptions import ValidationError from odoo.tests import common class TestBarcodeNomenclature(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Creates an empty nomenclature (rules will be added in the tests). cls.nomenclature = cls.env['barcode.nomenclature'].create({ 'name': 'Barcode Nomenclature Test', }) def test_barcode_nomenclature_parse_barcode_ean8_01(self): """ Parses some barcodes with a simple EAN-8 barcode rule and checks the result. """ self.env['barcode.rule'].create({ 'name': 'Rule Test #1', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean8', 'pattern': '........', }) # Must fail because too short. res = self.nomenclature.parse_barcode('0002') self.assertEqual(res['code'], '0002') self.assertEqual(res['type'], 'error', "Must fail because the barcode is too short") self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '0002') self.assertEqual(res['value'], 0) # Must fail because wrong checksum (last digit). res = self.nomenclature.parse_barcode('12345678') self.assertEqual(res['code'], '12345678') self.assertEqual(res['type'], 'error', "Must fail because the checksum digit is wrong") self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '12345678') self.assertEqual(res['value'], 0) # Must pass (right number of digits, right checksum). res = self.nomenclature.parse_barcode('12345670') self.assertEqual(res['code'], '12345670') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean8') self.assertEqual(res['base_code'], '12345670') self.assertEqual(res['value'], 0, "No value must be located into the barcode") # Must pass (right number of digits, right checksum). res = self.nomenclature.parse_barcode('02003405') self.assertEqual(res['code'], '02003405') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean8') self.assertEqual(res['base_code'], '02003405') self.assertEqual(res['value'], 0, "No value must be located into the barcode") def test_barcode_nomenclature_parse_barcode_ean8_02_validation_error(self): """ Try to parse a barcode with a wrong barcode rule. """ barcode_rule = self.env['barcode.rule'].create({ 'name': 'Rule Test #1', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean8', }) with self.assertRaises(ValidationError), self.cr.savepoint(): # Must fail because empty braces. barcode_rule.pattern = '......{}..' with self.assertRaises(ValidationError), self.cr.savepoint(): # Must fail because decimal can't be before integer. barcode_rule.pattern = '......{DN}' with self.assertRaises(ValidationError), self.cr.savepoint(): # Must fail because a pattern can't have multiple braces group. barcode_rule.pattern = '....{NN}{DD}' with self.assertRaises(ValidationError), self.cr.savepoint(): # Must fail because '*' isn't accepted (should be '.*' instead). barcode_rule.pattern = '*' def test_barcode_nomenclature_parse_barcode_ean8_03_value(self): """ Parses some barcodes with a EAN-8 barcode rule who convert the barcode into value and checks the result. """ self.env['barcode.rule'].create({ 'name': 'Rule Test #2', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean8', 'pattern': '{NNNNNNNN}', }) res = self.nomenclature.parse_barcode('0002') self.assertEqual(res['code'], '0002') self.assertEqual(res['type'], 'error', "Must fail because the barcode is too short") self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '0002') self.assertEqual(res['value'], 0) res = self.nomenclature.parse_barcode('12345678') self.assertEqual(res['code'], '12345678') self.assertEqual(res['type'], 'error', "Must fail because the checksum digit is wrong") self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '12345678') self.assertEqual(res['value'], 0) # Must pass (right number of digits, right checksum). res = self.nomenclature.parse_barcode('12345670') self.assertEqual(res['code'], '12345670') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean8') self.assertEqual(res['base_code'], '00000000', "All the barcode should be consumed into the value") self.assertEqual(res['value'], 12345670.0, "The barcode must be converted into value") # Must pass (right number of digits, right checksum). res = self.nomenclature.parse_barcode('02003405') self.assertEqual(res['code'], '02003405') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean8') self.assertEqual(res['base_code'], '00000000', "All the barcode should be consumed into the value") self.assertEqual(res['value'], 2003405.0, "The barcode must be converted into value") def test_barcode_nomenclature_parse_barcode_ean8_04_multiple_rules(self): """ Parses some barcodes with a nomenclature containing multiple EAN-8 barcode rule and checks the right one is took depending of the pattern. """ self.env['barcode.rule'].create({ 'name': 'Rule Test #1', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean8', 'pattern': '11.....{N}', }) self.env['barcode.rule'].create({ 'name': 'Rule Test #1', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean8', 'pattern': '66{NN}....', }) # Only fits the second barcode rule. res = self.nomenclature.parse_barcode('11012344') self.assertEqual(res['code'], '11012344') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean8') self.assertEqual(res['base_code'], '11012340') self.assertEqual(res['value'], 4) # Only fits the second barcode rule. res = self.nomenclature.parse_barcode('66012344') self.assertEqual(res['code'], '66012344') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean8') self.assertEqual(res['base_code'], '66002344') self.assertEqual(res['value'], 1) # Doesn't fit any barcode rule. res = self.nomenclature.parse_barcode('16012344') self.assertEqual(res['code'], '16012344') self.assertEqual(res['type'], 'error') self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '16012344') self.assertEqual(res['value'], 0) def test_barcode_nomenclature_parse_barcode_ean13_01(self): """ Parses some barcodes with a EAN-13 barcode rule who contains a value and checks the result. """ self.env['barcode.rule'].create({ 'name': 'Rule Test #3', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean13', 'pattern': '1........{NND}.', }) # Must fail because too short. res = self.nomenclature.parse_barcode('0002') self.assertEqual(res['code'], '0002') self.assertEqual(res['type'], 'error', "Must fail because the barcode is too short") self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '0002') self.assertEqual(res['value'], 0) # Must fail because wrong checksum (last digit). res = self.nomenclature.parse_barcode('12345678') self.assertEqual(res['code'], '12345678') self.assertEqual(res['type'], 'error', "Must fail because the checksum digit is wrong") self.assertEqual(res['encoding'], '') self.assertEqual(res['base_code'], '12345678') self.assertEqual(res['value'], 0) # Must pass (right number of digits, right checksum). res = self.nomenclature.parse_barcode('1020034051259') self.assertEqual(res['code'], '1020034051259') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean13') self.assertEqual(res['base_code'], '1020034050009') self.assertEqual(res['value'], 12.5, "Should taken only the value part (NND)") def test_barcode_nomenclature_parse_barcode_ean13_02_sequence(self): """ Parses some barcodes with a nomenclature containing two EAN-13 barcode rule and checks the good one is took depending of its sequence. """ first_created_rule = self.env['barcode.rule'].create({ 'name': 'Rule Test #1', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean13', 'pattern': '.....{NNNDDDD}.', 'sequence': 3, }) self.env['barcode.rule'].create({ 'name': 'Rule Test #2', 'barcode_nomenclature_id': self.nomenclature.id, 'encoding': 'ean13', 'pattern': '22......{NNDD}.', 'sequence': 2, }) # Invalids the cache to reset the nomenclature barcode rules' order. self.env['barcode.nomenclature'].invalidate_cache() # Only fits the second barcode rule. res = self.nomenclature.parse_barcode('2012345610255') self.assertEqual(res['code'], '2012345610255') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean13') self.assertEqual(res['base_code'], '2012300000008') self.assertEqual(res['value'], 456.1025) # Fits the two barcode rules, but should take the second one (lower sequence). res = self.nomenclature.parse_barcode('2212345610259') self.assertEqual(res['code'], '2212345610259') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean13') self.assertEqual(res['base_code'], '2212345600007') self.assertEqual(res['value'], 10.25) # Invalids the cache to reset the nomenclature barcode rules' order. first_created_rule.sequence = 1 self.env['barcode.nomenclature'].invalidate_cache() # Should take the first one now (lower sequence). res = self.nomenclature.parse_barcode('2212345610259') self.assertEqual(res['code'], '2212345610259') self.assertEqual(res['type'], 'product') self.assertEqual(res['encoding'], 'ean13') self.assertEqual(res['base_code'], '2212300000002') self.assertEqual(res['value'], 456.1025)
44.871486
11,173
1,045
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api class BarcodeEventsMixin(models.AbstractModel): """ Mixin class for objects reacting when a barcode is scanned in their form views which contains `<field name="_barcode_scanned" widget="barcode_handler"/>`. Models using this mixin must implement the method on_barcode_scanned. It works like an onchange and receives the scanned barcode in parameter. """ _name = 'barcodes.barcode_events_mixin' _description = 'Barcode Event Mixin' _barcode_scanned = fields.Char("Barcode Scanned", help="Value of the last barcode scanned.", store=False) @api.onchange('_barcode_scanned') def _on_barcode_scanned(self): barcode = self._barcode_scanned if barcode: self._barcode_scanned = "" return self.on_barcode_scanned(barcode) def on_barcode_scanned(self, barcode): raise NotImplementedError("In order to use barcodes.barcode_events_mixin, method on_barcode_scanned must be implemented")
41.8
1,045
513
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class IrHttp(models.AbstractModel): _inherit = 'ir.http' def session_info(self): res = super(IrHttp, self).session_info() if self.env.user.has_group('base.group_user'): res['max_time_between_keys_in_ms'] = int( self.env['ir.config_parameter'].sudo().get_param('barcode.max_time_between_keys_in_ms', default='100')) return res
34.2
513
6,348
py
PYTHON
15.0
import re from odoo import models, fields, api UPC_EAN_CONVERSIONS = [ ('none', 'Never'), ('ean2upc', 'EAN-13 to UPC-A'), ('upc2ean', 'UPC-A to EAN-13'), ('always', 'Always'), ] class BarcodeNomenclature(models.Model): _name = 'barcode.nomenclature' _description = 'Barcode Nomenclature' name = fields.Char(string='Barcode Nomenclature', size=32, required=True, help='An internal identification of the barcode nomenclature') rule_ids = fields.One2many('barcode.rule', 'barcode_nomenclature_id', string='Rules', help='The list of barcode rules') upc_ean_conv = fields.Selection( UPC_EAN_CONVERSIONS, string='UPC/EAN Conversion', required=True, default='always', help="UPC Codes can be converted to EAN by prefixing them with a zero. This setting determines if a UPC/EAN barcode should be automatically converted in one way or another when trying to match a rule with the other encoding.") @api.model def get_barcode_check_digit(self, numeric_barcode): # todo master: remove this method return self.env['ir.actions.report'].get_barcode_check_digit(numeric_barcode) @api.model def check_encoding(self, barcode, encoding): # todo master: remove this method return self.env['ir.actions.report'].check_barcode_encoding(barcode, encoding) @api.model def sanitize_ean(self, ean): """ Returns a valid zero padded EAN-13 from an EAN prefix. :type ean: str """ ean = ean[0:13].zfill(13) return ean[0:-1] + str(self.get_barcode_check_digit(ean)) @api.model def sanitize_upc(self, upc): """ Returns a valid zero padded UPC-A from a UPC-A prefix. :type upc: str """ return self.sanitize_ean('0' + upc)[1:] def match_pattern(self, barcode, pattern): """Checks barcode matches the pattern and retrieves the optional numeric value in barcode. :param barcode: :type barcode: str :param pattern: :type pattern: str :return: an object containing: - value: the numerical value encoded in the barcode (0 if no value encoded) - base_code: the barcode in which numerical content is replaced by 0's - match: boolean :rtype: dict """ match = { 'value': 0, 'base_code': barcode, 'match': False, } barcode = barcode.replace('\\', '\\\\').replace('{', '\\{').replace('}', '\\}').replace('.', '\\.') numerical_content = re.search("[{][N]*[D]*[}]", pattern) # look for numerical content in pattern if numerical_content: # the pattern encodes a numerical content num_start = numerical_content.start() # start index of numerical content num_end = numerical_content.end() # end index of numerical content value_string = barcode[num_start:num_end - 2] # numerical content in barcode whole_part_match = re.search("[{][N]*[D}]", numerical_content.group()) # looks for whole part of numerical content decimal_part_match = re.search("[{N][D]*[}]", numerical_content.group()) # looks for decimal part whole_part = value_string[:whole_part_match.end() - 2] # retrieve whole part of numerical content in barcode decimal_part = "0." + value_string[decimal_part_match.start():decimal_part_match.end() - 1] # retrieve decimal part if whole_part == '': whole_part = '0' match['value'] = int(whole_part) + float(decimal_part) match['base_code'] = barcode[:num_start] + (num_end - num_start - 2) * "0" + barcode[num_end - 2:] # replace numerical content by 0's in barcode match['base_code'] = match['base_code'].replace("\\\\", "\\").replace("\\{", "{").replace("\\}", "}").replace("\\.", ".") pattern = pattern[:num_start] + (num_end - num_start - 2) * "0" + pattern[num_end:] # replace numerical content by 0's in pattern to match match['match'] = re.match(pattern, match['base_code'][:len(pattern)]) return match def parse_barcode(self, barcode): """ Attempts to interpret and parse a barcode. :param barcode: :type barcode: str :return: A object containing various information about the barcode, like as: - code: the barcode - type: the barcode's type - value: if the id encodes a numerical value, it will be put there - base_code: the barcode code with all the encoding parts set to zero; the one put on the product in the backend :rtype: dict """ parsed_result = { 'encoding': '', 'type': 'error', 'code': barcode, 'base_code': barcode, 'value': 0, } for rule in self.rule_ids: cur_barcode = barcode if rule.encoding == 'ean13' and self.check_encoding(barcode, 'upca') and self.upc_ean_conv in ['upc2ean', 'always']: cur_barcode = '0' + cur_barcode elif rule.encoding == 'upca' and self.check_encoding(barcode, 'ean13') and barcode[0] == '0' and self.upc_ean_conv in ['ean2upc', 'always']: cur_barcode = cur_barcode[1:] if not self.check_encoding(barcode, rule.encoding): continue match = self.match_pattern(cur_barcode, rule.pattern) if match['match']: if rule.type == 'alias': barcode = rule.alias parsed_result['code'] = barcode else: parsed_result['encoding'] = rule.encoding parsed_result['type'] = rule.type parsed_result['value'] = match['value'] parsed_result['code'] = cur_barcode if rule.encoding == "ean13": parsed_result['base_code'] = self.sanitize_ean(match['base_code']) elif rule.encoding == "upca": parsed_result['base_code'] = self.sanitize_upc(match['base_code']) else: parsed_result['base_code'] = match['base_code'] return parsed_result return parsed_result
44.391608
6,348
409
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields class ResCompany(models.Model): _inherit = 'res.company' def _get_default_nomenclature(self): return self.env.ref('barcodes.default_barcode_nomenclature', raise_if_not_found=False) nomenclature_id = fields.Many2one( 'barcode.nomenclature', string="Nomenclature", default=_get_default_nomenclature, )
25.5625
409
2,411
py
PYTHON
15.0
import re from odoo import models, fields, api, _ from odoo.exceptions import ValidationError class BarcodeRule(models.Model): _name = 'barcode.rule' _description = 'Barcode Rule' _order = 'sequence asc, id' name = fields.Char(string='Rule Name', size=32, required=True, help='An internal identification for this barcode nomenclature rule') barcode_nomenclature_id = fields.Many2one('barcode.nomenclature', string='Barcode Nomenclature') sequence = fields.Integer(string='Sequence', help='Used to order rules such that rules with a smaller sequence match first') encoding = fields.Selection( string='Encoding', required=True, default='any', selection=[ ('any', 'Any'), ('ean13', 'EAN-13'), ('ean8', 'EAN-8'), ('upca', 'UPC-A'), ], help='This rule will apply only if the barcode is encoded with the specified encoding') type = fields.Selection( string='Type', required=True, selection=[ ('alias', 'Alias'), ('product', 'Unit Product'), ], default='product') pattern = fields.Char(string='Barcode Pattern', size=32, help="The barcode matching pattern", required=True, default='.*') alias = fields.Char(string='Alias', size=32, default='0', help='The matched pattern will alias to this barcode', required=True) @api.constrains('pattern') def _check_pattern(self): for rule in self: p = rule.pattern.replace('\\\\', 'X').replace('\\{', 'X').replace('\\}', 'X') findall = re.findall("[{]|[}]", p) # p does not contain escaped { or } if len(findall) == 2: if not re.search("[{][N]*[D]*[}]", p): raise ValidationError(_("There is a syntax error in the barcode pattern %(pattern)s: braces can only contain N's followed by D's.", pattern=rule.pattern)) elif re.search("[{][}]", p): raise ValidationError(_("There is a syntax error in the barcode pattern %(pattern)s: empty braces.", pattern=rule.pattern)) elif len(findall) != 0: raise ValidationError(_("There is a syntax error in the barcode pattern %(pattern)s: a rule can only contain one pair of braces.", pattern=rule.pattern)) elif p == '*': raise ValidationError(_(" '*' is not a valid Regex Barcode Pattern. Did you mean '.*' ?"))
56.069767
2,411
653
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2018-now jeffery9@gmail.com { 'name': 'China - City Data', 'version': '1.8', 'icon': '/l10n_cn/static/description/icon.png', 'category': 'Accounting/Localizations', 'author': 'Jeffery Chen Fan<jeffery9@gmail.com>', 'description': """ Includes the following data for the Chinese localization ======================================================== City Data/城市数据 """, 'depends': ['l10n_cn','base_address_city'], 'data': [ 'data/res_city_data.xml', ], 'license': 'LGPL-3', }
28.043478
645
1,236
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Event Meeting / Rooms', 'category': 'Marketing/Events', 'sequence': 1002, 'version': '1.0', 'summary': 'Event: meeting and chat rooms', 'website': 'https://www.odoo.com/app/events', 'description': "", 'depends': [ 'website_event', 'website_jitsi', ], 'demo': ['data/website_event_meet_demo.xml'], 'data': [ 'security/ir.model.access.csv', 'security/security.xml', 'views/event_meet_templates_list.xml', 'views/event_meet_templates_page.xml', 'views/event_meeting_room_views.xml', 'views/event_event_views.xml', 'views/event_type_views.xml', ], 'application': False, 'installable': True, 'assets': { 'web.assets_frontend': [ 'website_event_meet/static/src/scss/event_meet_templates.scss', 'website_event_meet/static/src/js/customize_options.js', 'website_event_meet/static/src/js/website_event_meeting_room.js', 'website_event_meet/static/src/js/website_event_create_meeting_room_button.js', ], }, 'license': 'LGPL-3', }
32.526316
1,236
3,475
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.event.tests.common import TestEventCommon from odoo.tests import Form class TestWebsiteEventMeet(TestEventCommon): def test_meeting_room_create(self): """Test that the field of the mixin are automatically filled.""" new_meeting_room_form = Form(self.env["event.meeting.room"]) new_meeting_room_form.name = "Test name" new_meeting_room_form.event_id = self.event_0 new_meeting_room_form.target_audience = "dev" new_meeting_room_form.room_max_capacity = "20" meeting_room = new_meeting_room_form.save() self.assertTrue(meeting_room.chat_room_id) self.assertEqual(meeting_room.chat_room_id.max_capacity, "20") # Try to create a meeting room without filling the related field # It must create the `chat.room` with the default value meeting_room = self.env["event.meeting.room"].create({ "name": "Test 2", "event_id": self.event_0.id, "target_audience": "dev" }) self.assertTrue(meeting_room.chat_room_id) self.assertTrue(meeting_room.chat_room_id.name) self.assertEqual(meeting_room.chat_room_id.max_capacity, "8") # Ensure default value for room_max_capacity in event.meeting.room self.assertEqual(meeting_room.room_max_capacity, "8") def test_meeting_room_copy(self): """Test the duplication of the meeting room.""" meeting_room_1 = self.env["event.meeting.room"].create({ "name": "Test meeting room", "event_id": self.event_0.id, "target_audience": "dev", "room_max_capacity": "20", }) self.assertEqual(meeting_room_1.room_name, 'odoo-room-test-meeting-room') meeting_room_2 = meeting_room_1.copy() self.assertEqual(meeting_room_2.room_name, 'odoo-room-test-meeting-room-1') chat_room_1 = meeting_room_1.chat_room_id chat_room_2 = meeting_room_2.chat_room_id self.assertTrue(chat_room_1) self.assertTrue(chat_room_2) self.assertNotEqual(chat_room_1.id, chat_room_2.id, "Must create a new chat room") self.assertNotEqual(chat_room_1.name, chat_room_2.name, "Must generate a new chat room name") self.assertEqual(chat_room_1.max_capacity, "20", "Must set the max capacity on the chat room") self.assertEqual(chat_room_2.max_capacity, "20", "Must copy the max capacity") meeting_room_3 = meeting_room_1.copy() self.assertEqual(meeting_room_3.room_name, 'odoo-room-test-meeting-room-2') # Ensure room_max_capacity is copied to new meeting room self.assertEqual(meeting_room_3.room_max_capacity, "20") # Ensure max_capacity in linked chat room is same self.assertEqual(meeting_room_3.chat_room_id.max_capacity, "20") def test_meeting_room_unlink(self): """Test the duplication of the meeting room.""" meeting_room = self.env["event.meeting.room"].create({ "name": "Test meeting room", "event_id": self.event_0.id, "target_audience": "dev", "room_max_capacity": "20", }) self.assertTrue(meeting_room.chat_room_id) chat_room_id = meeting_room.chat_room_id.id meeting_room.unlink() self.assertFalse(self.env["chat.room"].browse(chat_room_id).exists())
45.723684
3,475
605
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 EventType(models.Model): _inherit = "event.type" meeting_room_allow_creation = fields.Boolean( "Allow Room Creation", compute='_compute_meeting_room_allow_creation', readonly=False, store=True, help="Let Visitors Create Rooms") @api.depends('community_menu') def _compute_meeting_room_allow_creation(self): for event_type in self: event_type.meeting_room_allow_creation = event_type.community_menu
33.611111
605
2,414
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 Event(models.Model): _inherit = "event.event" meeting_room_ids = fields.One2many("event.meeting.room", "event_id", string="Meeting rooms") meeting_room_count = fields.Integer("Room count", compute="_compute_meeting_room_count") meeting_room_allow_creation = fields.Boolean( "Allow Room Creation", compute="_compute_meeting_room_allow_creation", readonly=False, store=True, help="Let Visitors Create Rooms") @api.depends("event_type_id", "website_menu", "community_menu") def _compute_community_menu(self): """ At type onchange: synchronize. At website_menu update: synchronize. """ for event in self: if event.event_type_id and event.event_type_id != event._origin.event_type_id: event.community_menu = event.event_type_id.community_menu elif event.website_menu and (event.website_menu != event._origin.website_menu or not event.community_menu): event.community_menu = True elif not event.website_menu: event.community_menu = False @api.depends("meeting_room_ids") def _compute_meeting_room_count(self): meeting_room_count = self.env["event.meeting.room"].sudo().read_group( domain=[("event_id", "in", self.ids)], fields=["id:count"], groupby=["event_id"], ) meeting_room_count = { result["event_id"][0]: result["event_id_count"] for result in meeting_room_count } for event in self: event.meeting_room_count = meeting_room_count.get(event.id, 0) @api.depends("event_type_id", "community_menu", "meeting_room_allow_creation") def _compute_meeting_room_allow_creation(self): for event in self: if event.event_type_id and event.event_type_id != event._origin.event_type_id: event.meeting_room_allow_creation = event.event_type_id.meeting_room_allow_creation elif event.community_menu and event.community_menu != event._origin.community_menu: event.meeting_room_allow_creation = True elif not event.community_menu or not event.meeting_room_allow_creation: event.meeting_room_allow_creation = False
46.423077
2,414
352
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 EventMenu(models.Model): _inherit = "website.event.menu" menu_type = fields.Selection( selection_add=[("meeting_room", "Event Meeting Room Menus")], ondelete={'meeting_room': 'cascade'})
29.333333
352
2,233
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo import api, fields, models from odoo.addons.http_routing.models.ir_http import slug class EventMeetingRoom(models.Model): _name = "event.meeting.room" _description = "Event Meeting Room" _order = "is_pinned DESC, id" _inherit = [ 'chat.room.mixin', 'website.published.mixin', ] _DELAY_CLEAN = datetime.timedelta(hours=4) name = fields.Char("Topic", required=True, translate=True) active = fields.Boolean('Active', default=True) is_published = fields.Boolean(copy=True) # make the inherited field copyable event_id = fields.Many2one("event.event", string="Event", required=True, ondelete="cascade") is_pinned = fields.Boolean("Is Pinned") chat_room_id = fields.Many2one("chat.room", required=True, ondelete="restrict") room_max_capacity = fields.Selection(default="8", copy=True) summary = fields.Char("Summary", translate=True) target_audience = fields.Char("Audience", translate=True) @api.depends('name', 'event_id.name') def _compute_website_url(self): super(EventMeetingRoom, self)._compute_website_url() for meeting_room in self: if meeting_room.id: base_url = meeting_room.event_id.get_base_url() meeting_room.website_url = '%s/event/%s/meeting_room/%s' % (base_url, slug(meeting_room.event_id), slug(meeting_room)) @api.model_create_multi def create(self, values_list): for values in values_list: if not values.get("chat_room_id") and not values.get('room_name'): values['room_name'] = 'odoo-room-%s' % (values['name']) return super(EventMeetingRoom, self).create(values_list) @api.autovacuum def _archive_meeting_rooms(self): """Archive all non-pinned room with 0 participant if nobody has joined it for a moment.""" self.sudo().search([ ("is_pinned", "=", False), ("active", "=", True), ("room_participant_count", "=", 0), ("room_last_activity", "<", fields.Datetime.now() - self._DELAY_CLEAN), ]).active = False
41.351852
2,233
6,855
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from werkzeug.exceptions import Forbidden, NotFound from odoo import exceptions, http from odoo.http import request from odoo.addons.http_routing.models.ir_http import slug from odoo.addons.website_event.controllers.community import EventCommunityController from odoo.osv import expression _logger = logging.getLogger(__name__) class WebsiteEventMeetController(EventCommunityController): def _get_event_rooms_base_domain(self, event): search_domain_base = [('event_id', '=', event.id)] if not request.env.user.has_group('event.group_event_registration_desk'): search_domain_base = expression.AND([search_domain_base, [('is_published', '=', True)]]) return search_domain_base def _sort_event_rooms(self, room): return (room.website_published, room.is_pinned, room.room_last_activity, room.id) # ------------------------------------------------------------ # MAIN PAGE # ------------------------------------------------------------ @http.route(["/event/<model('event.event'):event>/community"], type="http", auth="public", website=True, sitemap=True) def community(self, event, page=1, lang=None, **kwargs): """Display the meeting rooms of the event on the frontend side. :param event: event for which we display the meeting rooms :param lang: lang id used to perform a search """ return request.render( "website_event_meet.event_meet", self._event_meeting_rooms_get_values(event, lang=lang) ) def _event_meeting_rooms_get_values(self, event, lang=None): search_domain = self._get_event_rooms_base_domain(event) meeting_rooms_all = request.env['event.meeting.room'].sudo().search(search_domain) if lang: search_domain = expression.AND([ search_domain, [('room_lang_id', '=', int(lang))] ]) meeting_rooms = request.env['event.meeting.room'].sudo().search(search_domain) meeting_rooms = meeting_rooms.sorted(self._sort_event_rooms, reverse=True) is_event_user = request.env.user.has_group("event.group_event_registration_desk") if not is_event_user: meeting_rooms = meeting_rooms.filtered(lambda m: not m.room_is_full) visitor = request.env['website.visitor']._get_visitor_from_request() return { # event information "event": event, 'main_object': event, # rooms "meeting_rooms": meeting_rooms, "current_lang": request.env["res.lang"].browse(int(lang)) if lang else False, "available_languages": meeting_rooms_all.mapped("room_lang_id"), "default_lang_code": request.context.get('lang', request.env.user.lang), "default_username": visitor.display_name if visitor else None, # environment "is_event_user": is_event_user, } @http.route("/event/<model('event.event'):event>/meeting_room_create", type="http", auth="public", methods=["POST"], website=True) def create_meeting_room(self, event, **post): if not event or (not event.is_published and not request.env.user.user_has_groups('base.group_user')) or not event.meeting_room_allow_creation: raise Forbidden() name = post.get("name") summary = post.get("summary") target_audience = post.get("audience") lang_code = post.get("lang_code") max_capacity = post.get("capacity") # get the record to be sure they really exist lang = request.env["res.lang"].search([("code", "=", lang_code)], limit=1) if not lang or max_capacity == "no_limit": raise Forbidden() meeting_room = request.env["event.meeting.room"].sudo().create({ "name": name, "summary": summary, "target_audience": target_audience, "is_pinned": False, "event_id": event.id, "room_lang_id": lang.id, "room_max_capacity": max_capacity, "is_published": True, }) _logger.info("New meeting room (%s) created by %s (uid %s)" % (name, request.httprequest.remote_addr, request.env.uid)) return request.redirect(f"/event/{slug(event)}/meeting_room/{slug(meeting_room)}") @http.route(["/event/active_langs"], type="json", auth="public") def active_langs(self): return request.env["res.lang"].sudo().get_installed() # ------------------------------------------------------------ # ROOM PAGE VIEW # ------------------------------------------------------------ @http.route('''/event/<model('event.event', "[('community_menu', '=', True)]"):event>/meeting_room/<model("event.meeting.room","[('event_id','=',event.id)]"):meeting_room>''', type="http", auth="public", website=True, sitemap=True) def event_meeting_room_page(self, event, meeting_room, **post): """Display the meeting room frontend view. :param event: Event for which we display the meeting rooms :param meeting_room: Meeting Room to display """ if meeting_room not in event.sudo().meeting_room_ids: raise NotFound() try: meeting_room.check_access_rule('read') except exceptions.AccessError: raise Forbidden() meeting_room = meeting_room.sudo() return request.render( "website_event_meet.event_meet_main", self._event_meeting_room_page_get_values(event, meeting_room), ) def _event_meeting_room_page_get_values(self, event, meeting_room): # search for meeting room list. Set a limit to 6 because it is better than 5 or 7 meeting_rooms_other = request.env['event.meeting.room'].sudo().search([ ('event_id', '=', event.id), ('id', '!=', meeting_room.id), ('is_published', '=', True), ], limit=6) if not request.env.user.has_group("event.group_event_manager"): # only the event manager can see meeting rooms which are full meeting_rooms_other = meeting_rooms_other.filtered(lambda m: not m.room_is_full) meeting_rooms_other = meeting_rooms_other.sorted(self._sort_event_rooms, reverse=True) return { # event information 'event': event, 'main_object': meeting_room, 'meeting_room': meeting_room, # sidebar 'meeting_rooms_other': meeting_rooms_other, # options 'option_widescreen': True, 'is_event_user': request.env.user.has_group('event.group_event_registration_desk'), }
42.84375
6,855
1,069
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from babel.dates import format_datetime from odoo import _ from odoo.http import request from odoo.addons.website_event.controllers import main class WebsiteEventController(main.WebsiteEventController): def _prepare_event_register_values(self, event, **post): values = super(WebsiteEventController, self)._prepare_event_register_values(event, **post) if "from_room_id" in post and not event.is_ongoing: meeting_room = request.env["event.meeting.room"].browse(int(post["from_room_id"])).sudo().exists() if meeting_room and meeting_room.is_published: date_begin = format_datetime(event.with_context(tz=event.date_tz).date_begin, format="medium") values["toast_message"] = ( _('The event %s starts on %s (%s). \nJoin us there to chat about "%s" !') % (event.name, date_begin, event.date_tz, meeting_room.name) ) return values
42.76
1,069
555
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'France - Factur-X integration with Chorus Pro', 'version': '1.0', 'category': 'Accounting/Localizations/EDI', 'description': """ Add supports to fill three optional fields used when using Chorus Pro, especially when invoicing public services. """, 'depends': [ 'account', 'account_edi_facturx', 'l10n_fr' ], 'data': [ 'views/account_move_views.xml', ], 'license': 'LGPL-3', }
27.75
555
370
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" buyer_reference = fields.Char(help="'Service Exécutant' in Chorus PRO.") contract_reference = fields.Char(help="'Numéro de Marché' in Chorus PRO.") purchase_order_reference = fields.Char(help="'Engagement Juridique' in Chorus PRO.")
36.7
367
834
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Kenya Tremol Device EDI Integration", 'summary': """ Kenya Tremol Device EDI Integration """, 'description': """ This module integrates with the Kenyan G03 Tremol control unit device to the KRA through TIMS. """, 'author': 'Odoo', 'category': 'Accounting/Localizations/EDI', 'version': '1.0', 'license': 'LGPL-3', 'depends': ['l10n_ke'], 'data': [ 'views/account_move_view.xml', 'views/product_view.xml', 'views/report_invoice.xml', 'views/res_config_settings_view.xml', 'views/res_partner_views.xml', ], 'assets': { 'web.assets_backend': [ 'l10n_ke_edi_tremol/static/src/js/send_invoice.js', ], }, }
30.888889
834
9,125
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 odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged('post_install_l10n', 'post_install', '-at_install') class TestKeMoveExport(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref='l10n_ke.l10nke_chart_template'): super().setUpClass(chart_template_ref=chart_template_ref) cls.partner_a.write({ 'name': 'Sirius Cybernetics Corporation', 'street': 'Test Street', 'street2': 'Further Test Street', 'city': 'Nairobi', 'zip': '00500', 'country_id': cls.env.ref('base.ke').id, 'vat': 'A000123456F', }) cls.product_a.write({ 'name': 'Infinite Improbability Drive', 'l10n_ke_hsn_code': '0039.11.53', 'l10n_ke_hsn_name': 'Spacecraft including satellites and suborbital and spacecraft launch vehicles' }) cls.standard_rate_tax = cls.env['account.tax'].create({ 'name': '16% tax', 'amount': 16.0, 'amount_type': 'percent', }) @classmethod def line_dict_to_bytes(cls, line_dict): """ Helper method for creating the expected lines """ msg = b'1' + b';'.join([ # 0x31, command to add a line line_dict.get('name', b''.ljust(36)), # 36 characters for the name line_dict.get('vat_class', b'A'), # 1 symbol for vat class (a because the tax is 16.0%) line_dict.get('price', b'1'), # up to 13 symbols for the unit price, tax included line_dict.get('uom', b' '), # 3 symbols for uom line_dict.get('item_code', b''.ljust(10)), # 10 symbols for item code (only reported when the tax is not 16.0%) line_dict.get('item_desc', b''.ljust(20)), # item description (only reported when the tex is not 16.0%) line_dict.get('vat_rate', b'16.0'), # vat rate ]) if line_dict.get('quantity'): msg += b'*' + line_dict.get('quantity') # 1 to 10 symbols for quantity if line_dict.get('discount'): msg += b',' + line_dict.get('discount') # 1 to 7 symbols for discount/addition return msg def test_export_simple_invoice(self): """ The _l10n_ke_get_cu_messages function serialises the data from the invoice as a series of messages representing commands to the device. The proxy must only wrap these messages (with the checksum, etc) and send them to the device, and issue a response. """ simple_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'quantity': 10, 'price_unit': 1234.56, 'tax_ids': [(6, 0, [self.company_data['company'].account_sale_tax_id.id])], 'discount': 25, }), ], }) simple_invoice.action_post() generated_messages = simple_invoice._l10n_ke_get_cu_messages() expected_sale_line = self.line_dict_to_bytes({ 'name': b'Infinite Improbability Drive ', 'price': b'1432.09', # This is the unit price, tax included 'quantity': b'10.0', 'discount': b'-25.0%', }) expected_messages = [ # open invoice b'01; 0;0;1;Sirius Cybernetics Corporation;A000123456F ;Test StreetFurther Test Street;Test StreetFurther Test Street;00500Nairobi ; ;INV202300001 ', # sale of article expected_sale_line, # close invoice b'8', # read date / time b'h', ] self.assertEqual(generated_messages, expected_messages) # Next assign the invoice a control unit number, and create a credit note from the invoice simple_invoice.l10n_ke_cu_invoice_number = '42424200420000004242' simple_credit_note = simple_invoice._reverse_moves() simple_credit_note.action_post() generated_messages = simple_credit_note._l10n_ke_get_cu_messages() # The credit note of the simple invoice should have the same content, excepting that expected_credit_note_header = [b''.join([ b'0', b'1;', b' 0;', b'0;', b'A;', # This reserved 'field' is a capital 'A' instead of a '1' b'Sirius Cybernetics Corporation;', b'A000123456F ;', b'Test StreetFurther Test Street;', b'Test StreetFurther Test Street;', b'00500Nairobi ;', b' ;', b'4242420042000000424;', # The 'Related invoice number' is the control unit number of the reversed invoice b'RINV202300001 ', # The invoice number is the number of the credit note ])] expected_messages = expected_credit_note_header + expected_messages[1:] self.assertEqual(generated_messages, expected_messages) def test_export_global_discount_invoice(self): """ Negative lines can be used as global discounts, the function that serialises the invoice should recognise these discount lines, and subtract them from positive lines, representing the subtraction as a discount. Existing discounts on lines should be handled correctly too. """ global_discount_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'quantity': 10, 'price_unit': 10, 'tax_ids': [(6, 0, [self.company_data['company'].account_sale_tax_id.id])], 'discount': 10 }), (0, 0, { 'name': "don't panic", 'quantity': 1, 'price_unit': -10, 'tax_ids': [(6, 0, [self.company_data['company'].account_sale_tax_id.id])], }), ], }) global_discount_invoice.action_post() generated_messages = global_discount_invoice._l10n_ke_get_cu_messages() expected_discounted_line = self.line_dict_to_bytes({ 'name': b'Infinite Improbability Drive ', 'price': b'11.6', 'quantity': b'10.0', # The discount is -20%, because there is an existing discount on the line of 10%, and # another negative line with the amount -10 would be another -10% discount. 'discount': b'-20.0%', }) expected_messages = [ b'01; 0;0;1;Sirius Cybernetics Corporation;A000123456F ;Test StreetFurther Test Street;Test StreetFurther Test Street;00500Nairobi ; ;INV202300001 ', expected_discounted_line, b'8', b'h' ] self.assertEqual(generated_messages, expected_messages) # A copy of the invoice where the positive line is the product of a double negative # (negative price and negative quantity) should yeild exactly the same representation. double_negative_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'quantity': -10, 'price_unit': -10, 'tax_ids': [(6, 0, [self.company_data['company'].account_sale_tax_id.id])], 'discount': 10 }), (0, 0, { 'name': "don't panic", 'quantity': 1, 'price_unit': -10, 'tax_ids': [(6, 0, [self.company_data['company'].account_sale_tax_id.id])], }), ], }) double_negative_invoice.action_post() generated_messages = double_negative_invoice._l10n_ke_get_cu_messages() # There representation is exactly the same, excepting that the name of the invoice is different expected_double_negative_header = [b'01; 0;0;1;Sirius Cybernetics Corporation;A000123456F ;Test StreetFurther Test Street;Test StreetFurther Test Street;00500Nairobi ; ;INV202300002 '] expected_messages = expected_double_negative_header + expected_messages[1:] self.assertEqual(generated_messages, expected_messages)
49.863388
9,125
14,737
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import json import re from datetime import datetime from odoo import models, fields, _ from odoo.exceptions import UserError _logger = logging.getLogger(__name__) class AccountMove(models.Model): _inherit = 'account.move' l10n_ke_cu_datetime = fields.Datetime(string='CU Signing Date and Time', copy=False) l10n_ke_cu_serial_number = fields.Char(string='CU Serial Number', copy=False) l10n_ke_cu_invoice_number = fields.Char(string='CU Invoice Number', copy=False) l10n_ke_cu_qrcode = fields.Char(string='CU QR Code', copy=False) # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- def _l10n_ke_fmt(self, string, length, ljust=True): """ Function for common formatting behaviour :param string: string to be formatted/encoded :param length: integer length to justify (if enabled), and then truncate the string to :param ljust: boolean representing whether the string should be justified :returns: byte-string justified/truncated, with all non-alphanumeric characters removed """ if not string: string = '' return re.sub('[^A-Za-z0-9 ]+', '', str(string)).encode('cp1251').ljust(length if ljust else 0)[:length] # ------------------------------------------------------------------------- # CHECKS # ------------------------------------------------------------------------- def _l10n_ke_validate_move(self): """ Returns list of errors related to misconfigurations per move Find misconfigurations on the move, the lines of the move, and the taxes on those lines that would result in rejection by the KRA. """ errors = [] for move in self: move_errors = [] if move.country_code != 'KE': move_errors.append(_("This invoice is not a Kenyan invoice and therefore can not be sent to the device.")) if move.company_id.currency_id != self.env.ref('base.KES'): move_errors.append(_("This invoice's company currency is not in Kenyan Shillings, conversion to KES is not possible.")) if move.state != 'posted': move_errors.append(_("This invoice/credit note has not been posted. Please confirm it to continue.")) if move.move_type not in ('out_refund', 'out_invoice'): move_errors.append(_("The document being sent should be an invoice or credit note.")) if any([move.l10n_ke_cu_invoice_number, move.l10n_ke_cu_serial_number, move.l10n_ke_cu_qrcode, move.l10n_ke_cu_datetime]): move_errors.append(_("The document already has details related to the fiscal device. Please make sure that the invoice has not already been sent.")) # The credit note should refer to the control unit number (receipt number) of the original # invoice to which it relates. if move.move_type == 'out_refund' and not move.reversed_entry_id.l10n_ke_cu_invoice_number: move_errors.append(_("This credit note must reference the previous invoice, and this previous invoice must have already been submitted.")) for line in move.invoice_line_ids.filtered(lambda l: not l.display_type): if not line.tax_ids or len(line.tax_ids) > 1: move_errors.append(_("On line %s, you must select one and only one tax.", line.name)) else: if line.tax_ids.amount == 0 and not (line.product_id and line.product_id.l10n_ke_hsn_code and line.product_id.l10n_ke_hsn_name): move_errors.append(_("On line %s, a product with a HS Code and HS Name must be selected, since the tax is 0%% or exempt.", line.name)) for tax in move.invoice_line_ids.tax_ids: if tax.amount not in (16, 8, 0): move_errors.append(_("Tax '%s' is used, but only taxes of 16%%, 8%%, 0%% or Exempt can be sent. Please reconfigure or change the tax.", tax.name)) if move_errors: errors.append((move.name, move_errors)) return errors # ------------------------------------------------------------------------- # SERIALISERS # ------------------------------------------------------------------------- def _l10n_ke_cu_open_invoice_message(self): """ Serialise the required fields for opening an invoice :returns: a list containing one byte-string representing the <CMD> and <DATA> of the message sent to the fiscal device. """ headquarter_address = (self.commercial_partner_id.street or '') + (self.commercial_partner_id.street2 or '') customer_address = (self.partner_id.street or '') + (self.partner_id.street2 or '') postcode_and_city = (self.partner_id.zip or '') + '' + (self.partner_id.city or '') invoice_elements = [ b'1', # Reserved - 1 symbol with value '1' b' 0', # Reserved - 6 symbols with value ‘ 0’ b'0', # Reserved - 1 symbol with value '0' b'1' if self.move_type == 'out_invoice' else b'A', # 1 symbol with value '1' (new invoice), 'A' (credit note), or '@' (debit note) self._l10n_ke_fmt(self.commercial_partner_id.name, 30), # 30 symbols for Company name self._l10n_ke_fmt(self.commercial_partner_id.vat, 14), # 14 Symbols for the client PIN number self._l10n_ke_fmt(headquarter_address, 30), # 30 Symbols for customer headquarters self._l10n_ke_fmt(customer_address, 30), # 30 Symbols for the address self._l10n_ke_fmt(postcode_and_city, 30), # 30 symbols for the customer post code and city self._l10n_ke_fmt('', 30), # 30 symbols for the exemption number ] if self.move_type == 'out_refund': invoice_elements.append(self._l10n_ke_fmt(self.reversed_entry_id.l10n_ke_cu_invoice_number, 19)), # 19 symbols for related invoice number invoice_elements.append(re.sub('[^A-Za-z0-9 ]+', '', self.name)[-15:].ljust(15).encode('cp1251')) # 15 symbols for trader system invoice number # Command: Open fiscal record (0x30) return [b'\x30' + b';'.join(invoice_elements)] def _l10n_ke_cu_lines_messages(self): """ Serialise the data of each line on the invoice This function transforms the lines in order to handle the differences between the KRA expected data and the lines in odoo. If a discount line (as a negative line) has been added to the invoice lines, find a suitable line/lines to distribute the discount accross :returns: List of byte-strings representing each command <CMD> and the <DATA> of the line, which will be sent to the fiscal device in order to add a line to the opened invoice. """ def is_discount_line(line): return line.price_subtotal < 0.0 def is_candidate(discount_line, other_line): """ If the of one line match those of the discount line, the discount can be distributed accross that line """ discount_taxes = discount_line.tax_ids.flatten_taxes_hierarchy() other_line_taxes = other_line.tax_ids.flatten_taxes_hierarchy() return set(discount_taxes.ids) == set(other_line_taxes.ids) lines = self.invoice_line_ids.filtered(lambda l: not l.display_type and l.quantity and l.price_total) # The device expects all monetary values in Kenyan Shillings if self.currency_id == self.company_id.currency_id: currency_rate = 1 else: currency_rate = abs(lines[0].balance / lines[0].price_subtotal) discount_dict = {line.id: line.discount for line in lines if line.price_total > 0} for line in lines: if not is_discount_line(line): continue # Search for non-discount lines candidate_vals_list = [l for l in lines if not is_discount_line(l) and is_candidate(l, line)] candidate_vals_list = sorted(candidate_vals_list, key=lambda x: x.price_unit * x.quantity, reverse=True) line_to_discount = abs(line.price_unit * line.quantity) for candidate in candidate_vals_list: still_to_discount = abs(candidate.price_unit * candidate.quantity * (100.0 - discount_dict[candidate.id]) / 100.0) if line_to_discount >= still_to_discount: discount_dict[candidate.id] = 100.0 line_to_discount -= still_to_discount else: rest_to_discount = abs((line_to_discount / (candidate.price_unit * candidate.quantity)) * 100.0) discount_dict[candidate.id] += rest_to_discount break vat_class = {16.0: 'A', 8.0: 'B'} msgs = [] for line in self.invoice_line_ids.filtered(lambda l: not l.display_type and l.quantity and l.price_total > 0 and not discount_dict.get(l.id) >= 100): # Here we use the original discount of the line, since it the distributed discount has not been applied in the price_total price = round(line.price_total / abs(line.quantity) * 100 / (100 - line.discount), 2) * currency_rate percentage = line.tax_ids[0].amount # Letter to classify tax, 0% taxes are handled conditionally, as the tax can be zero-rated or exempt letter = '' if percentage in vat_class: letter = vat_class[percentage] else: report_line_ids = line.tax_ids.invoice_repartition_line_ids.filtered(lambda l: l.repartition_type == 'base').tag_ids.tax_report_line_ids.ids try: exempt_report_line = self.env.ref('l10n_ke.tax_report_line_exempt_sales_base') except ValueError: raise UserError(_("Tax exempt report line cannot be found, please update the l10n_ke module.")) letter = 'E' if exempt_report_line.id in report_line_ids else 'C' uom = line.product_uom_id and line.product_uom_id.name or '' hscode = re.sub('[^0-9.]+', '', line.product_id.l10n_ke_hsn_code)[:10].ljust(10).encode('cp1251') if letter not in ('A', 'B') else b''.ljust(10) hsname = self._l10n_ke_fmt(line.product_id.l10n_ke_hsn_name, 20) if letter not in ('A', 'B') else b''.ljust(20) line_data = b';'.join([ self._l10n_ke_fmt(line.name, 36), # 36 symbols for the article's name self._l10n_ke_fmt(letter, 1), # 1 symbol for article's vat class ('A', 'B', 'C', 'D', or 'E') str(price)[:13].encode('cp1251'), # 1 to 13 symbols for article's price self._l10n_ke_fmt(uom, 3), # 3 symbols for unit of measure hscode, # 10 symbols for HS code in the format xxxx.xx.xx (can be empty) hsname, # 20 symbols for the HS name (can be empty) str(percentage).encode('cp1251')[:5] # up to 5 symbols for vat rate ]) # 1 to 10 symbols for quantity line_data += b'*' + str(abs(line.quantity)).encode('cp1251')[:10] if discount_dict.get(line.id): # 1 to 7 symbols for percentage of discount/addition discount_sign = b'-' if discount_dict[line.id] > 0 else b'+' discount = discount_sign + str(abs(discount_dict[line.id])).encode('cp1251')[:6] line_data += b',' + discount + b'%' # Command: Sale of article (0x31) msgs += [b'\x31' + line_data] return msgs def _l10n_ke_get_cu_messages(self): """ Composes a list of all the command and data parts of the messages required for the fiscal device to open an invoice, add lines and subsequently close it. """ self.ensure_one() msgs = self._l10n_ke_cu_open_invoice_message() msgs += self._l10n_ke_cu_lines_messages() # Command: Close fiscal reciept (0x38) msgs += [b'\x38'] # Command: Read date and time (0x68) msgs += [b'\x68'] return msgs # ------------------------------------------------------------------------- # POST COMMANDS / RECEIVE DATA # ------------------------------------------------------------------------- def l10n_ke_action_cu_post(self): """ Returns the client action descriptor dictionary for sending the invoice(s) to the fiscal device. """ # Check the configuration of the invoice errors = self._l10n_ke_validate_move() if errors: error_msg = "" for move, error_list in errors: error_list = '\n'.join(error_list) error_msg += _("Invalid invoice configuration on %s:\n%s\n\n", move, error_list) raise UserError(error_msg) return { 'type': 'ir.actions.client', 'tag': 'post_send', 'params': { 'invoices': { move.id: { 'messages': json.dumps([msg.decode('cp1251') for msg in move._l10n_ke_get_cu_messages()]), 'proxy_address': move.company_id.l10n_ke_cu_proxy_address, 'company_vat': move.company_id.vat } for move in self } } } def l10n_ke_cu_response(self, response): """ Set the fields related to the fiscal device on the invoice. This is intended to be utilized by an RPC call from the javascript client action. """ move = self.browse(int(response['move_id'])) replies = [msg for msg in response['replies']] move.update({ 'l10n_ke_cu_serial_number': response['serial_number'], 'l10n_ke_cu_invoice_number': replies[-2].split(';')[0], 'l10n_ke_cu_qrcode': replies[-2].split(';')[1].strip(), 'l10n_ke_cu_datetime': datetime.strptime(replies[-1], '%d-%m-%Y %H:%M'), })
55.387218
14,733
403
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 ResCompany(models.Model): _inherit = 'res.company' l10n_ke_cu_proxy_address = fields.Char( default="http://localhost:8069", string='Fiscal Device Proxy Address', help='The address of the proxy server for the fiscal device.', )
31
403
494
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 ProductTemplate(models.Model): _inherit = "product.template" l10n_ke_hsn_code = fields.Char( string='KRA Item Code', help='Product code needed when not 16% VAT rated. ', ) l10n_ke_hsn_name = fields.Char( string='KRA Item Description', help='Product code description needed when not 16% VAT rated. ', )
30.875
494
326
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' l10n_ke_cu_proxy_address = fields.Char(related='company_id.l10n_ke_cu_proxy_address', readonly=False)
32.6
326
479
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 ResPartner(models.Model): _inherit = 'res.partner' l10n_ke_exemption_number = fields.Char( string='Exemption Number', help='The exemption number of the partner. Provided by the Kenyan government.', ) def _commercial_fields(self): return super()._commercial_fields() + ['l10n_ke_exemption_number']
29.9375
479
875
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Maintenance', 'version': '1.0', 'sequence': 100, 'category': 'Manufacturing/Maintenance', 'description': """ Track equipments and maintenance requests""", 'depends': ['mail'], 'summary': 'Track equipment and manage maintenance requests', 'website': 'https://www.odoo.com/app/maintenance', 'data': [ 'security/maintenance.xml', 'security/ir.model.access.csv', 'data/maintenance_data.xml', 'data/mail_data.xml', 'views/maintenance_views.xml', 'views/mail_activity_views.xml', 'data/maintenance_cron.xml', ], 'demo': ['data/maintenance_demo.xml'], 'installable': True, 'application': True, 'assets': { 'web.assets_backend': [ 'maintenance/static/src/**/*', ], }, 'license': 'LGPL-3', }
28.225806
875
6,017
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo.tests.common import TransactionCase from dateutil import relativedelta import datetime class TestEquipment(TransactionCase): """ Test used to check that when doing equipment/maintenance_request/equipment_category creation.""" def setUp(self): super(TestEquipment, self).setUp() self.equipment = self.env['maintenance.equipment'] self.maintenance_request = self.env['maintenance.request'] self.res_users = self.env['res.users'] self.maintenance_team = self.env['maintenance.team'] self.main_company = self.env.ref('base.main_company') res_user = self.env.ref('base.group_user') res_manager = self.env.ref('maintenance.group_equipment_manager') self.user = self.res_users.create(dict( name="Normal User/Employee", company_id=self.main_company.id, login="emp", email="empuser@yourcompany.example.com", groups_id=[(6, 0, [res_user.id])] )) self.manager = self.res_users.create(dict( name="Equipment Manager", company_id=self.main_company.id, login="hm", email="eqmanager@yourcompany.example.com", groups_id=[(6, 0, [res_manager.id])] )) self.equipment_monitor = self.env['maintenance.equipment.category'].create({ 'name': 'Monitors - Test', }) def test_10_equipment_request_category(self): # Create a new equipment equipment_01 = self.equipment.with_user(self.manager).create({ 'name': 'Samsung Monitor "15', 'category_id': self.equipment_monitor.id, 'technician_user_id': self.ref('base.user_root'), 'owner_user_id': self.user.id, 'assign_date': time.strftime('%Y-%m-%d'), 'serial_no': 'MT/127/18291015', 'model': 'NP355E5X', 'color': 3, }) # Check that equipment is created or not assert equipment_01, "Equipment not created" # Create new maintenance request maintenance_request_01 = self.maintenance_request.with_user(self.user).create({ 'name': 'Resolution is bad', 'user_id': self.user.id, 'owner_user_id': self.user.id, 'equipment_id': equipment_01.id, 'color': 7, 'stage_id': self.ref('maintenance.stage_0'), 'maintenance_team_id': self.ref('maintenance.equipment_team_maintenance') }) # I check that maintenance_request is created or not assert maintenance_request_01, "Maintenance Request not created" # I check that Initially maintenance request is in the "New Request" stage self.assertEqual(maintenance_request_01.stage_id.id, self.ref('maintenance.stage_0')) # I check that change the maintenance_request stage on click statusbar maintenance_request_01.with_user(self.user).write({'stage_id': self.ref('maintenance.stage_1')}) # I check that maintenance request is in the "In Progress" stage self.assertEqual(maintenance_request_01.stage_id.id, self.ref('maintenance.stage_1')) def test_20_cron(self): """ Check the cron creates the necessary preventive maintenance requests""" equipment_cron = self.equipment.create({ 'name': 'High Maintenance Monitor because of Color Calibration', 'category_id': self.equipment_monitor.id, 'technician_user_id': self.ref('base.user_root'), 'owner_user_id': self.user.id, 'assign_date': time.strftime('%Y-%m-%d'), 'period': 7, 'color': 3, }) maintenance_request_cron = self.maintenance_request.create({ 'name': 'Need a special calibration', 'user_id': self.user.id, 'request_date': (datetime.datetime.now() + relativedelta.relativedelta(days=7)).strftime('%Y-%m-%d'), 'maintenance_type': 'preventive', 'owner_user_id': self.user.id, 'equipment_id': equipment_cron.id, 'color': 7, 'stage_id': self.ref('maintenance.stage_0'), 'maintenance_team_id': self.ref('maintenance.equipment_team_maintenance') }) self.env['maintenance.equipment']._cron_generate_requests() # As it is generating the requests for one month in advance, we should have 4 requests in total tot_requests = self.maintenance_request.search([('equipment_id', '=', equipment_cron.id)]) self.assertEqual(len(tot_requests), 1, 'The cron should have generated just 1 request for the High Maintenance Monitor.') def test_21_cron(self): """ Check the creation of maintenance requests by the cron""" team_test = self.maintenance_team.create({ 'name': 'team_test', }) equipment = self.equipment.create({ 'name': 'High Maintenance Monitor because of Color Calibration', 'category_id': self.equipment_monitor.id, 'technician_user_id': self.ref('base.user_root'), 'owner_user_id': self.user.id, 'assign_date': time.strftime('%Y-%m-%d'), 'period': 7, 'color': 3, 'maintenance_team_id': team_test.id, 'maintenance_duration': 3.0, }) self.env['maintenance.equipment']._cron_generate_requests() tot_requests = self.maintenance_request.search([('equipment_id', '=', equipment.id)]) self.assertEqual(len(tot_requests), 1, 'The cron should have generated just 1 request for the High Maintenance Monitor.') self.assertEqual(tot_requests.maintenance_team_id.id, team_test.id, 'The maintenance team should be the same as equipment one') self.assertEqual(tot_requests.duration, 3.0, 'Equipement maintenance duration is not the same as the request one')
44.902985
6,017
7,097
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo.tests.common import TransactionCase from odoo.exceptions import AccessError class TestEquipmentMulticompany(TransactionCase): def test_00_equipment_multicompany_user(self): """Test Check maintenance with equipment manager and user in multi company environment""" # Use full models Equipment = self.env['maintenance.equipment'] MaintenanceRequest = self.env['maintenance.request'] Category = self.env['maintenance.equipment.category'] ResUsers = self.env['res.users'] ResCompany = self.env['res.company'] MaintenanceTeam = self.env['maintenance.team'] # Use full reference. group_user = self.env.ref('base.group_user') group_manager = self.env.ref('maintenance.group_equipment_manager') # Company A company_a = ResCompany.create({ 'name': 'Company A', 'currency_id': self.env.ref('base.USD').id, }) # Create one child company having parent company is 'Your company' company_b = ResCompany.create({ 'name': 'Company B', 'currency_id': self.env.ref('base.USD').id, }) # Create equipment manager. cids = [company_a.id, company_b.id] equipment_manager = ResUsers.create({ 'name': 'Equipment Manager', 'company_id': company_a.id, 'login': 'e_equipment_manager', 'email': 'eqmanager@yourcompany.example.com', 'groups_id': [(6, 0, [group_manager.id])], 'company_ids': [(6, 0, [company_a.id, company_b.id])] }) # Create equipment user user = ResUsers.create({ 'name': 'Normal User/Employee', 'company_id': company_b.id, 'login': 'emp', 'email': 'empuser@yourcompany.example.com', 'groups_id': [(6, 0, [group_user.id])], 'company_ids': [(6, 0, [company_b.id])] }) # create a maintenance team for company A user team = MaintenanceTeam.with_user(equipment_manager).create({ 'name': 'Metrology', 'company_id': company_a.id, }) # create a maintenance team for company B user teamb = MaintenanceTeam.with_user(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Subcontractor', 'company_id': company_b.id, }) # User should not able to create equipment category. with self.assertRaises(AccessError): Category.with_user(user).create({ 'name': 'Software', 'company_id': company_b.id, 'technician_user_id': user.id, }) # create equipment category for equipment manager category_1 = Category.with_user(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Monitors - Test', 'company_id': company_b.id, 'technician_user_id': equipment_manager.id, }) # create equipment category for equipment manager Category.with_user(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Computers - Test', 'company_id': company_b.id, 'technician_user_id': equipment_manager.id, }) # create equipment category for equipment user Category.with_user(equipment_manager).create({ 'name': 'Phones - Test', 'company_id': company_a.id, 'technician_user_id': equipment_manager.id, }) # Check category for user equipment_manager and user self.assertEqual(Category.with_user(equipment_manager).with_context(allowed_company_ids=cids).search_count([]), 3) self.assertEqual(Category.with_user(user).search_count([]), 2) # User should not able to create equipment. with self.assertRaises(AccessError): Equipment.with_user(user).create({ 'name': 'Samsung Monitor 15', 'category_id': category_1.id, 'assign_date': time.strftime('%Y-%m-%d'), 'company_id': company_b.id, 'owner_user_id': user.id, }) Equipment.with_user(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'Acer Laptop', 'category_id': category_1.id, 'assign_date': time.strftime('%Y-%m-%d'), 'company_id': company_b.id, 'owner_user_id': user.id, }) # create an equipment for user Equipment.with_user(equipment_manager).with_context(allowed_company_ids=cids).create({ 'name': 'HP Laptop', 'category_id': category_1.id, 'assign_date': time.strftime('%Y-%m-%d'), 'company_id': company_b.id, 'owner_user_id': equipment_manager.id, }) # Now there are total 2 equipments created and can view by equipment_manager user self.assertEqual(Equipment.with_user(equipment_manager).with_context(allowed_company_ids=cids).search_count([]), 2) # And there is total 1 equipment can be view by Normal User ( Which user is followers) self.assertEqual(Equipment.with_user(user).search_count([]), 1) # create an equipment team BY user with self.assertRaises(AccessError): MaintenanceTeam.with_user(user).create({ 'name': 'Subcontractor', 'company_id': company_b.id, }) # create an equipment category BY user with self.assertRaises(AccessError): Category.with_user(user).create({ 'name': 'Computers', 'company_id': company_b.id, 'technician_user_id': user.id, }) # create an maintenance stage BY user with self.assertRaises(AccessError): self.env['maintenance.stage'].with_user(user).create({ 'name': 'identify corrective maintenance requirements', }) # Create an maintenance request for ( User Follower ). MaintenanceRequest.with_user(user).create({ 'name': 'Some keys are not working', 'company_id': company_b.id, 'user_id': user.id, 'owner_user_id': user.id, }) # Create an maintenance request for equipment_manager (Admin Follower) MaintenanceRequest.with_user(equipment_manager).create({ 'name': 'Battery drains fast', 'company_id': company_a.id, 'user_id': equipment_manager.id, 'owner_user_id': equipment_manager.id, }) # Now here is total 1 maintenance request can be view by Normal User self.assertEqual(MaintenanceRequest.with_user(equipment_manager).with_context(allowed_company_ids=cids).search_count([]), 2) self.assertEqual(MaintenanceRequest.with_user(user).search_count([]), 1)
40.554286
7,097
24,729
py
PYTHON
15.0
# -*- coding: utf-8 -*- import ast from datetime import date, datetime, timedelta from odoo import api, fields, models, SUPERUSER_ID, _ from odoo.exceptions import UserError from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT class MaintenanceStage(models.Model): """ Model for case stages. This models the main stages of a Maintenance Request management flow. """ _name = 'maintenance.stage' _description = 'Maintenance Stage' _order = 'sequence, id' name = fields.Char('Name', required=True, translate=True) sequence = fields.Integer('Sequence', default=20) fold = fields.Boolean('Folded in Maintenance Pipe') done = fields.Boolean('Request Done') class MaintenanceEquipmentCategory(models.Model): _name = 'maintenance.equipment.category' _inherit = ['mail.alias.mixin', 'mail.thread'] _description = 'Maintenance Equipment Category' @api.depends('equipment_ids') def _compute_fold(self): # fix mutual dependency: 'fold' depends on 'equipment_count', which is # computed with a read_group(), which retrieves 'fold'! self.fold = False for category in self: category.fold = False if category.equipment_count else True name = fields.Char('Category Name', required=True, translate=True) company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) technician_user_id = fields.Many2one('res.users', 'Responsible', tracking=True, default=lambda self: self.env.uid) color = fields.Integer('Color Index') note = fields.Html('Comments', translate=True) equipment_ids = fields.One2many('maintenance.equipment', 'category_id', string='Equipments', copy=False) equipment_count = fields.Integer(string="Equipment", compute='_compute_equipment_count') maintenance_ids = fields.One2many('maintenance.request', 'category_id', copy=False) maintenance_count = fields.Integer(string="Maintenance Count", compute='_compute_maintenance_count') alias_id = fields.Many2one( 'mail.alias', 'Alias', ondelete='restrict', required=True, help="Email alias for this equipment category. New emails will automatically " "create a new equipment under this category.") fold = fields.Boolean(string='Folded in Maintenance Pipe', compute='_compute_fold', store=True) def _compute_equipment_count(self): equipment_data = self.env['maintenance.equipment'].read_group([('category_id', 'in', self.ids)], ['category_id'], ['category_id']) mapped_data = dict([(m['category_id'][0], m['category_id_count']) for m in equipment_data]) for category in self: category.equipment_count = mapped_data.get(category.id, 0) def _compute_maintenance_count(self): maintenance_data = self.env['maintenance.request'].read_group([('category_id', 'in', self.ids)], ['category_id'], ['category_id']) mapped_data = dict([(m['category_id'][0], m['category_id_count']) for m in maintenance_data]) for category in self: category.maintenance_count = mapped_data.get(category.id, 0) @api.ondelete(at_uninstall=False) def _unlink_except_contains_maintenance_requests(self): for category in self: if category.equipment_ids or category.maintenance_ids: raise UserError(_("You cannot delete an equipment category containing equipments or maintenance requests.")) def _alias_get_creation_values(self): values = super(MaintenanceEquipmentCategory, self)._alias_get_creation_values() values['alias_model_id'] = self.env['ir.model']._get('maintenance.request').id if self.id: values['alias_defaults'] = defaults = ast.literal_eval(self.alias_defaults or "{}") defaults['category_id'] = self.id return values class MaintenanceEquipment(models.Model): _name = 'maintenance.equipment' _inherit = ['mail.thread', 'mail.activity.mixin'] _description = 'Maintenance Equipment' _check_company_auto = True def _track_subtype(self, init_values): self.ensure_one() if 'owner_user_id' in init_values and self.owner_user_id: return self.env.ref('maintenance.mt_mat_assign') return super(MaintenanceEquipment, self)._track_subtype(init_values) def name_get(self): result = [] for record in self: if record.name and record.serial_no: result.append((record.id, record.name + '/' + record.serial_no)) if record.name and not record.serial_no: result.append((record.id, record.name)) return result @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): args = args or [] equipment_ids = [] if name: equipment_ids = self._search([('name', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid) if not equipment_ids: equipment_ids = self._search([('name', operator, name)] + args, limit=limit, access_rights_uid=name_get_uid) return equipment_ids name = fields.Char('Equipment Name', required=True, translate=True) company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) active = fields.Boolean(default=True) technician_user_id = fields.Many2one('res.users', string='Technician', tracking=True) owner_user_id = fields.Many2one('res.users', string='Owner', tracking=True) category_id = fields.Many2one('maintenance.equipment.category', string='Equipment Category', tracking=True, group_expand='_read_group_category_ids') partner_id = fields.Many2one('res.partner', string='Vendor', check_company=True) partner_ref = fields.Char('Vendor Reference') location = fields.Char('Location') model = fields.Char('Model') serial_no = fields.Char('Serial Number', copy=False) assign_date = fields.Date('Assigned Date', tracking=True) effective_date = fields.Date('Effective Date', default=fields.Date.context_today, required=True, help="Date at which the equipment became effective. This date will be used to compute the Mean Time Between Failure.") cost = fields.Float('Cost') note = fields.Html('Note') warranty_date = fields.Date('Warranty Expiration Date') color = fields.Integer('Color Index') scrap_date = fields.Date('Scrap Date') maintenance_ids = fields.One2many('maintenance.request', 'equipment_id') maintenance_count = fields.Integer(compute='_compute_maintenance_count', string="Maintenance Count", store=True) maintenance_open_count = fields.Integer(compute='_compute_maintenance_count', string="Current Maintenance", store=True) period = fields.Integer('Days between each preventive maintenance') next_action_date = fields.Date(compute='_compute_next_maintenance', string='Date of the next preventive maintenance', store=True) maintenance_team_id = fields.Many2one('maintenance.team', string='Maintenance Team', check_company=True) maintenance_duration = fields.Float(help="Maintenance Duration in hours.") @api.depends('effective_date', 'period', 'maintenance_ids.request_date', 'maintenance_ids.close_date') def _compute_next_maintenance(self): date_now = fields.Date.context_today(self) equipments = self.filtered(lambda x: x.period > 0) for equipment in equipments: next_maintenance_todo = self.env['maintenance.request'].search([ ('equipment_id', '=', equipment.id), ('maintenance_type', '=', 'preventive'), ('stage_id.done', '!=', True), ('close_date', '=', False)], order="request_date asc", limit=1) last_maintenance_done = self.env['maintenance.request'].search([ ('equipment_id', '=', equipment.id), ('maintenance_type', '=', 'preventive'), ('stage_id.done', '=', True), ('close_date', '!=', False)], order="close_date desc", limit=1) if next_maintenance_todo and last_maintenance_done: next_date = next_maintenance_todo.request_date date_gap = next_maintenance_todo.request_date - last_maintenance_done.close_date # If the gap between the last_maintenance_done and the next_maintenance_todo one is bigger than 2 times the period and next request is in the future # We use 2 times the period to avoid creation too closed request from a manually one created if date_gap > timedelta(0) and date_gap > timedelta(days=equipment.period) * 2 and next_maintenance_todo.request_date > date_now: # If the new date still in the past, we set it for today if last_maintenance_done.close_date + timedelta(days=equipment.period) < date_now: next_date = date_now else: next_date = last_maintenance_done.close_date + timedelta(days=equipment.period) elif next_maintenance_todo: next_date = next_maintenance_todo.request_date date_gap = next_maintenance_todo.request_date - date_now # If next maintenance to do is in the future, and in more than 2 times the period, we insert an new request # We use 2 times the period to avoid creation too closed request from a manually one created if date_gap > timedelta(0) and date_gap > timedelta(days=equipment.period) * 2: next_date = date_now + timedelta(days=equipment.period) elif last_maintenance_done: next_date = last_maintenance_done.close_date + timedelta(days=equipment.period) # If when we add the period to the last maintenance done and we still in past, we plan it for today if next_date < date_now: next_date = date_now else: next_date = equipment.effective_date + timedelta(days=equipment.period) equipment.next_action_date = next_date (self - equipments).next_action_date = False @api.depends('maintenance_ids.stage_id.done') def _compute_maintenance_count(self): for equipment in self: equipment.maintenance_count = len(equipment.maintenance_ids) equipment.maintenance_open_count = len(equipment.maintenance_ids.filtered(lambda x: not x.stage_id.done)) @api.onchange('company_id') def _onchange_company_id(self): if self.company_id and self.maintenance_team_id: if self.maintenance_team_id.company_id and not self.maintenance_team_id.company_id.id == self.company_id.id: self.maintenance_team_id = False @api.onchange('category_id') def _onchange_category_id(self): self.technician_user_id = self.category_id.technician_user_id _sql_constraints = [ ('serial_no', 'unique(serial_no)', "Another asset already exists with this serial number!"), ] @api.model def create(self, vals): equipment = super(MaintenanceEquipment, self).create(vals) if equipment.owner_user_id: equipment.message_subscribe(partner_ids=[equipment.owner_user_id.partner_id.id]) return equipment def write(self, vals): if vals.get('owner_user_id'): self.message_subscribe(partner_ids=self.env['res.users'].browse(vals['owner_user_id']).partner_id.ids) return super(MaintenanceEquipment, self).write(vals) @api.model def _read_group_category_ids(self, categories, domain, order): """ Read group customization in order to display all the categories in the kanban view, even if they are empty. """ category_ids = categories._search([], order=order, access_rights_uid=SUPERUSER_ID) return categories.browse(category_ids) def _prepare_maintenance_request_vals(self, date): self.ensure_one() return { 'name': _('Preventive Maintenance - %s', self.name), 'request_date': date, 'schedule_date': date, 'category_id': self.category_id.id, 'equipment_id': self.id, 'maintenance_type': 'preventive', 'owner_user_id': self.owner_user_id.id, 'user_id': self.technician_user_id.id, 'maintenance_team_id': self.maintenance_team_id.id, 'duration': self.maintenance_duration, 'company_id': self.company_id.id or self.env.company.id } def _create_new_request(self, date): self.ensure_one() vals = self._prepare_maintenance_request_vals(date) maintenance_requests = self.env['maintenance.request'].create(vals) return maintenance_requests @api.model def _cron_generate_requests(self): """ Generates maintenance request on the next_action_date or today if none exists """ for equipment in self.search([('period', '>', 0)]): next_requests = self.env['maintenance.request'].search([('stage_id.done', '=', False), ('equipment_id', '=', equipment.id), ('maintenance_type', '=', 'preventive'), ('request_date', '=', equipment.next_action_date)]) if not next_requests: equipment._create_new_request(equipment.next_action_date) class MaintenanceRequest(models.Model): _name = 'maintenance.request' _inherit = ['mail.thread.cc', 'mail.activity.mixin'] _description = 'Maintenance Request' _order = "id desc" _check_company_auto = True @api.returns('self') def _default_stage(self): return self.env['maintenance.stage'].search([], limit=1) def _creation_subtype(self): return self.env.ref('maintenance.mt_req_created') def _track_subtype(self, init_values): self.ensure_one() if 'stage_id' in init_values: return self.env.ref('maintenance.mt_req_status') return super(MaintenanceRequest, self)._track_subtype(init_values) def _get_default_team_id(self): MT = self.env['maintenance.team'] team = MT.search([('company_id', '=', self.env.company.id)], limit=1) if not team: team = MT.search([], limit=1) return team.id name = fields.Char('Subjects', required=True) company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) description = fields.Html('Description') request_date = fields.Date('Request Date', tracking=True, default=fields.Date.context_today, help="Date requested for the maintenance to happen") owner_user_id = fields.Many2one('res.users', string='Created by User', default=lambda s: s.env.uid) category_id = fields.Many2one('maintenance.equipment.category', related='equipment_id.category_id', string='Category', store=True, readonly=True) equipment_id = fields.Many2one('maintenance.equipment', string='Equipment', ondelete='restrict', index=True, check_company=True) user_id = fields.Many2one('res.users', string='Technician', tracking=True) stage_id = fields.Many2one('maintenance.stage', string='Stage', ondelete='restrict', tracking=True, group_expand='_read_group_stage_ids', default=_default_stage, copy=False) priority = fields.Selection([('0', 'Very Low'), ('1', 'Low'), ('2', 'Normal'), ('3', 'High')], string='Priority') color = fields.Integer('Color Index') close_date = fields.Date('Close Date', help="Date the maintenance was finished. ") kanban_state = fields.Selection([('normal', 'In Progress'), ('blocked', 'Blocked'), ('done', 'Ready for next stage')], string='Kanban State', required=True, default='normal', tracking=True) # active = fields.Boolean(default=True, help="Set active to false to hide the maintenance request without deleting it.") archive = fields.Boolean(default=False, help="Set archive to true to hide the maintenance request without deleting it.") maintenance_type = fields.Selection([('corrective', 'Corrective'), ('preventive', 'Preventive')], string='Maintenance Type', default="corrective") schedule_date = fields.Datetime('Scheduled Date', help="Date the maintenance team plans the maintenance. It should not differ much from the Request Date. ") maintenance_team_id = fields.Many2one('maintenance.team', string='Team', required=True, default=_get_default_team_id, check_company=True) duration = fields.Float(help="Duration in hours.") done = fields.Boolean(related='stage_id.done') def archive_equipment_request(self): self.write({'archive': True}) def reset_equipment_request(self): """ Reinsert the maintenance request into the maintenance pipe in the first stage""" first_stage_obj = self.env['maintenance.stage'].search([], order="sequence asc", limit=1) # self.write({'active': True, 'stage_id': first_stage_obj.id}) self.write({'archive': False, 'stage_id': first_stage_obj.id}) @api.onchange('company_id') def _onchange_company_id(self): if self.company_id and self.maintenance_team_id: if self.maintenance_team_id.company_id and not self.maintenance_team_id.company_id.id == self.company_id.id: self.maintenance_team_id = False @api.onchange('equipment_id') def onchange_equipment_id(self): if self.equipment_id: self.user_id = self.equipment_id.technician_user_id if self.equipment_id.technician_user_id else self.equipment_id.category_id.technician_user_id self.category_id = self.equipment_id.category_id if self.equipment_id.maintenance_team_id: self.maintenance_team_id = self.equipment_id.maintenance_team_id.id @api.onchange('category_id') def onchange_category_id(self): if not self.user_id or not self.equipment_id or (self.user_id and not self.equipment_id.technician_user_id): self.user_id = self.category_id.technician_user_id @api.model def create(self, vals): # context: no_log, because subtype already handle this request = super(MaintenanceRequest, self).create(vals) if request.owner_user_id or request.user_id: request._add_followers() if request.equipment_id and not request.maintenance_team_id: request.maintenance_team_id = request.equipment_id.maintenance_team_id if not request.stage_id.done: request.close_date = False elif request.stage_id.done and not request.close_date: request.close_date = fields.Date.today() request.activity_update() return request def write(self, vals): # Overridden to reset the kanban_state to normal whenever # the stage (stage_id) of the Maintenance Request changes. if vals and 'kanban_state' not in vals and 'stage_id' in vals: vals['kanban_state'] = 'normal' res = super(MaintenanceRequest, self).write(vals) if vals.get('owner_user_id') or vals.get('user_id'): self._add_followers() if 'stage_id' in vals: self.filtered(lambda m: m.stage_id.done).write({'close_date': fields.Date.today()}) self.filtered(lambda m: not m.stage_id.done).write({'close_date': False}) self.activity_feedback(['maintenance.mail_act_maintenance_request']) self.activity_update() if vals.get('user_id') or vals.get('schedule_date'): self.activity_update() if vals.get('equipment_id'): # need to change description of activity also so unlink old and create new activity self.activity_unlink(['maintenance.mail_act_maintenance_request']) self.activity_update() return res def activity_update(self): """ Update maintenance activities based on current record set state. It reschedule, unlink or create maintenance request activities. """ self.filtered(lambda request: not request.schedule_date).activity_unlink(['maintenance.mail_act_maintenance_request']) for request in self.filtered(lambda request: request.schedule_date): date_dl = fields.Datetime.from_string(request.schedule_date).date() updated = request.activity_reschedule( ['maintenance.mail_act_maintenance_request'], date_deadline=date_dl, new_user_id=request.user_id.id or request.owner_user_id.id or self.env.uid) if not updated: if request.equipment_id: note = _('Request planned for <a href="#" data-oe-model="%s" data-oe-id="%s">%s</a>') % ( request.equipment_id._name, request.equipment_id.id, request.equipment_id.display_name) else: note = False request.activity_schedule( 'maintenance.mail_act_maintenance_request', fields.Datetime.from_string(request.schedule_date).date(), note=note, user_id=request.user_id.id or request.owner_user_id.id or self.env.uid) def _add_followers(self): for request in self: partner_ids = (request.owner_user_id.partner_id + request.user_id.partner_id).ids request.message_subscribe(partner_ids=partner_ids) @api.model def _read_group_stage_ids(self, stages, domain, order): """ Read group customization in order to display all the stages in the kanban view, even if they are empty """ stage_ids = stages._search([], order=order, access_rights_uid=SUPERUSER_ID) return stages.browse(stage_ids) class MaintenanceTeam(models.Model): _name = 'maintenance.team' _description = 'Maintenance Teams' name = fields.Char('Team Name', required=True, translate=True) active = fields.Boolean(default=True) company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) member_ids = fields.Many2many( 'res.users', 'maintenance_team_users_rel', string="Team Members", domain="[('company_ids', 'in', company_id)]") color = fields.Integer("Color Index", default=0) request_ids = fields.One2many('maintenance.request', 'maintenance_team_id', copy=False) equipment_ids = fields.One2many('maintenance.equipment', 'maintenance_team_id', copy=False) # For the dashboard only todo_request_ids = fields.One2many('maintenance.request', string="Requests", copy=False, compute='_compute_todo_requests') todo_request_count = fields.Integer(string="Number of Requests", compute='_compute_todo_requests') todo_request_count_date = fields.Integer(string="Number of Requests Scheduled", compute='_compute_todo_requests') todo_request_count_high_priority = fields.Integer(string="Number of Requests in High Priority", compute='_compute_todo_requests') todo_request_count_block = fields.Integer(string="Number of Requests Blocked", compute='_compute_todo_requests') todo_request_count_unscheduled = fields.Integer(string="Number of Requests Unscheduled", compute='_compute_todo_requests') @api.depends('request_ids.stage_id.done') def _compute_todo_requests(self): for team in self: team.todo_request_ids = self.env['maintenance.request'].search([('maintenance_team_id', '=', team.id), ('stage_id.done', '=', False)]) team.todo_request_count = len(team.todo_request_ids) team.todo_request_count_date = self.env['maintenance.request'].search_count([('maintenance_team_id', '=', team.id), ('schedule_date', '!=', False)]) team.todo_request_count_high_priority = self.env['maintenance.request'].search_count([('maintenance_team_id', '=', team.id), ('priority', '=', '3')]) team.todo_request_count_block = self.env['maintenance.request'].search_count([('maintenance_team_id', '=', team.id), ('kanban_state', '=', 'blocked')]) team.todo_request_count_unscheduled = self.env['maintenance.request'].search_count([('maintenance_team_id', '=', team.id), ('schedule_date', '=', False)]) @api.depends('equipment_ids') def _compute_equipment(self): for team in self: team.equipment_count = len(team.equipment_ids)
55.322148
24,729
1,008
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Google Spreadsheet', 'version': '1.0', 'category': 'Hidden/Tools', 'description': """ The module adds the possibility to display data from Odoo in Google Spreadsheets in real time. ================================================================================================= """, 'depends': ['google_drive'], 'data': [ 'data/google_spreadsheet_data.xml', 'views/google_spreadsheet_views.xml', 'views/res_config_settings_views.xml', ], 'demo': [], 'installable': True, 'auto_install': False, 'assets': { 'web.assets_backend': [ 'google_spreadsheet/static/src/**/*.js', ], 'web.assets_qweb': [ 'google_spreadsheet/static/src/**/*.xml', ], 'web.qunit_suite_tests': [ 'google_spreadsheet/static/tests/**/*', ], }, 'license': 'LGPL-3', }
30.545455
1,008
386
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" google_drive_uri_copy = fields.Char(related='google_drive_uri', string='URI Copy', help="The URL to generate the authorization code from Google", readonly=False)
38.6
386
3,997
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging import requests from lxml import etree import re import werkzeug.urls from odoo import api, models from odoo.tools import misc from odoo.addons.google_account import TIMEOUT _logger = logging.getLogger(__name__) class GoogleDrive(models.Model): _inherit = 'google.drive.config' def get_google_scope(self): scope = super(GoogleDrive, self).get_google_scope() return '%s https://www.googleapis.com/auth/spreadsheets' % scope @api.model def write_config_formula(self, attachment_id, spreadsheet_key, model, domain, groupbys, view_id): access_token = self.get_access_token(scope='https://www.googleapis.com/auth/spreadsheets') formula = self._get_data_formula(model, domain, groupbys, view_id) url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') dbname = self._cr.dbname user = self.env['res.users'].browse(self.env.user.id).read(['login', 'password'])[0] username = user['login'] password = user['password'] if not password: config_formula = '=oe_settings("%s";"%s")' % (url, dbname) else: config_formula = '=oe_settings("%s";"%s";"%s";"%s")' % (url, dbname, username, password) request = { "valueInputOption": "USER_ENTERED", "data": [ {"range": "A1", "values": [[formula]]}, {"range": "O60", "values": [[config_formula]]}, ] } try: req = requests.post( 'https://sheets.googleapis.com/v4/spreadsheets/%s/values:batchUpdate?%s' % (spreadsheet_key, werkzeug.urls.url_encode({'access_token': access_token})), data=json.dumps(request), headers={'content-type': 'application/json', 'If-Match': '*'}, timeout=TIMEOUT, ) except IOError: _logger.warning("An error occured while writing the formula on the Google Spreadsheet.") description = ''' formula: %s ''' % formula if attachment_id: self.env['ir.attachment'].browse(attachment_id).write({'description': description}) return True def _get_data_formula(self, model, domain, groupbys, view_id): fields = self.env[model].fields_view_get(view_id=view_id, view_type='tree') doc = etree.XML(fields.get('arch')) display_fields = [] for node in doc.xpath("//field"): if node.get('modifiers'): modifiers = json.loads(node.get('modifiers')) if not modifiers.get('invisible') and not modifiers.get('column_invisible'): display_fields.append(node.get('name')) fields = " ".join(display_fields) domain = domain.replace("'", r"\'").replace('"', "'").replace('True', 'true').replace('False', 'false') if groupbys: fields = "%s %s" % (groupbys, fields) formula = '=oe_read_group("%s";"%s";"%s";"%s")' % (model, fields, groupbys, domain) else: formula = '=oe_browse("%s";"%s";"%s")' % (model, fields, domain) return formula @api.model def set_spreadsheet(self, model, domain, groupbys, view_id): config = self.env.ref('google_spreadsheet.google_spreadsheet_template') if self._module_deprecated(): return { 'url': config.google_drive_template_url, 'deprecated': True, 'formula': self._get_data_formula(model, domain, groupbys, view_id), } title = 'Spreadsheet %s' % model res = self.copy_doc(False, config.google_drive_resource_id, title, model) mo = re.search("(key=|/d/)([A-Za-z0-9-_]+)", res['url']) if mo: key = mo.group(2) self.write_config_formula(res.get('id'), key, model, domain, groupbys, view_id) return res
39.574257
3,997
1,129
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Products Expiration Date', 'category': 'Inventory/Inventory', 'depends': ['stock'], 'demo': [], 'description': """ Track different dates on products and production lots. ====================================================== Following dates can be tracked: ------------------------------- - end of life - best before date - removal date - alert date Also implements the removal strategy First Expiry First Out (FEFO) widely used, for example, in food industries. """, 'data': ['security/ir.model.access.csv', 'security/stock_security.xml', 'views/production_lot_views.xml', 'views/product_template_views.xml', 'views/res_config_settings_views.xml', 'views/stock_move_views.xml', 'views/stock_quant_views.xml', 'wizard/confirm_expiry_view.xml', 'report/report_deliveryslip.xml', 'report/report_lot_barcode.xml', 'data/product_expiry_data.xml'], 'license': 'LGPL-3', }
35.28125
1,129
26,423
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from odoo import fields from odoo.addons.mail.tests.common import mail_new_test_user from odoo.addons.stock.tests.common import TestStockCommon from odoo.tests.common import Form class TestStockProductionLot(TestStockCommon): @classmethod def setUpClass(cls): super(TestStockProductionLot, cls).setUpClass() # Creates a tracked product with expiration dates. cls.apple_product = cls.ProductObj.create({ 'name': 'Apple', 'type': 'product', 'tracking': 'lot', 'use_expiration_date': True, 'expiration_time': 10, 'use_time': 5, 'removal_time': 8, 'alert_time': 4, }) def test_00_stock_production_lot(self): """ Test Scheduled Task on lot with an alert_date in the past creates an activity """ # create product self.productAAA = self.ProductObj.create({ 'name': 'Product AAA', 'type': 'product', 'tracking':'lot', 'company_id': self.env.company.id, }) # create a new lot with with alert date in the past self.lot1_productAAA = self.LotObj.create({ 'name': 'Lot 1 ProductAAA', 'product_id': self.productAAA.id, 'alert_date': fields.Date.to_string(datetime.today() - relativedelta(days=15)), 'company_id': self.env.company.id, }) picking_in = self.PickingObj.create({ 'picking_type_id': self.picking_type_in, 'location_id': self.supplier_location, 'location_dest_id': self.stock_location }) move_a = self.MoveObj.create({ 'name': self.productAAA.name, 'product_id': self.productAAA.id, 'product_uom_qty': 33, 'product_uom': self.productAAA.uom_id.id, 'picking_id': picking_in.id, 'location_id': self.supplier_location, 'location_dest_id': self.stock_location }) self.assertEqual(picking_in.move_lines.state, 'draft', 'Wrong state of move line.') picking_in.action_confirm() self.assertEqual(picking_in.move_lines.state, 'assigned', 'Wrong state of move line.') # Replace pack operation of incoming shipments. picking_in.action_assign() move_a.move_line_ids.qty_done = 33 move_a.move_line_ids.lot_id = self.lot1_productAAA.id # Transfer Incoming Shipment. picking_in._action_done() # run scheduled tasks self.env['stock.production.lot']._alert_date_exceeded() # check a new activity has been created activity_id = self.env.ref('product_expiry.mail_activity_type_alert_date_reached').id activity_count = self.env['mail.activity'].search_count([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=', self.lot1_productAAA.id) ]) self.assertEqual(activity_count, 1, 'No activity created while there should be one') # run the scheduler a second time self.env['stock.production.lot']._alert_date_exceeded() # check there is still only one activity, no additional activity is created if there is already an existing activity activity_count = self.env['mail.activity'].search_count([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=', self.lot1_productAAA.id) ]) self.assertEqual(activity_count, 1, 'There should be one and only one activity') # mark the activity as done mail_activity = self.env['mail.activity'].search([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=', self.lot1_productAAA.id) ]) mail_activity.action_done() # check there is no more activity (because it is already done) activity_count = self.env['mail.activity'].search_count([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=', self.lot1_productAAA.id) ]) self.assertEqual(activity_count, 0,"As activity is done, there shouldn't be any related activity") # run the scheduler a third time self.env['stock.production.lot']._alert_date_exceeded() # check there is no activity created activity_count = self.env['mail.activity'].search_count([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=',self.lot1_productAAA.id) ]) self.assertEqual(activity_count, 0, "As there is already an activity marked as done, there shouldn't be any related activity created for this lot") def test_01_stock_production_lot(self): """ Test Scheduled Task on lot with an alert_date in future does not create an activity """ # create product self.productBBB = self.ProductObj.create({ 'name': 'Product BBB', 'type': 'product', 'tracking':'lot' }) # create a new lot with with alert date in the past self.lot1_productBBB = self.LotObj.create({ 'name': 'Lot 1 ProductBBB', 'product_id': self.productBBB.id, 'alert_date': fields.Date.to_string(datetime.today() + relativedelta(days=15)), 'company_id': self.env.company.id, }) picking_in = self.PickingObj.create({ 'picking_type_id': self.picking_type_in, 'location_id': self.supplier_location, 'location_dest_id': self.stock_location}) move_b = self.MoveObj.create({ 'name': self.productBBB.name, 'product_id': self.productBBB.id, 'product_uom_qty': 44, 'product_uom': self.productBBB.uom_id.id, 'picking_id': picking_in.id, 'location_id': self.supplier_location, 'location_dest_id': self.stock_location}) self.assertEqual(picking_in.move_lines.state, 'draft', 'Wrong state of move line.') picking_in.action_confirm() self.assertEqual(picking_in.move_lines.state, 'assigned', 'Wrong state of move line.') # Replace pack operation of incoming shipments. picking_in.action_assign() move_b.move_line_ids.qty_done = 44 move_b.move_line_ids.lot_id = self.lot1_productBBB.id # Transfer Incoming Shipment. picking_in._action_done() # run scheduled tasks self.env['stock.production.lot']._alert_date_exceeded() # check a new activity has not been created activity_id = self.env.ref('product_expiry.mail_activity_type_alert_date_reached').id activity_count = self.env['mail.activity'].search_count([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=', self.lot1_productBBB.id) ]) self.assertEqual(activity_count, 0, "An activity has been created while it shouldn't") def test_02_stock_production_lot(self): """ Test Scheduled Task on lot without an alert_date does not create an activity """ # create product self.productCCC = self.ProductObj.create({'name': 'Product CCC', 'type': 'product', 'tracking':'lot'}) # create a new lot with with alert date in the past self.lot1_productCCC = self.LotObj.create({'name': 'Lot 1 ProductCCC', 'product_id': self.productCCC.id, 'company_id': self.env.company.id}) picking_in = self.PickingObj.create({ 'picking_type_id': self.picking_type_in, 'location_id': self.supplier_location, 'location_dest_id': self.stock_location}) move_c = self.MoveObj.create({ 'name': self.productCCC.name, 'product_id': self.productCCC.id, 'product_uom_qty': 44, 'product_uom': self.productCCC.uom_id.id, 'picking_id': picking_in.id, 'location_id': self.supplier_location, 'location_dest_id': self.stock_location}) self.assertEqual(picking_in.move_lines.state, 'draft', 'Wrong state of move line.') picking_in.action_confirm() self.assertEqual(picking_in.move_lines.state, 'assigned', 'Wrong state of move line.') # Replace pack operation of incoming shipments. picking_in.action_assign() move_c.move_line_ids.qty_done = 55 move_c.move_line_ids.lot_id = self.lot1_productCCC.id # Transfer Incoming Shipment. picking_in._action_done() # run scheduled tasks self.env['stock.production.lot']._alert_date_exceeded() # check a new activity has not been created activity_id = self.env.ref('product_expiry.mail_activity_type_alert_date_reached').id activity_count = self.env['mail.activity'].search_count([ ('activity_type_id', '=', activity_id), ('res_model_id', '=', self.env.ref('stock.model_stock_production_lot').id), ('res_id', '=', self.lot1_productCCC.id) ]) self.assertEqual(activity_count, 0, "An activity has been created while it shouldn't") def test_03_onchange_expiration_date(self): """ Updates the `expiration_date` of the lot production and checks other date fields are updated as well. """ # Keeps track of the current datetime and set a delta for the compares. today_date = datetime.today() time_gap = timedelta(seconds=10) # Creates a new lot number and saves it... lot_form = Form(self.LotObj) lot_form.name = 'Apple Box #1' lot_form.product_id = self.apple_product lot_form.company_id = self.env.company apple_lot = lot_form.save() # ...then checks date fields have the expected values. exp_date = apple_lot.expiration_date self.assertAlmostEqual( today_date + timedelta(days=self.apple_product.expiration_time), exp_date, delta=time_gap) self.assertAlmostEqual( exp_date - timedelta(days=self.apple_product.use_time), apple_lot.use_date, delta=time_gap) self.assertAlmostEqual( exp_date - timedelta(days=self.apple_product.removal_time), apple_lot.removal_date, delta=time_gap) self.assertAlmostEqual( exp_date - timedelta(days=self.apple_product.alert_time), apple_lot.alert_date, delta=time_gap) difference = timedelta(days=20) new_date = apple_lot.expiration_date + difference old_use_date = apple_lot.use_date old_removal_date = apple_lot.removal_date old_alert_date = apple_lot.alert_date # Modifies the lot `expiration_date`... lot_form = Form(apple_lot) lot_form.expiration_date = new_date apple_lot = lot_form.save() # ...then checks all other date fields were correclty updated. self.assertAlmostEqual( apple_lot.use_date, old_use_date + difference, delta=time_gap) self.assertAlmostEqual( apple_lot.removal_date, old_removal_date + difference, delta=time_gap) self.assertAlmostEqual( apple_lot.alert_date, old_alert_date + difference, delta=time_gap) def test_04_expiration_date_on_receipt(self): """ Test we can set an expiration date on receipt and all expiration date will be correctly set. """ partner = self.env['res.partner'].create({ 'name': 'Apple\'s Joe', 'company_id': self.env.ref('base.main_company').id, }) expiration_date = datetime.today() + timedelta(days=30) time_gap = timedelta(seconds=10) # Receives a tracked production using expiration date. picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_in') with picking_form.move_ids_without_package.new() as move: move.product_id = self.apple_product move.product_uom_qty = 4 receipt = picking_form.save() receipt.action_confirm() # Defines a date during the receipt. move_form = Form(receipt.move_ids_without_package, view="stock.view_stock_move_operations") with move_form.move_line_ids.new() as line: line.lot_name = 'Apple Box #2' line.expiration_date = expiration_date line.qty_done = 4 move = move_form.save() receipt._action_done() # Get back the lot created when the picking was done... apple_lot = self.env['stock.production.lot'].search( [('product_id', '=', self.apple_product.id)], limit=1, ) # ... and checks all date fields are correctly set. self.assertAlmostEqual( apple_lot.expiration_date, expiration_date, delta=time_gap) self.assertAlmostEqual( apple_lot.use_date, expiration_date - timedelta(days=self.apple_product.use_time), delta=time_gap) self.assertAlmostEqual( apple_lot.removal_date, expiration_date - timedelta(days=self.apple_product.removal_time), delta=time_gap) self.assertAlmostEqual( apple_lot.alert_date, expiration_date - timedelta(days=self.apple_product.alert_time), delta=time_gap) def test_04_2_expiration_date_on_receipt(self): """ Test we can set an expiration date on receipt even if all expiration date related fields aren't set on product. """ partner = self.env['res.partner'].create({ 'name': 'Apple\'s Joe', 'company_id': self.env.ref('base.main_company').id, }) # Unset some fields. self.apple_product.expiration_time = False self.apple_product.removal_time = False expiration_date = datetime.today() + timedelta(days=30) time_gap = timedelta(seconds=10) # Receives a tracked production using expiration date. picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_in') with picking_form.move_ids_without_package.new() as move: move.product_id = self.apple_product move.product_uom_qty = 4 receipt = picking_form.save() receipt.action_confirm() # Defines a date during the receipt. move = receipt.move_ids_without_package[0] line = move.move_line_ids[0] self.assertEqual(move.use_expiration_date, True) line.lot_name = 'Apple Box #3' line.expiration_date = expiration_date line.qty_done = 4 receipt._action_done() # Get back the lot created when the picking was done... apple_lot = self.env['stock.production.lot'].search( [('product_id', '=', self.apple_product.id)], limit=1, ) # ... and checks all date fields are correctly set. self.assertAlmostEqual( apple_lot.expiration_date, expiration_date, delta=time_gap, msg="Must be define even if the product's `expiration_time` isn't set.") self.assertAlmostEqual( apple_lot.use_date, expiration_date - timedelta(days=self.apple_product.use_time), delta=time_gap) self.assertAlmostEqual( apple_lot.removal_date, expiration_date - timedelta(days=self.apple_product.removal_time), delta=time_gap, msg="`removal_date` should always be calculated when an expiration date is defined") self.assertAlmostEqual( apple_lot.alert_date, expiration_date - timedelta(days=self.apple_product.alert_time), delta=time_gap) def test_05_confirmation_on_delivery(self): """ Test when user tries to delivery expired lot, he/she gets a confirmation wizard. """ partner = self.env['res.partner'].create({ 'name': 'Cider & Son', 'company_id': self.env.ref('base.main_company').id, }) # Creates 3 lots (1 non-expired lot, 2 expired lots) lot_form = Form(self.LotObj) # Creates the lot. lot_form.name = 'good-apple-lot' lot_form.product_id = self.apple_product lot_form.company_id = self.env.company good_lot = lot_form.save() lot_form = Form(self.LotObj) # Creates the lot. lot_form.name = 'expired-apple-lot-01' lot_form.product_id = self.apple_product lot_form.company_id = self.env.company expired_lot_1 = lot_form.save() lot_form = Form(expired_lot_1) # Edits the lot to make it expired. lot_form.expiration_date = datetime.today() - timedelta(days=10) expired_lot_1 = lot_form.save() # Case #1: make a delivery with no expired lot. picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = self.apple_product move.product_uom_qty = 4 # Saves and confirms it... delivery_1 = picking_form.save() delivery_1.action_confirm() # ... then create a move line with the non-expired lot and valids the picking. delivery_1.move_line_ids_without_package = [(5, 0), (0, 0, { 'company_id': self.env.company.id, 'location_id': delivery_1.move_lines.location_id.id, 'location_dest_id': delivery_1.move_lines.location_dest_id.id, 'lot_id': good_lot.id, 'product_id': self.apple_product.id, 'product_uom_id': self.apple_product.uom_id.id, 'qty_done': 4, })] res = delivery_1.button_validate() # Validate a delivery for good products must not raise anything. self.assertEqual(res, True) # Case #2: make a delivery with one non-expired lot and one expired lot. picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = self.apple_product move.product_uom_qty = 8 # Saves and confirms it... delivery_2 = picking_form.save() delivery_2.action_confirm() # ... then create a move line for the non-expired lot and for an expired # lot and valids the picking. delivery_2.move_line_ids_without_package = [(5, 0), (0, 0, { 'company_id': self.env.company.id, 'location_id': delivery_2.move_lines.location_id.id, 'location_dest_id': delivery_2.move_lines.location_dest_id.id, 'lot_id': good_lot.id, 'product_id': self.apple_product.id, 'product_uom_id': self.apple_product.uom_id.id, 'qty_done': 4, }), (0, 0, { 'company_id': self.env.company.id, 'location_id': delivery_2.move_lines.location_id.id, 'location_dest_id': delivery_2.move_lines.location_dest_id.id, 'lot_id': expired_lot_1.id, 'product_id': self.apple_product.id, 'product_uom_id': self.apple_product.uom_id.id, 'qty_done': 4, })] res = delivery_2.button_validate() # Validate a delivery containing expired products must raise a confirmation wizard. self.assertNotEqual(res, True) self.assertEqual(res['res_model'], 'expiry.picking.confirmation') # Case #3: make a delivery with only on expired lot. picking_form = Form(self.env['stock.picking']) picking_form.partner_id = partner picking_form.picking_type_id = self.env.ref('stock.picking_type_out') with picking_form.move_ids_without_package.new() as move: move.product_id = self.apple_product move.product_uom_qty = 4 # Saves and confirms it... delivery_3 = picking_form.save() delivery_3.action_confirm() # ... then create two move lines with expired lot and valids the picking. delivery_3.move_line_ids_without_package = [(5, 0), (0, 0, { 'company_id': self.env.company.id, 'location_id': delivery_3.move_lines.location_id.id, 'location_dest_id': delivery_3.move_lines.location_dest_id.id, 'lot_id': expired_lot_1.id, 'product_id': self.apple_product.id, 'product_uom_id': self.apple_product.uom_id.id, 'qty_done': 4, })] res = delivery_3.button_validate() # Validate a delivery containing expired products must raise a confirmation wizard. self.assertNotEqual(res, True) self.assertEqual(res['res_model'], 'expiry.picking.confirmation') def test_edit_removal_date_in_inventory_mode(self): """ Try to edit removal_date with the inventory mode. """ user_group_stock_manager = self.env.ref('stock.group_stock_manager') self.demo_user = mail_new_test_user( self.env, name='Demo user', login='userdemo', email='d.d@example.com', groups='stock.group_stock_manager', ) lot_form = Form(self.LotObj) lot_form.name = 'LOT001' lot_form.product_id = self.apple_product lot_form.company_id = self.env.company apple_lot = lot_form.save() quant = self.StockQuantObj.with_context(inventory_mode=True).create({ 'product_id': self.apple_product.id, 'location_id': self.stock_location, 'quantity': 10, 'lot_id': apple_lot.id, }) # Try to write on quant with inventory mode new_date = datetime.today() + timedelta(days=15) quant.with_user(self.demo_user).with_context(inventory_mode=True).write({'removal_date': new_date}) self.assertEqual(quant.removal_date, new_date) def test_apply_lot_date_on_sml(self): """ When assigning a lot to a SML, if the lot has an expiration date, the latter should be applied on the SML """ exp_date = fields.Datetime.today() + relativedelta(days=15) lot = self.env['stock.production.lot'].create({ 'name': 'Lot 1', 'product_id': self.apple_product.id, 'expiration_date': fields.Datetime.to_string(exp_date), 'company_id': self.env.company.id, }) sml = self.env['stock.move.line'].create({ 'location_id': self.supplier_location, 'location_dest_id': self.stock_location, 'product_id': self.apple_product.id, 'qty_done': 3, 'product_uom_id': self.apple_product.uom_id.id, 'lot_id': lot.id, 'company_id': self.env.company.id, }) self.assertEqual(sml.expiration_date, exp_date) exp_date = exp_date + relativedelta(days=10) lot.expiration_date = exp_date self.assertEqual(sml.expiration_date, exp_date) def test_apply_lot_without_date_on_sml(self): """ When assigning a lot to a SML, if the lot has no expiration date, dates on lot and SML should be correctly set """ #create lot without expiration date lot = self.env['stock.production.lot'].create({ 'name': 'Lot 1', 'product_id': self.apple_product.id, 'company_id': self.env.company.id, }) sml = self.env['stock.move.line'].create({ 'location_id': self.supplier_location, 'location_dest_id': self.stock_location, 'product_id': self.apple_product.id, 'qty_done': 3, 'product_uom_id': self.apple_product.uom_id.id, 'lot_id': lot.id, 'company_id': self.env.company.id, }) today_date = datetime.today() time_gap = timedelta(seconds=10) exp_date = today_date + timedelta(days=self.apple_product.expiration_time) self.assertAlmostEqual(sml.expiration_date, exp_date, delta=time_gap) self.assertAlmostEqual( lot.expiration_date, exp_date, delta=time_gap) self.assertAlmostEqual( lot.use_date, exp_date - timedelta(days=self.apple_product.use_time), delta=time_gap) self.assertAlmostEqual( lot.removal_date, exp_date - timedelta(days=self.apple_product.removal_time), delta=time_gap) self.assertAlmostEqual( lot.alert_date, exp_date - timedelta(days=self.apple_product.alert_time), delta=time_gap) def test_apply_same_date_on_expiry_fields(self): expiration_time = 10 self.apple_product.write({ 'expiration_time': expiration_time, 'use_time': 0, 'removal_time': 0, 'alert_time': 0, }) lot = self.env['stock.production.lot'].create({ 'product_id': self.apple_product.id, 'company_id': self.env.company.id, }) delta = timedelta(seconds=10) expiration_date = datetime.today() + timedelta(days=expiration_time) err_msg = "The time on the product is set to 0, it means that the corresponding date should be the same as the expiration one" self.assertAlmostEqual(lot.expiration_date, expiration_date, delta=delta) self.assertAlmostEqual(lot.use_date, expiration_date, delta=delta, msg=err_msg) self.assertAlmostEqual(lot.removal_date, expiration_date, delta=delta, msg=err_msg) self.assertAlmostEqual(lot.alert_date, expiration_date, delta=delta, msg=err_msg)
44.784746
26,423
2,524
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 ConfirmExpiry(models.TransientModel): _name = 'expiry.picking.confirmation' _description = 'Confirm Expiry' lot_ids = fields.Many2many('stock.production.lot', readonly=True, required=True) picking_ids = fields.Many2many('stock.picking', readonly=True) description = fields.Char('Description', compute='_compute_descriptive_fields') show_lots = fields.Boolean('Show Lots', compute='_compute_descriptive_fields') @api.depends('lot_ids') def _compute_descriptive_fields(self): # Shows expired lots only if we are more than one expired lot. self.show_lots = len(self.lot_ids) > 1 if self.show_lots: # For multiple expired lots, they are listed in the wizard view. self.description = _( "You are going to deliver some product expired lots." "\nDo you confirm you want to proceed ?" ) else: # For one expired lot, its name is written in the wizard message. self.description = _( "You are going to deliver the product %(product_name)s, %(lot_name)s which is expired." "\nDo you confirm you want to proceed ?", product_name=self.lot_ids.product_id.display_name, lot_name=self.lot_ids.name ) def process(self): picking_to_validate = self.env.context.get('button_validate_picking_ids') if picking_to_validate: picking_to_validate = self.env['stock.picking'].browse(picking_to_validate) ctx = dict(self.env.context, skip_expired=True) ctx.pop('default_lot_ids') return picking_to_validate.with_context(ctx).button_validate() return True def process_no_expired(self): """ Don't process for concerned pickings (ones with expired lots), but process for all other pickings (in case of multi). """ # Remove `self.pick_ids` from `button_validate_picking_ids` and call # `button_validate` with the subset (if any). pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids')) pickings_to_validate = pickings_to_validate - self.picking_ids if pickings_to_validate: return pickings_to_validate.with_context(skip_expired=True).button_validate() return True
47.622642
2,524
3,233
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo import api, fields, models from odoo.tools.sql import column_exists, create_column class StockMoveLine(models.Model): _inherit = "stock.move.line" expiration_date = fields.Datetime( string='Expiration Date', compute='_compute_expiration_date', store=True, help='This is the date on which the goods with this Serial Number may' ' become dangerous and must not be consumed.') def _auto_init(self): """ Create column for 'expiration_date' here to avoid MemoryError when letting the ORM compute it after module installation. Since both 'lot_id.expiration_date' and 'product_id.use_expiration_date' are new fields introduced in this module, there is no need for an UPDATE statement here. """ if not column_exists(self._cr, "stock_move_line", "expiration_date"): create_column(self._cr, "stock_move_line", "expiration_date", "timestamp") return super()._auto_init() @api.depends('product_id', 'picking_type_use_create_lots', 'lot_id.expiration_date') def _compute_expiration_date(self): for move_line in self: if move_line.lot_id.expiration_date: move_line.expiration_date = move_line.lot_id.expiration_date elif move_line.picking_type_use_create_lots: if move_line.product_id.use_expiration_date: if not move_line.expiration_date: move_line.expiration_date = fields.Datetime.today() + datetime.timedelta(days=move_line.product_id.expiration_time) else: move_line.expiration_date = False @api.onchange('lot_id') def _onchange_lot_id(self): if not self.picking_type_use_existing_lots or not self.product_id.use_expiration_date: return if self.lot_id: self.expiration_date = self.lot_id.expiration_date else: self.expiration_date = False @api.onchange('product_id', 'product_uom_id') def _onchange_product_id(self): res = super()._onchange_product_id() if self.picking_type_use_create_lots: if self.product_id.use_expiration_date: self.expiration_date = fields.Datetime.today() + datetime.timedelta(days=self.product_id.expiration_time) else: self.expiration_date = False return res def _assign_production_lot(self, lot): super()._assign_production_lot(lot) self.lot_id._update_date_values(self[0].expiration_date) def _get_value_production_lot(self): res = super()._get_value_production_lot() if self.expiration_date: res.update({ 'expiration_date': self.expiration_date, 'use_date': self.expiration_date - datetime.timedelta(days=self.product_id.use_time), 'removal_date': self.expiration_date - datetime.timedelta(days=self.product_id.removal_time), 'alert_date': self.expiration_date - datetime.timedelta(days=self.product_id.alert_time), }) return res
44.902778
3,233
1,195
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 StockQuant(models.Model): _inherit = 'stock.quant' removal_date = fields.Datetime(related='lot_id.removal_date', store=True, readonly=False) use_expiration_date = fields.Boolean(related='product_id.use_expiration_date', readonly=True) @api.model def _get_inventory_fields_create(self): """ Returns a list of fields user can edit when he want to create a quant in `inventory_mode`. """ res = super()._get_inventory_fields_create() res += ['removal_date'] return res @api.model def _get_inventory_fields_write(self): """ Returns a list of fields user can edit when he want to edit a quant in `inventory_mode`. """ res = super()._get_inventory_fields_write() res += ['removal_date'] return res @api.model def _get_removal_strategy_order(self, removal_strategy): if removal_strategy == 'fefo': return 'removal_date, in_date, id' return super(StockQuant, self)._get_removal_strategy_order(removal_strategy)
36.212121
1,195
1,814
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 Product(models.Model): _inherit = "product.product" def action_open_quants(self): # Override to hide the `removal_date` column if not needed. if not any(product.use_expiration_date for product in self): self = self.with_context(hide_removal_date=True) return super().action_open_quants() class ProductTemplate(models.Model): _inherit = 'product.template' use_expiration_date = fields.Boolean(string='Expiration Date', help='When this box is ticked, you have the possibility to specify dates to manage' ' product expiration, on the product and on the corresponding lot/serial numbers') expiration_time = fields.Integer(string='Expiration Time', help='Number of days after the receipt of the products (from the vendor' ' or in stock after production) after which the goods may become dangerous' ' and must not be consumed. It will be computed on the lot/serial number.') use_time = fields.Integer(string='Best Before Time', help='Number of days before the Expiration Date after which the goods starts' ' deteriorating, without being dangerous yet. It will be computed on the lot/serial number.') removal_time = fields.Integer(string='Removal Time', help='Number of days before the Expiration Date after which the goods' ' should be removed from the stock. It will be computed on the lot/serial number.') alert_time = fields.Integer(string='Alert Time', help='Number of days before the Expiration Date after which an alert should be' ' raised on the lot/serial number. It will be computed on the lot/serial number.')
51.828571
1,814
978
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo import fields, models class StockMove(models.Model): _inherit = "stock.move" use_expiration_date = fields.Boolean( string='Use Expiration Date', related='product_id.use_expiration_date') def _generate_serial_move_line_commands(self, lot_names, origin_move_line=None): """Override to add a default `expiration_date` into the move lines values.""" move_lines_commands = super()._generate_serial_move_line_commands(lot_names, origin_move_line=origin_move_line) if self.product_id.use_expiration_date: date = fields.Datetime.today() + datetime.timedelta(days=self.product_id.expiration_time) for move_line_command in move_lines_commands: move_line_vals = move_line_command[2] move_line_vals['expiration_date'] = date return move_lines_commands
44.454545
978
1,634
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class StockPicking(models.Model): _inherit = "stock.picking" def _pre_action_done_hook(self): res = super()._pre_action_done_hook() # We use the 'skip_expired' context key to avoid to make the check when # user did already confirmed the wizard about expired lots. if res is True and not self.env.context.get('skip_expired'): pickings_to_warn_expired = self._check_expired_lots() if pickings_to_warn_expired: return pickings_to_warn_expired._action_generate_expired_wizard() return res def _check_expired_lots(self): expired_pickings = self.move_line_ids.filtered(lambda ml: ml.lot_id.product_expiry_alert).picking_id return expired_pickings def _action_generate_expired_wizard(self): expired_lot_ids = self.move_line_ids.filtered(lambda ml: ml.lot_id.product_expiry_alert).lot_id.ids view_id = self.env.ref('product_expiry.confirm_expiry_view').id context = dict(self.env.context) context.update({ 'default_picking_ids': [(6, 0, self.ids)], 'default_lot_ids': [(6, 0, expired_lot_ids)], }) return { 'name': _('Confirmation'), 'type': 'ir.actions.act_window', 'res_model': 'expiry.picking.confirmation', 'view_mode': 'form', 'views': [(view_id, 'form')], 'view_id': view_id, 'target': 'new', 'context': context, }
38.904762
1,634
805
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' group_expiry_date_on_delivery_slip = fields.Boolean("Display Expiration Dates on Delivery Slips", implied_group='product_expiry.group_expiry_date_on_delivery_slip') @api.onchange('group_lot_on_delivery_slip') def _onchange_group_lot_on_delivery_slip(self): if not self.group_lot_on_delivery_slip: self.group_expiry_date_on_delivery_slip = False @api.onchange('module_product_expiry') def _onchange_module_product_expiry(self): if not self.module_product_expiry: self.group_expiry_date_on_delivery_slip = False
38.333333
805
6,185
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo import api, fields, models, SUPERUSER_ID, _ class StockProductionLot(models.Model): _inherit = 'stock.production.lot' use_expiration_date = fields.Boolean( string='Use Expiration Date', related='product_id.use_expiration_date') expiration_date = fields.Datetime(string='Expiration Date', help='This is the date on which the goods with this Serial Number may become dangerous and must not be consumed.') use_date = fields.Datetime(string='Best before Date', help='This is the date on which the goods with this Serial Number start deteriorating, without being dangerous yet.') removal_date = fields.Datetime(string='Removal Date', help='This is the date on which the goods with this Serial Number should be removed from the stock. This date will be used in FEFO removal strategy.') alert_date = fields.Datetime(string='Alert Date', help='Date to determine the expired lots and serial numbers using the filter "Expiration Alerts".') product_expiry_alert = fields.Boolean(compute='_compute_product_expiry_alert', help="The Expiration Date has been reached.") product_expiry_reminded = fields.Boolean(string="Expiry has been reminded") @api.depends('expiration_date') def _compute_product_expiry_alert(self): current_date = fields.Datetime.now() for lot in self: if lot.expiration_date: lot.product_expiry_alert = lot.expiration_date <= current_date else: lot.product_expiry_alert = False def _get_dates(self, product_id=None): """Returns dates based on number of days configured in current lot's product.""" mapped_fields = { 'use_date': 'use_time', 'removal_date': 'removal_time', 'alert_date': 'alert_time' } res = {} product = self.env['product.product'].browse(product_id) or self.product_id if product.use_expiration_date: expiration_date = datetime.datetime.now() + datetime.timedelta(days=product.expiration_time) res['expiration_date'] = fields.Datetime.to_string(expiration_date) for field in mapped_fields: duration = getattr(product, mapped_fields[field]) date = expiration_date - datetime.timedelta(days=duration) res[field] = fields.Datetime.to_string(date) return res # Assign dates according to products data @api.model_create_multi def create(self, vals_list): for vals in vals_list: dates = self._get_dates(vals.get('product_id') or self.env.context.get('default_product_id')) for d in dates: if not vals.get(d): vals[d] = dates[d] return super().create(vals_list) @api.onchange('expiration_date') def _onchange_expiration_date(self): if not self._origin or not (self.expiration_date and self._origin.expiration_date): return time_delta = self.expiration_date - self._origin.expiration_date # As we compare expiration_date with _origin.expiration_date, we need to # use `_get_date_values` with _origin to keep a stability in the values. # Otherwise it will recompute from the updated values if the user calls # this onchange multiple times without save between each onchange. vals = self._origin._get_date_values(time_delta, self.expiration_date) self.update(vals) @api.onchange('product_id') def _onchange_product(self): dates_dict = self._get_dates() for field, value in dates_dict.items(): setattr(self, field, value) @api.model def _alert_date_exceeded(self): """Log an activity on internally stored lots whose alert_date has been reached. No further activity will be generated on lots whose alert_date has already been reached (even if the alert_date is changed). """ alert_lots = self.env['stock.production.lot'].search([ ('alert_date', '<=', fields.Date.today()), ('product_expiry_reminded', '=', False)]) lot_stock_quants = self.env['stock.quant'].search([ ('lot_id', 'in', alert_lots.ids), ('quantity', '>', 0), ('location_id.usage', '=', 'internal')]) alert_lots = lot_stock_quants.mapped('lot_id') for lot in alert_lots: lot.activity_schedule( 'product_expiry.mail_activity_type_alert_date_reached', user_id=lot.product_id.responsible_id.id or SUPERUSER_ID, note=_("The alert date has been reached for this lot/serial number") ) alert_lots.write({ 'product_expiry_reminded': True }) def _update_date_values(self, new_date): if new_date: time_delta = new_date - (self.expiration_date or fields.Datetime.now()) vals = self._get_date_values(time_delta, new_date) vals['expiration_date'] = new_date self.write(vals) def _get_date_values(self, time_delta, new_date=False): ''' Return a dict with different date values updated depending of the time_delta. Used in the onchange of `expiration_date` and when user defines a date at the receipt. ''' vals = { 'use_date': self.use_date and (self.use_date + time_delta) or new_date, 'removal_date': self.removal_date and (self.removal_date + time_delta) or new_date, 'alert_date': self.alert_date and (self.alert_date + time_delta) or new_date, } return vals class ProcurementGroup(models.Model): _inherit = 'procurement.group' @api.model def _run_scheduler_tasks(self, use_new_cursor=False, company_id=False): super(ProcurementGroup, self)._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id) self.env['stock.production.lot']._alert_date_exceeded() if use_new_cursor: self.env.cr.commit()
46.856061
6,185
1,059
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Serbia - Accounting", "version": "1.0", "category": "Accounting/Localizations/Account Charts", "description": """ This is the base module of the Serbian localization. It manages chart of accounts and taxes. """, "author": "Modoolar, Odoo S.A.", "depends": ["account", "base_vat"], "data": [ "data/account_chart_template_data.xml", "data/account.account.template.csv", "data/l10n_rs_chart_data.xml", "data/account_tax_group_data.xml", 'data/account_tax_report_data.xml', "data/account_tax_template_data.xml", "data/fiscal_position_data.xml", "data/account.group.template.csv", "data/account_chart_template_configure_data.xml", "data/menuitem_data.xml", "views/account_move.xml", "views/res_partner.xml", "views/report_invoice.xml", ], "demo": ["demo/demo_company.xml"], "license": "LGPL-3", }
35.3
1,059
373
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class AccountMove(models.Model): _inherit = 'account.move' l10n_rs_company_registry = fields.Char(string='Company ID', related='partner_id.l10n_rs_company_registry') l10n_rs_turnover_date = fields.Date(string='Turnover Date')
33.909091
373
568
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class ResPartner(models.Model): _inherit = 'res.partner' l10n_rs_company_registry = fields.Char(string='Company ID', help='The registry number of the company.') _sql_constraints = [ ( 'company_registry_country_uniq', 'unique (l10n_rs_company_registry, country_id)', 'The company registry of the partner must be unique across all partners of a same country !' ) ]
31.555556
568
580
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Alipay Payment Acquirer', 'category': 'Accounting/Payment Acquirers', 'version': '2.0', 'sequence': 345, 'summary': 'Payment Acquirer: Alipay Implementation', 'description': """Alipay Payment Acquirer""", 'depends': ['payment'], 'data': [ 'views/payment_alipay_templates.xml', 'views/payment_views.xml', 'data/payment_acquirer_data.xml', ], 'application': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
30.526316
580
778
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 AlipayCommon(PaymentCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.currency_yuan = cls._prepare_currency('CNY') cls.alipay = cls._prepare_acquirer('alipay', update_values={ 'alipay_merchant_partner_id': 'dummy', 'alipay_md5_signature_key': 'dummy', 'alipay_seller_email': 'dummy', 'fees_active': False, # Only activate fees in dedicated tests }) # override defaults for helpers cls.acquirer = cls.alipay cls.currency = cls.currency_yuan
35.363636
778
8,076
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo.tools import mute_logger from .common import AlipayCommon from ..controllers.main import AlipayController @tagged('post_install', '-at_install') class AlipayTest(AlipayCommon): def test_compatible_acquirers(self): self.alipay.alipay_payment_method = 'express_checkout' acquirers = self.env['payment.acquirer']._get_compatible_acquirers( partner_id=self.partner.id, currency_id=self.currency_yuan.id, # 'CNY' company_id=self.company.id, ) self.assertIn(self.alipay, acquirers) acquirers = self.env['payment.acquirer']._get_compatible_acquirers( partner_id=self.partner.id, currency_id=self.currency_euro.id, company_id=self.company.id, ) self.assertNotIn(self.alipay, acquirers) self.alipay.alipay_payment_method = 'standard_checkout' acquirers = self.env['payment.acquirer']._get_compatible_acquirers( partner_id=self.partner.id, currency_id=self.currency_yuan.id, # 'CNY' company_id=self.company.id, ) self.assertIn(self.alipay, acquirers) acquirers = self.env['payment.acquirer']._get_compatible_acquirers( partner_id=self.partner.id, currency_id=self.currency_euro.id, company_id=self.company.id, ) self.assertIn(self.alipay, acquirers) def test_01_redirect_form_standard_checkout(self): self.alipay.alipay_payment_method = 'standard_checkout' self._test_alipay_redirect_form() def test_02_redirect_form_express_checkout(self): self.alipay.alipay_payment_method = 'express_checkout' self._test_alipay_redirect_form() def _test_alipay_redirect_form(self): tx = self.create_transaction(flow='redirect') # Only flow implemented expected_values = { '_input_charset': 'utf-8', 'notify_url': self._build_url(AlipayController._notify_url), 'out_trade_no': self.reference, 'partner': self.alipay.alipay_merchant_partner_id, 'return_url': self._build_url(AlipayController._return_url), 'subject': self.reference, 'total_fee': str(self.amount), # Fees disabled by default } if self.alipay.alipay_payment_method == 'standard_checkout': expected_values.update({ 'service': 'create_forex_trade', 'product_code': 'NEW_OVERSEAS_SELLER', 'currency': self.currency_yuan.name, }) else: expected_values.update({ 'service': 'create_direct_pay_by_user', 'payment_type': str(1), 'seller_email': self.alipay.alipay_seller_email, }) sign = self.alipay._alipay_build_sign(expected_values) with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx._get_processing_values() redirect_form_data = self._extract_values_from_html_form(processing_values['redirect_form_html']) expected_values.update({ 'sign': sign, 'sign_type': 'MD5', }) self.assertEqual( redirect_form_data['action'], 'https://openapi.alipaydev.com/gateway.do', ) self.assertDictEqual( expected_values, redirect_form_data['inputs'], "Alipay: invalid inputs specified in the redirect form.", ) def test_03_redirect_form_with_fees(self): # update acquirer: compute fees self.alipay.write({ 'fees_active': True, 'fees_dom_fixed': 1.0, 'fees_dom_var': 0.35, 'fees_int_fixed': 1.5, 'fees_int_var': 0.50, }) transaction_fees = self.currency.round( self.alipay._compute_fees( self.amount, self.currency, self.partner.country_id, ) ) self.assertEqual(transaction_fees, 7.09) total_fee = self.currency.round(self.amount + transaction_fees) self.assertEqual(total_fee, 1118.2) tx = self.create_transaction(flow='redirect') self.assertEqual(tx.fees, 7.09) with mute_logger('odoo.addons.payment.models.payment_transaction'): processing_values = tx._get_processing_values() redirect_form_data = self._extract_values_from_html_form(processing_values['redirect_form_html']) self.assertEqual(redirect_form_data['inputs']['total_fee'], f'{total_fee:.2f}') def test_21_standard_checkout_feedback(self): self.alipay.alipay_payment_method = 'standard_checkout' self.currency = self.currency_euro self._test_alipay_feedback_processing() def test_22_express_checkout_feedback(self): self.alipay.alipay_payment_method = 'express_checkout' self.currency = self.currency_yuan self._test_alipay_feedback_processing() def _test_alipay_feedback_processing(self): # typical data posted by alipay after client has successfully paid custom_reference = 'test_ref_' + self.alipay.alipay_payment_method alipay_post_data = { 'trade_no': '2017112321001003690200384552', 'reference': custom_reference, 'total_fee': 1.95, 'trade_status': 'TRADE_CLOSED', } if self.alipay.alipay_payment_method == 'express_checkout': alipay_post_data.update({ 'seller_email': self.alipay.alipay_seller_email, }) else: alipay_post_data.update({ 'currency': 'EUR', }) alipay_post_data['sign'] = self.alipay._alipay_build_sign(alipay_post_data) with self.assertRaises(ValidationError): # unknown transactiion self.env['payment.transaction']._handle_feedback_data('alipay', alipay_post_data) tx = self.env['payment.transaction'].create({ 'amount': 1.95, 'acquirer_id': self.alipay.id, 'currency_id': self.currency.id, 'reference': custom_reference, 'partner_id': self.partner.id }) self.env['payment.transaction']._handle_feedback_data('alipay', alipay_post_data) self.assertEqual(tx.state, 'cancel', 'Alipay: wrong state after receiving a valid pending notification') self.assertEqual(tx.acquirer_reference, '2017112321001003690200384552', 'Alipay: wrong txn_id after receiving a valid pending notification') # reset the transaction tx.write({'state': 'draft', 'acquirer_reference': False}) # update notification from alipay should not go through since it has already been set as 'done' if self.alipay.alipay_payment_method == 'standard_checkout': alipay_post_data['trade_status'] = 'TRADE_FINISHED' else: alipay_post_data['trade_status'] = 'TRADE_SUCCESS' alipay_post_data['sign'] = self.alipay._alipay_build_sign(alipay_post_data) self.env['payment.transaction']._handle_feedback_data('alipay', alipay_post_data) self.assertEqual(tx.acquirer_reference, '2017112321001003690200384552', 'Alipay: notification should not go throught since it has already been validated') # this time it should go through since the transaction is not validated yet tx.write({'state': 'draft', 'acquirer_reference': False}) self.env['payment.transaction']._handle_feedback_data('alipay', alipay_post_data) self.assertEqual(tx.state, 'done', 'Alipay: wrong state after receiving a valid pending notification') self.assertEqual(tx.acquirer_reference, '2017112321001003690200384552', 'Alipay: wrong txn_id after receiving a valid pending notification')
41.84456
8,076
6,953
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from werkzeug import urls from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.tools.float_utils import float_compare from odoo.addons.payment_alipay.controllers.main import AlipayController _logger = logging.getLogger(__name__) class PaymentTransaction(models.Model): _inherit = 'payment.transaction' def _get_specific_rendering_values(self, processing_values): """ Override of payment to return Alipay-specific rendering values. Note: self.ensure_one() from `_get_processing_values` :param dict processing_values: The generic and specific processing values of the transaction :return: The dict of acquirer-specific processing values :rtype: dict """ res = super()._get_specific_rendering_values(processing_values) if self.provider != 'alipay': return res base_url = self.acquirer_id.get_base_url() if self.fees: # Similarly to what is done in `payment::payment.transaction.create`, we need to round # the sum of the amount and of the fees to avoid inconsistent string representations. # E.g., str(1111.11 + 7.09) == '1118.1999999999998' total_fee = self.currency_id.round(self.amount + self.fees) else: total_fee = self.amount rendering_values = { '_input_charset': 'utf-8', 'notify_url': urls.url_join(base_url, AlipayController._notify_url), 'out_trade_no': self.reference, 'partner': self.acquirer_id.alipay_merchant_partner_id, 'return_url': urls.url_join(base_url, AlipayController._return_url), 'subject': self.reference, 'total_fee': f'{total_fee:.2f}', } if self.acquirer_id.alipay_payment_method == 'standard_checkout': # https://global.alipay.com/docs/ac/global/create_forex_trade rendering_values.update({ 'service': 'create_forex_trade', 'product_code': 'NEW_OVERSEAS_SELLER', 'currency': self.currency_id.name, }) else: rendering_values.update({ 'service': 'create_direct_pay_by_user', 'payment_type': 1, 'seller_email': self.acquirer_id.alipay_seller_email, }) sign = self.acquirer_id._alipay_build_sign(rendering_values) rendering_values.update({ 'sign_type': 'MD5', 'sign': sign, 'api_url': self.acquirer_id._alipay_get_api_url(), }) return rendering_values @api.model def _get_tx_from_feedback_data(self, provider, data): """ Override of payment to find the transaction based on Alipay data. :param str provider: The provider of the acquirer that handled the transaction :param dict data: The feedback data sent by the provider :return: The transaction if found :rtype: recordset of `payment.transaction` :raise: ValidationError if inconsistent data were received :raise: ValidationError if the data match no transaction """ tx = super()._get_tx_from_feedback_data(provider, data) if provider != 'alipay': return tx reference = data.get('reference') or data.get('out_trade_no') txn_id = data.get('trade_no') if not reference or not txn_id: raise ValidationError( "Alipay: " + _( "Received data with missing reference %(r)s or txn_id %(t)s.", r=reference, t=txn_id ) ) tx = self.search([('reference', '=', reference), ('provider', '=', 'alipay')]) if not tx: raise ValidationError( "Alipay: " + _("No transaction found matching reference %s.", reference) ) # Verify signature (done here because we need the reference to get the acquirer) sign_check = tx.acquirer_id._alipay_build_sign(data) sign = data.get('sign') if sign != sign_check: raise ValidationError( "Alipay: " + _( "Expected signature %(sc) but received %(sign)s.", sc=sign_check, sign=sign ) ) return tx def _process_feedback_data(self, data): """ Override of payment to process the transaction based on Alipay data. Note: self.ensure_one() :param dict data: The feedback data sent by the provider :return: None :raise: ValidationError if inconsistent data were received """ super()._process_feedback_data(data) if self.provider != 'alipay': return if float_compare(float(data.get('total_fee', '0.0')), (self.amount + self.fees), 2) != 0: # mc_gross is amount + fees logging_values = { 'amount': data.get('total_fee', '0.0'), 'total': self.amount, 'fees': self.fees, 'reference': self.reference, } _logger.error( "the paid amount (%(amount)s) does not match the total + fees (%(total)s + " "%(fees)s) for the transaction with reference %(reference)s", logging_values ) raise ValidationError("Alipay: " + _("The amount does not match the total + fees.")) if self.acquirer_id.alipay_payment_method == 'standard_checkout': if data.get('currency') != self.currency_id.name: raise ValidationError( "Alipay: " + _( "The currency returned by Alipay %(rc)s does not match the transaction " "currency %(tc)s.", rc=data.get('currency'), tc=self.currency_id.name ) ) elif data.get('seller_email') != self.acquirer_id.alipay_seller_email: _logger.error( "the seller email (%s) does not match the configured Alipay account (%s).", data.get('seller_email'), self.acquirer_id.alipay_seller_email ) raise ValidationError( "Alipay: " + _("The seller email does not match the configured Alipay account.") ) self.acquirer_reference = data.get('trade_no') status = data.get('trade_status') if status in ['TRADE_FINISHED', 'TRADE_SUCCESS']: self._set_done() elif status == 'TRADE_CLOSED': self._set_canceled() else: _logger.info( "received invalid transaction status for transaction with reference %s: %s", self.reference, status ) self._set_error("Alipay: " + _("received invalid transaction status: %s", status))
41.386905
6,953
429
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['alipay'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]} return res
30.642857
429
2,858
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from hashlib import md5 from odoo import api, fields, models _logger = logging.getLogger(__name__) class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection( selection_add=[('alipay', "Alipay")], ondelete={'alipay': 'set default'}) alipay_payment_method = fields.Selection( string="Account", help="* Cross-border: For the overseas seller \n* Express Checkout: For the Chinese Seller", selection=[ ('express_checkout', 'Express Checkout (only for Chinese merchants)'), ('standard_checkout', 'Cross-border') ], default='express_checkout', required_if_provider='alipay') alipay_merchant_partner_id = fields.Char( string="Merchant Partner ID", help="The public partner ID solely used to identify the account with Alipay", required_if_provider='alipay') alipay_md5_signature_key = fields.Char( string="MD5 Signature Key", required_if_provider='alipay', groups='base.group_system') alipay_seller_email = fields.Char( string="Alipay Seller Email", help="The public Alipay partner email") @api.model def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs): """ Override of payment to unlist Alipay acquirers for unsupported currencies. """ acquirers = super()._get_compatible_acquirers(*args, currency_id=currency_id, **kwargs) currency = self.env['res.currency'].browse(currency_id).exists() if currency and currency.name != 'CNY': acquirers = acquirers.filtered( lambda a: a.provider != 'alipay' or a.alipay_payment_method != 'express_checkout' ) return acquirers def _alipay_build_sign(self, val): # Rearrange parameters in the data set alphabetically data_to_sign = sorted(val.items()) # Format key-value pairs of parameters that should be signed data_to_sign = [f"{k}={v}" for k, v in data_to_sign if k not in ['sign', 'sign_type', 'reference']] # Build the data string of &-separated key-value pairs data_string = '&'.join(data_to_sign) data_string += self.alipay_md5_signature_key return md5(data_string.encode('utf-8')).hexdigest() def _alipay_get_api_url(self): if self.state == 'enabled': return 'https://mapi.alipay.com/gateway.do' else: # test environment return 'https://openapi.alipaydev.com/gateway.do' def _get_default_payment_method_id(self): self.ensure_one() if self.provider != 'alipay': return super()._get_default_payment_method_id() return self.env.ref('payment_alipay.payment_method_alipay').id
43.30303
2,858
2,349
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import pprint import requests from odoo import _, http from odoo.exceptions import ValidationError from odoo.http import request _logger = logging.getLogger(__name__) class AlipayController(http.Controller): _return_url = '/payment/alipay/return' _notify_url = '/payment/alipay/notify' @http.route(_return_url, type='http', auth="public", methods=['GET']) def alipay_return_from_redirect(self, **data): """ Alipay return """ _logger.info("received Alipay return data:\n%s", pprint.pformat(data)) request.env['payment.transaction'].sudo()._handle_feedback_data('alipay', data) return request.redirect('/payment/status') @http.route(_notify_url, type='http', auth='public', methods=['POST'], csrf=False) def alipay_notify(self, **post): """ Alipay Notify """ _logger.info("received Alipay notification data:\n%s", pprint.pformat(post)) self._alipay_validate_notification(**post) request.env['payment.transaction'].sudo()._handle_feedback_data('alipay', post) return 'success' # Return 'success' to stop receiving notifications for this tx def _alipay_validate_notification(self, **post): tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_feedback_data( 'alipay', post ) if not tx_sudo: raise ValidationError( "Alipay: " + _( "Received notification data with unknown reference:\n%s", pprint.pformat(post) ) ) # Ensure that the notification was sent by Alipay # See https://global.alipay.com/docs/ac/wap/async acquirer_sudo = tx_sudo.acquirer_id val = { 'service': 'notify_verify', 'partner': acquirer_sudo.alipay_merchant_partner_id, 'notify_id': post['notify_id'] } response = requests.post(acquirer_sudo._alipay_get_api_url(), val, timeout=60) response.raise_for_status() if response.text != 'true': raise ValidationError( "Alipay: " + _( "Received notification data not acknowledged by Alipay:\n%s", pprint.pformat(post) ) )
38.508197
2,349
823
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Sales and MRP Management', 'version': '1.0', 'category': 'Hidden', 'description': """ This module provides facility to the user to install mrp and sales modulesat a time. ==================================================================================== It is basically used when we want to keep track of production orders generated from sales order. It adds sales name and sales Reference on production order. """, 'depends': ['mrp', 'sale_stock'], 'data': [ 'security/ir.model.access.csv', 'views/mrp_production_views.xml', 'views/sale_order_views.xml' ], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
31.653846
823
28,086
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase, Form class TestSaleMrpKitBom(TransactionCase): def _create_product(self, name, product_type, price): return self.env['product.product'].create({ 'name': name, 'type': product_type, 'standard_price': price, }) def test_sale_mrp_kit_bom_cogs(self): """Check invoice COGS aml after selling and delivering a product with Kit BoM having another product with Kit BoM as component""" # ---------------------------------------------- # BoM of Kit A: # - BoM Type: Kit # - Quantity: 3 # - Components: # * 2 x Kit B # * 1 x Component A (Cost: $3, Storable) # # BoM of Kit B: # - BoM Type: Kit # - Quantity: 10 # - Components: # * 2 x Component B (Cost: $4, Storable) # * 3 x Component BB (Cost: $5, Consumable) # ---------------------------------------------- self.env.user.company_id.anglo_saxon_accounting = True self.env.ref('base.USD').active = True self.stock_input_account = self.env['account.account'].create({ 'name': 'Stock Input', 'code': 'StockIn', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, }) self.stock_output_account = self.env['account.account'].create({ 'name': 'Stock Output', 'code': 'StockOut', 'reconcile': True, 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, }) self.stock_valuation_account = self.env['account.account'].create({ 'name': 'Stock Valuation', 'code': 'StockVal', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, }) self.expense_account = self.env['account.account'].create({ 'name': 'Expense Account', 'code': 'Exp', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, }) self.income_account = self.env['account.account'].create({ 'name': 'Income Account', 'code': 'Inc', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, }) self.stock_journal = self.env['account.journal'].create({ 'name': 'Stock Journal', 'code': 'STJTEST', 'type': 'general', }) self.recv_account = self.env['account.account'].create({ 'name': 'account receivable', 'code': 'RECV', 'user_type_id': self.env.ref('account.data_account_type_receivable').id, 'reconcile': True, }) self.pay_account = self.env['account.account'].create({ 'name': 'account payable', 'code': 'PAY', 'user_type_id': self.env.ref('account.data_account_type_payable').id, 'reconcile': True, }) self.customer = self.env['res.partner'].create({ 'name': 'customer', 'property_account_receivable_id': self.recv_account.id, 'property_account_payable_id': self.pay_account.id, }) self.journal_sale = self.env['account.journal'].create({ 'name': 'Sale Journal - Test', 'code': 'AJ-SALE', 'type': 'sale', 'company_id': self.env.user.company_id.id, }) self.component_a = self._create_product('Component A', 'product', 3.00) self.component_b = self._create_product('Component B', 'product', 4.00) self.component_bb = self._create_product('Component BB', 'consu', 5.00) self.kit_a = self._create_product('Kit A', 'product', 0.00) self.kit_b = self._create_product('Kit B', 'consu', 0.00) self.kit_a.write({ 'categ_id': self.env.ref('product.product_category_all').id, 'property_account_expense_id': self.expense_account.id, 'property_account_income_id': self.income_account.id, }) self.kit_a.categ_id.write({ 'property_stock_account_input_categ_id': self.stock_input_account.id, 'property_stock_account_output_categ_id': self.stock_output_account.id, 'property_stock_valuation_account_id': self.stock_valuation_account.id, 'property_stock_journal': self.stock_journal.id, 'property_valuation': 'real_time', }) # Create BoM for Kit A bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.kit_a bom_product_form.product_tmpl_id = self.kit_a.product_tmpl_id bom_product_form.product_qty = 3.0 bom_product_form.type = 'phantom' with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.kit_b bom_line.product_qty = 2.0 with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.component_a bom_line.product_qty = 1.0 self.bom_a = bom_product_form.save() # Create BoM for Kit B bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.kit_b bom_product_form.product_tmpl_id = self.kit_b.product_tmpl_id bom_product_form.product_qty = 10.0 bom_product_form.type = 'phantom' with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.component_b bom_line.product_qty = 2.0 with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.component_bb bom_line.product_qty = 3.0 self.bom_b = bom_product_form.save() so = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'order_line': [ (0, 0, { 'name': self.kit_a.name, 'product_id': self.kit_a.id, 'product_uom_qty': 1.0, 'product_uom': self.kit_a.uom_id.id, 'price_unit': 1, 'tax_id': False, })], }) so.action_confirm() so.picking_ids.move_lines.quantity_done = 1 so.picking_ids.button_validate() invoice = so.with_context(default_journal_id=self.journal_sale.id)._create_invoices() invoice.action_post() # Check the resulting accounting entries amls = invoice.line_ids self.assertEqual(len(amls), 4) stock_out_aml = amls.filtered(lambda aml: aml.account_id == self.stock_output_account) self.assertEqual(stock_out_aml.debit, 0) self.assertAlmostEqual(stock_out_aml.credit, 1.53, "Should not include the value of consumable component") cogs_aml = amls.filtered(lambda aml: aml.account_id == self.expense_account) self.assertAlmostEqual(cogs_aml.debit, 1.53, "Should not include the value of consumable component") self.assertEqual(cogs_aml.credit, 0) def test_reset_avco_kit(self): """ Test a specific use case : One product with 2 variant, each variant has its own BoM with either component_1 or component_2. Create a SO for one of the variant, confirm, cancel, reset to draft and then change the product of the SO -> There should be no traceback """ component_1 = self.env['product.product'].create({'name': 'compo 1'}) component_2 = self.env['product.product'].create({'name': 'compo 2'}) product_category = self.env['product.category'].create({ 'name': 'test avco kit', 'property_cost_method': 'average' }) attributes = self.env['product.attribute'].create({'name': 'Legs'}) steel_legs = self.env['product.attribute.value'].create({'attribute_id': attributes.id, 'name': 'Steel'}) aluminium_legs = self.env['product.attribute.value'].create( {'attribute_id': attributes.id, 'name': 'Aluminium'}) product_template = self.env['product.template'].create({ 'name': 'test product', 'categ_id': product_category.id, 'attribute_line_ids': [(0, 0, { 'attribute_id': attributes.id, 'value_ids': [(6, 0, [steel_legs.id, aluminium_legs.id])] })] }) product_variant_ids = product_template.product_variant_ids # BoM 1 with component_1 self.env['mrp.bom'].create({ 'product_id': product_variant_ids[0].id, 'product_tmpl_id': product_variant_ids[0].product_tmpl_id.id, 'product_qty': 1.0, 'consumption': 'flexible', 'type': 'phantom', 'bom_line_ids': [(0, 0, {'product_id': component_1.id, 'product_qty': 1})] }) # BoM 2 with component_2 self.env['mrp.bom'].create({ 'product_id': product_variant_ids[1].id, 'product_tmpl_id': product_variant_ids[1].product_tmpl_id.id, 'product_qty': 1.0, 'consumption': 'flexible', 'type': 'phantom', 'bom_line_ids': [(0, 0, {'product_id': component_2.id, 'product_qty': 1})] }) partner = self.env['res.partner'].create({'name': 'Testing Man'}) so = self.env['sale.order'].create({ 'partner_id': partner.id, }) # Create the order line self.env['sale.order.line'].create({ 'name': "Order line", 'product_id': product_variant_ids[0].id, 'order_id': so.id, }) so.action_confirm() so._action_cancel() so.action_draft() with Form(so) as so_form: with so_form.order_line.edit(0) as order_line_change: # The actual test, there should be no traceback here order_line_change.product_id = product_variant_ids[1] def test_sale_mrp_kit_cost(self): """ Check the total cost of a KIT: # BoM of Kit A: # - BoM Type: Kit # - Quantity: 1 # - Components: # * 1 x Component A (Cost: $ 6, QTY: 1, UOM: Dozens) # * 1 x Component B (Cost: $ 10, QTY: 2, UOM: Unit) # cost of Kit A = (6 * 1 * 12) + (10 * 2) = $ 92 """ self.customer = self.env['res.partner'].create({ 'name': 'customer' }) self.kit_product = self._create_product('Kit Product', 'product', 1.00) # Creating components self.component_a = self._create_product('Component A', 'product', 1.00) self.component_a.product_tmpl_id.standard_price = 6 self.component_b = self._create_product('Component B', 'product', 1.00) self.component_b.product_tmpl_id.standard_price = 10 cat = self.env['product.category'].create({ 'name': 'fifo', 'property_cost_method': 'fifo' }) self.kit_product.product_tmpl_id.categ_id = cat self.component_a.product_tmpl_id.categ_id = cat self.component_b.product_tmpl_id.categ_id = cat self.bom = self.env['mrp.bom'].create({ 'product_tmpl_id': self.kit_product.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom' }) self.env['mrp.bom.line'].create({ 'product_id': self.component_a.id, 'product_qty': 1.0, 'bom_id': self.bom.id, 'product_uom_id': self.env.ref('uom.product_uom_dozen').id, }) self.env['mrp.bom.line'].create({ 'product_id': self.component_b.id, 'product_qty': 2.0, 'bom_id': self.bom.id, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, }) # Create a SO with one unit of the kit product so = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'order_line': [ (0, 0, { 'name': self.kit_product.name, 'product_id': self.kit_product.id, 'product_uom_qty': 1.0, 'product_uom': self.kit_product.uom_id.id, })], }) so.action_confirm() line = so.order_line purchase_price = line.product_id.with_company(line.company_id)._compute_average_price(0, line.product_uom_qty, line.move_ids) self.assertEqual(purchase_price, 92, "The purchase price must be the total cost of the components multiplied by their unit of measure") def test_qty_delivered_with_bom(self): """Check the quantity delivered, when a bom line has a non integer quantity""" self.env.ref('product.decimal_product_uom').digits = 5 self.kit = self._create_product('Kit', 'product', 0.00) self.comp = self._create_product('Component', 'product', 0.00) # Create BoM for Kit bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.kit bom_product_form.product_tmpl_id = self.kit.product_tmpl_id bom_product_form.product_qty = 1.0 bom_product_form.type = 'phantom' with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.comp bom_line.product_qty = 0.08600 self.bom = bom_product_form.save() self.customer = self.env['res.partner'].create({ 'name': 'customer', }) so = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'order_line': [ (0, 0, { 'name': self.kit.name, 'product_id': self.kit.id, 'product_uom_qty': 10.0, 'product_uom': self.kit.uom_id.id, 'price_unit': 1, 'tax_id': False, })], }) so.action_confirm() self.assertTrue(so.picking_ids) self.assertEqual(so.order_line.qty_delivered, 0) picking = so.picking_ids picking.move_lines.quantity_done = 0.86000 picking.button_validate() # Checks the delivery amount (must be 10). self.assertEqual(so.order_line.qty_delivered, 10) def test_qty_delivered_with_bom_using_kit(self): """Check the quantity delivered, when one product is a kit and his bom uses another product that is also a kit""" self.kitA = self._create_product('Kit A', 'consu', 0.00) self.kitB = self._create_product('Kit B', 'consu', 0.00) self.compA = self._create_product('ComponentA', 'consu', 0.00) self.compB = self._create_product('ComponentB', 'consu', 0.00) # Create BoM for KitB bom_product_formA = Form(self.env['mrp.bom']) bom_product_formA.product_id = self.kitB bom_product_formA.product_tmpl_id = self.kitB.product_tmpl_id bom_product_formA.product_qty = 1.0 bom_product_formA.type = 'phantom' with bom_product_formA.bom_line_ids.new() as bom_line: bom_line.product_id = self.compA bom_line.product_qty = 1 with bom_product_formA.bom_line_ids.new() as bom_line: bom_line.product_id = self.compB bom_line.product_qty = 1 self.bomA = bom_product_formA.save() # Create BoM for KitA bom_product_formB = Form(self.env['mrp.bom']) bom_product_formB.product_id = self.kitA bom_product_formB.product_tmpl_id = self.kitA.product_tmpl_id bom_product_formB.product_qty = 1.0 bom_product_formB.type = 'phantom' with bom_product_formB.bom_line_ids.new() as bom_line: bom_line.product_id = self.compA bom_line.product_qty = 1 with bom_product_formB.bom_line_ids.new() as bom_line: bom_line.product_id = self.kitB bom_line.product_qty = 1 self.bomB = bom_product_formB.save() self.customer = self.env['res.partner'].create({ 'name': 'customer', }) so = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'order_line': [ (0, 0, { 'name': self.kitA.name, 'product_id': self.kitA.id, 'product_uom_qty': 1.0, 'product_uom': self.kitA.uom_id.id, 'price_unit': 1, 'tax_id': False, })], }) so.action_confirm() self.assertTrue(so.picking_ids) self.assertEqual(so.order_line.qty_delivered, 0) picking = so.picking_ids action = picking.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() # Checks the delivery amount (must be 1). self.assertEqual(so.order_line.qty_delivered, 1) def test_sale_kit_show_kit_in_delivery(self): """Create a kit with 2 product and activate 2 steps delivery and check that every stock move contains a bom_line_id """ wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) wh.write({'delivery_steps': 'pick_ship'}) kitA = self._create_product('Kit Product', 'product', 0.00) compA = self._create_product('ComponentA', 'product', 0.00) compB = self._create_product('ComponentB', 'product', 0.00) # Create BoM for KitB bom_product_formA = Form(self.env['mrp.bom']) bom_product_formA.product_id = kitA bom_product_formA.product_tmpl_id = kitA.product_tmpl_id bom_product_formA.product_qty = 1.0 bom_product_formA.type = 'phantom' with bom_product_formA.bom_line_ids.new() as bom_line: bom_line.product_id = compA bom_line.product_qty = 1 with bom_product_formA.bom_line_ids.new() as bom_line: bom_line.product_id = compB bom_line.product_qty = 1 bom_product_formA.save() customer = self.env['res.partner'].create({ 'name': 'customer', }) so = self.env['sale.order'].create({ 'partner_id': customer.id, 'order_line': [ (0, 0, { 'name': kitA.name, 'product_id': kitA.id, 'product_uom_qty': 1.0, 'product_uom': kitA.uom_id.id, 'price_unit': 1, 'tax_id': False, })] }) so.action_confirm() pick = so.picking_ids[0] ship = so.picking_ids[1] self.assertTrue(pick.move_ids_without_package[0].bom_line_id, "All component from kits should have a bom line") self.assertTrue(pick.move_ids_without_package[1].bom_line_id, "All component from kits should have a bom line") self.assertTrue(ship.move_ids_without_package[0].bom_line_id, "All component from kits should have a bom line") self.assertTrue(ship.move_ids_without_package[1].bom_line_id, "All component from kits should have a bom line") def test_qty_delivered_with_bom_using_kit2(self): """Create 2 kits products that have common components and activate 2 steps delivery Then create a sale order with these 2 products, and put everything in a pack in the first step of the delivery. After the shipping is done, check the done quantity is correct for each products. """ wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1) wh.write({'delivery_steps': 'pick_ship'}) kitAB = self._create_product('Kit AB', 'product', 0.00) kitABC = self._create_product('Kit ABC', 'product', 0.00) compA = self._create_product('ComponentA', 'product', 0.00) compB = self._create_product('ComponentB', 'product', 0.00) compC = self._create_product('ComponentC', 'product', 0.00) # Create BoM for KitB bom_product_formA = Form(self.env['mrp.bom']) bom_product_formA.product_id = kitAB bom_product_formA.product_tmpl_id = kitAB.product_tmpl_id bom_product_formA.product_qty = 1.0 bom_product_formA.type = 'phantom' with bom_product_formA.bom_line_ids.new() as bom_line: bom_line.product_id = compA bom_line.product_qty = 1 with bom_product_formA.bom_line_ids.new() as bom_line: bom_line.product_id = compB bom_line.product_qty = 1 bom_product_formA.save() # Create BoM for KitA bom_product_formB = Form(self.env['mrp.bom']) bom_product_formB.product_id = kitABC bom_product_formB.product_tmpl_id = kitABC.product_tmpl_id bom_product_formB.product_qty = 1.0 bom_product_formB.type = 'phantom' with bom_product_formB.bom_line_ids.new() as bom_line: bom_line.product_id = compA bom_line.product_qty = 1 with bom_product_formB.bom_line_ids.new() as bom_line: bom_line.product_id = compB bom_line.product_qty = 1 with bom_product_formB.bom_line_ids.new() as bom_line: bom_line.product_id = compC bom_line.product_qty = 1 bom_product_formB.save() customer = self.env['res.partner'].create({ 'name': 'customer', }) so = self.env['sale.order'].create({ 'partner_id': customer.id, 'order_line': [ (0, 0, { 'name': kitAB.name, 'product_id': kitAB.id, 'product_uom_qty': 1.0, 'product_uom': kitAB.uom_id.id, 'price_unit': 1, 'tax_id': False, }), (0, 0, { 'name': kitABC.name, 'product_id': kitABC.id, 'product_uom_qty': 1.0, 'product_uom': kitABC.uom_id.id, 'price_unit': 1, 'tax_id': False, })], }) so.action_confirm() pick = so.picking_ids[0] ship = so.picking_ids[1] pick.move_lines[0].quantity_done = 2 pick.move_lines[1].quantity_done = 2 pick.move_lines[2].quantity_done = 1 pick.action_put_in_pack() pick.button_validate() ship.package_level_ids.write({'is_done': True}) ship.package_level_ids._set_is_done() for move in ship.move_line_ids: self.assertEqual(move.product_uom_qty, move.qty_done, "Quantity done should be equal to the quantity reserved in the move line") def test_kit_in_delivery_slip(self): """ Suppose this structure: Sale order: - Kit 1 with a sales description("test"): |- Compo 1 - Product 1 - Kit 2 * Variant 1 - Compo 1 * Variant 2 - Compo 1 - Kit 4: - Compo 1 - Kit 5 - Kit 4 - Compo 1 This test ensures that, when delivering a Kit product with a sales description, the delivery report is correctly printed with all the products. """ kit_1, component_1, product_1, kit_3, kit_4 = self.env['product.product'].create([{ 'name': n, 'type': 'product', } for n in ['Kit 1', 'Compo 1', 'Product 1', 'Kit 3', 'Kit 4']]) kit_1.description_sale = "test" self.env['mrp.bom'].create([{ 'product_tmpl_id': kit_1.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': component_1.id, 'product_qty': 1}), ], }]) colors = ['red', 'blue'] prod_attr = self.env['product.attribute'].create({'name': 'Color', 'create_variant': 'always'}) prod_attr_values = self.env['product.attribute.value'].create([{'name': color, 'attribute_id': prod_attr.id, 'sequence': 1} for color in colors]) kit_2 = self.env['product.template'].create({ 'name': 'Kit 2', 'attribute_line_ids': [(0, 0, { 'attribute_id': prod_attr.id, 'value_ids': [(6, 0, prod_attr_values.ids)] })] }) self.env['mrp.bom'].create([{ 'product_tmpl_id': kit_2.id, 'product_id': kit_2.product_variant_ids[0].id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': component_1.id, 'product_qty': 1}), ], }]) self.env['mrp.bom'].create([{ 'product_tmpl_id': kit_2.id, 'product_id': kit_2.product_variant_ids[1].id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': component_1.id, 'product_qty': 1}), ], }]) self.env['mrp.bom'].create([{ 'product_tmpl_id': kit_3.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': component_1.id, 'product_qty': 1}), ], }]) self.env['mrp.bom'].create([{ 'product_tmpl_id': kit_4.product_tmpl_id.id, 'product_qty': 1, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': component_1.id, 'product_qty': 1}), (0, 0, {'product_id': kit_3.id, 'product_qty': 1}), ], }]) customer = self.env['res.partner'].create({ 'name': 'customer', }) so = self.env['sale.order'].create({ 'partner_id': customer.id, 'order_line': [ (0, 0, { 'product_id': kit_1.id, 'product_uom_qty': 1.0, }), (0, 0, { 'product_id': product_1.id, 'product_uom_qty': 1.0, }), (0, 0, { 'product_id': kit_2.product_variant_ids[0].id, 'product_uom_qty': 1.0, }), (0, 0, { 'product_id': kit_2.product_variant_ids[1].id, 'product_uom_qty': 1.0, }), (0, 0, { 'product_id': kit_3.id, 'product_uom_qty': 1.0, }), (0, 0, { 'product_id': kit_4.id, 'product_uom_qty': 1.0, })], }) so.action_confirm() picking = so.picking_ids self.assertEqual(len(so.picking_ids.move_ids_without_package), 7) picking.move_lines.quantity_done = 1 picking.button_validate() self.assertEqual(picking.state, 'done') report = self.env['ir.actions.report']._get_report_from_name('stock.report_deliveryslip') html_report = report._render_qweb_html(picking.ids)[0].decode('utf-8').split('\n') keys = [ "Kit 1", "Compo 1", "Kit 2 (red)", "Compo 1", "Kit 2 (blue)", "Compo 1", "Kit 3", "Compo 1", "Kit 4", "Compo 1", "Products not associated with a kit", "Product 1", ] for line in html_report: if not keys: break if keys[0] in line: keys = keys[1:] self.assertFalse(keys, "All keys should be in the report with the defined order")
41.061404
28,086
127,185
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 common, Form from odoo.exceptions import UserError from odoo.tools import mute_logger, float_compare from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data # these tests create accounting entries, and therefore need a chart of accounts @common.tagged('post_install', '-at_install') class TestSaleMrpFlow(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.env.ref('stock.route_warehouse0_mto').active = True # Useful models cls.StockMove = cls.env['stock.move'] cls.UoM = cls.env['uom.uom'] cls.MrpProduction = cls.env['mrp.production'] cls.Quant = cls.env['stock.quant'] cls.ProductCategory = cls.env['product.category'] cls.categ_unit = cls.env.ref('uom.product_uom_categ_unit') cls.categ_kgm = cls.env.ref('uom.product_uom_categ_kgm') cls.uom_kg = cls.env['uom.uom'].search([('category_id', '=', cls.categ_kgm.id), ('uom_type', '=', 'reference')], limit=1) cls.uom_kg.write({ 'name': 'Test-KG', 'rounding': 0.000001}) cls.uom_gm = cls.UoM.create({ 'name': 'Test-G', 'category_id': cls.categ_kgm.id, 'uom_type': 'smaller', 'factor': 1000.0, 'rounding': 0.001}) cls.uom_unit = cls.env['uom.uom'].search([('category_id', '=', cls.categ_unit.id), ('uom_type', '=', 'reference')], limit=1) cls.uom_unit.write({ 'name': 'Test-Unit', 'rounding': 0.01}) cls.uom_ten = cls.UoM.create({ 'name': 'Test-Ten', 'category_id': cls.categ_unit.id, 'factor_inv': 10, 'uom_type': 'bigger', 'rounding': 0.001}) cls.uom_dozen = cls.UoM.create({ 'name': 'Test-DozenA', 'category_id': cls.categ_unit.id, 'factor_inv': 12, 'uom_type': 'bigger', 'rounding': 0.001}) # Creating all components cls.component_a = cls._cls_create_product('Comp A', cls.uom_unit) cls.component_b = cls._cls_create_product('Comp B', cls.uom_unit) cls.component_c = cls._cls_create_product('Comp C', cls.uom_unit) cls.component_d = cls._cls_create_product('Comp D', cls.uom_unit) cls.component_e = cls._cls_create_product('Comp E', cls.uom_unit) cls.component_f = cls._cls_create_product('Comp F', cls.uom_unit) cls.component_g = cls._cls_create_product('Comp G', cls.uom_unit) # Create a kit 'kit_1' : # ----------------------- # # kit_1 --|- component_a x2 # |- component_b x1 # |- component_c x3 cls.kit_1 = cls._cls_create_product('Kit 1', cls.uom_unit) cls.bom_kit_1 = cls.env['mrp.bom'].create({ 'product_tmpl_id': cls.kit_1.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine = cls.env['mrp.bom.line'] BomLine.create({ 'product_id': cls.component_a.id, 'product_qty': 2.0, 'bom_id': cls.bom_kit_1.id}) BomLine.create({ 'product_id': cls.component_b.id, 'product_qty': 1.0, 'bom_id': cls.bom_kit_1.id}) BomLine.create({ 'product_id': cls.component_c.id, 'product_qty': 3.0, 'bom_id': cls.bom_kit_1.id}) # Create a kit 'kit_parent' : # --------------------------- # # kit_parent --|- kit_2 x2 --|- component_d x1 # | |- kit_1 x2 -------|- component_a x2 # | |- component_b x1 # | |- component_c x3 # | # |- kit_3 x1 --|- component_f x1 # | |- component_g x2 # | # |- component_e x1 # Creating all kits cls.kit_2 = cls._cls_create_product('Kit 2', cls.uom_unit) cls.kit_3 = cls._cls_create_product('kit 3', cls.uom_unit) cls.kit_parent = cls._cls_create_product('Kit Parent', cls.uom_unit) # Linking the kits and the components via some 'phantom' BoMs bom_kit_2 = cls.env['mrp.bom'].create({ 'product_tmpl_id': cls.kit_2.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine.create({ 'product_id': cls.component_d.id, 'product_qty': 1.0, 'bom_id': bom_kit_2.id}) BomLine.create({ 'product_id': cls.kit_1.id, 'product_qty': 2.0, 'bom_id': bom_kit_2.id}) bom_kit_parent = cls.env['mrp.bom'].create({ 'product_tmpl_id': cls.kit_parent.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine.create({ 'product_id': cls.component_e.id, 'product_qty': 1.0, 'bom_id': bom_kit_parent.id}) BomLine.create({ 'product_id': cls.kit_2.id, 'product_qty': 2.0, 'bom_id': bom_kit_parent.id}) bom_kit_3 = cls.env['mrp.bom'].create({ 'product_tmpl_id': cls.kit_3.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine.create({ 'product_id': cls.component_f.id, 'product_qty': 1.0, 'bom_id': bom_kit_3.id}) BomLine.create({ 'product_id': cls.component_g.id, 'product_qty': 2.0, 'bom_id': bom_kit_3.id}) BomLine.create({ 'product_id': cls.kit_3.id, 'product_qty': 2.0, 'bom_id': bom_kit_parent.id}) @classmethod def _cls_create_product(cls, name, uom_id, routes=()): p = Form(cls.env['product.product']) p.name = name p.detailed_type = 'product' p.uom_id = uom_id p.uom_po_id = uom_id p.route_ids.clear() for r in routes: p.route_ids.add(r) return p.save() def _create_product(self, name, uom_id, routes=()): p = Form(self.env['product.product']) p.name = name p.detailed_type = 'product' p.uom_id = uom_id p.uom_po_id = uom_id p.route_ids.clear() for r in routes: p.route_ids.add(r) return p.save() # Helper to process quantities based on a dict following this structure : # # qty_to_process = { # product_id: qty # } def _process_quantities(self, moves, quantities_to_process): """ Helper to process quantities based on a dict following this structure : qty_to_process = { product_id: qty } """ moves_to_process = moves.filtered(lambda m: m.product_id in quantities_to_process.keys()) for move in moves_to_process: move.write({'quantity_done': quantities_to_process[move.product_id]}) def _assert_quantities(self, moves, quantities_to_process): """ Helper to check expected quantities based on a dict following this structure : qty_to_process = { product_id: qty ... } """ moves_to_process = moves.filtered(lambda m: m.product_id in quantities_to_process.keys()) for move in moves_to_process: self.assertEqual(move.product_uom_qty, quantities_to_process[move.product_id]) def _create_move_quantities(self, qty_to_process, components, warehouse): """ Helper to creates moves in order to update the quantities of components on a specific warehouse. This ensure that all compute fields are triggered. The structure of qty_to_process should be the following : qty_to_process = { component: (qty, uom), ... } """ for comp in components: f = Form(self.env['stock.move']) f.name = 'Test Receipt Components' f.location_id = self.env.ref('stock.stock_location_suppliers') f.location_dest_id = warehouse.lot_stock_id f.product_id = comp f.product_uom = qty_to_process[comp][1] f.product_uom_qty = qty_to_process[comp][0] move = f.save() move._action_confirm() move._action_assign() move_line = move.move_line_ids[0] move_line.qty_done = qty_to_process[comp][0] move._action_done() def test_00_sale_mrp_flow(self): """ Test sale to mrp flow with diffrent unit of measure.""" # Create product A, B, C, D. # -------------------------- route_manufacture = self.company_data['default_warehouse'].manufacture_pull_id.route_id route_mto = self.company_data['default_warehouse'].mto_pull_id.route_id product_a = self._create_product('Product A', self.uom_unit, routes=[route_manufacture, route_mto]) product_c = self._create_product('Product C', self.uom_kg) product_b = self._create_product('Product B', self.uom_dozen, routes=[route_manufacture, route_mto]) product_d = self._create_product('Product D', self.uom_unit, routes=[route_manufacture, route_mto]) # ------------------------------------------------------------------------------------------ # Bill of materials for product A, B, D. # ------------------------------------------------------------------------------------------ # Bill of materials for Product A. with Form(self.env['mrp.bom']) as f: f.product_tmpl_id = product_a.product_tmpl_id f.product_qty = 2 f.product_uom_id = self.uom_dozen with f.bom_line_ids.new() as line: line.product_id = product_b line.product_qty = 3 line.product_uom_id = self.uom_unit with f.bom_line_ids.new() as line: line.product_id = product_c line.product_qty = 300.0 line.product_uom_id = self.uom_gm with f.bom_line_ids.new() as line: line.product_id = product_d line.product_qty = 4 line.product_uom_id = self.uom_unit # Bill of materials for Product B. with Form(self.env['mrp.bom']) as f: f.product_tmpl_id = product_b.product_tmpl_id f.product_qty = 1 f.product_uom_id = self.uom_unit f.type = 'phantom' with f.bom_line_ids.new() as line: line.product_id = product_c line.product_qty = 0.400 line.product_uom_id = self.uom_kg # Bill of materials for Product D. with Form(self.env['mrp.bom']) as f: f.product_tmpl_id = product_d.product_tmpl_id f.product_qty = 1 f.product_uom_id = self.uom_unit with f.bom_line_ids.new() as line: line.product_id = product_c line.product_qty = 1 line.product_uom_id = self.uom_kg # ---------------------------------------- # Create sales order of 10 Dozen product A. # ---------------------------------------- order_form = Form(self.env['sale.order']) order_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) with order_form.order_line.new() as line: line.product_id = product_a line.product_uom = self.uom_dozen line.product_uom_qty = 10 order = order_form.save() order.action_confirm() # Verify buttons are working as expected self.assertEqual(order.mrp_production_count, 1, "User should see the closest manufacture order in the smart button") # =============================================================================== # Sales order of 10 Dozen product A should create production order # like .. # =============================================================================== # Product A 10 Dozen. # Product C 6 kg # As product B phantom in bom A, product A will consume product C # ================================================================ # For 1 unit product B it will consume 400 gm # then for 15 unit (Product B 3 unit per 2 Dozen product A) # product B it will consume [ 6 kg ] product C) # Product A will consume 6 kg product C. # # [15 * 400 gm ( 6 kg product C)] = 6 kg product C # # Product C 1500.0 gm. # [ # For 2 Dozen product A will consume 300.0 gm product C # then for 10 Dozen product A will consume 1500.0 gm product C. # ] # # product D 20 Unit. # [ # For 2 dozen product A will consume 4 unit product D # then for 10 Dozen product A will consume 20 unit of product D. # ] # -------------------------------------------------------------------------------- # <><><><><><><><><><><><><><><><><><><><> # Check manufacturing order for product A. # <><><><><><><><><><><><><><><><><><><><> # Check quantity, unit of measure and state of manufacturing order. # ----------------------------------------------------------------- self.env['procurement.group'].run_scheduler() mnf_product_a = self.env['mrp.production'].search([('product_id', '=', product_a.id)]) self.assertTrue(mnf_product_a, 'Manufacturing order not created.') self.assertEqual(mnf_product_a.product_qty, 120, 'Wrong product quantity in manufacturing order.') self.assertEqual(mnf_product_a.product_uom_id, self.uom_unit, 'Wrong unit of measure in manufacturing order.') self.assertEqual(mnf_product_a.state, 'confirmed', 'Manufacturing order should be confirmed.') # ------------------------------------------------------------------------------------------ # Check 'To consume line' for production order of product A. # ------------------------------------------------------------------------------------------ # Check 'To consume line' with product c and uom kg. # ------------------------------------------------- moves = self.StockMove.search([ ('raw_material_production_id', '=', mnf_product_a.id), ('product_id', '=', product_c.id), ('product_uom', '=', self.uom_kg.id)]) # Check total consume line with product c and uom kg. self.assertEqual(len(moves), 1, 'Production move lines are not generated proper.') list_qty = {move.product_uom_qty for move in moves} self.assertEqual(list_qty, {6.0}, "Wrong product quantity in 'To consume line' of manufacturing order.") # Check state of consume line with product c and uom kg. for move in moves: self.assertEqual(move.state, 'confirmed', "Wrong state in 'To consume line' of manufacturing order.") # Check 'To consume line' with product c and uom gm. # --------------------------------------------------- move = self.StockMove.search([ ('raw_material_production_id', '=', mnf_product_a.id), ('product_id', '=', product_c.id), ('product_uom', '=', self.uom_gm.id)]) # Check total consume line of product c with gm. self.assertEqual(len(move), 1, 'Production move lines are not generated proper.') # Check quantity should be with 1500.0 ( 2 Dozen product A consume 300.0 gm then 10 Dozen (300.0 * (10/2)). self.assertEqual(move.product_uom_qty, 1500.0, "Wrong product quantity in 'To consume line' of manufacturing order.") # Check state of consume line with product c with and uom gm. self.assertEqual(move.state, 'confirmed', "Wrong state in 'To consume line' of manufacturing order.") # Check 'To consume line' with product D. # --------------------------------------- move = self.StockMove.search([ ('raw_material_production_id', '=', mnf_product_a.id), ('product_id', '=', product_d.id)]) # Check total consume line with product D. self.assertEqual(len(move), 1, 'Production lines are not generated proper.') # <><><><><><><><><><><><><><><><><><><><><><> # Manufacturing order for product D (20 unit). # <><><><><><><><><><><><><><><><><><><><><><> # FP Todo: find a better way to look for the production order mnf_product_d = self.MrpProduction.search([('product_id', '=', product_d.id)], order='id desc', limit=1) # Check state of production order D. self.assertEqual(mnf_product_d.state, 'confirmed', 'Manufacturing order should be confirmed.') # Check 'To consume line' state, quantity, uom of production order (product D). # ----------------------------------------------------------------------------- move = self.StockMove.search([('raw_material_production_id', '=', mnf_product_d.id), ('product_id', '=', product_c.id)]) self.assertEqual(move.product_uom_qty, 20, "Wrong product quantity in 'To consume line' of manufacturing order.") self.assertEqual(move.product_uom.id, self.uom_kg.id, "Wrong unit of measure in 'To consume line' of manufacturing order.") self.assertEqual(move.state, 'confirmed', "Wrong state in 'To consume line' of manufacturing order.") # ------------------------------- # Create inventory for product c. # ------------------------------- # Need 20 kg product c to produce 20 unit product D. # -------------------------------------------------- self.Quant.with_context(inventory_mode=True).create({ 'product_id': product_c.id, # uom = uom_kg 'inventory_quantity': 20, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, }).action_apply_inventory() # -------------------------------------------------- # Assign product c to manufacturing order of product D. # -------------------------------------------------- mnf_product_d.action_assign() self.assertEqual(mnf_product_d.reservation_state, 'assigned', 'Availability should be assigned') self.assertEqual(move.state, 'assigned', "Wrong state in 'To consume line' of manufacturing order.") # ------------------ # produce product D. # ------------------ mo_form = Form(mnf_product_d) mo_form.qty_producing = 20 mnf_product_d = mo_form.save() mnf_product_d._post_inventory() # Check state of manufacturing order. self.assertEqual(mnf_product_d.state, 'done', 'Manufacturing order should still be in progress state.') # Check available quantity of product D. self.assertEqual(product_d.qty_available, 20, 'Wrong quantity available of product D.') # ----------------------------------------------------------------- # Check product D assigned or not to production order of product A. # ----------------------------------------------------------------- self.assertEqual(mnf_product_a.state, 'confirmed', 'Manufacturing order should be confirmed.') move = self.StockMove.search([('raw_material_production_id', '=', mnf_product_a.id), ('product_id', '=', product_d.id)]) self.assertEqual(move.state, 'assigned', "Wrong state in 'To consume line' of manufacturing order.") # Create inventory for product C. # ------------------------------ # Need product C ( 20 kg + 6 kg + 1500.0 gm = 27.500 kg) # ------------------------------------------------------- self.Quant.with_context(inventory_mode=True).create({ 'product_id': product_c.id, # uom = uom_kg 'inventory_quantity': 27.51, # round up due to kg.rounding = 0.01 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, }).action_apply_inventory() # Assign product to manufacturing order of product A. # --------------------------------------------------- mnf_product_a.action_assign() self.assertEqual(mnf_product_a.reservation_state, 'assigned', 'Manufacturing order inventory state should be available.') moves = self.StockMove.search([('raw_material_production_id', '=', mnf_product_a.id), ('product_id', '=', product_c.id)]) # Check product c move line state. for move in moves: self.assertEqual(move.state, 'assigned', "Wrong state in 'To consume line' of manufacturing order.") # Produce product A. # ------------------ mo_form = Form(mnf_product_a) mo_form.qty_producing = mo_form.product_qty mnf_product_a = mo_form.save() mnf_product_a._post_inventory() # Check state of manufacturing order product A. self.assertEqual(mnf_product_a.state, 'done', 'Manufacturing order should still be in the progress state.') # Check product A avaialble quantity should be 120. self.assertEqual(product_a.qty_available, 120, 'Wrong quantity available of product A.') def test_01_sale_mrp_delivery_kit(self): """ Test delivered quantity on SO based on delivered quantity in pickings.""" # intial so product = self.env['product.product'].create({ 'name': 'Table Kit', 'type': 'consu', 'invoice_policy': 'delivery', 'categ_id': self.env.ref('product.product_category_all').id, }) # Remove the MTO route as purchase is not installed and since the procurement removal the exception is directly raised product.write({'route_ids': [(6, 0, [self.company_data['default_warehouse'].manufacture_pull_id.route_id.id])]}) product_wood_panel = self.env['product.product'].create({ 'name': 'Wood Panel', 'type': 'product', }) product_desk_bolt = self.env['product.product'].create({ 'name': 'Bolt', 'type': 'product', }) self.env['mrp.bom'].create({ 'product_tmpl_id': product.product_tmpl_id.id, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'sequence': 2, 'type': 'phantom', 'bom_line_ids': [ (0, 0, { 'product_id': product_wood_panel.id, 'product_qty': 1, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, }), (0, 0, { 'product_id': product_desk_bolt.id, 'product_qty': 4, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, }) ] }) partner = self.env['res.partner'].create({'name': 'My Test Partner'}) # if `delivery` module is installed, a default property is set for the carrier to use # However this will lead to an extra line on the SO (the delivery line), which will force # the SO to have a different flow (and `invoice_state` value) if 'property_delivery_carrier_id' in partner: partner.property_delivery_carrier_id = False f = Form(self.env['sale.order']) f.partner_id = partner with f.order_line.new() as line: line.product_id = product line.product_uom_qty = 5 so = f.save() # confirm our standard so, check the picking so.action_confirm() self.assertTrue(so.picking_ids, 'Sale MRP: no picking created for "invoice on delivery" storable products') # invoice in on delivery, nothing should be invoiced with self.assertRaises(UserError): so._create_invoices() self.assertEqual(so.invoice_status, 'no', 'Sale MRP: so invoice_status should be "nothing to invoice" after invoicing') # deliver partially (1 of each instead of 5), check the so's invoice_status and delivered quantities pick = so.picking_ids pick.move_lines.write({'quantity_done': 1}) wiz_act = pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() self.assertEqual(so.invoice_status, 'no', 'Sale MRP: so invoice_status should be "no" after partial delivery of a kit') del_qty = sum(sol.qty_delivered for sol in so.order_line) self.assertEqual(del_qty, 0.0, 'Sale MRP: delivered quantity should be zero after partial delivery of a kit') # deliver remaining products, check the so's invoice_status and delivered quantities self.assertEqual(len(so.picking_ids), 2, 'Sale MRP: number of pickings should be 2') pick_2 = so.picking_ids.filtered('backorder_id') for move in pick_2.move_lines: if move.product_id.id == product_desk_bolt.id: move.write({'quantity_done': 19}) else: move.write({'quantity_done': 4}) pick_2.button_validate() del_qty = sum(sol.qty_delivered for sol in so.order_line) self.assertEqual(del_qty, 5.0, 'Sale MRP: delivered quantity should be 5.0 after complete delivery of a kit') self.assertEqual(so.invoice_status, 'to invoice', 'Sale MRP: so invoice_status should be "to invoice" after complete delivery of a kit') def test_02_sale_mrp_anglo_saxon(self): """Test the price unit of a kit""" # This test will check that the correct journal entries are created when a stockable product in real time valuation # and in fifo cost method is sold in a company using anglo-saxon. # For this test, let's consider a product category called Test category in real-time valuation and real price costing method # Let's also consider a finished product with a bom with two components: component1(cost = 20) and component2(cost = 10) # These products are in the Test category # The bom consists of 2 component1 and 1 component2 # The invoice policy of the finished product is based on delivered quantities self.env.company.currency_id = self.env.ref('base.USD') self.uom_unit = self.UoM.create({ 'name': 'Test-Unit', 'category_id': self.categ_unit.id, 'factor': 1, 'uom_type': 'bigger', 'rounding': 1.0}) self.company = self.company_data['company'] self.company.anglo_saxon_accounting = True self.partner = self.env['res.partner'].create({'name': 'My Test Partner'}) self.category = self.env.ref('product.product_category_1').copy({'name': 'Test category','property_valuation': 'real_time', 'property_cost_method': 'fifo'}) account_type = self.env['account.account.type'].create({'name': 'RCV type', 'type': 'other', 'internal_group': 'asset'}) self.account_receiv = self.env['account.account'].create({'name': 'Receivable', 'code': 'RCV00' , 'user_type_id': account_type.id, 'reconcile': True}) account_expense = self.env['account.account'].create({'name': 'Expense', 'code': 'EXP00' , 'user_type_id': account_type.id, 'reconcile': True}) account_output = self.env['account.account'].create({'name': 'Output', 'code': 'OUT00' , 'user_type_id': account_type.id, 'reconcile': True}) account_valuation = self.env['account.account'].create({'name': 'Valuation', 'code': 'STV00' , 'user_type_id': account_type.id, 'reconcile': True}) self.partner.property_account_receivable_id = self.account_receiv self.category.property_account_income_categ_id = self.account_receiv self.category.property_account_expense_categ_id = account_expense self.category.property_stock_account_input_categ_id = self.account_receiv self.category.property_stock_account_output_categ_id = account_output self.category.property_stock_valuation_account_id = account_valuation self.category.property_stock_journal = self.env['account.journal'].create({'name': 'Stock journal', 'type': 'sale', 'code': 'STK00'}) Product = self.env['product.product'] self.finished_product = Product.create({ 'name': 'Finished product', 'type': 'product', 'uom_id': self.uom_unit.id, 'invoice_policy': 'delivery', 'categ_id': self.category.id}) self.component1 = Product.create({ 'name': 'Component 1', 'type': 'product', 'uom_id': self.uom_unit.id, 'categ_id': self.category.id, 'standard_price': 20}) self.component2 = Product.create({ 'name': 'Component 2', 'type': 'product', 'uom_id': self.uom_unit.id, 'categ_id': self.category.id, 'standard_price': 10}) # Create quants with sudo to avoid: # "You are not allowed to create 'Quants' (stock.quant) records. No group currently allows this operation." self.env['stock.quant'].sudo().create({ 'product_id': self.component1.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'quantity': 6.0, }) self.env['stock.quant'].sudo().create({ 'product_id': self.component2.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'quantity': 3.0, }) self.bom = self.env['mrp.bom'].create({ 'product_tmpl_id': self.finished_product.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine = self.env['mrp.bom.line'] BomLine.create({ 'product_id': self.component1.id, 'product_qty': 2.0, 'bom_id': self.bom.id}) BomLine.create({ 'product_id': self.component2.id, 'product_qty': 1.0, 'bom_id': self.bom.id}) # Create a SO for a specific partner for three units of the finished product so_vals = { 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, 'order_line': [(0, 0, { 'name': self.finished_product.name, 'product_id': self.finished_product.id, 'product_uom_qty': 3, 'product_uom': self.finished_product.uom_id.id, 'price_unit': self.finished_product.list_price })], 'pricelist_id': self.env.ref('product.list0').id, 'company_id': self.company.id, } self.so = self.env['sale.order'].create(so_vals) # Validate the SO self.so.action_confirm() # Deliver the three finished products pick = self.so.picking_ids # To check the products on the picking self.assertEqual(pick.move_lines.mapped('product_id'), self.component1 | self.component2) wiz_act = pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() # Create the invoice self.so._create_invoices() self.invoice = self.so.invoice_ids # Changed the invoiced quantity of the finished product to 2 move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.quantity = 2.0 self.invoice = move_form.save() self.invoice.action_post() aml = self.invoice.line_ids aml_expense = aml.filtered(lambda l: l.is_anglo_saxon_line and l.debit > 0) aml_output = aml.filtered(lambda l: l.is_anglo_saxon_line and l.credit > 0) # Check that the cost of Good Sold entries are equal to 2* (2 * 20 + 1 * 10) = 100 self.assertEqual(aml_expense.debit, 100, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_output.credit, 100, "Cost of Good Sold entry missing or mismatching") def test_03_sale_mrp_simple_kit_qty_delivered(self): """ Test that the quantities delivered are correct when a simple kit is ordered with multiple backorders """ # kit_1 structure: # ================ # kit_1 ---|- component_a x2 # |- component_b x1 # |- component_c x3 # Updating the quantities in stock to prevent # a 'Not enough inventory' warning message. stock_location = self.company_data['default_warehouse'].lot_stock_id self.env['stock.quant']._update_available_quantity(self.component_a, stock_location, 20) self.env['stock.quant']._update_available_quantity(self.component_b, stock_location, 10) self.env['stock.quant']._update_available_quantity(self.component_c, stock_location, 30) # Creation of a sale order for x10 kit_1 partner = self.env['res.partner'].create({'name': 'My Test Partner'}) f = Form(self.env['sale.order']) f.partner_id = partner with f.order_line.new() as line: line.product_id = self.kit_1 line.product_uom_qty = 10.0 # Confirming the SO to trigger the picking creation so = f.save() so.action_confirm() # Check picking creation self.assertEqual(len(so.picking_ids), 1) picking_original = so.picking_ids[0] move_lines = picking_original.move_lines # Check if the correct amount of stock.moves are created self.assertEqual(len(move_lines), 3) # Check if BoM is created and is for a 'Kit' bom_from_k1 = self.env['mrp.bom']._bom_find(self.kit_1)[self.kit_1] self.assertEqual(self.bom_kit_1.id, bom_from_k1.id) self.assertEqual(bom_from_k1.type, 'phantom') # Check there's only 1 order line on the SO and it's for x10 'kit_1' order_lines = so.order_line self.assertEqual(len(order_lines), 1) order_line = order_lines[0] self.assertEqual(order_line.product_id.id, self.kit_1.id) self.assertEqual(order_line.product_uom_qty, 10.0) # Check if correct qty is ordered for each component of the kit expected_quantities = { self.component_a: 20, self.component_b: 10, self.component_c: 30, } self._assert_quantities(move_lines, expected_quantities) # Process only x1 of the first component then create a backorder for the missing components picking_original.move_lines.sorted()[0].write({'quantity_done': 1}) wiz_act = so.picking_ids[0].button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # Check that the backorder was created, no kit should be delivered at this point self.assertEqual(len(so.picking_ids), 2) backorder_1 = so.picking_ids - picking_original self.assertEqual(backorder_1.backorder_id.id, picking_original.id) self.assertEqual(order_line.qty_delivered, 0) # Process only x6 each componenent in the picking # Then create a backorder for the missing components backorder_1.move_lines.write({'quantity_done': 6}) wiz_act = backorder_1.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # Check that a backorder is created self.assertEqual(len(so.picking_ids), 3) backorder_2 = so.picking_ids - picking_original - backorder_1 self.assertEqual(backorder_2.backorder_id.id, backorder_1.id) # With x6 unit of each components, we can only make 2 kits. # So only 2 kits should be delivered self.assertEqual(order_line.qty_delivered, 2) # Process x3 more unit of each components : # - Now only 3 kits should be delivered # - A backorder will be created, the SO should have 3 picking_ids linked to it. backorder_2.move_lines.write({'quantity_done': 3}) wiz_act = backorder_2.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() self.assertEqual(len(so.picking_ids), 4) backorder_3 = so.picking_ids - picking_original - backorder_2 - backorder_1 self.assertEqual(backorder_3.backorder_id.id, backorder_2.id) self.assertEqual(order_line.qty_delivered, 3) # Adding missing components qty_to_process = { self.component_a: 10, self.component_b: 1, self.component_c: 21, } self._process_quantities(backorder_3.move_lines, qty_to_process) # Validating the last backorder now it's complete backorder_3.button_validate() order_line._compute_qty_delivered() # All kits should be delivered self.assertEqual(order_line.qty_delivered, 10) def test_04_sale_mrp_kit_qty_delivered(self): """ Test that the quantities delivered are correct when a kit with subkits is ordered with multiple backorders and returns """ # 'kit_parent' structure: # --------------------------- # # kit_parent --|- kit_2 x2 --|- component_d x1 # | |- kit_1 x2 -------|- component_a x2 # | |- component_b x1 # | |- component_c x3 # | # |- kit_3 x1 --|- component_f x1 # | |- component_g x2 # | # |- component_e x1 # Updating the quantities in stock to prevent # a 'Not enough inventory' warning message. stock_location = self.company_data['default_warehouse'].lot_stock_id self.env['stock.quant']._update_available_quantity(self.component_a, stock_location, 56) self.env['stock.quant']._update_available_quantity(self.component_b, stock_location, 28) self.env['stock.quant']._update_available_quantity(self.component_c, stock_location, 84) self.env['stock.quant']._update_available_quantity(self.component_d, stock_location, 14) self.env['stock.quant']._update_available_quantity(self.component_e, stock_location, 7) self.env['stock.quant']._update_available_quantity(self.component_f, stock_location, 14) self.env['stock.quant']._update_available_quantity(self.component_g, stock_location, 28) # Creation of a sale order for x7 kit_parent partner = self.env['res.partner'].create({'name': 'My Test Partner'}) f = Form(self.env['sale.order']) f.partner_id = partner with f.order_line.new() as line: line.product_id = self.kit_parent line.product_uom_qty = 7.0 so = f.save() so.action_confirm() # Check picking creation, its move lines should concern # only components. Also checks that the quantities are corresponding # to the SO self.assertEqual(len(so.picking_ids), 1) order_line = so.order_line[0] picking_original = so.picking_ids[0] move_lines = picking_original.move_lines products = move_lines.mapped('product_id') kits = [self.kit_parent, self.kit_3, self.kit_2, self.kit_1] components = [self.component_a, self.component_b, self.component_c, self.component_d, self.component_e, self.component_f, self.component_g] expected_quantities = { self.component_a: 56.0, self.component_b: 28.0, self.component_c: 84.0, self.component_d: 14.0, self.component_e: 7.0, self.component_f: 14.0, self.component_g: 28.0 } self.assertEqual(len(move_lines), 7) self.assertTrue(not any(kit in products for kit in kits)) self.assertTrue(all(component in products for component in components)) self._assert_quantities(move_lines, expected_quantities) # Process only 7 units of each component qty_to_process = 7 move_lines.write({'quantity_done': qty_to_process}) # Create a backorder for the missing componenents wiz_act = picking_original.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # Check that a backorded is created self.assertEqual(len(so.picking_ids), 2) backorder_1 = so.picking_ids - picking_original self.assertEqual(backorder_1.backorder_id.id, picking_original.id) # Even if some components are delivered completely, # no KitParent should be delivered self.assertEqual(order_line.qty_delivered, 0) # Process just enough components to make 1 kit_parent qty_to_process = { self.component_a: 1, self.component_c: 5, } self._process_quantities(backorder_1.move_lines, qty_to_process) # Create a backorder for the missing componenents wiz_act = backorder_1.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # Only 1 kit_parent should be delivered at this point self.assertEqual(order_line.qty_delivered, 1) # Check that the second backorder is created self.assertEqual(len(so.picking_ids), 3) backorder_2 = so.picking_ids - picking_original - backorder_1 self.assertEqual(backorder_2.backorder_id.id, backorder_1.id) # Set the components quantities that backorder_2 should have expected_quantities = { self.component_a: 48, self.component_b: 21, self.component_c: 72, self.component_d: 7, self.component_f: 7, self.component_g: 21 } # Check that the computed quantities are matching the theorical ones. # Since component_e was totally processed, this componenent shouldn't be # present in backorder_2 self.assertEqual(len(backorder_2.move_lines), 6) move_comp_e = backorder_2.move_lines.filtered(lambda m: m.product_id.id == self.component_e.id) self.assertFalse(move_comp_e) self._assert_quantities(backorder_2.move_lines, expected_quantities) # Process enough components to make x3 kit_parents qty_to_process = { self.component_a: 16, self.component_b: 5, self.component_c: 24, self.component_g: 5 } self._process_quantities(backorder_2.move_lines, qty_to_process) # Create a backorder for the missing componenents wiz_act = backorder_2.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # Check that x3 kit_parents are indeed delivered self.assertEqual(order_line.qty_delivered, 3) # Check that the third backorder is created self.assertEqual(len(so.picking_ids), 4) backorder_3 = so.picking_ids - (picking_original + backorder_1 + backorder_2) self.assertEqual(backorder_3.backorder_id.id, backorder_2.id) # Check the components quantities that backorder_3 should have expected_quantities = { self.component_a: 32, self.component_b: 16, self.component_c: 48, self.component_d: 7, self.component_f: 7, self.component_g: 16 } self._assert_quantities(backorder_3.move_lines, expected_quantities) # Process all missing components self._process_quantities(backorder_3.move_lines, expected_quantities) # Validating the last backorder now it's complete. # All kits should be delivered backorder_3.button_validate() self.assertEqual(order_line.qty_delivered, 7.0) # Return all components processed by backorder_3 stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=backorder_3.ids, active_id=backorder_3.ids[0], active_model='stock.picking')) return_wiz = stock_return_picking_form.save() for return_move in return_wiz.product_return_moves: return_move.write({ 'quantity': expected_quantities[return_move.product_id], 'to_refund': True }) res = return_wiz.create_returns() return_pick = self.env['stock.picking'].browse(res['res_id']) # Process all components and validate the picking wiz_act = return_pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() # Now quantity delivered should be 3 again self.assertEqual(order_line.qty_delivered, 3) stock_return_picking_form = Form(self.env['stock.return.picking'] .with_context(active_ids=return_pick.ids, active_id=return_pick.ids[0], active_model='stock.picking')) return_wiz = stock_return_picking_form.save() for move in return_wiz.product_return_moves: move.quantity = expected_quantities[move.product_id] res = return_wiz.create_returns() return_of_return_pick = self.env['stock.picking'].browse(res['res_id']) # Process all components except one of each for move in return_of_return_pick.move_lines: move.write({ 'quantity_done': expected_quantities[move.product_id] - 1, 'to_refund': True }) wiz_act = return_of_return_pick.button_validate() Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # As one of each component is missing, only 6 kit_parents should be delivered self.assertEqual(order_line.qty_delivered, 6) # Check that the 4th backorder is created. self.assertEqual(len(so.picking_ids), 7) backorder_4 = so.picking_ids - (picking_original + backorder_1 + backorder_2 + backorder_3 + return_of_return_pick + return_pick) self.assertEqual(backorder_4.backorder_id.id, return_of_return_pick.id) # Check the components quantities that backorder_4 should have for move in backorder_4.move_lines: self.assertEqual(move.product_qty, 1) @mute_logger('odoo.tests.common.onchange') def test_05_mrp_sale_kit_availability(self): """ Check that the 'Not enough inventory' warning message shows correct informations when a kit is ordered """ warehouse_1 = self.env['stock.warehouse'].create({ 'name': 'Warehouse 1', 'code': 'WH1' }) warehouse_2 = self.env['stock.warehouse'].create({ 'name': 'Warehouse 2', 'code': 'WH2' }) # Those are all componenents needed to make kit_parents components = [self.component_a, self.component_b, self.component_c, self.component_d, self.component_e, self.component_f, self.component_g] # Set enough quantities to make 1 kit_uom_in_kit in WH1 self.env['stock.quant']._update_available_quantity(self.component_a, warehouse_1.lot_stock_id, 8) self.env['stock.quant']._update_available_quantity(self.component_b, warehouse_1.lot_stock_id, 4) self.env['stock.quant']._update_available_quantity(self.component_c, warehouse_1.lot_stock_id, 12) self.env['stock.quant']._update_available_quantity(self.component_d, warehouse_1.lot_stock_id, 2) self.env['stock.quant']._update_available_quantity(self.component_e, warehouse_1.lot_stock_id, 1) self.env['stock.quant']._update_available_quantity(self.component_f, warehouse_1.lot_stock_id, 2) self.env['stock.quant']._update_available_quantity(self.component_g, warehouse_1.lot_stock_id, 4) # Set quantities on WH2, but not enough to make 1 kit_parent self.env['stock.quant']._update_available_quantity(self.component_a, warehouse_2.lot_stock_id, 7) self.env['stock.quant']._update_available_quantity(self.component_b, warehouse_2.lot_stock_id, 3) self.env['stock.quant']._update_available_quantity(self.component_c, warehouse_2.lot_stock_id, 12) self.env['stock.quant']._update_available_quantity(self.component_d, warehouse_2.lot_stock_id, 1) self.env['stock.quant']._update_available_quantity(self.component_e, warehouse_2.lot_stock_id, 1) self.env['stock.quant']._update_available_quantity(self.component_f, warehouse_2.lot_stock_id, 1) self.env['stock.quant']._update_available_quantity(self.component_g, warehouse_2.lot_stock_id, 4) # Creation of a sale order for x7 kit_parent qty_ordered = 7 f = Form(self.env['sale.order']) f.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) f.warehouse_id = warehouse_2 with f.order_line.new() as line: line.product_id = self.kit_parent line.product_uom_qty = qty_ordered so = f.save() order_line = so.order_line[0] # Check that not enough enough quantities are available in the warehouse set in the SO # but there are enough quantities in Warehouse 1 for 1 kit_parent kit_parent_wh_order = self.kit_parent.with_context(warehouse=so.warehouse_id.id) # Check that not enough enough quantities are available in the warehouse set in the SO # but there are enough quantities in Warehouse 1 for 1 kit_parent self.assertEqual(kit_parent_wh_order.virtual_available, 0) kit_parent_wh_order.invalidate_cache() kit_parent_wh1 = self.kit_parent.with_context(warehouse=warehouse_1.id) self.assertEqual(kit_parent_wh1.virtual_available, 1) # Check there arn't enough quantities available for the sale order self.assertTrue(float_compare(order_line.virtual_available_at_date - order_line.product_uom_qty, 0, precision_rounding=line.product_uom.rounding) == -1) # We receive enoug of each component in Warehouse 2 to make 3 kit_parent qty_to_process = { self.component_a: (17, self.uom_unit), self.component_b: (12, self.uom_unit), self.component_c: (25, self.uom_unit), self.component_d: (5, self.uom_unit), self.component_e: (2, self.uom_unit), self.component_f: (5, self.uom_unit), self.component_g: (8, self.uom_unit), } self._create_move_quantities(qty_to_process, components, warehouse_2) # As 'Warehouse 2' is the warehouse linked to the SO, 3 kits should be available # But the quantity available in Warehouse 1 should stay 1 kit_parent_wh_order = self.kit_parent.with_context(warehouse=so.warehouse_id.id) self.assertEqual(kit_parent_wh_order.virtual_available, 3) kit_parent_wh_order.invalidate_cache() kit_parent_wh1 = self.kit_parent.with_context(warehouse=warehouse_1.id) self.assertEqual(kit_parent_wh1.virtual_available, 1) # Check there arn't enough quantities available for the sale order self.assertTrue(float_compare(order_line.virtual_available_at_date - order_line.product_uom_qty, 0, precision_rounding=line.product_uom.rounding) == -1) # We receive enough of each component in Warehouse 2 to make 7 kit_parent qty_to_process = { self.component_a: (32, self.uom_unit), self.component_b: (16, self.uom_unit), self.component_c: (48, self.uom_unit), self.component_d: (8, self.uom_unit), self.component_e: (4, self.uom_unit), self.component_f: (8, self.uom_unit), self.component_g: (16, self.uom_unit), } self._create_move_quantities(qty_to_process, components, warehouse_2) # Enough quantities should be available, no warning message should be displayed kit_parent_wh_order = self.kit_parent.with_context(warehouse=so.warehouse_id.id) self.assertEqual(kit_parent_wh_order.virtual_available, 7) def test_06_kit_qty_delivered_mixed_uom(self): """ Check that the quantities delivered are correct when a kit involves multiple UoMs on its components """ # Create some components component_uom_unit = self._create_product('Comp Unit', self.uom_unit) component_uom_dozen = self._create_product('Comp Dozen', self.uom_dozen) component_uom_kg = self._create_product('Comp Kg', self.uom_kg) # Create a kit 'kit_uom_1' : # ----------------------- # # kit_uom_1 --|- component_uom_unit x2 Test-Dozen # |- component_uom_dozen x1 Test-Dozen # |- component_uom_kg x3 Test-G kit_uom_1 = self._create_product('Kit 1', self.uom_unit) bom_kit_uom_1 = self.env['mrp.bom'].create({ 'product_tmpl_id': kit_uom_1.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine = self.env['mrp.bom.line'] BomLine.create({ 'product_id': component_uom_unit.id, 'product_qty': 2.0, 'product_uom_id': self.uom_dozen.id, 'bom_id': bom_kit_uom_1.id}) BomLine.create({ 'product_id': component_uom_dozen.id, 'product_qty': 1.0, 'product_uom_id': self.uom_dozen.id, 'bom_id': bom_kit_uom_1.id}) BomLine.create({ 'product_id': component_uom_kg.id, 'product_qty': 3.0, 'product_uom_id': self.uom_gm.id, 'bom_id': bom_kit_uom_1.id}) # Updating the quantities in stock to prevent # a 'Not enough inventory' warning message. stock_location = self.company_data['default_warehouse'].lot_stock_id self.env['stock.quant']._update_available_quantity(component_uom_unit, stock_location, 240) self.env['stock.quant']._update_available_quantity(component_uom_dozen, stock_location, 10) self.env['stock.quant']._update_available_quantity(component_uom_kg, stock_location, 0.03) # Creation of a sale order for x10 kit_1 partner = self.env['res.partner'].create({'name': 'My Test Partner'}) f = Form(self.env['sale.order']) f.partner_id = partner with f.order_line.new() as line: line.product_id = kit_uom_1 line.product_uom_qty = 10.0 so = f.save() so.action_confirm() picking_original = so.picking_ids[0] move_lines = picking_original.move_lines order_line = so.order_line[0] # Check that the quantities on the picking are the one expected for each components for ml in move_lines: corr_bom_line = bom_kit_uom_1.bom_line_ids.filtered(lambda b: b.product_id.id == ml.product_id.id) computed_qty = ml.product_uom._compute_quantity(ml.product_uom_qty, corr_bom_line.product_uom_id) self.assertEqual(computed_qty, order_line.product_uom_qty * corr_bom_line.product_qty) # Processe enough componenents in the picking to make 2 kit_uom_1 # Then create a backorder for the missing components qty_to_process = { component_uom_unit: 48, component_uom_dozen: 3, component_uom_kg: 0.006 } self._process_quantities(move_lines, qty_to_process) res = move_lines.picking_id.button_validate() Form(self.env[res['res_model']].with_context(res['context'])).save().process() # Check that a backorder is created self.assertEqual(len(so.picking_ids), 2) backorder_1 = so.picking_ids - picking_original self.assertEqual(backorder_1.backorder_id.id, picking_original.id) # Only 2 kits should be delivered self.assertEqual(order_line.qty_delivered, 2) # Adding missing components qty_to_process = { component_uom_unit: 192, component_uom_dozen: 7, component_uom_kg: 0.024 } self._process_quantities(backorder_1.move_lines, qty_to_process) # Validating the last backorder now it's complete backorder_1.button_validate() order_line._compute_qty_delivered() # All kits should be delivered self.assertEqual(order_line.qty_delivered, 10) @mute_logger('odoo.tests.common.onchange') def test_07_kit_availability_mixed_uom(self): """ Check that the 'Not enough inventory' warning message displays correct informations when a kit with multiple UoMs on its components is ordered """ # Create some components component_uom_unit = self._create_product('Comp Unit', self.uom_unit) component_uom_dozen = self._create_product('Comp Dozen', self.uom_dozen) component_uom_kg = self._create_product('Comp Kg', self.uom_kg) component_uom_gm = self._create_product('Comp g', self.uom_gm) components = [component_uom_unit, component_uom_dozen, component_uom_kg, component_uom_gm] # Create a kit 'kit_uom_in_kit' : # ----------------------- # kit_uom_in_kit --|- component_uom_gm x3 Test-KG # |- kit_uom_1 x2 Test-Dozen --|- component_uom_unit x2 Test-Dozen # |- component_uom_dozen x1 Test-Dozen # |- component_uom_kg x5 Test-G kit_uom_1 = self._create_product('Sub Kit 1', self.uom_unit) kit_uom_in_kit = self._create_product('Parent Kit', self.uom_unit) bom_kit_uom_1 = self.env['mrp.bom'].create({ 'product_tmpl_id': kit_uom_1.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine = self.env['mrp.bom.line'] BomLine.create({ 'product_id': component_uom_unit.id, 'product_qty': 2.0, 'product_uom_id': self.uom_dozen.id, 'bom_id': bom_kit_uom_1.id}) BomLine.create({ 'product_id': component_uom_dozen.id, 'product_qty': 1.0, 'product_uom_id': self.uom_dozen.id, 'bom_id': bom_kit_uom_1.id}) BomLine.create({ 'product_id': component_uom_kg.id, 'product_qty': 5.0, 'product_uom_id': self.uom_gm.id, 'bom_id': bom_kit_uom_1.id}) bom_kit_uom_in_kit = self.env['mrp.bom'].create({ 'product_tmpl_id': kit_uom_in_kit.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom'}) BomLine.create({ 'product_id': component_uom_gm.id, 'product_qty': 3.0, 'product_uom_id': self.uom_kg.id, 'bom_id': bom_kit_uom_in_kit.id}) BomLine.create({ 'product_id': kit_uom_1.id, 'product_qty': 2.0, 'product_uom_id': self.uom_dozen.id, 'bom_id': bom_kit_uom_in_kit.id}) # Create a simple warehouse to receives some products warehouse_1 = self.env['stock.warehouse'].create({ 'name': 'Warehouse 1', 'code': 'WH1' }) # Set enough quantities to make 1 kit_uom_in_kit in WH1 self.env['stock.quant']._update_available_quantity(component_uom_unit, warehouse_1.lot_stock_id, 576) self.env['stock.quant']._update_available_quantity(component_uom_dozen, warehouse_1.lot_stock_id, 24) self.env['stock.quant']._update_available_quantity(component_uom_kg, warehouse_1.lot_stock_id, 0.12) self.env['stock.quant']._update_available_quantity(component_uom_gm, warehouse_1.lot_stock_id, 3000) # Creation of a sale order for x5 kit_uom_in_kit qty_ordered = 5 f = Form(self.env['sale.order']) f.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) f.warehouse_id = warehouse_1 with f.order_line.new() as line: line.product_id = kit_uom_in_kit line.product_uom_qty = qty_ordered so = f.save() order_line = so.order_line[0] # Check that not enough enough quantities are available in the warehouse set in the SO # but there are enough quantities in Warehouse 1 for 1 kit_parent kit_uom_in_kit.with_context(warehouse=warehouse_1.id)._compute_quantities() virtual_available_wh_order = kit_uom_in_kit.virtual_available self.assertEqual(virtual_available_wh_order, 1) # Check there arn't enough quantities available for the sale order self.assertTrue(float_compare(order_line.virtual_available_at_date - order_line.product_uom_qty, 0, precision_rounding=line.product_uom.rounding) == -1) # We receive enough of each component in Warehouse 1 to make 3 kit_uom_in_kit. # Moves are created instead of only updating the quant quantities in order to trigger every compute fields. qty_to_process = { component_uom_unit: (1152, self.uom_unit), component_uom_dozen: (48, self.uom_dozen), component_uom_kg: (0.24, self.uom_kg), component_uom_gm: (6000, self.uom_gm) } self._create_move_quantities(qty_to_process, components, warehouse_1) # Check there arn't enough quantities available for the sale order self.assertTrue(float_compare(order_line.virtual_available_at_date - order_line.product_uom_qty, 0, precision_rounding=line.product_uom.rounding) == -1) kit_uom_in_kit.with_context(warehouse=warehouse_1.id)._compute_quantities() virtual_available_wh_order = kit_uom_in_kit.virtual_available self.assertEqual(virtual_available_wh_order, 3) # We process enough quantities to have enough kit_uom_in_kit available for the sale order. self._create_move_quantities(qty_to_process, components, warehouse_1) # We check that enough quantities were processed to sell 5 kit_uom_in_kit kit_uom_in_kit.with_context(warehouse=warehouse_1.id)._compute_quantities() self.assertEqual(kit_uom_in_kit.virtual_available, 5) def test_10_sale_mrp_kits_routes(self): # Create a kit 'kit_1' : # ----------------------- # # kit_1 --|- component_shelf1 x3 # |- component_shelf2 x2 stock_location_components = self.env['stock.location'].create({ 'name': 'Shelf 1', 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, }) stock_location_14 = self.env['stock.location'].create({ 'name': 'Shelf 2', 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, }) kit_1 = self._create_product('Kit1', self.uom_unit) component_shelf1 = self._create_product('Comp Shelf1', self.uom_unit) component_shelf2 = self._create_product('Comp Shelf2', self.uom_unit) with Form(self.env['mrp.bom']) as bom: bom.product_tmpl_id = kit_1.product_tmpl_id bom.product_qty = 1 bom.product_uom_id = self.uom_unit bom.type = 'phantom' with bom.bom_line_ids.new() as line: line.product_id = component_shelf1 line.product_qty = 3 line.product_uom_id = self.uom_unit with bom.bom_line_ids.new() as line: line.product_id = component_shelf2 line.product_qty = 2 line.product_uom_id = self.uom_unit # Creating 2 specific routes for each of the components of the kit route_shelf1 = self.env['stock.location.route'].create({ 'name': 'Shelf1 -> Customer', 'product_selectable': True, 'rule_ids': [(0, 0, { 'name': 'Shelf1 -> Customer', 'action': 'pull', 'picking_type_id': self.company_data['default_warehouse'].in_type_id.id, 'location_src_id': stock_location_components.id, 'location_id': self.ref('stock.stock_location_customers'), })], }) route_shelf2 = self.env['stock.location.route'].create({ 'name': 'Shelf2 -> Customer', 'product_selectable': True, 'rule_ids': [(0, 0, { 'name': 'Shelf2 -> Customer', 'action': 'pull', 'picking_type_id': self.company_data['default_warehouse'].in_type_id.id, 'location_src_id': stock_location_14.id, 'location_id': self.ref('stock.stock_location_customers'), })], }) component_shelf1.write({ 'route_ids': [(4, route_shelf1.id)]}) component_shelf2.write({ 'route_ids': [(4, route_shelf2.id)]}) # Set enough quantities to make 1 kit_uom_in_kit in WH1 self.env['stock.quant']._update_available_quantity(component_shelf1, self.company_data['default_warehouse'].lot_stock_id, 15) self.env['stock.quant']._update_available_quantity(component_shelf2, self.company_data['default_warehouse'].lot_stock_id, 10) # Creating a sale order for 5 kits and confirming it order_form = Form(self.env['sale.order']) order_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) with order_form.order_line.new() as line: line.product_id = kit_1 line.product_uom = self.uom_unit line.product_uom_qty = 5 order = order_form.save() order.action_confirm() # Now we check that the routes of the components were applied, in order to make sure the routes set # on the kit itself are ignored self.assertEqual(len(order.picking_ids), 2) self.assertEqual(len(order.picking_ids[0].move_lines), 1) self.assertEqual(len(order.picking_ids[1].move_lines), 1) moves = order.picking_ids.mapped('move_lines') move_shelf1 = moves.filtered(lambda m: m.product_id == component_shelf1) move_shelf2 = moves.filtered(lambda m: m.product_id == component_shelf2) self.assertEqual(move_shelf1.location_id.id, stock_location_components.id) self.assertEqual(move_shelf1.location_dest_id.id, self.ref('stock.stock_location_customers')) self.assertEqual(move_shelf2.location_id.id, stock_location_14.id) self.assertEqual(move_shelf2.location_dest_id.id, self.ref('stock.stock_location_customers')) def test_11_sale_mrp_explode_kits_uom_quantities(self): # Create a kit 'kit_1' : # ----------------------- # # 2x Dozens kit_1 --|- component_unit x6 Units # |- component_kg x7 Kg kit_1 = self._create_product('Kit1', self.uom_unit) component_unit = self._create_product('Comp Unit', self.uom_unit) component_kg = self._create_product('Comp Kg', self.uom_kg) with Form(self.env['mrp.bom']) as bom: bom.product_tmpl_id = kit_1.product_tmpl_id bom.product_qty = 2 bom.product_uom_id = self.uom_dozen bom.type = 'phantom' with bom.bom_line_ids.new() as line: line.product_id = component_unit line.product_qty = 6 line.product_uom_id = self.uom_unit with bom.bom_line_ids.new() as line: line.product_id = component_kg line.product_qty = 7 line.product_uom_id = self.uom_kg # Create a simple warehouse to receives some products warehouse_1 = self.env['stock.warehouse'].create({ 'name': 'Warehouse 1', 'code': 'WH1' }) # Set enough quantities to make 1 Test-Dozen kit_uom_in_kit self.env['stock.quant']._update_available_quantity(component_unit, warehouse_1.lot_stock_id, 12) self.env['stock.quant']._update_available_quantity(component_kg, warehouse_1.lot_stock_id, 14) # Creating a sale order for 3 Units of kit_1 and confirming it order_form = Form(self.env['sale.order']) order_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) order_form.warehouse_id = warehouse_1 with order_form.order_line.new() as line: line.product_id = kit_1 line.product_uom = self.uom_unit line.product_uom_qty = 2 order = order_form.save() order.action_confirm() # Now we check that the routes of the components were applied, in order to make sure the routes set # on the kit itself are ignored self.assertEqual(len(order.picking_ids), 1) self.assertEqual(len(order.picking_ids[0].move_lines), 2) # Finally, we check the quantities for each component on the picking move_component_unit = order.picking_ids[0].move_lines.filtered(lambda m: m.product_id == component_unit) move_component_kg = order.picking_ids[0].move_lines - move_component_unit self.assertEqual(move_component_unit.product_uom_qty, 0.5) self.assertEqual(move_component_kg.product_uom_qty, 0.58) def test_product_type_service_1(self): route_manufacture = self.company_data['default_warehouse'].manufacture_pull_id.route_id.id route_mto = self.company_data['default_warehouse'].mto_pull_id.route_id.id self.uom_unit = self.env.ref('uom.product_uom_unit') # Create finished product finished_product = self.env['product.product'].create({ 'name': 'Geyser', 'type': 'product', 'route_ids': [(4, route_mto), (4, route_manufacture)], }) # Create service type product product_raw = self.env['product.product'].create({ 'name': 'raw Geyser', 'type': 'service', }) # Create bom for finish product bom = self.env['mrp.bom'].create({ 'product_id': finished_product.id, 'product_tmpl_id': finished_product.product_tmpl_id.id, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'product_qty': 1.0, 'type': 'normal', 'bom_line_ids': [(5, 0), (0, 0, {'product_id': product_raw.id})] }) # Create sale order sale_form = Form(self.env['sale.order']) sale_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) with sale_form.order_line.new() as line: line.name = finished_product.name line.product_id = finished_product line.product_uom_qty = 1.0 line.product_uom = self.uom_unit line.price_unit = 10.0 sale_order = sale_form.save() sale_order.action_confirm() mo = self.env['mrp.production'].search([('product_id', '=', finished_product.id)]) self.assertTrue(mo, 'Manufacturing order created.') def test_cancel_flow_1(self): """ Sell a MTO/manufacture product. Cancel the delivery and the production order. Then duplicate the delivery. Another production order should be created.""" route_manufacture = self.company_data['default_warehouse'].manufacture_pull_id.route_id.id route_mto = self.company_data['default_warehouse'].mto_pull_id.route_id.id self.uom_unit = self.env.ref('uom.product_uom_unit') # Create finished product finished_product = self.env['product.product'].create({ 'name': 'Geyser', 'type': 'product', 'route_ids': [(4, route_mto), (4, route_manufacture)], }) product_raw = self.env['product.product'].create({ 'name': 'raw Geyser', 'type': 'product', }) # Create bom for finish product bom = self.env['mrp.bom'].create({ 'product_id': finished_product.id, 'product_tmpl_id': finished_product.product_tmpl_id.id, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'product_qty': 1.0, 'type': 'normal', 'bom_line_ids': [(5, 0), (0, 0, {'product_id': product_raw.id})] }) # Create sale order sale_form = Form(self.env['sale.order']) sale_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) with sale_form.order_line.new() as line: line.name = finished_product.name line.product_id = finished_product line.product_uom_qty = 1.0 line.product_uom = self.uom_unit line.price_unit = 10.0 sale_order = sale_form.save() sale_order.action_confirm() mo = self.env['mrp.production'].search([('product_id', '=', finished_product.id)]) delivery = sale_order.picking_ids delivery.action_cancel() mo.action_cancel() copied_delivery = delivery.copy() copied_delivery.action_confirm() mos = self.env['mrp.production'].search([('product_id', '=', finished_product.id)]) self.assertEqual(len(mos), 1) self.assertEqual(mos.state, 'cancel') def test_cancel_flow_2(self): """ Sell a MTO/manufacture product. Cancel the production order and the delivery. Then duplicate the delivery. Another production order should be created.""" route_manufacture = self.company_data['default_warehouse'].manufacture_pull_id.route_id.id route_mto = self.company_data['default_warehouse'].mto_pull_id.route_id.id self.uom_unit = self.env.ref('uom.product_uom_unit') # Create finished product finished_product = self.env['product.product'].create({ 'name': 'Geyser', 'type': 'product', 'route_ids': [(4, route_mto), (4, route_manufacture)], }) product_raw = self.env['product.product'].create({ 'name': 'raw Geyser', 'type': 'product', }) # Create bom for finish product bom = self.env['mrp.bom'].create({ 'product_id': finished_product.id, 'product_tmpl_id': finished_product.product_tmpl_id.id, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'product_qty': 1.0, 'type': 'normal', 'bom_line_ids': [(5, 0), (0, 0, {'product_id': product_raw.id})] }) # Create sale order sale_form = Form(self.env['sale.order']) sale_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) with sale_form.order_line.new() as line: line.name = finished_product.name line.product_id = finished_product line.product_uom_qty = 1.0 line.product_uom = self.uom_unit line.price_unit = 10.0 sale_order = sale_form.save() sale_order.action_confirm() mo = self.env['mrp.production'].search([('product_id', '=', finished_product.id)]) delivery = sale_order.picking_ids mo.action_cancel() delivery.action_cancel() copied_delivery = delivery.copy() copied_delivery.action_confirm() mos = self.env['mrp.production'].search([('product_id', '=', finished_product.id)]) self.assertEqual(len(mos), 1) self.assertEqual(mos.state, 'cancel') def test_12_sale_mrp_anglo_saxon_variant(self): """Test the price unit of kit with variants""" # Check that the correct bom are selected when computing price_unit for COGS self.env.company.currency_id = self.env.ref('base.USD') self.uom_unit = self.UoM.create({ 'name': 'Test-Unit', 'category_id': self.categ_unit.id, 'factor': 1, 'uom_type': 'bigger', 'rounding': 1.0}) self.company = self.company_data['company'] self.company.anglo_saxon_accounting = True self.partner = self.env['res.partner'].create({'name': 'My Test Partner'}) self.category = self.env.ref('product.product_category_1').copy({'name': 'Test category','property_valuation': 'real_time', 'property_cost_method': 'fifo'}) account_type = self.env['account.account.type'].create({'name': 'RCV type', 'type': 'other', 'internal_group': 'asset'}) self.account_receiv = self.env['account.account'].create({'name': 'Receivable', 'code': 'RCV00' , 'user_type_id': account_type.id, 'reconcile': True}) account_expense = self.env['account.account'].create({'name': 'Expense', 'code': 'EXP00' , 'user_type_id': account_type.id, 'reconcile': True}) account_output = self.env['account.account'].create({'name': 'Output', 'code': 'OUT00' , 'user_type_id': account_type.id, 'reconcile': True}) account_valuation = self.env['account.account'].create({'name': 'Valuation', 'code': 'STV00' , 'user_type_id': account_type.id, 'reconcile': True}) self.partner.property_account_receivable_id = self.account_receiv self.category.property_account_income_categ_id = self.account_receiv self.category.property_account_expense_categ_id = account_expense self.category.property_stock_account_input_categ_id = self.account_receiv self.category.property_stock_account_output_categ_id = account_output self.category.property_stock_valuation_account_id = account_valuation self.category.property_stock_journal = self.env['account.journal'].create({'name': 'Stock journal', 'type': 'sale', 'code': 'STK00'}) # Create variant attributes self.prod_att_1 = self.env['product.attribute'].create({'name': 'Color'}) self.prod_attr1_v1 = self.env['product.attribute.value'].create({'name': 'red', 'attribute_id': self.prod_att_1.id, 'sequence': 1}) self.prod_attr1_v2 = self.env['product.attribute.value'].create({'name': 'blue', 'attribute_id': self.prod_att_1.id, 'sequence': 2}) # Create Product template with variants self.product_template = self.env['product.template'].create({ 'name': 'Product Template', 'type': 'product', 'uom_id': self.uom_unit.id, 'invoice_policy': 'delivery', 'categ_id': self.category.id, 'attribute_line_ids': [(0, 0, { 'attribute_id': self.prod_att_1.id, 'value_ids': [(6, 0, [self.prod_attr1_v1.id, self.prod_attr1_v2.id])] })] }) # Get product variant self.pt_attr1_v1 = self.product_template.attribute_line_ids[0].product_template_value_ids[0] self.pt_attr1_v2 = self.product_template.attribute_line_ids[0].product_template_value_ids[1] self.variant_1 = self.product_template._get_variant_for_combination(self.pt_attr1_v1) self.variant_2 = self.product_template._get_variant_for_combination(self.pt_attr1_v2) def create_simple_bom_for_product(product, name, price): component = self.env['product.product'].create({ 'name': 'Component ' + name, 'type': 'product', 'uom_id': self.uom_unit.id, 'categ_id': self.category.id, 'standard_price': price }) self.env['stock.quant'].sudo().create({ 'product_id': component.id, 'location_id': self.company_data['default_warehouse'].lot_stock_id.id, 'quantity': 10.0, }) bom = self.env['mrp.bom'].create({ 'product_tmpl_id': self.product_template.id, 'product_id': product.id, 'product_qty': 1.0, 'type': 'phantom' }) self.env['mrp.bom.line'].create({ 'product_id': component.id, 'product_qty': 1.0, 'bom_id': bom.id }) create_simple_bom_for_product(self.variant_1, "V1", 20) create_simple_bom_for_product(self.variant_2, "V2", 10) def create_post_sale_order(product): so_vals = { 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, 'order_line': [(0, 0, { 'name': product.name, 'product_id': product.id, 'product_uom_qty': 2, 'product_uom': product.uom_id.id, 'price_unit': product.list_price })], 'pricelist_id': self.env.ref('product.list0').id, 'company_id': self.company.id, } so = self.env['sale.order'].create(so_vals) # Validate the SO so.action_confirm() # Deliver the three finished products pick = so.picking_ids # To check the products on the picking wiz_act = pick.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() # Create the invoice so._create_invoices() invoice = so.invoice_ids invoice.action_post() return invoice # Create a SO for variant 1 self.invoice_1 = create_post_sale_order(self.variant_1) self.invoice_2 = create_post_sale_order(self.variant_2) def check_cogs_entry_values(invoice, expected_value): aml = invoice.line_ids aml_expense = aml.filtered(lambda l: l.is_anglo_saxon_line and l.debit > 0) aml_output = aml.filtered(lambda l: l.is_anglo_saxon_line and l.credit > 0) self.assertEqual(aml_expense.debit, expected_value, "Cost of Good Sold entry missing or mismatching for variant") self.assertEqual(aml_output.credit, expected_value, "Cost of Good Sold entry missing or mismatching for variant") # Check that the cost of Good Sold entries for variant 1 are equal to 2 * 20 = 40 check_cogs_entry_values(self.invoice_1, 40) # Check that the cost of Good Sold entries for variant 2 are equal to 2 * 10 = 20 check_cogs_entry_values(self.invoice_2, 20) def test_13_so_return_kit(self): """ Test that when returning a SO containing only a kit that contains another kit, the SO delivered quantities is set to 0 (with the all-or-nothing policy). Products : Main Kit Nested Kit Screw BoMs : Main Kit BoM (kit), recipe : Nested Kit Bom (kit), recipe : Screw Business flow : Create those Create a Sales order selling one Main Kit BoM Confirm the sales order Validate the delivery (outgoing) (qty_delivered = 1) Create a return for the delivery Validate return for delivery (ingoing) (qty_delivered = 0) """ main_kit_product = self.env['product.product'].create({ 'name': 'Main Kit', 'type': 'product', }) nested_kit_product = self.env['product.product'].create({ 'name': 'Nested Kit', 'type': 'product', }) product = self.env['product.product'].create({ 'name': 'Screw', 'type': 'product', }) nested_kit_bom = self.env['mrp.bom'].create({ 'product_id': nested_kit_product.id, 'product_tmpl_id': nested_kit_product.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(5, 0), (0, 0, {'product_id': product.id})] }) main_bom = self.env['mrp.bom'].create({ 'product_id': main_kit_product.id, 'product_tmpl_id': main_kit_product.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(5, 0), (0, 0, {'product_id': nested_kit_product.id})] }) # Create a SO for product Main Kit Product order_form = Form(self.env['sale.order']) order_form.partner_id = self.env.ref('base.res_partner_2') with order_form.order_line.new() as line: line.product_id = main_kit_product line.product_uom_qty = 1 order = order_form.save() order.action_confirm() qty_del_not_yet_validated = sum(sol.qty_delivered for sol in order.order_line) self.assertEqual(qty_del_not_yet_validated, 0.0, 'No delivery validated yet') # Validate delivery pick = order.picking_ids pick.move_lines.write({'quantity_done': 1}) pick.button_validate() qty_del_validated = sum(sol.qty_delivered for sol in order.order_line) self.assertEqual(qty_del_validated, 1.0, 'The order went from warehouse to client, so it has been delivered') # 1 was delivered, now create a return stock_return_picking_form = Form(self.env['stock.return.picking'].with_context( active_ids=pick.ids, active_id=pick.ids[0], active_model='stock.picking')) return_wiz = stock_return_picking_form.save() for return_move in return_wiz.product_return_moves: return_move.write({ 'quantity': 1, 'to_refund': True }) res = return_wiz.create_returns() return_pick = self.env['stock.picking'].browse(res['res_id']) return_pick.move_line_ids.qty_done = 1 wiz_act = return_pick.button_validate() # validate return # Delivered quantities to the client should be 0 qty_del_return_validated = sum(sol.qty_delivered for sol in order.order_line) self.assertNotEqual(qty_del_return_validated, 1.0, "The return was validated, therefore the delivery from client to" " company was successful, and the client is left without his 1 product.") self.assertEqual(qty_del_return_validated, 0.0, "The return has processed, client doesn't have any quantity anymore") def test_14_change_bom_type(self): """ This test ensures that updating a Bom type during a flow does not lead to any error """ p1 = self._cls_create_product('Master', self.uom_unit) p2 = self._cls_create_product('Component', self.uom_unit) p3 = self.component_a p1.categ_id.write({ 'property_cost_method': 'average', 'property_valuation': 'real_time', }) stock_location = self.company_data['default_warehouse'].lot_stock_id self.env['stock.quant']._update_available_quantity(self.component_a, stock_location, 1) self.env['mrp.bom'].create({ 'product_tmpl_id': p1.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, { 'product_id': p2.id, 'product_qty': 1.0, })] }) p2_bom = self.env['mrp.bom'].create({ 'product_tmpl_id': p2.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, { 'product_id': p3.id, 'product_qty': 1.0, })] }) so_form = Form(self.env['sale.order']) so_form.partner_id = self.env['res.partner'].create({'name': 'Super Partner'}) with so_form.order_line.new() as so_line: so_line.product_id = p1 so = so_form.save() so.action_confirm() wiz_act = so.picking_ids.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() p2_bom.type = "normal" so._create_invoices() invoice = so.invoice_ids invoice.action_post() self.assertEqual(invoice.state, 'posted') def test_15_anglo_saxon_variant_price_unit(self): """ Test the price unit of a variant from which template has another variant with kit bom. Products: Template A variant NOKIT variant KIT: Component A Business Flow: create products and kit create SO selling both variants validate the delivery create the invoice post the invoice """ # Create environment self.env.company.currency_id = self.env.ref('base.USD') self.env.company.anglo_saxon_accounting = True self.partner = self.env.ref('base.res_partner_1') self.category = self.env.ref('product.product_category_1').copy({'name': 'Test category', 'property_valuation': 'real_time', 'property_cost_method': 'fifo'}) account_type = self.env['account.account.type'].create({'name': 'RCV type', 'type': 'other', 'internal_group': 'asset'}) account_receiv = self.env['account.account'].create({'name': 'Receivable', 'code': 'RCV00', 'user_type_id': account_type.id, 'reconcile': True}) account_expense = self.env['account.account'].create({'name': 'Expense', 'code': 'EXP00', 'user_type_id': account_type.id, 'reconcile': True}) account_output = self.env['account.account'].create({'name': 'Output', 'code': 'OUT00', 'user_type_id': account_type.id, 'reconcile': True}) account_valuation = self.env['account.account'].create({'name': 'Valuation', 'code': 'STV00', 'user_type_id': account_type.id, 'reconcile': True}) self.stock_location = self.company_data['default_warehouse'].lot_stock_id self.partner.property_account_receivable_id = account_receiv self.category.property_account_income_categ_id = account_receiv self.category.property_account_expense_categ_id = account_expense self.category.property_stock_account_input_categ_id = account_receiv self.category.property_stock_account_output_categ_id = account_output self.category.property_stock_valuation_account_id = account_valuation # Create variant attributes self.prod_att_test = self.env['product.attribute'].create({'name': 'test'}) self.prod_attr_KIT = self.env['product.attribute.value'].create({'name': 'KIT', 'attribute_id': self.prod_att_test.id, 'sequence': 1}) self.prod_attr_NOKIT = self.env['product.attribute.value'].create({'name': 'NOKIT', 'attribute_id': self.prod_att_test.id, 'sequence': 2}) # Create the template self.product_template = self.env['product.template'].create({ 'name': 'Template A', 'type': 'product', 'uom_id': self.uom_unit.id, 'invoice_policy': 'delivery', 'categ_id': self.category.id, 'attribute_line_ids': [(0, 0, { 'attribute_id': self.prod_att_test.id, 'value_ids': [(6, 0, [self.prod_attr_KIT.id, self.prod_attr_NOKIT.id])] })] }) # Create the variants self.pt_attr_KIT = self.product_template.attribute_line_ids[0].product_template_value_ids[0] self.pt_attr_NOKIT = self.product_template.attribute_line_ids[0].product_template_value_ids[1] self.variant_KIT = self.product_template._get_variant_for_combination(self.pt_attr_KIT) self.variant_NOKIT = self.product_template._get_variant_for_combination(self.pt_attr_NOKIT) # Assign a cost to the NOKIT variant self.variant_NOKIT.write({'standard_price': 25}) # Create the components self.comp_kit_a = self.env['product.product'].create({ 'name': 'Component Kit A', 'type': 'product', 'uom_id': self.uom_unit.id, 'categ_id': self.category.id, 'standard_price': 20 }) self.comp_kit_b = self.env['product.product'].create({ 'name': 'Component Kit B', 'type': 'product', 'uom_id': self.uom_unit.id, 'categ_id': self.category.id, 'standard_price': 10 }) # Create the bom bom = self.env['mrp.bom'].create({ 'product_tmpl_id': self.product_template.id, 'product_id': self.variant_KIT.id, 'product_qty': 1.0, 'type': 'phantom' }) self.env['mrp.bom.line'].create({ 'product_id': self.comp_kit_a.id, 'product_qty': 2.0, 'bom_id': bom.id }) self.env['mrp.bom.line'].create({ 'product_id': self.comp_kit_b.id, 'product_qty': 1.0, 'bom_id': bom.id }) # Create the quants self.env['stock.quant']._update_available_quantity(self.variant_KIT, self.stock_location, 1) self.env['stock.quant']._update_available_quantity(self.comp_kit_a, self.stock_location, 2) self.env['stock.quant']._update_available_quantity(self.comp_kit_b, self.stock_location, 1) self.env['stock.quant']._update_available_quantity(self.variant_NOKIT, self.stock_location, 1) # Create the sale order so_vals = { 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, 'order_line': [(0, 0, { 'name': self.variant_KIT.name, 'product_id': self.variant_KIT.id, 'product_uom_qty': 1, 'product_uom': self.uom_unit.id, 'price_unit': 100, }), (0, 0, { 'name': self.variant_NOKIT.name, 'product_id': self.variant_NOKIT.id, 'product_uom_qty': 1, 'product_uom': self.uom_unit.id, 'price_unit': 50 })], 'pricelist_id': self.env.ref('product.list0').id, 'company_id': self.env.company.id } so = self.env['sale.order'].create(so_vals) # Validate the sale order so.action_confirm() # Deliver the products pick = so.picking_ids wiz_act = pick.button_validate() Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save().process() # Create the invoice so._create_invoices() # Validate the invoice invoice = so.invoice_ids invoice.action_post() amls = invoice.line_ids aml_kit_expense = amls.filtered(lambda l: l.is_anglo_saxon_line and l.debit > 0 and l.product_id == self.variant_KIT) aml_kit_output = amls.filtered(lambda l: l.is_anglo_saxon_line and l.credit > 0 and l.product_id == self.variant_KIT) aml_nokit_expense = amls.filtered(lambda l: l.is_anglo_saxon_line and l.debit > 0 and l.product_id == self.variant_NOKIT) aml_nokit_output = amls.filtered(lambda l: l.is_anglo_saxon_line and l.credit > 0 and l.product_id == self.variant_NOKIT) # Check that the Cost of Goods Sold for variant KIT is equal to (2*20)+10 = 50 self.assertEqual(aml_kit_expense.debit, 50, "Cost of Good Sold entry missing or mismatching for variant with kit") self.assertEqual(aml_kit_output.credit, 50, "Cost of Good Sold entry missing or mismatching for variant with kit") # Check that the Cost of Goods Sold for variant NOKIT is equal to its standard_price = 25 self.assertEqual(aml_nokit_expense.debit, 25, "Cost of Good Sold entry missing or mismatching for variant without kit") self.assertEqual(aml_nokit_output.credit, 25, "Cost of Good Sold entry missing or mismatching for variant without kit") def test_reconfirm_cancelled_kit(self): so = self.env['sale.order'].create({ 'partner_id': self.env.ref('base.res_partner_1').id, 'order_line': [ (0, 0, { 'name': self.kit_1.name, 'product_id': self.kit_1.id, 'product_uom_qty': 1.0, 'price_unit': 1.0, }) ], }) # Updating the quantities in stock to prevent a 'Not enough inventory' warning message. stock_location = self.company_data['default_warehouse'].lot_stock_id self.env['stock.quant']._update_available_quantity(self.component_a, stock_location, 10) self.env['stock.quant']._update_available_quantity(self.component_b, stock_location, 10) self.env['stock.quant']._update_available_quantity(self.component_c, stock_location, 10) so.action_confirm() # Check picking creation self.assertEqual(len(so.picking_ids), 1, "A picking should be created after the SO validation") wiz_act = so.picking_ids.button_validate() wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save() wiz.process() so.action_cancel() so.action_draft() so.action_confirm() self.assertEqual(len(so.picking_ids), 1, "The product was already delivered, no need to re-create a delivery order") def test_anglo_saxo_return_and_credit_note(self): """ When posting a credit note for a returned kit, the value of the anglo-saxo lines should be based on the returned component's value """ stock_input_account, stock_output_account, stock_valuation_account, expense_account, stock_journal = _create_accounting_data(self.env) fifo = self.env['product.category'].create({ 'name': 'FIFO', 'property_valuation': 'real_time', 'property_cost_method': 'fifo', 'property_stock_account_input_categ_id': stock_input_account.id, 'property_stock_account_output_categ_id': stock_output_account.id, 'property_stock_valuation_account_id': stock_valuation_account.id, 'property_stock_journal': stock_journal.id, }) kit = self._create_product('Simple Kit', self.uom_unit) (kit + self.component_a).categ_id = fifo kit.property_account_expense_id = expense_account self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, {'product_id': self.component_a.id, 'product_qty': 1.0})] }) # Receive 3 components: one @10, one @20 and one @60 in_moves = self.env['stock.move'].create([{ 'name': 'IN move @%s' % p, 'product_id': self.component_a.id, 'location_id': self.env.ref('stock.stock_location_suppliers').id, 'location_dest_id': self.company_data['default_warehouse'].lot_stock_id.id, 'product_uom': self.component_a.uom_id.id, 'product_uom_qty': 1, 'price_unit': p, } for p in [10, 20, 60]]) in_moves._action_confirm() in_moves.quantity_done = 1 in_moves._action_done() # Sell 3 kits so = self.env['sale.order'].create({ 'partner_id': self.env.ref('base.res_partner_1').id, 'order_line': [ (0, 0, { 'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 3.0, 'product_uom': kit.uom_id.id, 'price_unit': 100, 'tax_id': False, })], }) so.action_confirm() # Deliver the components: 1@10, then 1@20 and then 1@60 pickings = [] picking = so.picking_ids while picking: pickings.append(picking) picking.move_lines.quantity_done = 1 action = picking.button_validate() if isinstance(action, dict): wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() picking = picking.backorder_ids invoice = so._create_invoices() invoice.action_post() # Receive one @100 in_moves = self.env['stock.move'].create({ 'name': 'IN move @100', 'product_id': self.component_a.id, 'location_id': self.env.ref('stock.stock_location_suppliers').id, 'location_dest_id': self.company_data['default_warehouse'].lot_stock_id.id, 'product_uom': self.component_a.uom_id.id, 'product_uom_qty': 1, 'price_unit': 100, }) in_moves._action_confirm() in_moves.quantity_done = 1 in_moves._action_done() # Return the second picking (i.e. one component @20) ctx = {'active_id': pickings[1].id, 'active_model': 'stock.picking'} return_wizard = Form(self.env['stock.return.picking'].with_context(ctx)).save() return_picking_id, dummy = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_picking_id) return_picking.move_lines.quantity_done = 1 return_picking.button_validate() # Add a credit note for the returned kit ctx = {'active_model': 'account.move', 'active_ids': invoice.ids} refund_wizard = self.env['account.move.reversal'].with_context(ctx).create({ 'refund_method': 'refund', 'journal_id': invoice.journal_id.id, }) action = refund_wizard.reverse_moves() reverse_invoice = self.env['account.move'].browse(action['res_id']) with Form(reverse_invoice) as reverse_invoice_form: with reverse_invoice_form.invoice_line_ids.edit(0) as line: line.quantity = 1 reverse_invoice.action_post() amls = reverse_invoice.line_ids stock_out_aml = amls.filtered(lambda aml: aml.account_id == stock_output_account) self.assertEqual(stock_out_aml.debit, 20, 'Should be to the value of the returned component') self.assertEqual(stock_out_aml.credit, 0) cogs_aml = amls.filtered(lambda aml: aml.account_id == expense_account) self.assertEqual(cogs_aml.debit, 0) self.assertEqual(cogs_aml.credit, 20, 'Should be to the value of the returned component') def test_anglo_saxo_return_and_create_invoice(self): """ When creating an invoice for a returned kit, the value of the anglo-saxo lines should be based on the returned component's value """ stock_input_account, stock_output_account, stock_valuation_account, expense_account, stock_journal = _create_accounting_data(self.env) fifo = self.env['product.category'].create({ 'name': 'FIFO', 'property_valuation': 'real_time', 'property_cost_method': 'fifo', 'property_stock_account_input_categ_id': stock_input_account.id, 'property_stock_account_output_categ_id': stock_output_account.id, 'property_stock_valuation_account_id': stock_valuation_account.id, 'property_stock_journal': stock_journal.id, }) kit = self._create_product('Simple Kit', self.uom_unit) (kit + self.component_a).categ_id = fifo (kit + self.component_a).invoice_policy = 'delivery' kit.property_account_expense_id = expense_account self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, {'product_id': self.component_a.id, 'product_qty': 1.0})] }) # Receive 3 components: one @10, one @20 and one @60 in_moves = self.env['stock.move'].create([{ 'name': 'IN move @%s' % p, 'product_id': self.component_a.id, 'location_id': self.env.ref('stock.stock_location_suppliers').id, 'location_dest_id': self.company_data['default_warehouse'].lot_stock_id.id, 'product_uom': self.component_a.uom_id.id, 'product_uom_qty': 1, 'price_unit': p, } for p in [10, 20, 60]]) in_moves._action_confirm() in_moves.quantity_done = 1 in_moves._action_done() # Sell 3 kits so = self.env['sale.order'].create({ 'partner_id': self.env.ref('base.res_partner_1').id, 'order_line': [ (0, 0, { 'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 3.0, 'product_uom': kit.uom_id.id, 'price_unit': 100, 'tax_id': False, })], }) so.action_confirm() # Deliver the components: 1@10, then 1@20 and then 1@60 pickings = [] picking = so.picking_ids while picking: pickings.append(picking) picking.move_lines.quantity_done = 1 action = picking.button_validate() if isinstance(action, dict): wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() picking = picking.backorder_ids invoice = so._create_invoices() invoice.action_post() # Receive one @100 in_moves = self.env['stock.move'].create({ 'name': 'IN move @100', 'product_id': self.component_a.id, 'location_id': self.env.ref('stock.stock_location_suppliers').id, 'location_dest_id': self.company_data['default_warehouse'].lot_stock_id.id, 'product_uom': self.component_a.uom_id.id, 'product_uom_qty': 1, 'price_unit': 100, }) in_moves._action_confirm() in_moves.quantity_done = 1 in_moves._action_done() # Return the second picking (i.e. one component @20) ctx = {'active_id': pickings[1].id, 'active_model': 'stock.picking'} return_wizard = Form(self.env['stock.return.picking'].with_context(ctx)).save() return_picking_id, dummy = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_picking_id) return_picking.move_lines.quantity_done = 1 return_picking.button_validate() # Create a new invoice for the returned kit ctx = {'active_model': 'sale.order', 'active_ids': so.ids} create_invoice_wizard = self.env['sale.advance.payment.inv'].with_context(ctx).create({'advance_payment_method': 'delivered'}) create_invoice_wizard.create_invoices() reverse_invoice = so.invoice_ids[-1] with Form(reverse_invoice) as reverse_invoice_form: with reverse_invoice_form.invoice_line_ids.edit(0) as line: line.quantity = 1 reverse_invoice.action_post() amls = reverse_invoice.line_ids stock_out_aml = amls.filtered(lambda aml: aml.account_id == stock_output_account) self.assertEqual(stock_out_aml.debit, 20, 'Should be to the value of the returned component') self.assertEqual(stock_out_aml.credit, 0) cogs_aml = amls.filtered(lambda aml: aml.account_id == expense_account) self.assertEqual(cogs_aml.debit, 0) self.assertEqual(cogs_aml.credit, 20, 'Should be to the value of the returned component') def test_kit_margin_and_return_picking(self): """ This test ensure that, when returning the components of a sold kit, the sale order line cost does not change""" kit = self._cls_create_product('Super Kit', self.uom_unit) (kit + self.component_a).categ_id.property_cost_method = 'fifo' self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, { 'product_id': self.component_a.id, 'product_qty': 1.0, })] }) self.component_a.standard_price = 10 kit.button_bom_cost() stock_location = self.company_data['default_warehouse'].lot_stock_id self.env['stock.quant']._update_available_quantity(self.component_a, stock_location, 1) so_form = Form(self.env['sale.order']) so_form.partner_id = self.partner_a with so_form.order_line.new() as line: line.product_id = kit so = so_form.save() so.action_confirm() line = so.order_line price = line.product_id.with_company(line.company_id)._compute_average_price(0, line.product_uom_qty, line.move_ids) self.assertEqual(price, 10) picking = so.picking_ids action = picking.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() ctx = {'active_ids':picking.ids, 'active_id': picking.ids[0], 'active_model': 'stock.picking'} return_picking_wizard_form = Form(self.env['stock.return.picking'].with_context(ctx)) return_picking_wizard = return_picking_wizard_form.save() return_picking_wizard.create_returns() price = line.product_id.with_company(line.company_id)._compute_average_price(0, line.product_uom_qty, line.move_ids) self.assertEqual(price, 10) def test_kit_decrease_sol_qty(self): """ Create and confirm a SO with a qty. Increasing/Decreasing the SOL qty should update the qty on the delivery. Then, process the delivery, make a return and adapt the SOL qty -> there should not be any new picking """ stock_location = self.company_data['default_warehouse'].lot_stock_id custo_location = self.env.ref('stock.stock_location_customers') grp_uom = self.env.ref('uom.group_uom') self.env.user.write({'groups_id': [(4, grp_uom.id)]}) # 100 kit_3 = 100 x compo_f + 200 x compo_g self.env['stock.quant']._update_available_quantity(self.component_f, stock_location, 100) self.env['stock.quant']._update_available_quantity(self.component_g, stock_location, 200) so_form = Form(self.env['sale.order']) so_form.partner_id = self.partner_a with so_form.order_line.new() as line: line.product_id = self.kit_3 line.product_uom_qty = 7 line.product_uom = self.uom_ten so = so_form.save() so.action_confirm() delivery = so.picking_ids self.assertRecordValues(delivery.move_lines, [ {'product_id': self.component_f.id, 'product_uom_qty': 70}, {'product_id': self.component_g.id, 'product_uom_qty': 140}, ]) # Decrease with Form(so) as so_form: with so_form.order_line.edit(0) as line: line.product_uom_qty = 6 self.assertRecordValues(delivery.move_lines, [ {'product_id': self.component_f.id, 'product_uom_qty': 60}, {'product_id': self.component_g.id, 'product_uom_qty': 120}, ]) # Increase with Form(so) as so_form: with so_form.order_line.edit(0) as line: line.product_uom_qty = 10 self.assertRecordValues(delivery.move_lines, [ {'product_id': self.component_f.id, 'product_uom_qty': 100}, {'product_id': self.component_g.id, 'product_uom_qty': 200}, ]) delivery.action_set_quantities_to_reservation() delivery.button_validate() # Return 2 [uom_ten] x kit_3 return_wizard_form = Form(self.env['stock.return.picking'].with_context(active_ids=delivery.ids, active_id=delivery.id, active_model='stock.picking')) return_wizard = return_wizard_form.save() return_wizard.product_return_moves[0].quantity = 20 return_wizard.product_return_moves[1].quantity = 40 action = return_wizard.create_returns() return_picking = self.env['stock.picking'].browse(action['res_id']) return_picking.action_set_quantities_to_reservation() return_picking.button_validate() # Adapt the SOL qty according to the delivered one with Form(so) as so_form: with so_form.order_line.edit(0) as line: line.product_uom_qty = 8 self.assertRecordValues(so.picking_ids.sorted('id').move_lines, [ {'product_id': self.component_f.id, 'location_dest_id': custo_location.id, 'quantity_done': 100, 'state': 'done'}, {'product_id': self.component_g.id, 'location_dest_id': custo_location.id, 'quantity_done': 200, 'state': 'done'}, {'product_id': self.component_f.id, 'location_dest_id': stock_location.id, 'quantity_done': 20, 'state': 'done'}, {'product_id': self.component_g.id, 'location_dest_id': stock_location.id, 'quantity_done': 40, 'state': 'done'}, ]) def test_kit_decrease_sol_qty_to_zero(self): """ Create and confirm a SO with a kit product. Increasing/Decreasing the SOL qty should update the qty on the delivery. """ stock_location = self.company_data['default_warehouse'].lot_stock_id grp_uom = self.env.ref('uom.group_uom') self.env.user.write({'groups_id': [(4, grp_uom.id)]}) # 10 kit_3 = 10 x compo_f + 20 x compo_g self.env['stock.quant']._update_available_quantity(self.component_f, stock_location, 10) self.env['stock.quant']._update_available_quantity(self.component_g, stock_location, 20) so_form = Form(self.env['sale.order']) so_form.partner_id = self.partner_a with so_form.order_line.new() as line: line.product_id = self.kit_3 line.product_uom_qty = 2 line.product_uom = self.uom_ten so = so_form.save() so.action_confirm() delivery = so.picking_ids self.assertRecordValues(delivery.move_lines, [ {'product_id': self.component_f.id, 'product_uom_qty': 20}, {'product_id': self.component_g.id, 'product_uom_qty': 40}, ]) # Decrease the qty to 0 with Form(so) as so_form: with so_form.order_line.edit(0) as line: line.product_uom_qty = 0 self.assertRecordValues(delivery.move_lines, [ {'product_id': self.component_f.id, 'product_uom_qty': 0}, {'product_id': self.component_g.id, 'product_uom_qty': 0}, ]) def test_kit_return_and_decrease_sol_qty_to_zero(self): """ Create and confirm a SO with a kit product. Deliver & Return the components Set the SOL qty to 0 """ stock_location = self.company_data['default_warehouse'].lot_stock_id grp_uom = self.env.ref('uom.group_uom') self.env.user.write({'groups_id': [(4, grp_uom.id)]}) # 10 kit_3 = 10 x compo_f + 20 x compo_g self.env['stock.quant']._update_available_quantity(self.component_f, stock_location, 10) self.env['stock.quant']._update_available_quantity(self.component_g, stock_location, 20) so_form = Form(self.env['sale.order']) so_form.partner_id = self.partner_a with so_form.order_line.new() as line: line.product_id = self.kit_3 line.product_uom_qty = 2 line.product_uom = self.uom_ten so = so_form.save() so.action_confirm() delivery = so.picking_ids for m in delivery.move_lines: m.quantity_done = m.product_uom_qty delivery.button_validate() self.assertEqual(delivery.state, 'done') self.assertEqual(so.order_line.qty_delivered, 2) ctx = {'active_id': delivery.id, 'active_model': 'stock.picking'} return_wizard = Form(self.env['stock.return.picking'].with_context(ctx)).save() return_picking_id, dummy = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_picking_id) for m in return_picking.move_lines: m.quantity_done = m.product_uom_qty return_picking.button_validate() self.assertEqual(return_picking.state, 'done') self.assertEqual(so.order_line.qty_delivered, 0) with Form(so) as so_form: with so_form.order_line.edit(0) as line: line.product_uom_qty = 0 self.assertEqual(so.picking_ids, delivery | return_picking) def test_fifo_reverse_and_create_new_invoice(self): """ FIFO automated Kit with one component Receive the component: 1@10, 1@50 Deliver 1 kit Post the invoice, add a credit note with option 'new draft inv' Post the second invoice COGS should be based on the delivered kit """ kit = self._create_product('Simple Kit', self.uom_unit) categ_form = Form(self.env['product.category']) categ_form.name = 'Super Fifo' categ_form.property_cost_method = 'fifo' categ_form.property_valuation = 'real_time' categ = categ_form.save() (kit + self.component_a).categ_id = categ self.env['mrp.bom'].create({ 'product_tmpl_id': kit.product_tmpl_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [(0, 0, {'product_id': self.component_a.id, 'product_qty': 1.0})] }) in_moves = self.env['stock.move'].create([{ 'name': 'IN move @%s' % p, 'product_id': self.component_a.id, 'location_id': self.env.ref('stock.stock_location_suppliers').id, 'location_dest_id': self.company_data['default_warehouse'].lot_stock_id.id, 'product_uom': self.component_a.uom_id.id, 'product_uom_qty': 1, 'price_unit': p, } for p in [10, 50]]) in_moves._action_confirm() in_moves.quantity_done = 1 in_moves._action_done() so = self.env['sale.order'].create({ 'partner_id': self.env.ref('base.res_partner_1').id, 'order_line': [ (0, 0, { 'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1.0, 'product_uom': kit.uom_id.id, 'price_unit': 100, 'tax_id': False, })], }) so.action_confirm() picking = so.picking_ids picking.move_lines.quantity_done = 1.0 picking.button_validate() invoice01 = so._create_invoices() invoice01.action_post() move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=invoice01.ids).create({ 'refund_method': 'modify', 'journal_id': invoice01.journal_id.id, }) reversal = move_reversal.reverse_moves() invoice02 = self.env['account.move'].browse(reversal['res_id']) invoice02.action_post() amls = invoice02.line_ids stock_out_aml = amls.filtered(lambda aml: aml.account_id == categ.property_stock_account_output_categ_id) self.assertEqual(stock_out_aml.debit, 0) self.assertEqual(stock_out_aml.credit, 10) cogs_aml = amls.filtered(lambda aml: aml.account_id == categ.property_account_expense_categ_id) self.assertEqual(cogs_aml.debit, 10) self.assertEqual(cogs_aml.credit, 0) def test_kit_avco_fully_owned_and_delivered_invoice_post_delivery(self): self.stock_account_product_categ.property_cost_method = 'average' compo01, compo02, kit = self.env['product.product'].create([{ 'name': name, 'type': 'product', 'standard_price': price, 'categ_id': self.stock_account_product_categ.id, 'invoice_policy': 'delivery', } for name, price in [ ('Compo 01', 10), ('Compo 02', 20), ('Kit', 0), ]]) self.env['stock.quant']._update_available_quantity(compo01, self.company_data['default_warehouse'].lot_stock_id, 1, owner_id=self.partner_b) self.env['stock.quant']._update_available_quantity(compo02, self.company_data['default_warehouse'].lot_stock_id, 1, owner_id=self.partner_b) self.env['mrp.bom'].create({ 'product_id': kit.id, 'product_tmpl_id': kit.product_tmpl_id.id, 'product_uom_id': kit.uom_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo01.id, 'product_qty': 1.0}), (0, 0, {'product_id': compo02.id, 'product_qty': 1.0}), ], }) so = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 1.0, 'product_uom': kit.uom_id.id, 'price_unit': 5, 'tax_id': False, })], }) so.action_confirm() so.picking_ids.move_lines.quantity_done = 1 so.picking_ids.button_validate() invoice = so._create_invoices() invoice.action_post() # COGS should not exist because the products are owned by an external partner amls = invoice.line_ids self.assertRecordValues(amls, [ # pylint: disable=bad-whitespace {'account_id': self.company_data['default_account_revenue'].id, 'debit': 0, 'credit': 5}, {'account_id': self.company_data['default_account_receivable'].id, 'debit': 5, 'credit': 0}, ]) def test_kit_avco_partially_owned_and_delivered_invoice_post_delivery(self): self.stock_account_product_categ.property_cost_method = 'average' compo01, compo02, kit = self.env['product.product'].create([{ 'name': name, 'type': 'product', 'standard_price': price, 'categ_id': self.stock_account_product_categ.id, 'invoice_policy': 'delivery', } for name, price in [ ('Compo 01', 10), ('Compo 02', 20), ('Kit', 0), ]]) self.env['stock.quant']._update_available_quantity(compo01, self.company_data['default_warehouse'].lot_stock_id, 1, owner_id=self.partner_b) self.env['stock.quant']._update_available_quantity(compo01, self.company_data['default_warehouse'].lot_stock_id, 1) self.env['stock.quant']._update_available_quantity(compo02, self.company_data['default_warehouse'].lot_stock_id, 1, owner_id=self.partner_b) self.env['stock.quant']._update_available_quantity(compo02, self.company_data['default_warehouse'].lot_stock_id, 1) self.env['mrp.bom'].create({ 'product_id': kit.id, 'product_tmpl_id': kit.product_tmpl_id.id, 'product_uom_id': kit.uom_id.id, 'product_qty': 1.0, 'type': 'phantom', 'bom_line_ids': [ (0, 0, {'product_id': compo01.id, 'product_qty': 1.0}), (0, 0, {'product_id': compo02.id, 'product_qty': 1.0}), ], }) so = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'name': kit.name, 'product_id': kit.id, 'product_uom_qty': 2.0, 'product_uom': kit.uom_id.id, 'price_unit': 5, 'tax_id': False, })], }) so.action_confirm() so.picking_ids.move_line_ids.qty_done = 1 so.picking_ids.button_validate() invoice = so._create_invoices() invoice.action_post() # COGS should not exist because the products are owned by an external partner amls = invoice.line_ids self.assertRecordValues(amls, [ # pylint: disable=bad-whitespace {'account_id': self.company_data['default_account_revenue'].id, 'debit': 0, 'credit': 10}, {'account_id': self.company_data['default_account_receivable'].id, 'debit': 10, 'credit': 0}, {'account_id': self.company_data['default_account_stock_out'].id, 'debit': 0, 'credit': 30}, {'account_id': self.company_data['default_account_expense'].id, 'debit': 30, 'credit': 0}, ]) def test_avoid_removing_kit_bom_in_use(self): so = self.env['sale.order'].create({ 'partner_id': self.partner_a.id, 'order_line': [ (0, 0, { 'name': self.kit_1.name, 'product_id': self.kit_1.id, 'product_uom_qty': 1.0, 'product_uom': self.kit_1.uom_id.id, 'price_unit': 5, 'tax_id': False, })], }) self.bom_kit_1.toggle_active() self.bom_kit_1.toggle_active() so.action_confirm() with self.assertRaises(UserError): self.bom_kit_1.toggle_active() with self.assertRaises(UserError): self.bom_kit_1.unlink() for move in so.order_line.move_ids: move.quantity_done = move.product_uom_qty so.picking_ids.button_validate() self.assertEqual(so.picking_ids.state, 'done') with self.assertRaises(UserError): self.bom_kit_1.toggle_active() with self.assertRaises(UserError): self.bom_kit_1.unlink() invoice = so._create_invoices() invoice.action_post() self.assertEqual(invoice.state, 'posted') self.bom_kit_1.toggle_active() self.bom_kit_1.toggle_active() self.bom_kit_1.unlink()
46.282751
127,185
12,478
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo.tests.common import TransactionCase, Form from odoo.tools import mute_logger class TestSaleMrpProcurement(TransactionCase): def test_sale_mrp(self): self.env.ref('stock.route_warehouse0_mto').active = True warehouse0 = self.env.ref('stock.warehouse0') # In order to test the sale_mrp module in OpenERP, I start by creating a new product 'Slider Mobile' # I define product category Mobile Products Sellable. with mute_logger('odoo.tests.common.onchange'): # Suppress warning on "Changing your cost method" when creating a # product category pc = Form(self.env['product.category']) pc.name = 'Mobile Products Sellable' product_category_allproductssellable0 = pc.save() uom_unit = self.env.ref('uom.product_uom_unit') self.assertIn("seller_ids", self.env['product.template'].fields_get()) # I define product for Slider Mobile. product = Form(self.env['product.template']) product.categ_id = product_category_allproductssellable0 product.list_price = 200.0 product.name = 'Slider Mobile' product.detailed_type = 'product' product.uom_id = uom_unit product.uom_po_id = uom_unit product.route_ids.clear() product.route_ids.add(warehouse0.manufacture_pull_id.route_id) product.route_ids.add(warehouse0.mto_pull_id.route_id) product_template_slidermobile0 = product.save() product_template_slidermobile0.standard_price = 189 product_component = Form(self.env['product.product']) product_component.name = 'Battery' product_product_bettery = product_component.save() with Form(self.env['mrp.bom']) as bom: bom.product_tmpl_id = product_template_slidermobile0 with bom.bom_line_ids.new() as line: line.product_id = product_product_bettery line.product_qty = 4 # I create a sale order for product Slider mobile so_form = Form(self.env['sale.order']) so_form.partner_id = self.env['res.partner'].create({'name': 'Another Test Partner'}) with so_form.order_line.new() as line: line.product_id = product_template_slidermobile0.product_variant_ids line.price_unit = 200 line.product_uom_qty = 500.0 line.customer_lead = 7.0 sale_order_so0 = so_form.save() # I confirm the sale order sale_order_so0.action_confirm() # I verify that a manufacturing order has been generated, and that its name and reference are correct mo = self.env['mrp.production'].search([('origin', 'like', sale_order_so0.name)], limit=1) self.assertTrue(mo, 'Manufacturing order has not been generated') # Check the mo is displayed on the so self.assertEqual(mo.id, sale_order_so0.action_view_mrp_production()['res_id']) def test_sale_mrp_pickings(self): """ Test sale of multiple mrp products in MTO to avoid generating multiple deliveries to the customer location """ self.env.ref('stock.route_warehouse0_mto').active = True # Create warehouse self.customer_location = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers') self.warehouse = self.env['stock.warehouse'].create({ 'name': 'Test Warehouse', 'code': 'TWH' }) self.uom_unit = self.env.ref('uom.product_uom_unit') # Create raw product for manufactured product product_form = Form(self.env['product.product']) product_form.name = 'Raw Stick' product_form.detailed_type = 'product' product_form.uom_id = self.uom_unit product_form.uom_po_id = self.uom_unit self.raw_product = product_form.save() # Create manufactured product product_form = Form(self.env['product.product']) product_form.name = 'Stick' product_form.uom_id = self.uom_unit product_form.uom_po_id = self.uom_unit product_form.detailed_type = 'product' product_form.route_ids.clear() product_form.route_ids.add(self.warehouse.manufacture_pull_id.route_id) product_form.route_ids.add(self.warehouse.mto_pull_id.route_id) self.finished_product = product_form.save() # Create manifactured product which uses another manifactured product_form = Form(self.env['product.product']) product_form.name = 'Arrow' product_form.detailed_type = 'product' product_form.route_ids.clear() product_form.route_ids.add(self.warehouse.manufacture_pull_id.route_id) product_form.route_ids.add(self.warehouse.mto_pull_id.route_id) self.complex_product = product_form.save() ## Create raw product for manufactured product product_form = Form(self.env['product.product']) product_form.name = 'Raw Iron' product_form.detailed_type = 'product' product_form.uom_id = self.uom_unit product_form.uom_po_id = self.uom_unit self.raw_product_2 = product_form.save() # Create bom for manufactured product bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.finished_product bom_product_form.product_tmpl_id = self.finished_product.product_tmpl_id bom_product_form.product_qty = 1.0 bom_product_form.type = 'normal' with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.raw_product bom_line.product_qty = 2.0 self.bom = bom_product_form.save() ## Create bom for manufactured product bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.complex_product bom_product_form.product_tmpl_id = self.complex_product.product_tmpl_id with bom_product_form.bom_line_ids.new() as line: line.product_id = self.finished_product line.product_qty = 1.0 with bom_product_form.bom_line_ids.new() as line: line.product_id = self.raw_product_2 line.product_qty = 1.0 self.complex_bom = bom_product_form.save() with Form(self.warehouse) as warehouse: warehouse.manufacture_steps = 'pbm_sam' so_form = Form(self.env['sale.order']) so_form.partner_id = self.env['res.partner'].create({'name': 'Another Test Partner'}) with so_form.order_line.new() as line: line.product_id = self.complex_product line.price_unit = 1 line.product_uom_qty = 1 with so_form.order_line.new() as line: line.product_id = self.finished_product line.price_unit = 1 line.product_uom_qty = 1 sale_order_so0 = so_form.save() sale_order_so0.action_confirm() # Verify buttons are working as expected self.assertEqual(sale_order_so0.mrp_production_count, 2, "User should see the correct number of manufacture orders in smart button") pickings = sale_order_so0.picking_ids # One delivery... self.assertEqual(len(pickings), 1) # ...with two products move_lines = pickings[0].move_lines self.assertEqual(len(move_lines), 2) def test_post_prod_location_child_of_stock_location(self): """ 3-steps manufacturing, the post-prod location is a child of the stock location. Have a manufactured product with the manufacture route and a RR min=max=0. Confirm a SO with that product -> It should generate a MO """ warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) manufacture_route = warehouse.manufacture_pull_id.route_id warehouse.manufacture_steps = 'pbm_sam' warehouse.sam_loc_id.location_id = warehouse.lot_stock_id product, component = self.env['product.product'].create([{ 'name': 'Finished', 'type': 'product', 'route_ids': [(6, 0, manufacture_route.ids)], }, { 'name': 'Component', 'type': 'consu', }]) self.env['mrp.bom'].create({ 'product_id': product.id, 'product_tmpl_id': product.product_tmpl_id.id, 'product_uom_id': product.uom_id.id, 'product_qty': 1.0, 'type': 'normal', 'bom_line_ids': [ (0, 0, {'product_id': component.id, 'product_qty': 1}), ], }) self.env['stock.warehouse.orderpoint'].create({ 'name': product.name, 'location_id': warehouse.lot_stock_id.id, 'product_id': product.id, 'product_min_qty': 0, 'product_max_qty': 0, 'trigger': 'auto', }) so = self.env['sale.order'].create({ 'partner_id': self.env['res.partner'].create({'name': 'Super Partner'}).id, 'order_line': [ (0, 0, { 'name': product.name, 'product_id': product.id, 'product_uom_qty': 1.0, 'product_uom': product.uom_id.id, 'price_unit': 1, })], }) so.action_confirm() self.assertEqual(so.state, 'sale') mo = self.env['mrp.production'].search([('product_id', '=', product.id)], order='id desc', limit=1) self.assertIn(so.name, mo.origin) def test_so_reordering_rule(self): Orderpoint = self.env['stock.warehouse.orderpoint'] # mulitple variant product car = self.env['product.template'].create({ 'name': 'Car', }) color_attribute = self.env['product.attribute'].create({'name': 'Color', 'sequence': 1}) color_red = self.env['product.attribute.value'].create({ 'name': 'Red', 'attribute_id': color_attribute.id, 'sequence': 1, }) color_blue = self.env['product.attribute.value'].create({ 'name': 'Blue', 'attribute_id': color_attribute.id, 'sequence': 2, }) self.env['product.template.attribute.line'].create({ 'product_tmpl_id': car.id, 'attribute_id': color_attribute.id, 'value_ids': [(6, 0, [color_red.id, color_blue.id])], }) mrp_prod = car.product_variant_id component_prod = self.env['product.product'].create({ 'name': 'Component 1', 'type': 'product', }) bom = self.env['mrp.bom'].create([{ 'product_tmpl_id': mrp_prod.product_tmpl_id.id, 'product_id': mrp_prod.id, 'product_qty': 1, 'type': 'normal', 'bom_line_ids': [ (0, 0, {'product_id': component_prod.id, 'product_qty': 2}), ], }]) customer = self.env['res.partner'].create({ 'name': 'customer', }) self.env['sale.order'].create({ 'partner_id': customer.id, 'order_line': [ (0, 0, { 'product_id': mrp_prod.id, 'product_uom_qty': 3, })], }).action_confirm() Orderpoint._get_orderpoint_action() # change product type to Kit mrp_prod.orderpoint_ids.unlink() bom.type = 'phantom' self.env['sale.order'].create({ 'partner_id': customer.id, 'order_line': [ (0, 0, { 'product_id': mrp_prod.id, 'product_uom_qty': 3, })], }).action_confirm() Orderpoint._get_orderpoint_action() orderpoint_kit = Orderpoint.search([('product_id', '=', mrp_prod.id)]) orderpoint_component = Orderpoint.search([('product_id', '=', component_prod.id)]) self.assertFalse(orderpoint_kit) self.assertEqual(orderpoint_component.qty_to_order, 3*2) # only exclude the kit variant self.assertIn(car.product_variant_id.id, Orderpoint._product_exclude_list()) self.assertNotIn((car.product_variant_ids - car.product_variant_id).id, Orderpoint._product_exclude_list())
39.865815
12,478
7,247
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form from odoo.addons.mrp.tests.common import TestMrpCommon class TestMultistepManufacturing(TestMrpCommon): def setUp(self): super(TestMultistepManufacturing, self).setUp() self.env.ref('stock.route_warehouse0_mto').active = True self.MrpProduction = self.env['mrp.production'] # Create warehouse warehouse_form = Form(self.env['stock.warehouse']) warehouse_form.name = 'Test' warehouse_form.code = 'Test' self.warehouse = warehouse_form.save() self.uom_unit = self.env.ref('uom.product_uom_unit') # Create manufactured product product_form = Form(self.env['product.product']) product_form.name = 'Stick' product_form.uom_id = self.uom_unit product_form.uom_po_id = self.uom_unit product_form.route_ids.clear() product_form.route_ids.add(self.warehouse.manufacture_pull_id.route_id) product_form.route_ids.add(self.warehouse.mto_pull_id.route_id) self.product_manu = product_form.save() # Create raw product for manufactured product product_form = Form(self.env['product.product']) product_form.name = 'Raw Stick' product_form.uom_id = self.uom_unit product_form.uom_po_id = self.uom_unit self.product_raw = product_form.save() # Create bom for manufactured product bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.product_manu bom_product_form.product_tmpl_id = self.product_manu.product_tmpl_id bom_product_form.product_qty = 1.0 bom_product_form.type = 'normal' with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.product_raw bom_line.product_qty = 2.0 self.bom_prod_manu = bom_product_form.save() # Create sale order sale_form = Form(self.env['sale.order']) sale_form.partner_id = self.env['res.partner'].create({'name': 'My Test Partner'}) sale_form.picking_policy = 'direct' sale_form.warehouse_id = self.warehouse with sale_form.order_line.new() as line: line.name = self.product_manu.name line.product_id = self.product_manu line.product_uom_qty = 1.0 line.product_uom = self.uom_unit line.price_unit = 10.0 self.sale_order = sale_form.save() def test_00_manufacturing_step_one(self): """ Testing for Step-1 """ # Change steps of manufacturing. with Form(self.warehouse) as warehouse: warehouse.manufacture_steps = 'mrp_one_step' # Confirm sale order. self.sale_order.action_confirm() # Check all procurements for created sale order mo_procurement = self.MrpProduction.search([('origin', '=', self.sale_order.name)]) # Get manufactured procurement self.assertEqual(mo_procurement.location_src_id.id, self.warehouse.lot_stock_id.id, "Source loction does not match.") self.assertEqual(mo_procurement.location_dest_id.id, self.warehouse.lot_stock_id.id, "Destination location does not match.") self.assertEqual(len(mo_procurement), 1, "No Procurement !") def test_01_manufacturing_step_two(self): """ Testing for Step-2 """ with Form(self.warehouse) as warehouse: warehouse.manufacture_steps = 'pbm' self.sale_order.action_confirm() # Get manufactured procurement mo_procurement = self.MrpProduction.search([('origin', '=', self.sale_order.name)]) mo = self.env['mrp.production'].search([ ('origin', '=', self.sale_order.name), ('product_id', '=', self.product_manu.id), ]) self.assertEqual(self.sale_order.action_view_mrp_production()['res_id'], mo.id) self.assertEqual(mo_procurement.location_src_id.id, self.warehouse.pbm_loc_id.id, "Source loction does not match.") self.assertEqual(mo_procurement.location_dest_id.id, self.warehouse.lot_stock_id.id, "Destination location does not match.") self.assertEqual(len(mo_procurement), 1, "No Procurement !") def test_cancel_multilevel_manufacturing(self): """ Testing for multilevel Manufacturing orders. When user creates multi-level manufacturing orders, and then cancelles child manufacturing order, an activity should be generated on parent MO, to notify user that demands from child MO has been cancelled. """ product_form = Form(self.env['product.product']) product_form.name = 'Screw' self.product_screw = product_form.save() # Add routes for manufacturing and make to order to the raw material product with Form(self.product_raw) as p1: p1.route_ids.clear() p1.route_ids.add(self.warehouse_1.manufacture_pull_id.route_id) p1.route_ids.add(self.warehouse_1.mto_pull_id.route_id) # New BoM for raw material product, it will generate another Production order i.e. child Production order bom_product_form = Form(self.env['mrp.bom']) bom_product_form.product_id = self.product_raw bom_product_form.product_tmpl_id = self.product_raw.product_tmpl_id bom_product_form.product_qty = 1.0 with bom_product_form.bom_line_ids.new() as bom_line: bom_line.product_id = self.product_screw bom_line.product_qty = 5.0 self.bom_prod_manu = bom_product_form.save() # create MO from sale order. self.sale_order.action_confirm() # Find child MO. child_manufaturing = self.env['mrp.production'].search([('product_id', '=', self.product_raw.id)]) self.assertTrue((len(child_manufaturing.ids) == 1), 'Manufacturing order of raw material must be generated.') # Cancel child MO. child_manufaturing.action_cancel() manufaturing_from_so = self.env['mrp.production'].search([('product_id', '=', self.product_manu.id)]) # Check if activity is generated or not on parent MO. exception = self.env['mail.activity'].search([('res_model', '=', 'mrp.production'), ('res_id', '=', manufaturing_from_so.id)]) self.assertEqual(len(exception.ids), 1, 'When user cancelled child manufacturing, exception must be generated on parent manufacturing.') def test_manufacturing_step_three(self): """ Testing for Step-3 """ with Form(self.warehouse) as warehouse: warehouse.manufacture_steps = 'pbm_sam' self.sale_order.action_confirm() mo = self.env['mrp.production'].search([ ('origin', '=', self.sale_order.name), ('product_id', '=', self.product_manu.id), ]) self.assertEqual(self.sale_order.mrp_production_count, 1) self.assertEqual(mo.sale_order_count, 1) self.assertEqual(self.sale_order.action_view_mrp_production()['res_id'], mo.id) self.assertEqual(mo.action_view_sale_orders()['res_id'], self.sale_order.id)
47.993377
7,247
7,885
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 import fields from odoo.addons.stock.tests.common2 import TestStockCommon from odoo.tests import Form class TestSaleMrpLeadTime(TestStockCommon): def setUp(self): super(TestSaleMrpLeadTime, self).setUp() self.env.ref('stock.route_warehouse0_mto').active = True # Update the product_1 with type, route, Manufacturing Lead Time and Customer Lead Time with Form(self.product_1) as p1: p1.type = 'product' p1.produce_delay = 5.0 p1.sale_delay = 5.0 p1.route_ids.clear() p1.route_ids.add(self.warehouse_1.manufacture_pull_id.route_id) p1.route_ids.add(self.warehouse_1.mto_pull_id.route_id) # Update the product_2 with type with Form(self.product_2) as p2: p2.type = 'consu' # Create Bill of materials for product_1 with Form(self.env['mrp.bom']) as bom: bom.product_tmpl_id = self.product_1.product_tmpl_id bom.product_qty = 2 with bom.bom_line_ids.new() as line: line.product_id = self.product_2 line.product_qty = 4 def test_00_product_company_level_delays(self): """ In order to check schedule date, set product's Manufacturing Lead Time and Customer Lead Time and also set company's Manufacturing Lead Time and Sales Safety Days.""" company = self.env.ref('base.main_company') # Update company with Manufacturing Lead Time and Sales Safety Days company.write({'manufacturing_lead': 3.0, 'security_lead': 3.0}) # Create sale order of product_1 order_form = Form(self.env['sale.order']) order_form.partner_id = self.partner_1 with order_form.order_line.new() as line: line.product_id = self.product_1 line.product_uom_qty = 10 order = order_form.save() # Confirm sale order order.action_confirm() # Check manufacturing order created or not manufacturing_order = self.env['mrp.production'].search([('product_id', '=', self.product_1.id), ('move_dest_ids', 'in', order.picking_ids[0].move_lines.ids)]) self.assertTrue(manufacturing_order, 'Manufacturing order should be created.') # Check schedule date of picking deadline_picking = fields.Datetime.from_string(order.date_order) + timedelta(days=self.product_1.sale_delay) out_date = deadline_picking - timedelta(days=company.security_lead) self.assertAlmostEqual( order.picking_ids[0].scheduled_date, out_date, delta=timedelta(seconds=1), msg='Schedule date of picking should be equal to: Order date + Customer Lead Time - Sales Safety Days.' ) self.assertAlmostEqual( order.picking_ids[0].date_deadline, deadline_picking, delta=timedelta(seconds=1), msg='Deadline date of picking should be equal to: Order date + Customer Lead Time.' ) # Check schedule date and deadline of manufacturing order mo_scheduled = out_date - timedelta(days=self.product_1.produce_delay) - timedelta(days=company.manufacturing_lead) self.assertAlmostEqual( fields.Datetime.from_string(manufacturing_order.date_planned_start), mo_scheduled, delta=timedelta(seconds=1), msg="Schedule date of manufacturing order should be equal to: Schedule date of picking - product's Manufacturing Lead Time - company's Manufacturing Lead Time." ) self.assertAlmostEqual( fields.Datetime.from_string(manufacturing_order.date_deadline), deadline_picking, delta=timedelta(seconds=1), msg="Deadline date of manufacturing order should be equal to the deadline of sale picking" ) def test_01_product_route_level_delays(self): """ In order to check schedule dates, set product's Manufacturing Lead Time and Customer Lead Time and also set warehouse route's delay.""" # Update warehouse_1 with Outgoing Shippings pick + pack + ship self.warehouse_1.write({'delivery_steps': 'pick_pack_ship'}) # Set delay on pull rule for pull_rule in self.warehouse_1.delivery_route_id.rule_ids: pull_rule.write({'delay': 2}) # Create sale order of product_1 order_form = Form(self.env['sale.order']) order_form.partner_id = self.partner_1 order_form.warehouse_id = self.warehouse_1 with order_form.order_line.new() as line: line.product_id = self.product_1 line.product_uom_qty = 6 order = order_form.save() # Confirm sale order order.action_confirm() # Run scheduler self.env['procurement.group'].run_scheduler() # Check manufacturing order created or not manufacturing_order = self.env['mrp.production'].search([('product_id', '=', self.product_1.id)]) self.assertTrue(manufacturing_order, 'Manufacturing order should be created.') # Check the picking crated or not self.assertTrue(order.picking_ids, "Pickings should be created.") # Check schedule date of ship type picking out = order.picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse_1.out_type_id) out_min_date = fields.Datetime.from_string(out.scheduled_date) out_date = fields.Datetime.from_string(order.date_order) + timedelta(days=self.product_1.sale_delay) - timedelta(days=out.move_lines[0].rule_id.delay) self.assertAlmostEqual( out_min_date, out_date, delta=timedelta(seconds=10), msg='Schedule date of ship type picking should be equal to: order date + Customer Lead Time - pull rule delay.' ) # Check schedule date of pack type picking pack = order.picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse_1.pack_type_id) pack_min_date = fields.Datetime.from_string(pack.scheduled_date) pack_date = out_date - timedelta(days=pack.move_lines[0].rule_id.delay) self.assertAlmostEqual( pack_min_date, pack_date, delta=timedelta(seconds=10), msg='Schedule date of pack type picking should be equal to: Schedule date of ship type picking - pull rule delay.' ) # Check schedule date of pick type picking pick = order.picking_ids.filtered(lambda r: r.picking_type_id == self.warehouse_1.pick_type_id) pick_min_date = fields.Datetime.from_string(pick.scheduled_date) self.assertAlmostEqual( pick_min_date, pack_date, delta=timedelta(seconds=10), msg='Schedule date of pick type picking should be equal to: Schedule date of pack type picking.' ) # Check schedule date and deadline date of manufacturing order mo_scheduled = out_date - timedelta(days=self.product_1.produce_delay) - timedelta(days=self.warehouse_1.delivery_route_id.rule_ids[0].delay) - timedelta(days=self.env.ref('base.main_company').manufacturing_lead) self.assertAlmostEqual( fields.Datetime.from_string(manufacturing_order.date_planned_start), mo_scheduled, delta=timedelta(seconds=1), msg="Schedule date of manufacturing order should be equal to: Schedule date of picking - product's Manufacturing Lead Time- delay pull_rule." ) self.assertAlmostEqual( manufacturing_order.date_deadline, order.picking_ids[0].date_deadline, delta=timedelta(seconds=1), msg="Deadline date of manufacturing order should be equal to the deadline of sale picking" )
48.67284
7,885
2,813
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 html2plaintext @common.tagged('post_install', '-at_install') class TestSaleMrpInvoices(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_by_lot = cls.env['product.product'].create({ 'name': 'Product By Lot', 'type': 'product', 'tracking': 'lot', }) cls.warehouse = cls.env['stock.warehouse'].search([('company_id', '=', cls.env.company.id)], limit=1) cls.stock_location = cls.warehouse.lot_stock_id cls.lot = cls.env['stock.production.lot'].create({ 'name': 'LOT0001', 'product_id': cls.product_by_lot.id, 'company_id': cls.env.company.id, }) cls.env['stock.quant']._update_available_quantity(cls.product_by_lot, cls.stock_location, 10, lot_id=cls.lot) cls.tracked_kit = cls.env['product.product'].create({ 'name': 'Simple Kit', 'type': 'consu', }) cls.env['mrp.bom'].create({ 'product_tmpl_id': cls.tracked_kit.product_tmpl_id.id, 'type': 'phantom', 'bom_line_ids': [(0, 0, { 'product_id': cls.product_by_lot.id, 'product_qty': 1, })] }) cls.partner = cls.env.ref('base.res_partner_1') def test_deliver_and_invoice_tracked_components(self): """ Suppose the lots are printed on the invoices. The user sells a kit that has one tracked component. The lot of the delivered component should be on the invoice. """ display_lots = self.env.ref('stock_account.group_lot_on_invoice') display_uom = self.env.ref('uom.group_uom') self.env.user.write({'groups_id': [(4, display_lots.id), (4, display_uom.id)]}) so = self.env['sale.order'].create({ 'partner_id': self.partner.id, 'order_line': [ (0, 0, {'name': self.tracked_kit.name, 'product_id': self.tracked_kit.id, 'product_uom_qty': 1}), ], }) so.action_confirm() action = so.picking_ids.button_validate() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() invoice = so._create_invoices() invoice.action_post() report = self.env['ir.actions.report']._get_report_from_name('account.report_invoice_with_payments') html = report._render_qweb_html(invoice.ids)[0] text = html2plaintext(html) self.assertRegex(text, r'Product By Lot\n1.00\nUnits\nLOT0001', "There should be a line that specifies 1 x LOT0001")
40.185714
2,813
2,569
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models class AccountMoveLine(models.Model): _inherit = "account.move.line" def _stock_account_get_anglo_saxon_price_unit(self): price_unit = super(AccountMoveLine, self)._stock_account_get_anglo_saxon_price_unit() so_line = self.sale_line_ids and self.sale_line_ids[-1] or False if so_line: bom = self.env['mrp.bom']._bom_find(products=so_line.product_id, company_id=so_line.company_id.id, bom_type='phantom')[so_line.product_id] if bom: is_line_reversing = self.move_id.move_type == 'out_refund' qty_to_invoice = self.product_uom_id._compute_quantity(self.quantity, self.product_id.uom_id) account_moves = so_line.invoice_lines.move_id.filtered(lambda m: m.state == 'posted' and bool(m.reversed_entry_id) == is_line_reversing) posted_invoice_lines = account_moves.line_ids.filtered(lambda l: l.is_anglo_saxon_line and l.product_id == self.product_id and l.balance > 0) qty_invoiced = sum([x.product_uom_id._compute_quantity(x.quantity, x.product_id.uom_id) for x in posted_invoice_lines]) reversal_cogs = posted_invoice_lines.move_id.reversal_move_id.line_ids.filtered(lambda l: l.is_anglo_saxon_line and l.product_id == self.product_id and l.balance > 0) qty_invoiced -= sum([line.product_uom_id._compute_quantity(line.quantity, line.product_id.uom_id) for line in reversal_cogs]) moves = so_line.move_ids average_price_unit = 0 components_qty = so_line._get_bom_component_qty(bom) storable_components = self.env['product.product'].search([('id', 'in', list(components_qty.keys())), ('type', '=', 'product')]) for product in storable_components: factor = components_qty[product.id]['qty'] prod_moves = moves.filtered(lambda m: m.product_id == product) prod_qty_invoiced = factor * qty_invoiced prod_qty_to_invoice = factor * qty_to_invoice product = product.with_company(self.company_id).with_context(is_returned=is_line_reversing) average_price_unit += factor * product._compute_average_price(prod_qty_invoiced, prod_qty_to_invoice, prod_moves) price_unit = average_price_unit / bom.product_qty or price_unit price_unit = self.product_id.uom_id._compute_price(price_unit, self.product_uom_id) return price_unit
69.432432
2,569
922
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class StockMove(models.Model): _inherit = 'stock.move' def _prepare_procurement_values(self): res = super()._prepare_procurement_values() res['analytic_account_id'] = self.sale_line_id.order_id.analytic_account_id return res class StockMoveLine(models.Model): _inherit = 'stock.move.line' def _compute_sale_price(self): kit_lines = self.filtered(lambda move_line: move_line.move_id.bom_line_id.bom_id.type == 'phantom') for move_line in kit_lines: unit_price = move_line.product_id.list_price qty = move_line.product_uom_id._compute_quantity(move_line.qty_done, move_line.product_id.uom_id) move_line.sale_price = unit_price * qty super(StockMoveLine, self - kit_lines)._compute_sale_price()
36.88
922
1,359
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 MrpProduction(models.Model): _inherit = 'mrp.production' sale_order_count = fields.Integer( "Count of Source SO", compute='_compute_sale_order_count', groups='sales_team.group_sale_salesman') @api.depends('procurement_group_id.mrp_production_ids.move_dest_ids.group_id.sale_id') def _compute_sale_order_count(self): for production in self: production.sale_order_count = len(production.procurement_group_id.mrp_production_ids.move_dest_ids.group_id.sale_id) def action_view_sale_orders(self): self.ensure_one() sale_order_ids = self.procurement_group_id.mrp_production_ids.move_dest_ids.group_id.sale_id.ids action = { 'res_model': 'sale.order', 'type': 'ir.actions.act_window', } if len(sale_order_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': sale_order_ids[0], }) else: action.update({ 'name': _("Sources Sale Orders of %s", self.name), 'domain': [('id', 'in', sale_order_ids)], 'view_mode': 'tree,form', }) return action
35.763158
1,359
1,390
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.exceptions import UserError class MrpBom(models.Model): _inherit = 'mrp.bom' def toggle_active(self): self.filtered(lambda bom: bom.active)._ensure_bom_is_free() return super().toggle_active() def unlink(self): self._ensure_bom_is_free() return super().unlink() def _ensure_bom_is_free(self): product_ids = [] for bom in self: if bom.type != 'phantom': continue product_ids += bom.product_id.ids or bom.product_tmpl_id.product_variant_ids.ids if not product_ids: return lines = self.env['sale.order.line'].search([ ('state', 'in', ('sale', 'done')), ('invoice_status', 'in', ('no', 'to invoice')), ('product_id', 'in', product_ids), ('move_ids.state', '!=', 'cancel'), ]) if lines: product_names = ', '.join(lines.product_id.mapped('name')) raise UserError(_('As long as there are some sale order lines that must be delivered/invoiced and are ' 'related to these bills of materials, you can not remove them.\n' 'The error concerns these products: %s', product_names))
37.567568
1,390
10,406
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.tools import float_compare class SaleOrder(models.Model): _inherit = 'sale.order' mrp_production_count = fields.Integer( "Count of MO generated", compute='_compute_mrp_production_count', groups='mrp.group_mrp_user') @api.depends('procurement_group_id.stock_move_ids.created_production_id.procurement_group_id.mrp_production_ids') def _compute_mrp_production_count(self): data = self.env['procurement.group'].read_group([('sale_id', 'in', self.ids)], ['ids:array_agg(id)'], ['sale_id']) mrp_count = dict() for item in data: procurement_groups = self.env['procurement.group'].browse(item['ids']) mrp_count[item['sale_id'][0]] = len( set(procurement_groups.stock_move_ids.created_production_id.procurement_group_id.mrp_production_ids.ids) | set(procurement_groups.mrp_production_ids.ids)) for sale in self: sale.mrp_production_count = mrp_count.get(sale.id) def action_view_mrp_production(self): self.ensure_one() procurement_groups = self.env['procurement.group'].search([('sale_id', 'in', self.ids)]) mrp_production_ids = set(procurement_groups.stock_move_ids.created_production_id.procurement_group_id.mrp_production_ids.ids) |\ set(procurement_groups.mrp_production_ids.ids) action = { 'res_model': 'mrp.production', 'type': 'ir.actions.act_window', } if len(mrp_production_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': mrp_production_ids.pop(), }) else: action.update({ 'name': _("Manufacturing Orders Generated by %s", self.name), 'domain': [('id', 'in', list(mrp_production_ids))], 'view_mode': 'tree,form', }) return action class SaleOrderLine(models.Model): _inherit = 'sale.order.line' @api.depends('product_uom_qty', 'qty_delivered', 'product_id', 'state') def _compute_qty_to_deliver(self): """The inventory widget should now be visible in more cases if the product is consumable.""" super(SaleOrderLine, self)._compute_qty_to_deliver() for line in self: # Hide the widget for kits since forecast doesn't support them. boms = self.env['mrp.bom'] if line.state == 'sale': boms = line.move_ids.mapped('bom_line_id.bom_id') elif line.state in ['draft', 'sent'] and line.product_id: boms = boms._bom_find(line.product_id, company_id=line.company_id.id, bom_type='phantom')[line.product_id] relevant_bom = boms.filtered(lambda b: b.type == 'phantom' and (b.product_id == line.product_id or (b.product_tmpl_id == line.product_id.product_tmpl_id and not b.product_id))) if relevant_bom: line.display_qty_widget = False continue if line.state == 'draft' and line.product_type == 'consu': components = line.product_id.get_components() if components and components != [line.product_id.id]: line.display_qty_widget = True def _compute_qty_delivered(self): super(SaleOrderLine, self)._compute_qty_delivered() for order_line in self: if order_line.qty_delivered_method == 'stock_move': boms = order_line.move_ids.filtered(lambda m: m.state != 'cancel').mapped('bom_line_id.bom_id') dropship = any(m._is_dropshipped() for m in order_line.move_ids) if not boms and dropship: boms = boms._bom_find(order_line.product_id, company_id=order_line.company_id.id, bom_type='phantom')[order_line.product_id] # We fetch the BoMs of type kits linked to the order_line, # the we keep only the one related to the finished produst. # This bom shoud be the only one since bom_line_id was written on the moves relevant_bom = boms.filtered(lambda b: b.type == 'phantom' and (b.product_id == order_line.product_id or (b.product_tmpl_id == order_line.product_id.product_tmpl_id and not b.product_id))) if relevant_bom: # In case of dropship, we use a 'all or nothing' policy since 'bom_line_id' was # not written on a move coming from a PO: all moves (to customer) must be done # and the returns must be delivered back to the customer # FIXME: if the components of a kit have different suppliers, multiple PO # are generated. If one PO is confirmed and all the others are in draft, receiving # the products for this PO will set the qty_delivered. We might need to check the # state of all PO as well... but sale_mrp doesn't depend on purchase. if dropship: moves = order_line.move_ids.filtered(lambda m: m.state != 'cancel') if any((m.location_dest_id.usage == 'customer' and m.state != 'done') or (m.location_dest_id.usage != 'customer' and m.state == 'done' and float_compare(m.quantity_done, sum(sub_m.product_uom._compute_quantity(sub_m.quantity_done, m.product_uom) for sub_m in m.returned_move_ids if sub_m.state == 'done'), precision_rounding=m.product_uom.rounding) > 0) for m in moves) or not moves: order_line.qty_delivered = 0 else: order_line.qty_delivered = order_line.product_uom_qty continue moves = order_line.move_ids.filtered(lambda m: m.state == 'done' and not m.scrapped) filters = { 'incoming_moves': lambda m: m.location_dest_id.usage == 'customer' and (not m.origin_returned_move_id or (m.origin_returned_move_id and m.to_refund)), 'outgoing_moves': lambda m: m.location_dest_id.usage != 'customer' and m.to_refund } order_qty = order_line.product_uom._compute_quantity(order_line.product_uom_qty, relevant_bom.product_uom_id) qty_delivered = moves._compute_kit_quantities(order_line.product_id, order_qty, relevant_bom, filters) order_line.qty_delivered += relevant_bom.product_uom_id._compute_quantity(qty_delivered, order_line.product_uom) # If no relevant BOM is found, fall back on the all-or-nothing policy. This happens # when the product sold is made only of kits. In this case, the BOM of the stock moves # do not correspond to the product sold => no relevant BOM. elif boms: # if the move is ingoing, the product **sold** has delivered qty 0 if all(m.state == 'done' and m.location_dest_id.usage == 'customer' for m in order_line.move_ids): order_line.qty_delivered = order_line.product_uom_qty else: order_line.qty_delivered = 0.0 def compute_uom_qty(self, new_qty, stock_move, rounding=True): #check if stock move concerns a kit if stock_move.bom_line_id: return new_qty * stock_move.bom_line_id.product_qty return super(SaleOrderLine, self).compute_uom_qty(new_qty, stock_move, rounding) def _get_bom_component_qty(self, bom): bom_quantity = self.product_id.uom_id._compute_quantity(1, bom.product_uom_id, rounding_method='HALF-UP') boms, lines = bom.explode(self.product_id, bom_quantity) components = {} for line, line_data in lines: product = line.product_id.id uom = line.product_uom_id qty = line_data['qty'] if components.get(product, False): if uom.id != components[product]['uom']: from_uom = uom to_uom = self.env['uom.uom'].browse(components[product]['uom']) qty = from_uom._compute_quantity(qty, to_uom) components[product]['qty'] += qty else: # To be in the uom reference of the product to_uom = self.env['product.product'].browse(product).uom_id if uom.id != to_uom.id: from_uom = uom qty = from_uom._compute_quantity(qty, to_uom) components[product] = {'qty': qty, 'uom': to_uom.id} return components def _get_qty_procurement(self, previous_product_uom_qty=False): self.ensure_one() # Specific case when we change the qty on a SO for a kit product. # We don't try to be too smart and keep a simple approach: we use the quantity of entire # kits that are currently in delivery bom = self.env['mrp.bom']._bom_find(self.product_id, bom_type='phantom')[self.product_id] if bom: moves = self.move_ids.filtered(lambda r: r.state != 'cancel' and not r.scrapped) filters = { 'incoming_moves': lambda m: m.location_dest_id.usage == 'customer' and (not m.origin_returned_move_id or (m.origin_returned_move_id and m.to_refund)), 'outgoing_moves': lambda m: m.location_dest_id.usage != 'customer' and m.to_refund } order_qty = previous_product_uom_qty.get(self.id, 0) if previous_product_uom_qty else self.product_uom_qty order_qty = self.product_uom._compute_quantity(order_qty, bom.product_uom_id) qty = moves._compute_kit_quantities(self.product_id, order_qty, bom, filters) return bom.product_uom_id._compute_quantity(qty, self.product_uom) return super(SaleOrderLine, self)._get_qty_procurement(previous_product_uom_qty=previous_product_uom_qty)
59.462857
10,406
1,760
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Resellers', 'category': 'Website/Website', 'summary': 'Publish your resellers/partners and forward leads to them', 'version': '1.0', 'description': """ This module allows to publish your resellers/partners on your website and to forward incoming leads/opportunities to them. **Publish a partner** To publish a partner, set a *Level* in their contact form (in the Partner Assignment section) and click the *Publish* button. **Forward leads** Forwarding leads can be done for one or several leads at a time. The action is available in the *Assigned Partner* section of the lead/opportunity form view and in the *Action* menu of the list view. The automatic assignment is figured from the weight of partner levels and the geolocalization. Partners get leads that are located around them. """, 'depends': ['base_geolocalize', 'crm', 'account', 'website_partner', 'website_google_map', 'portal'], 'data': [ 'data/crm_tag_data.xml', 'data/mail_template_data.xml', 'security/ir.model.access.csv', 'security/ir_rule.xml', 'wizard/crm_forward_to_partner_view.xml', 'views/res_partner_views.xml', 'views/crm_lead_views.xml', 'views/website_crm_partner_assign_templates.xml', 'report/crm_partner_report_view.xml', ], 'demo': [ 'data/res_partner_demo.xml', 'data/crm_lead_demo.xml', 'data/res_partner_grade_demo.xml', ], 'installable': True, 'assets': { 'web.assets_frontend': [ 'website_crm_partner_assign/static/src/**/*', ], }, 'license': 'LGPL-3', }
35.918367
1,760
7,454
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from odoo.exceptions import AccessError from odoo.tests.common import TransactionCase from odoo.addons.crm.tests.common import TestCrmCommon from odoo.addons.mail.tests.common import mail_new_test_user class TestPartnerAssign(TransactionCase): def setUp(self): super(TestPartnerAssign, self).setUp() self.customer_uk = self.env['res.partner'].create({ 'name': 'Nigel', 'country_id': self.env.ref('base.uk').id, 'city': 'Birmingham', 'zip': 'B46 3AG', 'street': 'Cannon Hill Park', }) self.lead_uk = self.env['crm.lead'].create({ 'type': 'opportunity', 'name': 'Office Design and Architecture', 'partner_id': self.customer_uk.id }) def geo_find(addr, **kw): return { 'Wavre, Belgium': (50.7158956, 4.6128075), 'Cannon Hill Park, B46 3AG Birmingham, United Kingdom': (52.45216, -1.898578), }.get(addr) patcher = patch('odoo.addons.base_geolocalize.models.base_geocoder.GeoCoder.geo_find', wraps=geo_find) patcher.start() self.addCleanup(patcher.stop) def test_partner_assign(self): """ Test the automatic assignation using geolocalisation """ partner_be = self.env['res.partner'].create({ "name": "Agrolait", "is_company": True, "city": "Wavre", "zip": "1300", "country_id": self.env.ref("base.be").id, "street": "69 rue de Namur", "partner_weight": 10, }) partner_uk = self.env['res.partner'].create({ "name": "Think Big Systems", "is_company": True, "city": "London", "country_id": self.env.ref("base.uk").id, "street": "89 Lingfield Tower", "partner_weight": 10, }) lead = self.lead_uk # In order to test find nearest Partner functionality and assign to opportunity, # I Set Geo Lattitude and Longitude according to partner address. # YTI Note: We should probably mock the call partner_be.with_context(force_geo_localize=True).geo_localize() # I check Geo Latitude and Longitude of partner after set self.assertTrue(50 < partner_be.partner_latitude < 51, "Latitude is wrong: 50 < %s < 51" % partner_be.partner_latitude) self.assertTrue(3 < partner_be.partner_longitude < 5, "Longitude is wrong: 3 < %s < 5" % partner_be.partner_longitude) # I assign nearest partner to opportunity. lead.assign_partner() # I check assigned partner of opportunity who is nearest Geo Latitude and Longitude of opportunity. self.assertEqual(lead.partner_assigned_id, partner_uk, "Opportuniy is not assigned nearest partner") self.assertTrue(50 < lead.partner_latitude < 55, "Latitude is wrong: 50 < %s < 55" % lead.partner_latitude) self.assertTrue(-4 < lead.partner_longitude < -1, "Longitude is wrong: -4 < %s < -1" % lead.partner_longitude) self.assertTrue(lead.date_partner_assign, "Partner Assignment Date should be set") # I forward this opportunity to its nearest partner. context = dict(self.env.context, default_model='crm.lead', default_res_id=lead.id, active_ids=lead.ids) lead_forwarded = self.env['crm.lead.forward.to.partner'].with_context(context).create({}) try: lead_forwarded.action_forward() except: pass class TestPartnerLeadPortal(TestCrmCommon): def setUp(self): super(TestPartnerLeadPortal, self).setUp() # Partner Grade self.grade = self.env['res.partner.grade'].create({ 'name': "Grade Test", 'partner_weight': 42, 'sequence': 3, }) # Integrating user/partner, having a salesman self.user_portal = mail_new_test_user( self.env, login='user_portal', name='Patrick Portal', email='portal@test.example.com', company_id=self.env.ref("base.main_company").id, grade_id=self.grade.id, user_id=self.user_sales_manager.id, notification_type='inbox', groups='base.group_portal', ) # New lead, assigned to the new portal self.lead_portal = self.env['crm.lead'].with_context(mail_notrack=True).create({ 'type': "lead", 'name': "Test lead new", 'user_id': False, 'team_id': False, 'description': "This is the description of the test new lead.", 'partner_assigned_id': self.user_portal.partner_id.id }) def test_partner_lead_accept(self): """ Test an integrating partner accepting the lead """ self.lead_portal.with_user(self.user_portal).partner_interested(comment="Oh yeah, I take that lead !") self.assertEqual(self.lead_portal.type, 'opportunity') def test_partner_lead_decline(self): """ Test an integrating partner decline the lead """ self.lead_portal.with_user(self.user_portal).partner_desinterested(comment="No thanks, I have enough leads !", contacted=True, spam=False) self.assertFalse(self.lead_portal.partner_assigned_id.id, 'The partner_assigned_id of the declined lead should be False.') self.assertTrue(self.user_portal.partner_id in self.lead_portal.sudo().partner_declined_ids, 'Partner who has declined the lead should be in the declined_partner_ids.') def test_lead_access_right(self): """ Test another portal user can not write on every leads """ # portal user having no right poor_portal_user = self.env['res.users'].with_context({'no_reset_password': True, 'mail_notrack': True}).create({ 'name': 'Poor Partner (not integrating one)', 'email': 'poor.partner@ododo.com', 'login': 'poorpartner', 'groups_id': [(6, 0, [self.env.ref('base.group_portal').id])], }) # try to accept a lead that is not mine with self.assertRaises(AccessError): self.lead_portal.with_user(poor_portal_user).partner_interested(comment="Oh yeah, I take that lead !") def test_lead_creation(self): """ Test the opportinuty creation from portal """ data = self.env['crm.lead'].with_user(self.user_portal).create_opp_portal({ 'title': "L'ours bleu", 'description': 'A good joke', 'contact_name': 'Renaud Rutten', }) opportunity = self.env['crm.lead'].browse(data['id']) salesmanteam = self.env['crm.team']._get_default_team_id(user_id=self.user_portal.user_id.id) self.assertEqual(opportunity.team_id, salesmanteam, 'The created opportunity should have the same team as the salesman default team of the opportunity creator.') self.assertEqual(opportunity.partner_assigned_id, self.user_portal.partner_id, 'Assigned Partner of created opportunity is the (portal) creator.') def test_portal_mixin_url(self): record_action = self.lead_portal.get_access_action(self.user_portal.id) self.assertEqual(record_action['url'], '/my/opportunity/%s' % self.lead_portal.id) self.assertEqual(record_action['type'], 'ir.actions.act_url')
46.298137
7,454
7,637
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 CrmLeadForwardToPartner(models.TransientModel): """ Forward info history to partners. """ _name = 'crm.lead.forward.to.partner' _description = 'Lead forward to partner' @api.model def _convert_to_assignation_line(self, lead, partner): lead_location = [] partner_location = [] if lead.country_id: lead_location.append(lead.country_id.name) if lead.city: lead_location.append(lead.city) if partner: if partner.country_id: partner_location.append(partner.country_id.name) if partner.city: partner_location.append(partner.city) return {'lead_id': lead.id, 'lead_location': ", ".join(lead_location), 'partner_assigned_id': partner and partner.id or False, 'partner_location': ", ".join(partner_location), 'lead_link': self.get_lead_portal_url(lead), } @api.model def default_get(self, fields): res = super(CrmLeadForwardToPartner, self).default_get(fields) active_ids = self.env.context.get('active_ids') if 'body' in fields: template = self.env.ref('website_crm_partner_assign.email_template_lead_forward_mail', False) if template: res['body'] = template.body_html if active_ids: default_composition_mode = self.env.context.get('default_composition_mode') res['assignation_lines'] = [] leads = self.env['crm.lead'].browse(active_ids) if default_composition_mode == 'mass_mail': partner_assigned_dict = leads.search_geo_partner() else: partner_assigned_dict = {lead.id: lead.partner_assigned_id.id for lead in leads} res['partner_id'] = leads[0].partner_assigned_id.id for lead in leads: partner_id = partner_assigned_dict.get(lead.id) or False partner = self.env['res.partner'].browse(partner_id) res['assignation_lines'].append((0, 0, self._convert_to_assignation_line(lead, partner))) return res def action_forward(self): self.ensure_one() template = self.env.ref('website_crm_partner_assign.email_template_lead_forward_mail', False) if not template: raise UserError(_('The Forward Email Template is not in the database')) portal_group = self.env.ref('base.group_portal') local_context = self.env.context.copy() if not (self.forward_type == 'single'): no_email = set() for lead in self.assignation_lines: if lead.partner_assigned_id and not lead.partner_assigned_id.email: no_email.add(lead.partner_assigned_id.name) if no_email: raise UserError(_('Set an email address for the partner(s): %s') % ", ".join(no_email)) if self.forward_type == 'single' and not self.partner_id.email: raise UserError(_('Set an email address for the partner %s', self.partner_id.name)) partners_leads = {} for lead in self.assignation_lines: partner = self.forward_type == 'single' and self.partner_id or lead.partner_assigned_id lead_details = { 'lead_link': lead.lead_link, 'lead_id': lead.lead_id, } if partner: partner_leads = partners_leads.get(partner.id) if partner_leads: partner_leads['leads'].append(lead_details) else: partners_leads[partner.id] = {'partner': partner, 'leads': [lead_details]} for partner_id, partner_leads in partners_leads.items(): in_portal = False if portal_group: for contact in (partner.child_ids or partner).filtered(lambda contact: contact.user_ids): in_portal = portal_group.id in [g.id for g in contact.user_ids[0].groups_id] local_context['partner_id'] = partner_leads['partner'] local_context['partner_leads'] = partner_leads['leads'] local_context['partner_in_portal'] = in_portal template.with_context(local_context).send_mail(self.id) leads = self.env['crm.lead'] for lead_data in partner_leads['leads']: leads |= lead_data['lead_id'] values = {'partner_assigned_id': partner_id, 'user_id': partner_leads['partner'].user_id.id} leads.with_context(mail_auto_subscribe_no_notify=1).write(values) self.env['crm.lead'].message_subscribe([partner_id]) return True def get_lead_portal_url(self, lead): action = lead.type == 'opportunity' and 'action_portal_opportunities' or 'action_portal_leads' action_ref = self.env.ref('website_crm_partner_assign.%s' % (action,), False) portal_link = "%s/?db=%s#id=%s&action=%s&view_type=form" % ( lead.get_base_url(), self.env.cr.dbname, lead.id, action_ref and action_ref.id or False) return portal_link def get_portal_url(self): if self: portal_url = self[0].get_base_url() else: portal_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') portal_link = "%s/?db=%s" % (portal_url, self.env.cr.dbname) return portal_link forward_type = fields.Selection([ ('single', 'a single partner: manual selection of partner'), ('assigned', "several partners: automatic assignment, using GPS coordinates and partner's grades") ], 'Forward selected leads to', default=lambda self: self.env.context.get('forward_type') or 'single') partner_id = fields.Many2one('res.partner', 'Forward Leads To') assignation_lines = fields.One2many('crm.lead.assignation', 'forward_id', 'Partner Assignment') body = fields.Html('Contents', help='Automatically sanitized HTML contents') class CrmLeadAssignation(models.TransientModel): _name = 'crm.lead.assignation' _description = 'Lead Assignation' forward_id = fields.Many2one('crm.lead.forward.to.partner', 'Partner Assignment') lead_id = fields.Many2one('crm.lead', 'Lead') lead_location = fields.Char('Lead Location') partner_assigned_id = fields.Many2one('res.partner', 'Assigned Partner') partner_location = fields.Char('Partner Location') lead_link = fields.Char('Link to Lead') @api.onchange('lead_id') def _onchange_lead_id(self): lead = self.lead_id if not lead: self.lead_location = False else: lead_location = [] if lead.country_id: lead_location.append(lead.country_id.name) if lead.city: lead_location.append(lead.city) self.lead_location = ", ".join(lead_location) @api.onchange('partner_assigned_id') def _onchange_partner_assigned_id(self): partner = self.partner_assigned_id if not partner: self.lead_location = False else: partner_location = [] if partner.country_id: partner_location.append(partner.country_id.name) if partner.city: partner_location.append(partner.city) self.partner_location = ", ".join(partner_location)
45.458333
7,637
510
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.http_routing.models.ir_http import url_for class Website(models.Model): _inherit = "website" def get_suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('Resellers'), url_for('/partners'), 'website_crm_partner_assign')) return suggested_controllers
36.428571
510
14,196
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import random from odoo import api, fields, models, _ from odoo.exceptions import AccessDenied, AccessError, UserError from odoo.tools import html_escape class CrmLead(models.Model): _inherit = "crm.lead" partner_latitude = fields.Float('Geo Latitude', digits=(10, 7)) partner_longitude = fields.Float('Geo Longitude', digits=(10, 7)) partner_assigned_id = fields.Many2one('res.partner', 'Assigned Partner', tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", help="Partner this case has been forwarded/assigned to.", index=True) partner_declined_ids = fields.Many2many( 'res.partner', 'crm_lead_declined_partner', 'lead_id', 'partner_id', string='Partner not interested') date_partner_assign = fields.Date( 'Partner Assignment Date', compute='_compute_date_partner_assign', copy=True, readonly=False, store=True, help="Last date this case was forwarded/assigned to a partner") @api.depends("partner_assigned_id") def _compute_date_partner_assign(self): for lead in self: if not lead.partner_assigned_id: lead.date_partner_assign = False else: lead.date_partner_assign = fields.Date.context_today(lead) def _merge_get_fields(self): fields_list = super(CrmLead, self)._merge_get_fields() fields_list += ['partner_latitude', 'partner_longitude', 'partner_assigned_id', 'date_partner_assign'] return fields_list def assign_salesman_of_assigned_partner(self): salesmans_leads = {} for lead in self: if lead.active and lead.probability < 100: if lead.partner_assigned_id and lead.partner_assigned_id.user_id != lead.user_id: salesmans_leads.setdefault(lead.partner_assigned_id.user_id.id, []).append(lead.id) for salesman_id, leads_ids in salesmans_leads.items(): leads = self.browse(leads_ids) leads.write({'user_id': salesman_id}) def action_assign_partner(self): return self.assign_partner(partner_id=False) def assign_partner(self, partner_id=False): partner_dict = {} res = False if not partner_id: partner_dict = self.search_geo_partner() for lead in self: if not partner_id: partner_id = partner_dict.get(lead.id, False) if not partner_id: tag_to_add = self.env.ref('website_crm_partner_assign.tag_portal_lead_partner_unavailable', False) if tag_to_add: lead.write({'tag_ids': [(4, tag_to_add.id, False)]}) continue lead.assign_geo_localize(lead.partner_latitude, lead.partner_longitude) partner = self.env['res.partner'].browse(partner_id) if partner.user_id: lead._handle_salesmen_assignment(user_ids=partner.user_id.ids, team_id=partner.team_id.id) lead.write({'partner_assigned_id': partner_id}) return res def assign_geo_localize(self, latitude=False, longitude=False): if latitude and longitude: self.write({ 'partner_latitude': latitude, 'partner_longitude': longitude }) return True # Don't pass context to browse()! We need country name in english below for lead in self: if lead.partner_latitude and lead.partner_longitude: continue if lead.country_id: result = self.env['res.partner']._geo_localize( lead.street, lead.zip, lead.city, lead.state_id.name, lead.country_id.name ) if result: lead.write({ 'partner_latitude': result[0], 'partner_longitude': result[1] }) return True def _prepare_customer_values(self, partner_name, is_company=False, parent_id=False): res = super()._prepare_customer_values(partner_name, is_company=is_company, parent_id=parent_id) res.update({ 'partner_latitude': self.partner_latitude, 'partner_longitude': self.partner_longitude, }) return res def search_geo_partner(self): Partner = self.env['res.partner'] res_partner_ids = {} self.assign_geo_localize() for lead in self: partner_ids = [] if not lead.country_id: continue latitude = lead.partner_latitude longitude = lead.partner_longitude if latitude and longitude: # 1. first way: in the same country, small area partner_ids = Partner.search([ ('partner_weight', '>', 0), ('partner_latitude', '>', latitude - 2), ('partner_latitude', '<', latitude + 2), ('partner_longitude', '>', longitude - 1.5), ('partner_longitude', '<', longitude + 1.5), ('country_id', '=', lead.country_id.id), ('id', 'not in', lead.partner_declined_ids.mapped('id')), ]) # 2. second way: in the same country, big area if not partner_ids: partner_ids = Partner.search([ ('partner_weight', '>', 0), ('partner_latitude', '>', latitude - 4), ('partner_latitude', '<', latitude + 4), ('partner_longitude', '>', longitude - 3), ('partner_longitude', '<', longitude + 3), ('country_id', '=', lead.country_id.id), ('id', 'not in', lead.partner_declined_ids.mapped('id')), ]) # 3. third way: in the same country, extra large area if not partner_ids: partner_ids = Partner.search([ ('partner_weight', '>', 0), ('partner_latitude', '>', latitude - 8), ('partner_latitude', '<', latitude + 8), ('partner_longitude', '>', longitude - 8), ('partner_longitude', '<', longitude + 8), ('country_id', '=', lead.country_id.id), ('id', 'not in', lead.partner_declined_ids.mapped('id')), ]) # 5. fifth way: anywhere in same country if not partner_ids: # still haven't found any, let's take all partners in the country! partner_ids = Partner.search([ ('partner_weight', '>', 0), ('country_id', '=', lead.country_id.id), ('id', 'not in', lead.partner_declined_ids.mapped('id')), ]) # 6. sixth way: closest partner whatsoever, just to have at least one result if not partner_ids: # warning: point() type takes (longitude, latitude) as parameters in this order! self._cr.execute("""SELECT id, distance FROM (select id, (point(partner_longitude, partner_latitude) <-> point(%s,%s)) AS distance FROM res_partner WHERE active AND partner_longitude is not null AND partner_latitude is not null AND partner_weight > 0 AND id not in (select partner_id from crm_lead_declined_partner where lead_id = %s) ) AS d ORDER BY distance LIMIT 1""", (longitude, latitude, lead.id)) res = self._cr.dictfetchone() if res: partner_ids = Partner.browse([res['id']]) if partner_ids: res_partner_ids[lead.id] = random.choices( partner_ids.ids, partner_ids.mapped('partner_weight'), )[0] return res_partner_ids def partner_interested(self, comment=False): message = _('<p>I am interested by this lead.</p>') if comment: message += '<p>%s</p>' % html_escape(comment) for lead in self: lead.message_post(body=message) lead.sudo().convert_opportunity(lead.partner_id.id) # sudo required to convert partner data def partner_desinterested(self, comment=False, contacted=False, spam=False): if contacted: message = '<p>%s</p>' % _('I am not interested by this lead. I contacted the lead.') else: message = '<p>%s</p>' % _('I am not interested by this lead. I have not contacted the lead.') partner_ids = self.env['res.partner'].search( [('id', 'child_of', self.env.user.partner_id.commercial_partner_id.id)]) self.message_unsubscribe(partner_ids=partner_ids.ids) if comment: message += '<p>%s</p>' % html_escape(comment) self.message_post(body=message) values = { 'partner_assigned_id': False, } if spam: tag_spam = self.env.ref('website_crm_partner_assign.tag_portal_lead_is_spam', False) if tag_spam and tag_spam not in self.tag_ids: values['tag_ids'] = [(4, tag_spam.id, False)] if partner_ids: values['partner_declined_ids'] = [(4, p, 0) for p in partner_ids.ids] self.sudo().write(values) def update_lead_portal(self, values): self.check_access_rights('write') for lead in self: lead_values = { 'expected_revenue': values['expected_revenue'], 'probability': values['probability'] or False, 'priority': values['priority'], 'date_deadline': values['date_deadline'] or False, } # As activities may belong to several users, only the current portal user activity # will be modified by the portal form. If no activity exist we create a new one instead # that we assign to the portal user. user_activity = lead.sudo().activity_ids.filtered(lambda activity: activity.user_id == self.env.user)[:1] if values['activity_date_deadline']: if user_activity: user_activity.sudo().write({ 'activity_type_id': values['activity_type_id'], 'summary': values['activity_summary'], 'date_deadline': values['activity_date_deadline'], }) else: self.env['mail.activity'].sudo().create({ 'res_model_id': self.env.ref('crm.model_crm_lead').id, 'res_id': lead.id, 'user_id': self.env.user.id, 'activity_type_id': values['activity_type_id'], 'summary': values['activity_summary'], 'date_deadline': values['activity_date_deadline'], }) lead.write(lead_values) def update_contact_details_from_portal(self, values): self.check_access_rights('write') fields = ['partner_name', 'phone', 'mobile', 'email_from', 'street', 'street2', 'city', 'zip', 'state_id', 'country_id'] if any([key not in fields for key in values]): raise UserError(_("Not allowed to update the following field(s) : %s.") % ", ".join([key for key in values if not key in fields])) return self.sudo().write(values) @api.model def create_opp_portal(self, values): if not (self.env.user.partner_id.grade_id or self.env.user.commercial_partner_id.grade_id): raise AccessDenied() user = self.env.user self = self.sudo() if not (values['contact_name'] and values['description'] and values['title']): return { 'errors': _('All fields are required !') } tag_own = self.env.ref('website_crm_partner_assign.tag_portal_lead_own_opp', False) values = { 'contact_name': values['contact_name'], 'name': values['title'], 'description': values['description'], 'priority': '2', 'partner_assigned_id': user.commercial_partner_id.id, } if tag_own: values['tag_ids'] = [(4, tag_own.id, False)] lead = self.create(values) lead.assign_salesman_of_assigned_partner() lead.convert_opportunity(lead.partner_id.id) return { 'id': lead.id } # # DO NOT FORWARD PORT IN MASTER # instead, crm.lead should implement portal.mixin # def get_access_action(self, access_uid=None): """ Instead of the classic form view, redirect to the online document for portal users or if force_website=True in the context. """ self.ensure_one() user, record = self.env.user, self if access_uid: try: record.check_access_rights('read') record.check_access_rule("read") except AccessError: return super(CrmLead, self).get_access_action(access_uid) user = self.env['res.users'].sudo().browse(access_uid) record = self.with_user(user) if user.share or self.env.context.get('force_website'): try: record.check_access_rights('read') record.check_access_rule('read') except AccessError: pass else: return { 'type': 'ir.actions.act_url', 'url': '/my/opportunity/%s' % record.id, } return super(CrmLead, self).get_access_action(access_uid)
46.090909
14,196
2,850
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.addons.http_routing.models.ir_http import slug class ResPartnerGrade(models.Model): _name = 'res.partner.grade' _order = 'sequence' _inherit = ['website.published.mixin'] _description = 'Partner Grade' sequence = fields.Integer('Sequence') active = fields.Boolean('Active', default=lambda *args: 1) name = fields.Char('Level Name', translate=True) partner_weight = fields.Integer('Level Weight', default=1, help="Gives the probability to assign a lead to this partner. (0 means no assignment.)") def _compute_website_url(self): super(ResPartnerGrade, self)._compute_website_url() for grade in self: grade.website_url = "/partners/grade/%s" % (slug(grade)) def _default_is_published(self): return True class ResPartnerActivation(models.Model): _name = 'res.partner.activation' _order = 'sequence' _description = 'Partner Activation' sequence = fields.Integer('Sequence') name = fields.Char('Name', required=True) class ResPartner(models.Model): _inherit = "res.partner" partner_weight = fields.Integer( 'Level Weight', compute='_compute_partner_weight', readonly=False, store=True, tracking=True, help="This should be a numerical value greater than 0 which will decide the contention for this partner to take this lead/opportunity.") grade_id = fields.Many2one('res.partner.grade', 'Partner Level', tracking=True) grade_sequence = fields.Integer(related='grade_id.sequence', readonly=True, store=True) activation = fields.Many2one('res.partner.activation', 'Activation', index=True, tracking=True) date_partnership = fields.Date('Partnership Date') date_review = fields.Date('Latest Partner Review') date_review_next = fields.Date('Next Partner Review') # customer implementation assigned_partner_id = fields.Many2one( 'res.partner', 'Implemented by', ) implemented_partner_ids = fields.One2many( 'res.partner', 'assigned_partner_id', string='Implementation References', ) implemented_count = fields.Integer(compute='_compute_implemented_partner_count', store=True) @api.depends('implemented_partner_ids', 'implemented_partner_ids.website_published', 'implemented_partner_ids.active') def _compute_implemented_partner_count(self): for partner in self: partner.implemented_count = len(partner.implemented_partner_ids.filtered('website_published')) @api.depends('grade_id.partner_weight') def _compute_partner_weight(self): for partner in self: partner.partner_weight = partner.grade_id.partner_weight if partner.grade_id else 0
41.304348
2,850
2,599
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 CrmPartnerReportAssign(models.Model): """ CRM Lead Report """ _name = "crm.partner.report.assign" _auto = False _description = "CRM Partnership Analysis" partner_id = fields.Many2one('res.partner', 'Partner', required=False, readonly=True) grade_id = fields.Many2one('res.partner.grade', 'Grade', readonly=True) activation = fields.Many2one('res.partner.activation', 'Activation', index=True) user_id = fields.Many2one('res.users', 'User', readonly=True) date_review = fields.Date('Latest Partner Review') date_partnership = fields.Date('Partnership Date') country_id = fields.Many2one('res.country', 'Country', readonly=True) team_id = fields.Many2one('crm.team', 'Sales Team', readonly=True) nbr_opportunities = fields.Integer('# of Opportunity', readonly=True) turnover = fields.Float('Turnover', readonly=True) date = fields.Date('Invoice Account Date', readonly=True) _depends = { 'account.invoice.report': ['invoice_date', 'partner_id', 'price_subtotal', 'state', 'move_type'], 'crm.lead': ['partner_assigned_id'], 'res.partner': ['activation', 'country_id', 'date_partnership', 'date_review', 'grade_id', 'parent_id', 'team_id', 'user_id'], } @property def _table_query(self): """ CRM Lead Report @param cr: the current row, from the database cursor """ return """ SELECT COALESCE(2 * i.id, 2 * p.id + 1) AS id, p.id as partner_id, (SELECT country_id FROM res_partner a WHERE a.parent_id=p.id AND country_id is not null limit 1) as country_id, p.grade_id, p.activation, p.date_review, p.date_partnership, p.user_id, p.team_id, (SELECT count(id) FROM crm_lead WHERE partner_assigned_id=p.id) AS nbr_opportunities, i.price_subtotal as turnover, i.invoice_date as date FROM res_partner p left join ({account_invoice_report}) i on (i.partner_id=p.id and i.move_type in ('out_invoice','out_refund') and i.state='posted') """.format( account_invoice_report=self.env['account.invoice.report']._table_query )
44.810345
2,599
15,092
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import werkzeug.urls from collections import OrderedDict from werkzeug.exceptions import NotFound from odoo import fields from odoo import http from odoo.http import request from odoo.addons.http_routing.models.ir_http import slug, unslug from odoo.addons.website.models.ir_http import sitemap_qs2dom from odoo.addons.portal.controllers.portal import CustomerPortal from odoo.addons.website_partner.controllers.main import WebsitePartnerPage from odoo.tools.translate import _ class WebsiteAccount(CustomerPortal): def get_domain_my_lead(self, user): return [ ('partner_assigned_id', 'child_of', user.commercial_partner_id.id), ('type', '=', 'lead') ] def get_domain_my_opp(self, user): return [ ('partner_assigned_id', 'child_of', user.commercial_partner_id.id), ('type', '=', 'opportunity') ] def _prepare_home_portal_values(self, counters): values = super()._prepare_home_portal_values(counters) if 'lead_count' in counters: values['lead_count'] = request.env['crm.lead'].search_count(self.get_domain_my_lead(request.env.user)) if 'opp_count' in counters: values['opp_count'] = request.env['crm.lead'].search_count(self.get_domain_my_opp(request.env.user)) return values @http.route(['/my/leads', '/my/leads/page/<int:page>'], type='http', auth="user", website=True) def portal_my_leads(self, page=1, date_begin=None, date_end=None, sortby=None, **kw): values = self._prepare_portal_layout_values() CrmLead = request.env['crm.lead'] domain = self.get_domain_my_lead(request.env.user) searchbar_sortings = { 'date': {'label': _('Newest'), 'order': 'create_date desc'}, 'name': {'label': _('Name'), 'order': 'name'}, 'contact_name': {'label': _('Contact Name'), 'order': 'contact_name'}, } # default sort by value if not sortby: sortby = 'date' order = searchbar_sortings[sortby]['order'] if date_begin and date_end: domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)] # pager lead_count = CrmLead.search_count(domain) pager = request.website.pager( url="/my/leads", url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby}, total=lead_count, page=page, step=self._items_per_page ) # content according to pager and archive selected leads = CrmLead.search(domain, order=order, limit=self._items_per_page, offset=pager['offset']) values.update({ 'date': date_begin, 'leads': leads, 'page_name': 'lead', 'default_url': '/my/leads', 'pager': pager, 'searchbar_sortings': searchbar_sortings, 'sortby': sortby, }) return request.render("website_crm_partner_assign.portal_my_leads", values) @http.route(['/my/opportunities', '/my/opportunities/page/<int:page>'], type='http', auth="user", website=True) def portal_my_opportunities(self, page=1, date_begin=None, date_end=None, sortby=None, filterby=None, **kw): values = self._prepare_portal_layout_values() CrmLead = request.env['crm.lead'] domain = self.get_domain_my_opp(request.env.user) today = fields.Date.today() this_week_end_date = fields.Date.to_string(fields.Date.from_string(today) + datetime.timedelta(days=7)) searchbar_filters = { 'all': {'label': _('Active'), 'domain': []}, 'today': {'label': _('Today Activities'), 'domain': [('activity_date_deadline', '=', today)]}, 'week': {'label': _('This Week Activities'), 'domain': [('activity_date_deadline', '>=', today), ('activity_date_deadline', '<=', this_week_end_date)]}, 'overdue': {'label': _('Overdue Activities'), 'domain': [('activity_date_deadline', '<', today)]}, 'won': {'label': _('Won'), 'domain': [('stage_id.is_won', '=', True)]}, 'lost': {'label': _('Lost'), 'domain': [('active', '=', False), ('probability', '=', 0)]}, } searchbar_sortings = { 'date': {'label': _('Newest'), 'order': 'create_date desc'}, 'name': {'label': _('Name'), 'order': 'name'}, 'contact_name': {'label': _('Contact Name'), 'order': 'contact_name'}, 'revenue': {'label': _('Expected Revenue'), 'order': 'expected_revenue desc'}, 'probability': {'label': _('Probability'), 'order': 'probability desc'}, 'stage': {'label': _('Stage'), 'order': 'stage_id'}, } # default sort by value if not sortby: sortby = 'date' order = searchbar_sortings[sortby]['order'] # default filter by value if not filterby: filterby = 'all' domain += searchbar_filters[filterby]['domain'] if filterby == 'lost': CrmLead = CrmLead.with_context(active_test=False) if date_begin and date_end: domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)] # pager opp_count = CrmLead.search_count(domain) pager = request.website.pager( url="/my/opportunities", url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'filterby': filterby}, total=opp_count, page=page, step=self._items_per_page ) # content according to pager opportunities = CrmLead.search(domain, order=order, limit=self._items_per_page, offset=pager['offset']) values.update({ 'date': date_begin, 'opportunities': opportunities, 'page_name': 'opportunity', 'default_url': '/my/opportunities', 'pager': pager, 'searchbar_sortings': searchbar_sortings, 'sortby': sortby, 'searchbar_filters': OrderedDict(sorted(searchbar_filters.items())), 'filterby': filterby, }) return request.render("website_crm_partner_assign.portal_my_opportunities", values) @http.route(['''/my/lead/<model('crm.lead', "[('type','=', 'lead')]"):lead>'''], type='http', auth="user", website=True) def portal_my_lead(self, lead, **kw): if lead.type != 'lead': raise NotFound() return request.render("website_crm_partner_assign.portal_my_lead", {'lead': lead}) @http.route(['''/my/opportunity/<model('crm.lead', "[('type','=', 'opportunity')]"):opp>'''], type='http', auth="user", website=True) def portal_my_opportunity(self, opp, **kw): if opp.type != 'opportunity': raise NotFound() return request.render( "website_crm_partner_assign.portal_my_opportunity", { 'opportunity': opp, 'user_activity': opp.sudo().activity_ids.filtered(lambda activity: activity.user_id == request.env.user)[:1], 'stages': request.env['crm.stage'].search([('is_won', '!=', True)], order='sequence desc, name desc, id desc'), 'activity_types': request.env['mail.activity.type'].sudo().search(['|', ('res_model', '=', opp._name), ('res_model', '=', False)]), 'states': request.env['res.country.state'].sudo().search([]), 'countries': request.env['res.country'].sudo().search([]), }) class WebsiteCrmPartnerAssign(WebsitePartnerPage): _references_per_page = 40 def sitemap_partners(env, rule, qs): if not qs or qs.lower() in '/partners': yield {'loc': '/partners'} Grade = env['res.partner.grade'] dom = [('website_published', '=', True)] dom += sitemap_qs2dom(qs=qs, route='/partners/grade/', field=Grade._rec_name) for grade in env['res.partner.grade'].search(dom): loc = '/partners/grade/%s' % slug(grade) if not qs or qs.lower() in loc: yield {'loc': loc} partners_dom = [('is_company', '=', True), ('grade_id', '!=', False), ('website_published', '=', True), ('grade_id.website_published', '=', True), ('country_id', '!=', False)] dom += sitemap_qs2dom(qs=qs, route='/partners/country/') countries = env['res.partner'].sudo().read_group(partners_dom, fields=['id', 'country_id'], groupby='country_id') for country in countries: loc = '/partners/country/%s' % slug(country['country_id']) if not qs or qs.lower() in loc: yield {'loc': loc} @http.route([ '/partners', '/partners/page/<int:page>', '/partners/grade/<model("res.partner.grade"):grade>', '/partners/grade/<model("res.partner.grade"):grade>/page/<int:page>', '/partners/country/<model("res.country"):country>', '/partners/country/<model("res.country"):country>/page/<int:page>', '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>', '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>/page/<int:page>', ], type='http', auth="public", website=True, sitemap=sitemap_partners) def partners(self, country=None, grade=None, page=0, **post): country_all = post.pop('country_all', False) partner_obj = request.env['res.partner'] country_obj = request.env['res.country'] search = post.get('search', '') base_partner_domain = [('is_company', '=', True), ('grade_id', '!=', False), ('website_published', '=', True)] if not request.env['res.users'].has_group('website.group_website_publisher'): base_partner_domain += [('grade_id.website_published', '=', True)] if search: base_partner_domain += ['|', ('name', 'ilike', search), ('website_description', 'ilike', search)] # group by grade grade_domain = list(base_partner_domain) if not country and not country_all: country_code = request.session['geoip'].get('country_code') if country_code: country = country_obj.search([('code', '=', country_code)], limit=1) if country: grade_domain += [('country_id', '=', country.id)] grades = partner_obj.sudo().read_group( grade_domain, ["id", "grade_id"], groupby="grade_id") grades_partners = partner_obj.sudo().search_count(grade_domain) # flag active grade for grade_dict in grades: grade_dict['active'] = grade and grade_dict['grade_id'][0] == grade.id grades.insert(0, { 'grade_id_count': grades_partners, 'grade_id': (0, _("All Categories")), 'active': bool(grade is None), }) # group by country country_domain = list(base_partner_domain) if grade: country_domain += [('grade_id', '=', grade.id)] countries = partner_obj.sudo().read_group( country_domain, ["id", "country_id"], groupby="country_id", orderby="country_id") countries_partners = partner_obj.sudo().search_count(country_domain) # flag active country for country_dict in countries: country_dict['active'] = country and country_dict['country_id'] and country_dict['country_id'][0] == country.id countries.insert(0, { 'country_id_count': countries_partners, 'country_id': (0, _("All Countries")), 'active': bool(country is None), }) # current search if grade: base_partner_domain += [('grade_id', '=', grade.id)] if country: base_partner_domain += [('country_id', '=', country.id)] # format pager if grade and not country: url = '/partners/grade/' + slug(grade) elif country and not grade: url = '/partners/country/' + slug(country) elif country and grade: url = '/partners/grade/' + slug(grade) + '/country/' + slug(country) else: url = '/partners' url_args = {} if search: url_args['search'] = search if country_all: url_args['country_all'] = True partner_count = partner_obj.sudo().search_count(base_partner_domain) pager = request.website.pager( url=url, total=partner_count, page=page, step=self._references_per_page, scope=7, url_args=url_args) # search partners matching current search parameters partner_ids = partner_obj.sudo().search( base_partner_domain, order="grade_sequence ASC, implemented_count DESC, display_name ASC, id ASC", offset=pager['offset'], limit=self._references_per_page) partners = partner_ids.sudo() google_map_partner_ids = ','.join(str(p.id) for p in partners) google_maps_api_key = request.website.google_maps_api_key values = { 'countries': countries, 'country_all': country_all, 'current_country': country, 'grades': grades, 'current_grade': grade, 'partners': partners, 'google_map_partner_ids': google_map_partner_ids, 'pager': pager, 'searches': post, 'search_path': "%s" % werkzeug.urls.url_encode(post), 'google_maps_api_key': google_maps_api_key, } return request.render("website_crm_partner_assign.index", values, status=partners and 200 or 404) # Do not use semantic controller due to sudo() @http.route(['/partners/<partner_id>'], type='http', auth="public", website=True) def partners_detail(self, partner_id, **post): _, partner_id = unslug(partner_id) current_grade, current_country = None, None grade_id = post.get('grade_id') country_id = post.get('country_id') if grade_id: current_grade = request.env['res.partner.grade'].browse(int(grade_id)).exists() if country_id: current_country = request.env['res.country'].browse(int(country_id)).exists() if partner_id: partner = request.env['res.partner'].sudo().browse(partner_id) is_website_publisher = request.env['res.users'].has_group('website.group_website_publisher') if partner.exists() and (partner.website_published or is_website_publisher): values = { 'main_object': partner, 'partner': partner, 'current_grade': current_grade, 'current_country': current_country } return request.render("website_crm_partner_assign.partner", values) return self.partners(**post)
45.321321
15,092
451
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Subcontracting Management with Stock Valuation', 'version': '0.1', 'category': 'Hidden', 'description': """ This bridge module allows to manage subcontracting with valuation. """, 'depends': ['mrp_subcontracting', 'mrp_account'], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
30.066667
451
14,805
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import Command, fields from odoo.tests.common import Form from odoo.tools.float_utils import float_round, float_compare from odoo.addons.mrp_subcontracting.tests.common import TestMrpSubcontractingCommon from odoo.addons.mrp_account.tests.test_bom_price import TestBomPrice class TestAccountSubcontractingFlows(TestMrpSubcontractingCommon): def test_subcontracting_account_flow_1(self): self.stock_location = self.env.ref('stock.stock_location_stock') self.customer_location = self.env.ref('stock.stock_location_customers') self.supplier_location = self.env.ref('stock.stock_location_suppliers') self.uom_unit = self.env.ref('uom.product_uom_unit') self.env.ref('product.product_category_all').property_cost_method = 'fifo' # IN 10@10 comp1 10@20 comp2 move1 = self.env['stock.move'].create({ 'name': 'IN 10 units @ 10.00 per unit', 'location_id': self.supplier_location.id, 'location_dest_id': self.env.company.subcontracting_location_id.id, 'product_id': self.comp1.id, 'product_uom': self.uom_unit.id, 'product_uom_qty': 10.0, 'price_unit': 10.0, }) move1._action_confirm() move1._action_assign() move1.move_line_ids.qty_done = 10.0 move1._action_done() move2 = self.env['stock.move'].create({ 'name': 'IN 10 units @ 20.00 per unit', 'location_id': self.supplier_location.id, 'location_dest_id': self.env.company.subcontracting_location_id.id, 'product_id': self.comp2.id, 'product_uom': self.uom_unit.id, 'product_uom_qty': 10.0, 'price_unit': 20.0, }) move2._action_confirm() move2._action_assign() move2.move_line_ids.qty_done = 10.0 move2._action_done() picking_form = Form(self.env['stock.picking']) picking_form.picking_type_id = self.env.ref('stock.picking_type_in') picking_form.partner_id = self.subcontractor_partner1 with picking_form.move_ids_without_package.new() as move: move.product_id = self.finished move.product_uom_qty = 1 picking_receipt = picking_form.save() picking_receipt.move_lines.price_unit = 15.0 picking_receipt.action_confirm() # Suppose the additional cost changes: picking_receipt.move_lines.price_unit = 30.0 picking_receipt.move_lines.quantity_done = 1.0 picking_receipt._action_done() mo = picking_receipt._get_subcontract_production() # Finished is made of 1 comp1 and 1 comp2. # Cost of comp1 = 10 # Cost of comp2 = 20 # --> Cost of finished = 10 + 20 = 30 # Additionnal cost = 30 (from the purchase order line or directly set on the stock move here) # Total cost of subcontracting 1 unit of finished = 30 + 30 = 60 self.assertEqual(mo.move_finished_ids.stock_valuation_layer_ids.value, 60) self.assertEqual(picking_receipt.move_lines.stock_valuation_layer_ids.value, 0) self.assertEqual(picking_receipt.move_lines.product_id.value_svl, 60) # Do the same without any additionnal cost picking_form = Form(self.env['stock.picking']) picking_form.picking_type_id = self.env.ref('stock.picking_type_in') picking_form.partner_id = self.subcontractor_partner1 with picking_form.move_ids_without_package.new() as move: move.product_id = self.finished move.product_uom_qty = 1 picking_receipt = picking_form.save() picking_receipt.move_lines.price_unit = 0 picking_receipt.action_confirm() picking_receipt.move_lines.quantity_done = 1.0 picking_receipt._action_done() mo = picking_receipt._get_subcontract_production() # In this case, since there isn't any additionnal cost, the total cost of the subcontracting # is the sum of the components' costs: 10 + 20 = 30 self.assertEqual(mo.move_finished_ids.stock_valuation_layer_ids.value, 30) self.assertEqual(picking_receipt.move_lines.product_id.value_svl, 90) def test_subcontracting_account_backorder(self): """ This test uses tracked (serial and lot) component and tracked (serial) finished product The original subcontracting production order will be split into 4 backorders. This test ensure the extra cost asked from the subcontractor is added correctly on all the finished product valuation layer. Not only the first one. """ todo_nb = 4 self.comp2.tracking = 'lot' self.comp1.tracking = 'serial' self.comp2.standard_price = 100 self.finished.tracking = 'serial' self.env.ref('product.product_category_all').property_cost_method = 'fifo' # Create a receipt picking from the subcontractor picking_form = Form(self.env['stock.picking']) picking_form.picking_type_id = self.env.ref('stock.picking_type_in') picking_form.partner_id = self.subcontractor_partner1 with picking_form.move_ids_without_package.new() as move: move.product_id = self.finished move.product_uom_qty = todo_nb picking_receipt = picking_form.save() # Mimic the extra cost on the po line picking_receipt.move_lines.price_unit = 50 picking_receipt.action_confirm() # We should be able to call the 'record_components' button self.assertTrue(picking_receipt.display_action_record_components) lot_comp2 = self.env['stock.production.lot'].create({ 'name': 'lot_comp2', 'product_id': self.comp2.id, 'company_id': self.env.company.id, }) serials_finished = [] serials_comp1 = [] for i in range(todo_nb): serials_finished.append(self.env['stock.production.lot'].create({ 'name': 'serial_fin_%s' % i, 'product_id': self.finished.id, 'company_id': self.env.company.id, })) serials_comp1.append(self.env['stock.production.lot'].create({ 'name': 'serials_comp1_%s' % i, 'product_id': self.comp1.id, 'company_id': self.env.company.id, })) for i in range(todo_nb): action = picking_receipt.action_record_components() mo = self.env['mrp.production'].browse(action['res_id']) mo_form = Form(mo.with_context(**action['context']), view=action['view_id']) mo_form.lot_producing_id = serials_finished[i] with mo_form.move_line_raw_ids.edit(0) as ml: self.assertEqual(ml.product_id, self.comp1) ml.lot_id = serials_comp1[i] with mo_form.move_line_raw_ids.edit(1) as ml: self.assertEqual(ml.product_id, self.comp2) ml.lot_id = lot_comp2 mo = mo_form.save() mo.subcontracting_record_component() # We should not be able to call the 'record_components' button picking_receipt.button_validate() f_layers = self.finished.stock_valuation_layer_ids self.assertEqual(len(f_layers), 4) for layer in f_layers: self.assertEqual(layer.value, 100 + 50) def test_tracked_compo_and_backorder(self): """ Suppose a subcontracted product P with two tracked components, P is FIFO Create a receipt for 10 x P, receive 5, then 3 and then 2 """ self.env.ref('product.product_category_all').property_cost_method = 'fifo' self.comp1.tracking = 'lot' self.comp1.standard_price = 10 self.comp2.tracking = 'lot' self.comp2.standard_price = 20 lot01, lot02 = self.env['stock.production.lot'].create([{ 'name': "Lot of %s" % product.name, 'product_id': product.id, 'company_id': self.env.company.id, } for product in (self.comp1, self.comp2)]) receipt_form = Form(self.env['stock.picking']) receipt_form.picking_type_id = self.env.ref('stock.picking_type_in') receipt_form.partner_id = self.subcontractor_partner1 with receipt_form.move_ids_without_package.new() as move: move.product_id = self.finished move.product_uom_qty = 10 receipt = receipt_form.save() # add an extra cost receipt.move_lines.price_unit = 50 receipt.action_confirm() for qty_producing in (5, 3, 2): action = receipt.action_record_components() mo = self.env['mrp.production'].browse(action['res_id']) mo_form = Form(mo.with_context(**action['context']), view=action['view_id']) mo_form.qty_producing = qty_producing with mo_form.move_line_raw_ids.edit(0) as ml: ml.lot_id = lot01 with mo_form.move_line_raw_ids.edit(1) as ml: ml.lot_id = lot02 mo = mo_form.save() mo.subcontracting_record_component() action = receipt.button_validate() if isinstance(action, dict): wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() receipt = receipt.backorder_ids self.assertRecordValues(self.finished.stock_valuation_layer_ids, [ {'quantity': 5, 'value': 5 * (10 + 20 + 50)}, {'quantity': 3, 'value': 3 * (10 + 20 + 50)}, {'quantity': 2, 'value': 2 * (10 + 20 + 50)}, ]) class TestBomPriceSubcontracting(TestBomPrice): def test_01_compute_price_subcontracting_cost(self): """Test calculation of bom cost with subcontracting.""" self.table_head.uom_po_id = self.dozen partner = self.env['res.partner'].create({ 'name': 'A name can be a Many2one...' }) (self.bom_1 | self.bom_2).write({ 'type': 'subcontract', 'subcontractor_ids': [Command.link(partner.id)] }) suppliers = self.env['product.supplierinfo'].create([ { 'name': partner.id, 'product_tmpl_id': self.dining_table.product_tmpl_id.id, 'price': 150.0, }, { 'name': partner.id, 'product_tmpl_id': self.table_head.product_tmpl_id.id, 'price': 120.0, # 10 by Unit because uom_po_id is in dozen } ]) self.assertEqual(suppliers.mapped('is_subcontractor'), [True, True]) # ----------------------------------------------------------------- # Cost of BoM (Dining Table 1 Unit) # ----------------------------------------------------------------- # Component Cost = Table Head 1 Unit * 300 = 300 (478.75 from it's components) # Screw 5 Unit * 10 = 50 # Leg 4 Unit * 25 = 100 # Glass 1 Unit * 100 = 100 # Subcontracting 1 Unit * 150 = 150 # Total = 700 [878.75 if components of Table Head considered] (for 1 Unit) # ----------------------------------------------------------------- self.assertEqual(self.dining_table.standard_price, 1000, "Initial price of the Product should be 1000") self.dining_table.button_bom_cost() self.assertEqual(float_round(self.dining_table.standard_price, precision_digits=2), 700.0, "After computing price from BoM price should be 700") # Cost of BoM (Table Head 1 Dozen) # ----------------------------------------------------------------- # Component Cost = Plywood Sheet 12 Unit * 200 = 2400 # Bolt 60 Unit * 10 = 600 # Colour 12 Unit * 100 = 1200 # Corner Slide 57 Unit * 25 = 1425 # Subcontracting 1 Dozen * 120 = 120 # Total = 5745 # 1 Unit price (5745/12) = 478.75 # ----------------------------------------------------------------- self.assertEqual(self.table_head.standard_price, 300, "Initial price of the Product should be 300") self.Product.browse([self.dining_table.id, self.table_head.id]).action_bom_cost() self.assertEqual(float_compare(self.table_head.standard_price, 478.75, precision_digits=2), 0, "After computing price from BoM price should be 878.75") self.assertEqual(float_compare(self.dining_table.standard_price, 878.75, precision_digits=2), 0, "After computing price from BoM price should be 878.75") def test_02_compute_price_subcontracting_cost(self): """Test calculation of bom cost with subcontracting and supplier in different currency.""" currency_a = self.env['res.currency'].create({ 'name': 'ZEN', 'symbol': 'Z', 'rounding': 0.01, 'currency_unit_label': 'Zenny', 'rate_ids': [(0, 0, { 'name': fields.Date.today(), 'company_rate': 0.5, })], }) partner = self.env['res.partner'].create({ 'name': 'supplier', }) product = self.env['product.product'].create({ 'name': 'product', 'type': 'product', 'standard_price': 100, 'company_id': self.env.company.id, }) supplier = self.env['product.supplierinfo'].create([{ 'name': partner.id, 'product_tmpl_id': product.product_tmpl_id.id, 'price': 120.0, 'currency_id': currency_a.id, }]) self.env['mrp.bom'].create({ 'product_tmpl_id': product.product_tmpl_id.id, 'product_qty': 1, 'type': 'subcontract', 'subcontractor_ids': [Command.link(partner.id)], 'bom_line_ids': [ (0, 0, {'product_id': self.table_head.id, 'product_qty': 1}), ], }) self.table_head.standard_price = 100 self.assertEqual(supplier.is_subcontractor, True) self.assertEqual(product.standard_price, 100, "Initial price of the Product should be 100") product.button_bom_cost() # 120 Zen = 240 USD (120 * 2) # price = 240 + 100 (1 unit of component "table_head") = 340 self.assertEqual(product.standard_price, 340, "After computing price from BoM price should be 340")
47.300319
14,805
965
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class ProductProduct(models.Model): _inherit = 'product.product' def _compute_bom_price(self, bom, boms_to_recompute=False, byproduct_bom=False): """ Add the price of the subcontracting supplier if it exists with the bom configuration. """ price = super()._compute_bom_price(bom, boms_to_recompute, byproduct_bom) if bom and bom.type == 'subcontract': seller = self._select_seller(quantity=bom.product_qty, uom_id=bom.product_uom_id, params={'subcontractor_ids': bom.subcontractor_ids}) if seller: seller_price = seller.currency_id._convert(seller.price, self.env.company.currency_id, (bom.company_id or self.env.company), fields.Date.today()) price += seller.product_uom._compute_price(seller_price, self.uom_id) return price
53.611111
965
325
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class StockMove(models.Model): _inherit = 'stock.move' def _should_force_price_unit(self): self.ensure_one() return self.is_subcontract or super()._should_force_price_unit()
27.083333
325
791
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.osv.expression import OR class StockPicking(models.Model): _inherit = 'stock.picking' def action_view_stock_valuation_layers(self): action = super(StockPicking, self).action_view_stock_valuation_layers() subcontracted_productions = self._get_subcontract_production() if not subcontracted_productions: return action domain = action['domain'] domain_subcontracting = [('id', 'in', (subcontracted_productions.move_raw_ids | subcontracted_productions.move_finished_ids).stock_valuation_layer_ids.ids)] domain = OR([domain, domain_subcontracting]) return dict(action, domain=domain)
41.631579
791
724
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class MrpProduction(models.Model): _inherit = 'mrp.production' def _cal_price(self, consumed_moves): finished_move = self.move_finished_ids.filtered(lambda x: x.product_id == self.product_id and x.state not in ('done', 'cancel') and x.quantity_done > 0) # Take the price unit of the reception move last_done_receipt = finished_move.move_dest_ids.filtered(lambda m: m.state == 'done')[-1:] if last_done_receipt.is_subcontract: self.extra_cost = last_done_receipt._get_price_unit() return super()._cal_price(consumed_moves=consumed_moves)
45.25
724
1,085
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Opportunity to Quotation', 'version': '1.0', 'category': 'Hidden', 'description': """ This module adds a shortcut on one or several opportunity cases in the CRM. =========================================================================== This shortcut allows you to generate a sales order based on the selected case. If different cases are open (a list), it generates one sales order by case. The case is then closed and linked to the generated sales order. We suggest you to install this module, if you installed both the sale and the crm modules. """, 'depends': ['sale_management', 'crm'], 'data': [ 'security/ir.model.access.csv', 'views/partner_views.xml', 'views/sale_order_views.xml', 'views/crm_lead_views.xml', 'views/crm_team_views.xml', 'wizard/crm_opportunity_to_quotation_views.xml' ], 'auto_install': True, 'uninstall_hook': 'uninstall_hook', 'license': 'LGPL-3', }
35
1,085
4,804
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.crm.tests import common as crm_common from odoo.tests.common import tagged, users @tagged('lead_manage') class TestLeadConvertToTicket(crm_common.TestCrmCommon): @classmethod def setUpClass(cls): super(TestLeadConvertToTicket, cls).setUpClass() cls.lead_1.write({ 'user_id': cls.user_sales_salesman.id, }) @users('user_sales_salesman') def test_lead_convert_to_quotation_create(self): """ Test partner creation while converting """ # Perform initial tests, do not repeat them at each test lead = self.lead_1.with_user(self.env.user) self.assertEqual(lead.partner_id, self.env['res.partner']) new_partner = self.env['res.partner'].search([('email_normalized', '=', 'amy.wong@test.example.com')]) self.assertEqual(new_partner, self.env['res.partner']) # invoke wizard and apply it convert = self.env['crm.quotation.partner'].with_context({ 'active_model': 'crm.lead', 'active_id': lead.id }).create({}) self.assertEqual(convert.action, 'create') self.assertEqual(convert.partner_id, self.env['res.partner']) action = convert.action_apply() # test lead update new_partner = self.env['res.partner'].search([('email_normalized', '=', 'amy.wong@test.example.com')]) self.assertEqual(lead.partner_id, new_partner) # test wizard action (does not create anything, just returns action) self.assertEqual(action['res_model'], 'sale.order') self.assertEqual(action['context']['default_partner_id'], new_partner.id) @users('user_sales_salesman') def test_lead_convert_to_quotation_exist(self): """ Test taking only existing customer while converting """ lead = self.lead_1.with_user(self.env.user) # invoke wizard and apply it convert = self.env['crm.quotation.partner'].with_context({ 'active_model': 'crm.lead', 'active_id': lead.id }).create({'action': 'exist'}) self.assertEqual(convert.action, 'exist') self.assertEqual(convert.partner_id, self.env['res.partner']) action = convert.action_apply() # test lead update new_partner = self.env['res.partner'].search([('email_normalized', '=', 'amy.wong@test.example.com')]) self.assertEqual(new_partner, self.env['res.partner']) convert.write({'partner_id': self.contact_2.id}) action = convert.action_apply() # test lead update new_partner = self.env['res.partner'].search([('email_normalized', '=', 'amy.wong@test.example.com')]) self.assertEqual(new_partner, self.env['res.partner']) self.assertEqual(lead.partner_id, self.contact_2) # TDE TODO: have a real sync assert for lead / contact self.assertEqual(lead.email_from, self.contact_2.email) self.assertEqual(lead.mobile, self.contact_2.mobile) self.assertEqual(action['context']['default_partner_id'], self.contact_2.id) @users('user_sales_salesman') def test_lead_convert_to_quotation_false_match_create(self): lead = self.lead_1.with_user(self.env.user) # invoke wizard and apply it convert = self.env['crm.quotation.partner'].with_context({ 'active_model': 'crm.lead', 'active_id': lead.id, }).create({'action': 'create'}) convert.write({'partner_id': self.contact_2.id}) self.assertEqual(convert.action, 'create') # ignore matching partner and create a new one convert.action_apply() self.assertTrue(bool(lead.partner_id.id)) self.assertNotEqual(lead.partner_id, self.contact_2) @users('user_sales_salesman') def test_lead_convert_to_quotation_nothing(self): """ Test doing nothing about customer while converting """ lead = self.lead_1.with_user(self.env.user) # invoke wizard and apply it convert = self.env['crm.quotation.partner'].with_context({ 'active_model': 'crm.lead', 'active_id': lead.id, 'default_action': 'nothing', }).create({}) self.assertEqual(convert.action, 'nothing') self.assertEqual(convert.partner_id, self.env['res.partner']) action = convert.action_apply() # test lead update new_partner = self.env['res.partner'].search([('email_normalized', '=', 'amy.wong@test.example.com')]) self.assertEqual(new_partner, self.env['res.partner']) self.assertEqual(lead.partner_id, self.env['res.partner']) self.assertEqual(action['context']['default_partner_id'], False)
40.033333
4,804
1,683
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.crm.tests.test_crm_lead_merge import TestLeadMergeCommon from odoo.tests.common import tagged, users @tagged('lead_manage') class TestLeadSaleMerge(TestLeadMergeCommon): @users('user_sales_manager') def test_merge_method_dependencies(self): """ Test if dependences for leads are not lost while merging leads. In this test leads are ordered as lead_w_contact -----------lead---seq=30 lead_w_email -------------lead---seq=3 lead_1 -------------------lead---seq=1 lead_w_partner_company ---lead---seq=1----------------orders lead_w_partner -----------lead---seq=False------------orders """ TestLeadMergeCommon.merge_fields.append('order_ids') orders = self.env['sale.order'].sudo().create([ {'partner_id': self.contact_1.id, 'opportunity_id': self.lead_w_partner_company.id, }, {'partner_id': self.contact_1.id, 'opportunity_id': self.lead_w_partner.id, } ]) self.assertEqual(self.lead_w_partner_company.order_ids, orders[0]) self.assertEqual(self.lead_w_partner.order_ids, orders[1]) leads = self.env['crm.lead'].browse(self.leads.ids)._sort_by_confidence_level(reverse=True) with self.assertLeadMerged(self.lead_w_contact, leads, name=self.lead_w_contact.name, order_ids=orders ): leads._merge_opportunity(auto_unlink=False, max_length=None)
42.075
1,683
2,198
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 Opportunity2Quotation(models.TransientModel): _name = 'crm.quotation.partner' _description = 'Create new or use existing Customer on new Quotation' @api.model def default_get(self, fields): result = super(Opportunity2Quotation, self).default_get(fields) active_model = self._context.get('active_model') if active_model != 'crm.lead': raise UserError(_('You can only apply this action from a lead.')) lead = False if result.get('lead_id'): lead = self.env['crm.lead'].browse(result['lead_id']) elif 'lead_id' in fields and self._context.get('active_id'): lead = self.env['crm.lead'].browse(self._context['active_id']) if lead: result['lead_id'] = lead.id partner_id = result.get('partner_id') or lead._find_matching_partner().id if 'action' in fields and not result.get('action'): result['action'] = 'exist' if partner_id else 'create' if 'partner_id' in fields and not result.get('partner_id'): result['partner_id'] = partner_id return result action = fields.Selection([ ('create', 'Create a new customer'), ('exist', 'Link to an existing customer'), ('nothing', 'Do not link to a customer') ], string='Quotation Customer', required=True) lead_id = fields.Many2one('crm.lead', "Associated Lead", required=True) partner_id = fields.Many2one('res.partner', 'Customer') def action_apply(self): """ Convert lead to opportunity or merge lead and opportunity and open the freshly created opportunity view. """ self.ensure_one() if self.action == 'create': self.lead_id._handle_partner_assignment(create_missing=True) elif self.action == 'exist': self.lead_id._handle_partner_assignment(force_partner_id=self.partner_id.id, create_missing=False) return self.lead_id.action_new_quotation()
42.269231
2,198
1,839
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 CrmTeam(models.Model): _inherit = 'crm.team' def _compute_dashboard_button_name(self): super(CrmTeam, self)._compute_dashboard_button_name() teams_with_opp = self.filtered(lambda team: team.use_opportunities) if self._context.get('in_sales_app'): teams_with_opp.update({'dashboard_button_name': _("Sales Analysis")}) def action_primary_channel_button(self): if self._context.get('in_sales_app') and self.use_opportunities: return self.env["ir.actions.actions"]._for_xml_id("sale.action_order_report_so_salesteam") return super(CrmTeam,self).action_primary_channel_button() def _graph_get_model(self): if self.use_opportunities and self._context.get('in_sales_app') : return 'sale.report' return super(CrmTeam,self)._graph_get_model() def _graph_date_column(self): if self.use_opportunities and self._context.get('in_sales_app'): return 'date' return super(CrmTeam,self)._graph_date_column() def _graph_y_query(self): if self.use_opportunities and self._context.get('in_sales_app'): return 'SUM(price_subtotal)' return super(CrmTeam,self)._graph_y_query() def _graph_title_and_key(self): if self.use_opportunities and self._context.get('in_sales_app'): return ['', _('Sales: Untaxed Total')] return super(CrmTeam,self)._graph_title_and_key() def _extra_sql_conditions(self): if self.use_opportunities and self._context.get('in_sales_app'): return "AND state in ('sale', 'done', 'pos_done')" return super(CrmTeam,self)._extra_sql_conditions()
41.795455
1,839
574
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 SaleOrder(models.Model): _inherit = 'sale.order' opportunity_id = fields.Many2one( 'crm.lead', string='Opportunity', check_company=True, domain="[('type', '=', 'opportunity'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]") def action_confirm(self): return super(SaleOrder, self.with_context({k:v for k,v in self._context.items() if k != 'default_tag_ids'})).action_confirm()
38.266667
574
270
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResUsers(models.Model): _inherit = 'res.users' target_sales_invoiced = fields.Integer('Invoiced in Sales Orders Target')
27
270
4,569
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from dateutil.relativedelta import relativedelta from odoo import api, fields, models class CrmLead(models.Model): _inherit = 'crm.lead' sale_amount_total = fields.Monetary(compute='_compute_sale_data', string="Sum of Orders", help="Untaxed Total of Confirmed Orders", currency_field='company_currency') quotation_count = fields.Integer(compute='_compute_sale_data', string="Number of Quotations") sale_order_count = fields.Integer(compute='_compute_sale_data', string="Number of Sale Orders") order_ids = fields.One2many('sale.order', 'opportunity_id', string='Orders') @api.depends('order_ids.state', 'order_ids.currency_id', 'order_ids.amount_untaxed', 'order_ids.date_order', 'order_ids.company_id') def _compute_sale_data(self): for lead in self: total = 0.0 quotation_cnt = 0 sale_order_cnt = 0 company_currency = lead.company_currency or self.env.company.currency_id for order in lead.order_ids: if order.state in ('draft', 'sent'): quotation_cnt += 1 if order.state not in ('draft', 'sent', 'cancel'): sale_order_cnt += 1 total += order.currency_id._convert( order.amount_untaxed, company_currency, order.company_id, order.date_order or fields.Date.today()) lead.sale_amount_total = total lead.quotation_count = quotation_cnt lead.sale_order_count = sale_order_cnt def action_sale_quotations_new(self): if not self.partner_id: return self.env["ir.actions.actions"]._for_xml_id("sale_crm.crm_quotation_partner_action") else: return self.action_new_quotation() def action_new_quotation(self): action = self.env["ir.actions.actions"]._for_xml_id("sale_crm.sale_action_quotations_new") action['context'] = { 'search_default_opportunity_id': self.id, 'default_opportunity_id': self.id, 'search_default_partner_id': self.partner_id.id, 'default_partner_id': self.partner_id.id, 'default_campaign_id': self.campaign_id.id, 'default_medium_id': self.medium_id.id, 'default_origin': self.name, 'default_source_id': self.source_id.id, 'default_company_id': self.company_id.id or self.env.company.id, 'default_tag_ids': [(6, 0, self.tag_ids.ids)] } if self.team_id: action['context']['default_team_id'] = self.team_id.id, if self.user_id: action['context']['default_user_id'] = self.user_id.id return action def action_view_sale_quotation(self): action = self.env["ir.actions.actions"]._for_xml_id("sale.action_quotations_with_onboarding") action['context'] = { 'search_default_draft': 1, 'search_default_partner_id': self.partner_id.id, 'default_partner_id': self.partner_id.id, 'default_opportunity_id': self.id } action['domain'] = [('opportunity_id', '=', self.id), ('state', 'in', ['draft', 'sent'])] quotations = self.mapped('order_ids').filtered(lambda l: l.state in ('draft', 'sent')) if len(quotations) == 1: action['views'] = [(self.env.ref('sale.view_order_form').id, 'form')] action['res_id'] = quotations.id return action def action_view_sale_order(self): action = self.env["ir.actions.actions"]._for_xml_id("sale.action_orders") action['context'] = { 'search_default_partner_id': self.partner_id.id, 'default_partner_id': self.partner_id.id, 'default_opportunity_id': self.id, } action['domain'] = [('opportunity_id', '=', self.id), ('state', 'not in', ('draft', 'sent', 'cancel'))] orders = self.mapped('order_ids').filtered(lambda l: l.state not in ('draft', 'sent', 'cancel')) if len(orders) == 1: action['views'] = [(self.env.ref('sale.view_order_form').id, 'form')] action['res_id'] = orders.id return action def _merge_get_fields_specific(self): fields_info = super(CrmLead, self)._merge_get_fields_specific() # add all the orders from all lead to merge fields_info['order_ids'] = lambda fname, leads: [(4, order.id) for order in leads.order_ids] return fields_info
48.606383
4,569
680
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Discuss (full)', 'version': '1.0', 'category': 'Hidden', 'sequence': 9877, 'summary': 'Test of Discuss with all possible overrides installed.', 'description': """Test of Discuss with all possible overrides installed, including feature and performance tests.""", 'depends': [ 'crm_livechat', 'hr_holidays', 'im_livechat', 'mail', 'mail_bot', 'website_livechat', ], 'data': [ ], 'demo': [ ], 'installable': True, 'application': False, 'license': 'LGPL-3', }
26.153846
680
45,422
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date from dateutil.relativedelta import relativedelta from odoo import Command from odoo.tests.common import users, tagged, TransactionCase, warmup from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT @tagged('post_install', '-at_install') class TestDiscussFullPerformance(TransactionCase): def setUp(self): super().setUp() self.users = self.env['res.users'].create([ { 'email': 'e.e@example.com', 'groups_id': [Command.link(self.env.ref('base.group_user').id)], 'login': 'emp', 'name': 'Ernest Employee', 'notification_type': 'inbox', 'signature': '--\nErnest', }, {'name': 'test1', 'login': 'test1', 'email': 'test1@example.com'}, {'name': 'test2', 'login': 'test2', 'email': 'test2@example.com'}, {'name': 'test3', 'login': 'test3'}, {'name': 'test4', 'login': 'test4'}, {'name': 'test5', 'login': 'test5'}, {'name': 'test6', 'login': 'test6'}, {'name': 'test7', 'login': 'test7'}, {'name': 'test8', 'login': 'test8'}, {'name': 'test9', 'login': 'test9'}, {'name': 'test10', 'login': 'test10'}, {'name': 'test11', 'login': 'test11'}, {'name': 'test12', 'login': 'test12'}, {'name': 'test13', 'login': 'test13'}, {'name': 'test14', 'login': 'test14'}, {'name': 'test15', 'login': 'test15'}, ]) self.employees = self.env['hr.employee'].create([{ 'user_id': user.id, } for user in self.users]) self.leave_type = self.env['hr.leave.type'].create({ 'leave_validation_type': 'no_validation', 'requires_allocation': 'no', 'name': 'Legal Leaves', 'time_type': 'leave', }) self.leaves = self.env['hr.leave'].create([{ 'date_from': date.today() + relativedelta(days=-2), 'date_to': date.today() + relativedelta(days=2), 'employee_id': employee.id, 'holiday_status_id': self.leave_type.id, } for employee in self.employees]) @users('emp') @warmup def test_init_messaging(self): """Test performance of `_init_messaging`.""" channel_general = self.env.ref('mail.channel_all_employees') # Unfortunately #general cannot be deleted. Assertions below assume data from a fresh db with demo. self.env['mail.channel'].sudo().search([('id', '!=', channel_general.id)]).unlink() user_root = self.env.ref('base.user_root') # create public channels channel_channel_public_1 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='public 1', privacy='public')['id']) channel_channel_public_1.add_members((self.users[0] + self.users[2] + self.users[3] + self.users[4] + self.users[8]).partner_id.ids) channel_channel_public_2 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='public 2', privacy='public')['id']) channel_channel_public_2.add_members((self.users[0] + self.users[2] + self.users[4] + self.users[7] + self.users[9]).partner_id.ids) # create groups channels channel_channel_group_1 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='group 1', privacy='groups')['id']) channel_channel_group_1.add_members((self.users[0] + self.users[2] + self.users[3] + self.users[6] + self.users[12]).partner_id.ids) channel_channel_group_2 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='group 2', privacy='groups')['id']) channel_channel_group_2.add_members((self.users[0] + self.users[2] + self.users[6] + self.users[7] + self.users[13]).partner_id.ids) # create private channels channel_channel_private_1 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='private 1', privacy='private')['id']) channel_channel_private_1.add_members((self.users[0] + self.users[2] + self.users[3] + self.users[5] + self.users[10]).partner_id.ids) channel_channel_private_2 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='private 2', privacy='private')['id']) channel_channel_private_2.add_members((self.users[0] + self.users[2] + self.users[5] + self.users[7] + self.users[11]).partner_id.ids) # create chats channel_chat_1 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_get((self.users[0] + self.users[14]).partner_id.ids)['id']) channel_chat_2 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_get((self.users[0] + self.users[15]).partner_id.ids)['id']) channel_chat_3 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_get((self.users[0] + self.users[2]).partner_id.ids)['id']) channel_chat_4 = self.env['mail.channel'].browse(self.env['mail.channel'].channel_get((self.users[0] + self.users[3]).partner_id.ids)['id']) # create groups channel_group_1 = self.env['mail.channel'].browse(self.env['mail.channel'].create_group((self.users[0] + self.users[12]).partner_id.ids)['id']) # create livechats im_livechat_channel = self.env['im_livechat.channel'].sudo().create({'name': 'support', 'user_ids': [Command.link(self.users[0].id)]}) self.users[0].im_status = 'online' # make available for livechat (ignore leave) channel_livechat_1 = self.env['mail.channel'].browse(im_livechat_channel._open_livechat_mail_channel(anonymous_name='anon 1', previous_operator_id=self.users[0].partner_id.id, user_id=self.users[1].id, country_id=self.env.ref('base.in').id)['id']) channel_livechat_1.with_user(self.users[1]).message_post(body="test") channel_livechat_2 = self.env['mail.channel'].browse(im_livechat_channel.with_user(self.env.ref('base.public_user'))._open_livechat_mail_channel(anonymous_name='anon 2', previous_operator_id=self.users[0].partner_id.id, country_id=self.env.ref('base.be').id)['id']) channel_livechat_2.with_user(self.env.ref('base.public_user')).sudo().message_post(body="test") # add needaction self.users[0].notification_type = 'inbox' message = channel_channel_public_1.message_post(body='test', message_type='comment', author_id=self.users[2].partner_id.id, partner_ids=self.users[0].partner_id.ids) # add star message.toggle_message_starred() self.env.company.sudo().name = 'YourCompany' self.maxDiff = None self.users[0].flush() self.users[0].invalidate_cache() with self.assertQueryCount(emp=93): # ent: 89 init_messaging = self.users[0].with_user(self.users[0])._init_messaging() self.assertEqual(init_messaging, { 'needaction_inbox_counter': 1, 'starred_counter': 1, 'channels': [ { 'avatarCacheKey': channel_general._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': user_root.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': 'General announcements for all employees.', 'group_based_subscription': True, 'id': channel_general.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_general.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_general._channel_last_message_ids()), 'memberCount': len(self.env.ref('base.group_user').users | user_root), 'message_needaction_counter': 0, 'message_unread_counter': 5, 'name': 'general', 'public': 'groups', 'rtcSessions': [('insert', [])], 'seen_message_id': False, 'state': 'open', 'uuid': channel_general.uuid, }, { 'avatarCacheKey': channel_channel_public_1._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'id': channel_channel_public_1.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_channel_public_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_channel_public_1._channel_last_message_ids()), 'message_needaction_counter': 1, 'memberCount': 5, 'message_unread_counter': 0, 'name': 'public 1', 'public': 'public', 'rtcSessions': [('insert', [])], 'seen_message_id': next(res['message_id'] for res in channel_channel_public_1._channel_last_message_ids()), 'state': 'open', 'uuid': channel_channel_public_1.uuid, }, { 'avatarCacheKey': channel_channel_public_2._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'id': channel_channel_public_2.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_channel_public_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_channel_public_2._channel_last_message_ids()), 'memberCount': 5, 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'public 2', 'public': 'public', 'rtcSessions': [('insert', [])], 'seen_message_id': next(res['message_id'] for res in channel_channel_public_2._channel_last_message_ids()), 'state': 'open', 'uuid': channel_channel_public_2.uuid, }, { 'avatarCacheKey': channel_channel_group_1._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'id': channel_channel_group_1.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_channel_group_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_channel_group_1._channel_last_message_ids()), 'memberCount': 5, 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'group 1', 'public': 'groups', 'rtcSessions': [('insert', [])], 'seen_message_id': next(res['message_id'] for res in channel_channel_group_1._channel_last_message_ids()), 'state': 'open', 'uuid': channel_channel_group_1.uuid, }, { 'avatarCacheKey': channel_channel_group_2._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'id': channel_channel_group_2.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_channel_group_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_channel_group_2._channel_last_message_ids()), 'memberCount': 5, 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'group 2', 'public': 'groups', 'rtcSessions': [('insert', [])], 'seen_message_id': next(res['message_id'] for res in channel_channel_group_2._channel_last_message_ids()), 'state': 'open', 'uuid': channel_channel_group_2.uuid, }, { 'avatarCacheKey': channel_channel_private_1._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'id': channel_channel_private_1.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_channel_private_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_channel_private_1._channel_last_message_ids()), 'memberCount': 5, 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'private 1', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_message_id': next(res['message_id'] for res in channel_channel_private_1._channel_last_message_ids()), 'state': 'open', 'uuid': channel_channel_private_1.uuid, }, { 'avatarCacheKey': channel_channel_private_2._get_avatar_cache_key(), 'channel_type': 'channel', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'id': channel_channel_private_2.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_channel_private_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_channel_private_2._channel_last_message_ids()), 'memberCount': 5, 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'private 2', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_message_id': next(res['message_id'] for res in channel_channel_private_2._channel_last_message_ids()), 'state': 'open', 'uuid': channel_channel_private_2.uuid, }, { 'avatarCacheKey': channel_group_1._get_avatar_cache_key(), 'channel_type': 'group', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_group_1.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_group_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': False, 'memberCount': 2, 'members': [ { 'active': True, 'display_name': 'Ernest Employee', 'email': 'e.e@example.com', 'id': self.users[0].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'Ernest Employee', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[0]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[0].id, }, { 'active': True, 'display_name': 'test12', 'email': False, 'id': self.users[12].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'test12', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[12]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[12].id, }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': '', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_message_id': False, 'seen_partners_info': [ { 'fetched_message_id': False, 'id': channel_group_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, { 'fetched_message_id': False, 'id': channel_group_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[12].partner_id).id, 'partner_id': self.users[12].partner_id.id, 'seen_message_id': False, } ], 'state': 'open', 'uuid': channel_group_1.uuid, }, { 'avatarCacheKey': channel_chat_1._get_avatar_cache_key(), 'channel_type': 'chat', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_chat_1.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_chat_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': False, 'memberCount': 2, 'members': [ { 'active': True, 'display_name': 'Ernest Employee', 'email': 'e.e@example.com', 'id': self.users[0].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'Ernest Employee', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[0]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[0].id, }, { 'active': True, 'display_name': 'test14', 'email': False, 'id': self.users[14].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'test14', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[14]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[14].id, }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'Ernest Employee, test14', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_partners_info': [ { 'fetched_message_id': False, 'id': channel_chat_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, { 'fetched_message_id': False, 'id': channel_chat_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[14].partner_id).id, 'partner_id': self.users[14].partner_id.id, 'seen_message_id': False, }, ], 'seen_message_id': False, 'state': 'open', 'uuid': channel_chat_1.uuid, }, { 'avatarCacheKey': channel_chat_2._get_avatar_cache_key(), 'channel_type': 'chat', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_chat_2.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_chat_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': False, 'memberCount': 2, 'members': [ { 'active': True, 'display_name': 'Ernest Employee', 'email': 'e.e@example.com', 'id': self.users[0].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'Ernest Employee', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[0]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[0].id, }, { 'active': True, 'display_name': 'test15', 'email': False, 'id': self.users[15].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'test15', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[15]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[15].id, }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'Ernest Employee, test15', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_partners_info': [ { 'fetched_message_id': False, 'id': channel_chat_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, { 'fetched_message_id': False, 'id': channel_chat_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[15].partner_id).id, 'partner_id': self.users[15].partner_id.id, 'seen_message_id': False, }, ], 'seen_message_id': False, 'state': 'open', 'uuid': channel_chat_2.uuid, }, { 'avatarCacheKey': channel_chat_3._get_avatar_cache_key(), 'channel_type': 'chat', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_chat_3.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_chat_3.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': False, 'memberCount': 2, 'members': [ { 'active': True, 'display_name': 'Ernest Employee', 'email': 'e.e@example.com', 'id': self.users[0].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'Ernest Employee', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[0]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[0].id, }, { 'active': True, 'display_name': 'test2', 'email': 'test2@example.com', 'id': self.users[2].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'test2', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[2]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[2].id, }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'Ernest Employee, test2', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_partners_info': [ { 'fetched_message_id': False, 'id': channel_chat_3.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, { 'fetched_message_id': False, 'id': channel_chat_3.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[2].partner_id).id, 'partner_id': self.users[2].partner_id.id, 'seen_message_id': False, }, ], 'seen_message_id': False, 'state': 'open', 'uuid': channel_chat_3.uuid, }, { 'avatarCacheKey': channel_chat_4._get_avatar_cache_key(), 'channel_type': 'chat', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_chat_4.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_chat_4.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': False, 'memberCount': 2, 'members': [ { 'active': True, 'display_name': 'Ernest Employee', 'email': 'e.e@example.com', 'id': self.users[0].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'Ernest Employee', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[0]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[0].id, }, { 'active': True, 'display_name': 'test3', 'email': False, 'id': self.users[3].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'test3', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[3]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[3].id, }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'Ernest Employee, test3', 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_partners_info': [ { 'fetched_message_id': False, 'id': channel_chat_4.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, { 'fetched_message_id': False, 'id': channel_chat_4.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[3].partner_id).id, 'partner_id': self.users[3].partner_id.id, 'seen_message_id': False, }, ], 'seen_message_id': False, 'state': 'open', 'uuid': channel_chat_4.uuid, }, { 'avatarCacheKey': channel_livechat_1._get_avatar_cache_key(), 'channel_type': 'livechat', 'create_uid': self.env.user.id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_livechat_1.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_livechat_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_livechat_1._channel_last_message_ids()), 'memberCount': 2, 'livechat_visitor': { 'country': False, 'id': self.users[1].partner_id.id, 'name': 'test1', }, 'members': [ { 'active': True, 'email': False, 'id': self.users[0].partner_id.id, 'im_status': False, 'livechat_username': False, 'name': 'Ernest Employee', }, { 'active': True, 'email': False, 'id': self.users[1].partner_id.id, 'im_status': False, 'livechat_username': False, 'name': 'test1', }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'test1 Ernest Employee', 'operator_pid': (self.users[0].partner_id.id, 'Ernest Employee'), 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_partners_info': [ { 'fetched_message_id': False, 'id': channel_livechat_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, { 'fetched_message_id': next(res['message_id'] for res in channel_livechat_1._channel_last_message_ids()), 'id': channel_livechat_1.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[1].partner_id).id, 'partner_id': self.users[1].partner_id.id, 'seen_message_id': next(res['message_id'] for res in channel_livechat_1._channel_last_message_ids()), }, ], 'seen_message_id': False, 'state': 'open', 'uuid': channel_livechat_1.uuid, }, { 'avatarCacheKey': channel_livechat_2._get_avatar_cache_key(), 'channel_type': 'livechat', 'create_uid': self.env.ref('base.public_user').id, 'custom_channel_name': False, 'defaultDisplayMode': False, 'description': False, 'group_based_subscription': False, 'guestMembers': [('insert', [])], 'id': channel_livechat_2.id, 'invitedGuests': [('insert', [])], 'invitedPartners': [('insert', [])], 'is_minimized': False, 'is_pinned': True, 'last_interest_dt': channel_livechat_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'last_message_id': next(res['message_id'] for res in channel_livechat_2._channel_last_message_ids()), 'memberCount': 2, 'livechat_visitor': { 'country': (self.env.ref('base.be').id, 'Belgium'), 'id': False, 'name': 'anon 2', }, 'members': [ { 'active': False, 'email': False, 'id': self.env.ref('base.public_partner').id, 'im_status': False, 'livechat_username': False, 'name': 'Public user', }, { 'active': True, 'email': False, 'id': self.users[0].partner_id.id, 'im_status': False, 'livechat_username': False, 'name': 'Ernest Employee', }, ], 'message_needaction_counter': 0, 'message_unread_counter': 0, 'name': 'anon 2 Ernest Employee', 'operator_pid': (self.users[0].partner_id.id, 'Ernest Employee'), 'public': 'private', 'rtcSessions': [('insert', [])], 'seen_partners_info': [ { 'fetched_message_id': next(res['message_id'] for res in channel_livechat_2._channel_last_message_ids()), 'id': channel_livechat_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.env.ref('base.public_partner')).id, 'partner_id': self.env.ref('base.public_user').partner_id.id, 'seen_message_id': next(res['message_id'] for res in channel_livechat_2._channel_last_message_ids()), }, { 'fetched_message_id': False, 'id': channel_livechat_2.channel_last_seen_partner_ids.filtered(lambda p: p.partner_id == self.users[0].partner_id).id, 'partner_id': self.users[0].partner_id.id, 'seen_message_id': False, }, ], 'seen_message_id': False, 'state': 'open', 'uuid': channel_livechat_2.uuid, }, ], 'companyName': 'YourCompany', 'mail_failures': [], 'shortcodes': [ { 'description': False, 'id': 1, 'source': 'hello', 'substitution': 'Hello. How may I help you?', }, { 'description': False, 'id': 2, 'source': 'bye', 'substitution': 'Thanks for your feedback. Good bye!', }, ], 'menu_id': self.env['ir.model.data']._xmlid_to_res_id('mail.menu_root_discuss'), 'partner_root': { 'active': False, 'display_name': 'OdooBot', 'email': 'odoobot@example.com', 'id': user_root.partner_id.id, 'im_status': 'bot', 'is_internal_user': True, 'name': 'OdooBot', 'out_of_office_date_end': False, 'user_id': False, }, 'public_partners': [{ 'active': False, 'display_name': 'Public user', 'email': False, 'id': self.env.ref('base.public_partner').id, 'im_status': 'im_partner', 'is_internal_user': False, 'name': 'Public user', 'out_of_office_date_end': False, 'user_id': self.env.ref('base.public_user').id, }], 'currentGuest': False, 'current_partner': { 'active': True, 'display_name': 'Ernest Employee', 'email': 'e.e@example.com', 'id': self.users[0].partner_id.id, 'im_status': 'leave_offline', 'is_internal_user': True, 'name': 'Ernest Employee', 'out_of_office_date_end': self.leaves.filtered(lambda l: l.employee_id.user_id == self.users[0]).date_to.strftime(DEFAULT_SERVER_DATE_FORMAT), 'user_id': self.users[0].id, }, 'current_user_id': self.users[0].id, 'current_user_settings': { 'id': self.env['res.users.settings']._find_or_create_for_user(self.users[0]).id, 'is_discuss_sidebar_category_channel_open': True, 'is_discuss_sidebar_category_chat_open': True, 'is_discuss_sidebar_category_livechat_open': True, 'push_to_talk_key': False, 'use_push_to_talk': False, 'user_id': (self.users[0].id, 'Ernest Employee'), 'voice_active_duration': 0, 'volume_settings': [], }, })
56.991217
45,422
760
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Saudi Arabia - E-invoicing (Simplified)', 'icon': '/l10n_sa/static/description/icon.png', 'version': '0.1', 'depends': [ 'l10n_sa_pos', 'l10n_sa_edi', ], 'author': 'Odoo', 'summary': """ ZATCA E-Invoicing, support for PoS """, 'description': """ E-invoice implementation for the Kingdom of Saudi Arabia (PoS) """, 'category': 'Accounting/Localizations/EDI', 'license': 'LGPL-3', 'assets': { 'point_of_sale.assets': [ 'l10n_sa_edi_pos/static/src/js/pos_models.js', 'l10n_sa_edi_pos/static/src/js/PaymentScreen.js', ], } }
28.148148
760
277
py
PYTHON
15.0
from odoo import models class AccountMove(models.Model): _inherit = 'account.move' def _l10n_sa_check_refund_reason(self): return super()._l10n_sa_check_refund_reason() or (self.pos_order_ids and self.pos_order_ids[0].refunded_orders_count > 0 and self.ref)
34.625
277
758
py
PYTHON
15.0
from odoo import models, api, _ from odoo.exceptions import ValidationError class PosConfig(models.Model): _inherit = 'pos.config' @api.constrains('company_id', 'invoice_journal_id') def _check_company_invoice_journal(self): """ Override to make sure POS invoice journal was probably onboarded before being used """ super()._check_company_invoice_journal() for config in self: if config.company_id.country_id.code == 'SA' and config.invoice_journal_id and not config.invoice_journal_id._l10n_sa_ready_to_submit_einvoices(): raise ValidationError(_("The invoice journal of the point of sale %s must be properly onboarded according to ZATCA specifications.", config.name))
47.375
758
543
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models class AccountEdiXmlUBL21Zatca(models.AbstractModel): _inherit = "account.edi.xml.ubl_21.zatca" def _l10n_sa_get_payment_means_code(self, invoice): """ Return payment means code to be used to set the value on the XML file """ res = super()._l10n_sa_get_payment_means_code(invoice) if invoice._l10n_sa_is_simplified() and invoice.pos_order_ids: res = invoice.pos_order_ids.payment_ids[0].payment_method_id.type return res
36.2
543
513
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Import/Export invoices with Factur-X', 'description': ''' Support for invoice Export/Import in Factur-x format (1.0.04). ''', 'version': '1.0', 'category': 'Accounting/Accounting', 'depends': ['account_edi'], 'data': [ 'data/account_edi_data.xml', 'data/facturx_templates.xml', ], 'installable': True, 'post_init_hook': '_post_init_hook', 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
27
513
14,747
py
PYTHON
15.0
# -*- coding: utf-8 -*- from freezegun import freeze_time from odoo.addons.account_edi.tests.common import AccountEdiTestCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestAccountEdiFacturx(AccountEdiTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None, edi_format_ref='account_edi_facturx.edi_facturx_1_0_05'): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) if cls.env['ir.module.module'].search( [('name', '=', 'account_edi_ubl_cii'), ('state', '=', 'installed')], limit=1, ): cls.skipTest(cls, "Factur-X Tests skipped because account_edi_ubl_cii is installed.") # ==== Init ==== cls.tax_10_include = cls.env['account.tax'].create({ 'name': 'tax_10_include', 'amount_type': 'percent', 'amount': 10, 'type_tax_use': 'sale', 'price_include': True, 'include_base_amount': True, 'sequence': 10, }) cls.tax_20 = cls.env['account.tax'].create({ 'name': 'tax_20', 'amount_type': 'percent', 'amount': 20, 'type_tax_use': 'sale', 'sequence': 20, }) cls.tax_group = cls.env['account.tax'].create({ 'name': 'tax_group', 'amount_type': 'group', 'amount': 0.0, 'type_tax_use': 'sale', 'children_tax_ids': [(6, 0, (cls.tax_10_include + cls.tax_20).ids)], }) # ==== Invoice ==== cls.invoice = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': cls.journal.id, 'partner_id': cls.partner_b.id, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'product_id': cls.product_a.id, 'product_uom_id': cls.env.ref('uom.product_uom_dozen').id, 'price_unit': 275.0, 'quantity': 5, 'discount': 20.0, 'tax_ids': [(6, 0, cls.tax_20.ids)], })], }) cls.expected_invoice_facturx_values = ''' <CrossIndustryInvoice> <ExchangedDocumentContext> <GuidelineSpecifiedDocumentContextParameter> <ID>urn:cen.eu:en16931:2017#conformant#urn:factur-x.eu:1p0:extended</ID> </GuidelineSpecifiedDocumentContextParameter> </ExchangedDocumentContext> <ExchangedDocument> <ID>INV/2017/00001</ID> <TypeCode>380</TypeCode> <IssueDateTime> <DateTimeString format="102">20170101</DateTimeString> </IssueDateTime> </ExchangedDocument> <SupplyChainTradeTransaction> <IncludedSupplyChainTradeLineItem> <AssociatedDocumentLineDocument> <LineID>1</LineID> </AssociatedDocumentLineDocument> <SpecifiedTradeProduct> <Name>product_a</Name> </SpecifiedTradeProduct> <SpecifiedLineTradeAgreement> <GrossPriceProductTradePrice> <ChargeAmount>275.000</ChargeAmount> <AppliedTradeAllowanceCharge> <ChargeIndicator> <Indicator>false</Indicator> </ChargeIndicator> <ActualAmount>55.000</ActualAmount> </AppliedTradeAllowanceCharge> </GrossPriceProductTradePrice> <NetPriceProductTradePrice> <ChargeAmount>220.000</ChargeAmount> </NetPriceProductTradePrice> </SpecifiedLineTradeAgreement> <SpecifiedLineTradeDelivery> <BilledQuantity unitCode="C62">5.0</BilledQuantity> </SpecifiedLineTradeDelivery> <SpecifiedLineTradeSettlement> <ApplicableTradeTax> <TypeCode>VAT</TypeCode> <CategoryCode>S</CategoryCode> <RateApplicablePercent>20.0</RateApplicablePercent> </ApplicableTradeTax> <SpecifiedTradeSettlementLineMonetarySummation> <LineTotalAmount>1100.000</LineTotalAmount> </SpecifiedTradeSettlementLineMonetarySummation> </SpecifiedLineTradeSettlement> </IncludedSupplyChainTradeLineItem> <ApplicableHeaderTradeAgreement> <SellerTradeParty> <Name>company_1_data</Name> <DefinedTradeContact> <PersonName>company_1_data</PersonName> </DefinedTradeContact> <PostalTradeAddress/> </SellerTradeParty> <BuyerTradeParty> <Name>partner_b</Name> <DefinedTradeContact> <PersonName>partner_b</PersonName> </DefinedTradeContact> <PostalTradeAddress/> </BuyerTradeParty> <BuyerOrderReferencedDocument> <IssuerAssignedID>INV/2017/00001</IssuerAssignedID> </BuyerOrderReferencedDocument> </ApplicableHeaderTradeAgreement> <ApplicableHeaderTradeDelivery> <ShipToTradeParty> <Name>partner_b</Name> <DefinedTradeContact> <PersonName>partner_b</PersonName> </DefinedTradeContact> <PostalTradeAddress/> </ShipToTradeParty> </ApplicableHeaderTradeDelivery> <ApplicableHeaderTradeSettlement> <InvoiceCurrencyCode>Gol</InvoiceCurrencyCode> <ApplicableTradeTax> <CalculatedAmount>220.000</CalculatedAmount> <TypeCode>VAT</TypeCode> <BasisAmount>1100.000</BasisAmount> <CategoryCode>S</CategoryCode> <RateApplicablePercent>20.0</RateApplicablePercent> </ApplicableTradeTax> <BillingSpecifiedPeriod> <StartDateTime> <DateTimeString format="102">20170101</DateTimeString> </StartDateTime> </BillingSpecifiedPeriod> <SpecifiedTradePaymentTerms> <DueDateDateTime> <DateTimeString format="102">20170101</DateTimeString> </DueDateDateTime> </SpecifiedTradePaymentTerms> <SpecifiedTradeSettlementHeaderMonetarySummation> <LineTotalAmount>1100.000</LineTotalAmount> <TaxBasisTotalAmount>1100.000</TaxBasisTotalAmount> <TaxTotalAmount currencyID="Gol">220.000</TaxTotalAmount> <GrandTotalAmount>1320.000</GrandTotalAmount> <TotalPrepaidAmount>0.000</TotalPrepaidAmount> <DuePayableAmount>1320.000</DuePayableAmount> </SpecifiedTradeSettlementHeaderMonetarySummation> </ApplicableHeaderTradeSettlement> </SupplyChainTradeTransaction> </CrossIndustryInvoice> ''' #################################################### # Test export #################################################### def test_facturx(self): ''' Test the generated Facturx Edi attachment without any modification of the invoice. ''' self.assert_generated_file_equal(self.invoice, self.expected_invoice_facturx_values) @freeze_time('2017-02-01') def test_facturx_group_of_taxes(self): ''' Same as above with a group of taxes. ''' self.invoice.write({ 'invoice_line_ids': [(1, self.invoice.invoice_line_ids.id, {'tax_ids': [(6, 0, self.tax_group.ids)]})], }) applied_xpath = ''' <xpath expr="//AppliedTradeAllowanceCharge/ActualAmount" position="replace"> <ActualAmount>50.000</ActualAmount> </xpath> <xpath expr="//NetPriceProductTradePrice/ChargeAmount" position="replace"> <ChargeAmount>200.000</ChargeAmount> </xpath> <xpath expr="//SpecifiedLineTradeSettlement" position="replace"> <SpecifiedLineTradeSettlement> <ApplicableTradeTax> <TypeCode>VAT</TypeCode> <CategoryCode>S</CategoryCode> <RateApplicablePercent>10.0</RateApplicablePercent> </ApplicableTradeTax> <ApplicableTradeTax> <TypeCode>VAT</TypeCode> <CategoryCode>S</CategoryCode> <RateApplicablePercent>20.0</RateApplicablePercent> </ApplicableTradeTax> <SpecifiedTradeSettlementLineMonetarySummation> <LineTotalAmount>1000.000</LineTotalAmount> </SpecifiedTradeSettlementLineMonetarySummation> </SpecifiedLineTradeSettlement> </xpath> <xpath expr="//ApplicableHeaderTradeSettlement" position="replace"> <ApplicableHeaderTradeSettlement> <InvoiceCurrencyCode>Gol</InvoiceCurrencyCode> <ApplicableTradeTax> <CalculatedAmount>100.000</CalculatedAmount> <TypeCode>VAT</TypeCode> <BasisAmount>1000.000</BasisAmount> <CategoryCode>S</CategoryCode> <RateApplicablePercent>10.0</RateApplicablePercent> </ApplicableTradeTax> <ApplicableTradeTax> <CalculatedAmount>220.000</CalculatedAmount> <TypeCode>VAT</TypeCode> <BasisAmount>1100.000</BasisAmount> <CategoryCode>S</CategoryCode> <RateApplicablePercent>20.0</RateApplicablePercent> </ApplicableTradeTax> <BillingSpecifiedPeriod> <StartDateTime> <DateTimeString format="102">20170101</DateTimeString> </StartDateTime> </BillingSpecifiedPeriod> <SpecifiedTradePaymentTerms> <DueDateDateTime> <DateTimeString format="102">20170101</DateTimeString> </DueDateDateTime> </SpecifiedTradePaymentTerms> <SpecifiedTradeSettlementHeaderMonetarySummation> <LineTotalAmount>1000.000</LineTotalAmount> <TaxBasisTotalAmount>1000.000</TaxBasisTotalAmount> <TaxTotalAmount currencyID="Gol">320.000</TaxTotalAmount> <GrandTotalAmount>1320.000</GrandTotalAmount> <TotalPrepaidAmount>0.000</TotalPrepaidAmount> <DuePayableAmount>1320.000</DuePayableAmount> </SpecifiedTradeSettlementHeaderMonetarySummation> </ApplicableHeaderTradeSettlement> </xpath> ''' self.assert_generated_file_equal(self.invoice, self.expected_invoice_facturx_values, applied_xpath) def test_export_pdf(self): self.invoice.action_post() pdf_values = self.edi_format._get_embedding_to_invoice_pdf_values(self.invoice) self.assertEqual(pdf_values['name'], 'factur-x.xml') #################################################### # Test import #################################################### def test_invoice_edi_pdf(self): invoice = self._create_empty_vendor_bill() invoice_count = len(self.env['account.move'].search([])) self.update_invoice_from_file('account_edi_facturx', 'test_file', 'test_facturx.pdf', invoice) self.assertEqual(len(self.env['account.move'].search([])), invoice_count) self.assertEqual(invoice.amount_total, 525) self.create_invoice_from_file('account_edi_facturx', 'test_file', 'test_facturx.pdf') self.assertEqual(invoice.amount_total, 525) self.assertEqual(len(self.env['account.move'].search([])), invoice_count + 1) def test_invoice_edi_xml(self): invoice = self._create_empty_vendor_bill() invoice_count = len(self.env['account.move'].search([])) self.update_invoice_from_file('account_edi_facturx', 'test_file', 'test_facturx.xml', invoice) self.assertEqual(len(self.env['account.move'].search([])), invoice_count) self.assertEqual(invoice.amount_total, 4610) self.create_invoice_from_file('account_edi_facturx', 'test_file', 'test_facturx.xml') self.assertEqual(invoice.amount_total, 4610) self.assertEqual(len(self.env['account.move'].search([])), invoice_count + 1)
50.851724
14,747
1,394
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models class AccountTax(models.Model): _inherit = 'account.tax' def _get_unece_category_code(self, customer, supplier): """ By default, this method will try to compute the tax category (used by EDI for example) based on the amount and the tax repartition lines. This is hack-ish~ but a valid solution to get a default value in stable. In master, the Category selection field should be by default on taxes and filled for each tax in the demo data if possible. See https://unece.org/fileadmin/DAM/trade/untdid/d16b/tred/tred5305.htm for the codes. """ self.ensure_one() # Defaulting to standard tax. category = 'S' if self.type_tax_use == 'sale': eu_countries = self.env.ref('base.europe').country_ids if supplier.country_id in eu_countries and customer.country_id not in eu_countries: category = 'G' else: if customer.country_id != supplier.country_id \ and customer.country_id in eu_countries \ and supplier.country_id in eu_countries: category = 'K' # Taxes with a Zero amount will get the E code. (Exempt) elif self.amount == 0: category = 'E' return category
41
1,394
18,232
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models, fields, tools, _ from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, float_repr, is_html_empty, str2bool from odoo.tests.common import Form from odoo.exceptions import RedirectWarning, UserError from datetime import datetime from lxml import etree from PyPDF2 import PdfFileReader import base64 import markupsafe import io import logging _logger = logging.getLogger(__name__) DEFAULT_FACTURX_DATE_FORMAT = '%Y%m%d' class AccountEdiFormat(models.Model): _inherit = 'account.edi.format' def _post_invoice_edi(self, invoices): self.ensure_one() if self.code != 'facturx_1_0_05' or self._is_account_edi_ubl_cii_available(): return super()._post_invoice_edi(invoices) res = {} for invoice in invoices: attachment = self._export_facturx(invoice) res[invoice] = {'success': True, 'attachment': attachment} return res def _is_embedding_to_invoice_pdf_needed(self): # OVERRIDE self.ensure_one() return True if self.code == 'facturx_1_0_05' else super()._is_embedding_to_invoice_pdf_needed() def _get_embedding_to_invoice_pdf_values(self, invoice): values = super()._get_embedding_to_invoice_pdf_values(invoice) if values and self.code == 'facturx_1_0_05': values['name'] = 'factur-x.xml' return values def _prepare_invoice_report(self, pdf_writer, edi_document): self.ensure_one() if self.code != 'facturx_1_0_05' or self._is_account_edi_ubl_cii_available(): return super()._prepare_invoice_report(pdf_writer, edi_document) if not edi_document.attachment_id: return pdf_writer.embed_odoo_attachment(edi_document.attachment_id, subtype='text/xml') if not pdf_writer.is_pdfa and str2bool(self.env['ir.config_parameter'].sudo().get_param('edi.use_pdfa', 'False')): try: pdf_writer.convert_to_pdfa() except Exception as e: _logger.exception("Error while converting to PDF/A: %s", e) metadata_template = self.env.ref('account_edi_facturx.account_invoice_pdfa_3_facturx_metadata', raise_if_not_found=False) if metadata_template: pdf_writer.add_file_metadata(metadata_template._render({ 'title': edi_document.move_id.name, 'date': fields.Date.context_today(self), }).encode()) def _export_facturx(self, invoice): def format_date(dt): # Format the date in the Factur-x standard. dt = dt or datetime.now() return dt.strftime(DEFAULT_FACTURX_DATE_FORMAT) def format_monetary(number, currency): # Format the monetary values to avoid trailing decimals (e.g. 90.85000000000001). if currency.is_zero(number): # Ensure that we never return -0.0 number = 0.0 return float_repr(number, currency.decimal_places) self.ensure_one() # Create file content. seller_siret = 'siret' in invoice.company_id._fields and invoice.company_id.siret or invoice.company_id.company_registry buyer_siret = 'siret' in invoice.commercial_partner_id._fields and invoice.commercial_partner_id.siret tax_detail_vals = invoice._prepare_edi_tax_details( grouping_key_generator=lambda tax_values: { 'unece_tax_category_code': tax_values['tax_id']._get_unece_category_code(invoice.commercial_partner_id, invoice.company_id), 'amount': tax_values['tax_id'].amount, 'amount_type': tax_values['tax_id'].amount_type, # We need to check the type } ) # For compatibility with the old template that was not using a grouped tax details. Only used to get the tax amount. # Done here to avoid adding a key in the base method that shouldn't be used. (the tax_amount key should be used) tax_details = list(tax_detail_vals['tax_details'].values()) for line in tax_detail_vals['invoice_line_tax_details'].values(): tax_details.extend(list(line['tax_details'].values())) for tax_detail in tax_details: tax_detail['tax'] = tax_detail['group_tax_details'][0]['tax_id'] template_values = { **invoice._prepare_edi_vals_to_export(), 'tax_details': tax_detail_vals, 'format_date': format_date, 'format_monetary': format_monetary, 'is_html_empty': is_html_empty, 'seller_specified_legal_organization': seller_siret, 'buyer_specified_legal_organization': buyer_siret, # Chorus PRO fields 'buyer_reference': 'buyer_reference' in invoice._fields and invoice.buyer_reference or '', 'contract_reference': 'contract_reference' in invoice._fields and invoice.contract_reference or '', 'purchase_order_reference': 'purchase_order_reference' in invoice._fields and invoice.purchase_order_reference or '', } xml_content = markupsafe.Markup("<?xml version='1.0' encoding='UTF-8'?>") xml_content += self.env.ref('account_edi_facturx.account_invoice_facturx_export')._render(template_values) return self.env['ir.attachment'].create({ 'name': 'factur-x.xml', 'raw': xml_content.encode(), 'mimetype': 'application/xml' }) def _is_facturx(self, filename, tree): return self.code == 'facturx_1_0_05' and tree.tag == '{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}CrossIndustryInvoice' def _create_invoice_from_xml_tree(self, filename, tree, journal=None): self.ensure_one() if self._is_facturx(filename, tree) and not self._is_account_edi_ubl_cii_available(): return self._import_facturx(tree, self.env['account.move']) return super()._create_invoice_from_xml_tree(filename, tree, journal=journal) def _update_invoice_from_xml_tree(self, filename, tree, invoice): self.ensure_one() if self._is_facturx(filename, tree) and not self._is_account_edi_ubl_cii_available(): return self._import_facturx(tree, invoice) return super()._update_invoice_from_xml_tree(filename, tree, invoice) def _import_facturx(self, tree, invoice): """ Decodes a factur-x invoice into an invoice. :param tree: the factur-x tree to decode. :param invoice: the invoice to update or an empty recordset. :returns: the invoice where the factur-x data was imported. """ def _find_value(xpath, element=tree): return self._find_value(xpath, element, tree.nsmap) amount_total_import = None default_move_type = False if invoice._context.get('default_journal_id'): journal = self.env['account.journal'].browse(self.env.context['default_journal_id']) default_move_type = 'out_invoice' if journal.type == 'sale' else 'in_invoice' elif invoice._context.get('default_move_type'): default_move_type = self._context['default_move_type'] elif invoice.move_type in self.env['account.move'].get_invoice_types(include_receipts=True): # in case an attachment is saved on a draft invoice previously created, we might # have lost the default value in context but the type was already set default_move_type = invoice.move_type if not default_move_type: raise UserError(_("No information about the journal or the type of invoice is passed")) if default_move_type == 'entry': return # Total amount. elements = tree.xpath('//ram:GrandTotalAmount', namespaces=tree.nsmap) total_amount = elements and float(elements[0].text) or 0.0 # Refund type. # There is two modes to handle refund in Factur-X: # a) type_code == 380 for invoice, type_code == 381 for refund, all positive amounts. # b) type_code == 380, negative amounts in case of refund. # To handle both, we consider the 'a' mode and switch to 'b' if a negative amount is encountered. elements = tree.xpath('//rsm:ExchangedDocument/ram:TypeCode', namespaces=tree.nsmap) type_code = elements[0].text default_move_type.replace('_refund', '_invoice') if type_code == '381': default_move_type = 'out_refund' if default_move_type == 'out_invoice' else 'in_refund' refund_sign = -1 else: # Handle 'b' refund mode. if total_amount < 0: default_move_type = 'out_refund' if default_move_type == 'out_invoice' else 'in_refund' refund_sign = -1 if 'refund' in default_move_type else 1 # Write the type as the journal entry is already created. invoice.move_type = default_move_type # self could be a single record (editing) or be empty (new). with Form(invoice.with_context(default_move_type=default_move_type)) as invoice_form: partner_type = invoice_form.journal_id.type == 'purchase' and 'SellerTradeParty' or 'BuyerTradeParty' invoice_form.partner_id = self._retrieve_partner( name=_find_value(f"//ram:{partner_type}/ram:Name"), mail=_find_value(f"//ram:{partner_type}//ram:URIID[@schemeID='SMTP']"), vat=_find_value(f"//ram:{partner_type}/ram:SpecifiedTaxRegistration/ram:ID"), ) # Reference. elements = tree.xpath('//rsm:ExchangedDocument/ram:ID', namespaces=tree.nsmap) if elements: invoice_form.ref = elements[0].text # Name. elements = tree.xpath('//ram:BuyerOrderReferencedDocument/ram:IssuerAssignedID', namespaces=tree.nsmap) if elements: invoice_form.payment_reference = elements[0].text # Comment. elements = tree.xpath('//ram:IncludedNote/ram:Content', namespaces=tree.nsmap) if elements: invoice_form.narration = elements[0].text # Get currency string for new invoices, or invoices coming from outside elements = tree.xpath('//ram:InvoiceCurrencyCode', namespaces=tree.nsmap) if elements: currency_str = elements[0].text # Fallback for old invoices from odoo where the InvoiceCurrencyCode was not present else: elements = tree.xpath('//ram:TaxTotalAmount', namespaces=tree.nsmap) if elements: currency_str = elements[0].attrib.get('currencyID', None) # Currency. if currency_str: currency = self._retrieve_currency(currency_str) if currency and not currency.active: error_msg = _('The currency (%s) of the document you are uploading is not active in this database.\n' 'Please activate it before trying again to import.', currency.name) error_action = { 'view_mode': 'form', 'res_model': 'res.currency', 'type': 'ir.actions.act_window', 'target': 'new', 'res_id': currency.id, 'views': [[False, 'form']] } raise RedirectWarning(error_msg, error_action, _('Display the currency')) invoice_form.currency_id = currency # Store xml total amount. amount_total_import = total_amount * refund_sign # Date. elements = tree.xpath('//rsm:ExchangedDocument/ram:IssueDateTime/udt:DateTimeString', namespaces=tree.nsmap) if elements: date_str = elements[0].text date_obj = datetime.strptime(date_str, DEFAULT_FACTURX_DATE_FORMAT) invoice_form.invoice_date = date_obj.strftime(DEFAULT_SERVER_DATE_FORMAT) # Due date. elements = tree.xpath('//ram:SpecifiedTradePaymentTerms/ram:DueDateDateTime/udt:DateTimeString', namespaces=tree.nsmap) if elements: date_str = elements[0].text date_obj = datetime.strptime(date_str, DEFAULT_FACTURX_DATE_FORMAT) invoice_form.invoice_date_due = date_obj.strftime(DEFAULT_SERVER_DATE_FORMAT) # Invoice lines. elements = tree.xpath('//ram:IncludedSupplyChainTradeLineItem', namespaces=tree.nsmap) if elements: for element in elements: with invoice_form.invoice_line_ids.new() as invoice_line_form: # Sequence. line_elements = element.xpath('.//ram:AssociatedDocumentLineDocument/ram:LineID', namespaces=tree.nsmap) if line_elements: invoice_line_form.sequence = int(line_elements[0].text) # Product. name = _find_value('.//ram:SpecifiedTradeProduct/ram:Name', element) invoice_line_form.product_id = self._retrieve_product( default_code=_find_value('.//ram:SpecifiedTradeProduct/ram:SellerAssignedID', element), name=_find_value('.//ram:SpecifiedTradeProduct/ram:Name', element), barcode=_find_value('.//ram:SpecifiedTradeProduct/ram:GlobalID', element) ) # force original line description instead of the one copied from product's Sales Description if name: invoice_line_form.name = name # Quantity. line_elements = element.xpath('.//ram:SpecifiedLineTradeDelivery/ram:BilledQuantity', namespaces=tree.nsmap) if line_elements: invoice_line_form.quantity = float(line_elements[0].text) # Price Unit. line_elements = element.xpath('.//ram:GrossPriceProductTradePrice/ram:ChargeAmount', namespaces=tree.nsmap) if line_elements: quantity_elements = element.xpath('.//ram:GrossPriceProductTradePrice/ram:BasisQuantity', namespaces=tree.nsmap) if quantity_elements: invoice_line_form.price_unit = float(line_elements[0].text) / float(quantity_elements[0].text) else: invoice_line_form.price_unit = float(line_elements[0].text) # For Gross price, we need to check if a discount must be taken into account discount_elements = element.xpath('.//ram:AppliedTradeAllowanceCharge', namespaces=tree.nsmap) if discount_elements: discount_percent_elements = element.xpath( './/ram:AppliedTradeAllowanceCharge/ram:CalculationPercent', namespaces=tree.nsmap) if discount_percent_elements: invoice_line_form.discount = float(discount_percent_elements[0].text) else: # if discount not available, it will be computed from the gross and net prices. net_price_elements = element.xpath('.//ram:NetPriceProductTradePrice/ram:ChargeAmount', namespaces=tree.nsmap) if net_price_elements: quantity_elements = element.xpath( './/ram:NetPriceProductTradePrice/ram:BasisQuantity', namespaces=tree.nsmap) net_unit_price = float(net_price_elements[0].text) / float(quantity_elements[0].text) \ if quantity_elements else float(net_price_elements[0].text) invoice_line_form.discount = (invoice_line_form.price_unit - net_unit_price) / invoice_line_form.price_unit * 100. else: line_elements = element.xpath('.//ram:NetPriceProductTradePrice/ram:ChargeAmount', namespaces=tree.nsmap) if line_elements: quantity_elements = element.xpath('.//ram:NetPriceProductTradePrice/ram:BasisQuantity', namespaces=tree.nsmap) if quantity_elements: invoice_line_form.price_unit = float(line_elements[0].text) / float(quantity_elements[0].text) else: invoice_line_form.price_unit = float(line_elements[0].text) # Taxes tax_element = element.xpath('.//ram:SpecifiedLineTradeSettlement/ram:ApplicableTradeTax/ram:RateApplicablePercent', namespaces=tree.nsmap) invoice_line_form.tax_ids.clear() for eline in tax_element: tax = self._retrieve_tax( amount=eline.text, type_tax_use=invoice_form.journal_id.type ) if tax: invoice_line_form.tax_ids.add(tax) elif amount_total_import: # No lines in BASICWL. with invoice_form.invoice_line_ids.new() as invoice_line_form: invoice_line_form.name = invoice_form.comment or '/' invoice_line_form.quantity = 1 invoice_line_form.price_unit = amount_total_import return invoice_form.save()
53.940828
18,232
424
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Mass mailing sms on sale orders', 'category': 'Hidden', 'version': '1.0', 'summary': 'Add sale order info on mass mailing sms', 'description': """Mass mailing sms on sale orders""", 'depends': ['mass_mailing_sale', 'mass_mailing_sms'], 'auto_install': True, 'license': 'LGPL-3', }
32.615385
424
370
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class UtmCampaign(models.Model): _inherit = 'utm.campaign' ab_testing_sms_winner_selection = fields.Selection(selection_add=[ ('sale_quotation_count', 'Quotations'), ('sale_invoiced_amount', 'Revenues'), ])
28.461538
370
1,766
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # @author - Fekete Mihai <feketemihai@gmail.com>, Tatár Attila <atta@nvm.ro> # Copyright (C) 2019 NextERP Romania (https://nexterp.ro) # Copyright (C) 2015 Tatár Attila # Copyright (C) 2015 Forest and Biomass Services Romania (http://www.forbiom.eu). # Copyright (C) 2011 TOTAL PC SYSTEMS (http://www.erpsystems.ro). # Copyright (C) 2009 (<http://www.filsystem.ro>) { "name": "Romania - Accounting", "author": "Fekete Mihai (NextERP Romania SRL)", "website": "https://www.nexterp.ro", 'category': 'Accounting/Localizations/Account Charts', 'version': '1.0', "depends": [ 'account', 'base_vat', ], "description": """ This is the module to manage the Accounting Chart, VAT structure, Fiscal Position and Tax Mapping. It also adds the Registration Number for Romania in Odoo. ================================================================================================================ Romanian accounting chart and localization. """, "data": ['views/res_partner_view.xml', 'data/l10n_ro_chart_data.xml', 'data/account.group.template.csv', 'data/account.account.template.csv', 'data/l10n_ro_chart_post_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_data.xml', 'data/account_fiscal_position_data.xml', 'data/account_reconcile_model_template_data.xml', 'data/account_chart_template_data.xml', 'data/res.bank.csv', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
39.2
1,764
744
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # @author - Fekete Mihai <feketemihai@gmail.com> # Copyright (C) 2020 NextERP Romania (https://www.nexterp.ro) <contact@nexterp.ro> # Copyright (C) 2015 Forest and Biomass Services Romania (http://www.forbiom.eu). # Copyright (C) 2011 TOTAL PC SYSTEMS (http://www.erpsystems.ro). # Copyright (C) 2009 (<http://www.filsystem.ro>) from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" @api.model def _commercial_fields(self): return super(ResPartner, self)._commercial_fields() + ['nrc'] nrc = fields.Char(string='NRC', help='Registration number at the Registry of Commerce')
37.2
744
531
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'United Arab Emirates - Point of Sale', 'author': 'Odoo PS', 'category': 'Accounting/Localizations/Point of Sale', 'description': """ United Arab Emirates POS Localization ======================================================= """, 'depends': ['l10n_ae', 'point_of_sale'], 'qweb': ['static/src/xml/Screens/ReceiptScreen/OrderReceipt.xml'], 'auto_install': True, 'license': 'LGPL-3', }
35.4
531