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
449
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields, models class PhoneBlacklistRemove(models.TransientModel): _name = 'phone.blacklist.remove' _description = 'Remove phone from blacklist' phone = fields.Char(string="Phone Number", readonly=True, required=True) reason = fields.Char(name="Reason") def action_unblacklist_apply(self): return self.env['phone.blacklist'].action_remove_with_reason(self.phone, self.reason)
32.071429
449
12,316
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from odoo import api, fields, models, _ from odoo.addons.phone_validation.tools import phone_validation from odoo.exceptions import AccessError, UserError from odoo.osv import expression class PhoneMixin(models.AbstractModel): """ Purpose of this mixin is to offer two services * compute a sanitized phone number based on ´´_sms_get_number_fields´´. It takes first sanitized value, trying each field returned by the method (see ``MailThread._sms_get_number_fields()´´ for more details about the usage of this method); * compute blacklist state of records. It is based on phone.blacklist model and give an easy-to-use field and API to manipulate blacklisted records; Main API methods * ``_phone_set_blacklisted``: set recordset as blacklisted; * ``_phone_reset_blacklisted``: reactivate recordset (even if not blacklisted this method can be called safely); """ _name = 'mail.thread.phone' _description = 'Phone Blacklist Mixin' _inherit = ['mail.thread'] phone_sanitized = fields.Char( string='Sanitized Number', compute="_compute_phone_sanitized", compute_sudo=True, store=True, help="Field used to store sanitized phone number. Helps speeding up searches and comparisons.") phone_sanitized_blacklisted = fields.Boolean( string='Phone Blacklisted', compute="_compute_blacklisted", compute_sudo=True, store=False, search="_search_phone_sanitized_blacklisted", groups="base.group_user", help="If the sanitized phone number is on the blacklist, the contact won't receive mass mailing sms anymore, from any list") phone_blacklisted = fields.Boolean( string='Blacklisted Phone is Phone', compute="_compute_blacklisted", compute_sudo=True, store=False, groups="base.group_user", help="Indicates if a blacklisted sanitized phone number is a phone number. Helps distinguish which number is blacklisted \ when there is both a mobile and phone field in a model.") mobile_blacklisted = fields.Boolean( string='Blacklisted Phone Is Mobile', compute="_compute_blacklisted", compute_sudo=True, store=False, groups="base.group_user", help="Indicates if a blacklisted sanitized phone number is a mobile number. Helps distinguish which number is blacklisted \ when there is both a mobile and phone field in a model.") phone_mobile_search = fields.Char("Phone/Mobile", store=False, search='_search_phone_mobile_search') def _search_phone_mobile_search(self, operator, value): value = value.strip() if isinstance(value, str) else value phone_fields = [ fname for fname in self._phone_get_number_fields() if fname in self._fields and self._fields[fname].store ] if not phone_fields: raise UserError(_('Missing definition of phone fields.')) # search if phone/mobile is set or not if (value is True or not value) and operator in ('=', '!='): if value: # inverse the operator operator = '=' if operator == '!=' else '!=' op = expression.AND if operator == '=' else expression.OR return op([[(phone_field, operator, False)] for phone_field in phone_fields]) if len(value) < 3: raise UserError(_('Please enter at least 3 characters when searching a Phone/Mobile number.')) pattern = r'[\s\\./\(\)\-]' sql_operator = {'=like': 'LIKE', '=ilike': 'ILIKE'}.get(operator, operator) if value.startswith('+') or value.startswith('00'): if operator in expression.NEGATIVE_TERM_OPERATORS: # searching on +32485112233 should also finds 0032485112233 (and vice versa) # we therefore remove it from input value and search for both of them in db where_str = ' AND '.join( f"""model.{phone_field} IS NULL OR ( REGEXP_REPLACE(model.{phone_field}, %s, '', 'g') {sql_operator} %s OR REGEXP_REPLACE(model.{phone_field}, %s, '', 'g') {sql_operator} %s )""" for phone_field in phone_fields ) else: # searching on +32485112233 should also finds 0032485112233 (and vice versa) # we therefore remove it from input value and search for both of them in db where_str = ' OR '.join( f"""model.{phone_field} IS NOT NULL AND ( REGEXP_REPLACE(model.{phone_field}, %s, '', 'g') {sql_operator} %s OR REGEXP_REPLACE(model.{phone_field}, %s, '', 'g') {sql_operator} %s )""" for phone_field in phone_fields ) query = f"SELECT model.id FROM {self._table} model WHERE {where_str};" term = re.sub(pattern, '', value[1 if value.startswith('+') else 2:]) if operator not in ('=', '!='): # for like operators term = f'{term}%' self._cr.execute( query, (pattern, '00' + term, pattern, '+' + term) * len(phone_fields) ) else: if operator in expression.NEGATIVE_TERM_OPERATORS: where_str = ' AND '.join( f"(model.{phone_field} IS NULL OR REGEXP_REPLACE(model.{phone_field}, %s, '', 'g') {sql_operator} %s)" for phone_field in phone_fields ) else: where_str = ' OR '.join( f"(model.{phone_field} IS NOT NULL AND REGEXP_REPLACE(model.{phone_field}, %s, '', 'g') {sql_operator} %s)" for phone_field in phone_fields ) query = f"SELECT model.id FROM {self._table} model WHERE {where_str};" term = re.sub(pattern, '', value) if operator not in ('=', '!='): # for like operators term = f'%{term}%' self._cr.execute(query, (pattern, term) * len(phone_fields)) res = self._cr.fetchall() if not res: return [(0, '=', 1)] return [('id', 'in', [r[0] for r in res])] @api.depends(lambda self: self._phone_get_sanitize_triggers()) def _compute_phone_sanitized(self): self._assert_phone_field() number_fields = self._phone_get_number_fields() for record in self: for fname in number_fields: sanitized = record.phone_get_sanitized_number(number_fname=fname) if sanitized: break record.phone_sanitized = sanitized @api.depends('phone_sanitized') def _compute_blacklisted(self): # TODO : Should remove the sudo as compute_sudo defined on methods. # But if user doesn't have access to mail.blacklist, doen't work without sudo(). blacklist = set(self.env['phone.blacklist'].sudo().search([ ('number', 'in', self.mapped('phone_sanitized'))]).mapped('number')) number_fields = self._phone_get_number_fields() for record in self: record.phone_sanitized_blacklisted = record.phone_sanitized in blacklist mobile_blacklisted = phone_blacklisted = False # This is a bit of a hack. Assume that any "mobile" numbers will have the word 'mobile' # in them due to varying field names and assume all others are just "phone" numbers. # Note that the limitation of only having 1 phone_sanitized value means that a phone/mobile number # may not be calculated as blacklisted even though it is if both field values exist in a model. for number_field in number_fields: if 'mobile' in number_field: mobile_blacklisted = record.phone_sanitized_blacklisted and record.phone_get_sanitized_number(number_fname=number_field) == record.phone_sanitized else: phone_blacklisted = record.phone_sanitized_blacklisted and record.phone_get_sanitized_number(number_fname=number_field) == record.phone_sanitized record.mobile_blacklisted = mobile_blacklisted record.phone_blacklisted = phone_blacklisted @api.model def _search_phone_sanitized_blacklisted(self, operator, value): # Assumes operator is '=' or '!=' and value is True or False self._assert_phone_field() if operator != '=': if operator == '!=' and isinstance(value, bool): value = not value else: raise NotImplementedError() if value: query = """ SELECT m.id FROM phone_blacklist bl JOIN %s m ON m.phone_sanitized = bl.number AND bl.active """ else: query = """ SELECT m.id FROM %s m LEFT JOIN phone_blacklist bl ON m.phone_sanitized = bl.number AND bl.active WHERE bl.id IS NULL """ self._cr.execute(query % self._table) res = self._cr.fetchall() if not res: return [(0, '=', 1)] return [('id', 'in', [r[0] for r in res])] def _assert_phone_field(self): if not hasattr(self, "_phone_get_number_fields"): raise UserError(_('Invalid primary phone field on model %s', self._name)) if not any(fname in self and self._fields[fname].type == 'char' for fname in self._phone_get_number_fields()): raise UserError(_('Invalid primary phone field on model %s', self._name)) def _phone_get_sanitize_triggers(self): """ Tool method to get all triggers for sanitize """ res = [self._phone_get_country_field()] if self._phone_get_country_field() else [] return res + self._phone_get_number_fields() def _phone_get_number_fields(self): """ This method returns the fields to use to find the number to use to send an SMS on a record. """ return [] def _phone_get_country_field(self): if 'country_id' in self: return 'country_id' return False def phone_get_sanitized_numbers(self, number_fname='mobile', force_format='E164'): res = dict.fromkeys(self.ids, False) country_fname = self._phone_get_country_field() for record in self: number = record[number_fname] res[record.id] = phone_validation.phone_sanitize_numbers_w_record([number], record, record_country_fname=country_fname, force_format=force_format)[number]['sanitized'] return res def phone_get_sanitized_number(self, number_fname='mobile', force_format='E164'): self.ensure_one() country_fname = self._phone_get_country_field() number = self[number_fname] return phone_validation.phone_sanitize_numbers_w_record([number], self, record_country_fname=country_fname, force_format=force_format)[number]['sanitized'] def _phone_set_blacklisted(self): return self.env['phone.blacklist'].sudo()._add([r.phone_sanitized for r in self]) def _phone_reset_blacklisted(self): return self.env['phone.blacklist'].sudo()._remove([r.phone_sanitized for r in self]) def phone_action_blacklist_remove(self): # wizard access rights currently not working as expected and allows users without access to # open this wizard, therefore we check to make sure they have access before the wizard opens. can_access = self.env['phone.blacklist'].check_access_rights('write', raise_exception=False) if can_access: return { 'name': 'Are you sure you want to unblacklist this Phone Number?', 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'phone.blacklist.remove', 'target': 'new', } else: raise AccessError("You do not have the access right to unblacklist phone numbers. Please contact your administrator.")
51.078838
12,310
5,580
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models, _ from odoo.addons.phone_validation.tools import phone_validation from odoo.exceptions import UserError _logger = logging.getLogger(__name__) class PhoneBlackList(models.Model): """ Blacklist of phone numbers. Used to avoid sending unwanted messages to people. """ _name = 'phone.blacklist' _inherit = ['mail.thread'] _description = 'Phone Blacklist' _rec_name = 'number' number = fields.Char(string='Phone Number', required=True, index=True, tracking=True, help='Number should be E164 formatted') active = fields.Boolean(default=True, tracking=True) _sql_constraints = [ ('unique_number', 'unique (number)', 'Number already exists') ] @api.model_create_multi def create(self, values): # First of all, extract values to ensure emails are really unique (and don't modify values in place) to_create = [] done = set() for value in values: number = value['number'] sanitized_values = phone_validation.phone_sanitize_numbers_w_record([number], self.env.user)[number] sanitized = sanitized_values['sanitized'] if not sanitized: raise UserError(sanitized_values['msg'] + _(" Please correct the number and try again.")) if sanitized in done: continue done.add(sanitized) to_create.append(dict(value, number=sanitized)) """ To avoid crash during import due to unique email, return the existing records if any """ sql = '''SELECT number, id FROM phone_blacklist WHERE number = ANY(%s)''' numbers = [v['number'] for v in to_create] self._cr.execute(sql, (numbers,)) bl_entries = dict(self._cr.fetchall()) to_create = [v for v in to_create if v['number'] not in bl_entries] results = super(PhoneBlackList, self).create(to_create) return self.env['phone.blacklist'].browse(bl_entries.values()) | results def write(self, values): if 'number' in values: number = values['number'] sanitized_values = phone_validation.phone_sanitize_numbers_w_record([number], self.env.user)[number] sanitized = sanitized_values['sanitized'] if not sanitized: raise UserError(sanitized_values['msg'] + _(" Please correct the number and try again.")) values['number'] = sanitized return super(PhoneBlackList, self).write(values) def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None): """ Override _search in order to grep search on sanitized number field """ if args: new_args = [] for arg in args: if isinstance(arg, (list, tuple)) and arg[0] == 'number' and isinstance(arg[2], str): number = arg[2] sanitized = phone_validation.phone_sanitize_numbers_w_record([number], self.env.user)[number]['sanitized'] if sanitized: new_args.append([arg[0], arg[1], sanitized]) else: new_args.append(arg) else: new_args.append(arg) else: new_args = args return super(PhoneBlackList, self)._search(new_args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid) def add(self, number): sanitized = phone_validation.phone_sanitize_numbers_w_record([number], self.env.user)[number]['sanitized'] return self._add([sanitized]) def _add(self, numbers): """ Add or re activate a phone blacklist entry. :param numbers: list of sanitized numbers """ records = self.env["phone.blacklist"].with_context(active_test=False).search([('number', 'in', numbers)]) todo = [n for n in numbers if n not in records.mapped('number')] if records: records.action_unarchive() if todo: records += self.create([{'number': n} for n in todo]) return records def action_remove_with_reason(self, number, reason=None): records = self.remove(number) if reason: for record in records: record.message_post(body=_("Unblacklisting Reason: %s", reason)) return records def remove(self, number): sanitized = phone_validation.phone_sanitize_numbers_w_record([number], self.env.user)[number]['sanitized'] return self._remove([sanitized]) def _remove(self, numbers): """ Add de-activated or de-activate a phone blacklist entry. :param numbers: list of sanitized numbers """ records = self.env["phone.blacklist"].with_context(active_test=False).search([('number', 'in', numbers)]) todo = [n for n in numbers if n not in records.mapped('number')] if records: records.action_archive() if todo: records += self.create([{'number': n, 'active': False} for n in todo]) return records def phone_action_blacklist_remove(self): return { 'name': 'Are you sure you want to unblacklist this Phone Number?', 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'phone.blacklist.remove', 'target': 'new', } def action_add(self): self.add(self.number)
42.923077
5,580
1,798
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models from odoo.addons.phone_validation.tools import phone_validation class Partner(models.Model): _name = 'res.partner' _inherit = ['res.partner'] @api.onchange('phone', 'country_id', 'company_id') def _onchange_phone_validation(self): if self.phone: self.phone = self._phone_format(self.phone) @api.onchange('mobile', 'country_id', 'company_id') def _onchange_mobile_validation(self): if self.mobile: self.mobile = self._phone_format(self.mobile) def _phone_format(self, number, country=None, company=None): country = country or self.country_id or self.env.company.country_id if not country: return number return phone_validation.phone_format( number, country.code if country else None, country.phone_code if country else None, force_format='INTERNATIONAL', raise_exception=False ) def phone_get_sanitized_number(self, number_fname='mobile', force_format='E164'): """ Stand alone version, allowing to use it on partner model without having any dependency on sms module. To cleanup in master (15.3 +).""" self.ensure_one() country_fname = 'country_id' number = self[number_fname] return phone_validation.phone_sanitize_numbers_w_record([number], self, record_country_fname=country_fname, force_format=force_format)[number]['sanitized'] def _phone_get_number_fields(self): """ Stand alone version, allowing to use it on partner model without having any dependency on sms module. To cleanup in master (15.3 +).""" return ['mobile', 'phone']
40.863636
1,798
317
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. try: # import for usage in phonenumbers_patch/region_*.py files from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata # pylint: disable=unused-import except ImportError: pass
39.625
317
935
py
PYTHON
15.0
"""Auto-generated file, do not edit by hand. CI metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_CI = PhoneMetadata(id='CI', country_code=225, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[02]\\d{9}', possible_length=(10,)), fixed_line=PhoneNumberDesc(national_number_pattern='2(?:[15]\\d{3}|7(?:2(?:0[23]|1[2357]|[23][45]|4[3-5])|3(?:06|1[69]|[2-6]7)))\\d{5}', example_number='2123456789', possible_length=(10,)), mobile=PhoneNumberDesc(national_number_pattern='0704[0-7]\\d{5}|0(?:[15]\\d\\d|7(?:0[0-37-9]|[4-9][7-9]))\\d{6}', example_number='0123456789', possible_length=(10,)), number_format=[NumberFormat(pattern='(\\d{2})(\\d{2})(\\d)(\\d{5})', format='\\1 \\2 \\3 \\4', leading_digits_pattern=['2']), NumberFormat(pattern='(\\d{2})(\\d{2})(\\d{2})(\\d{4})', format='\\1 \\2 \\3 \\4', leading_digits_pattern=['0'])])
103.888889
935
574
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Booths Sale/Exhibitors Bridge', 'category': 'Marketing/Events', 'version': '1.0', 'summary': 'Bridge module between website_event_booth_exhibitor and website_event_booth_sale.', 'description': """ """, 'depends': ['website_event_exhibitor', 'website_event_booth_sale'], 'data': [], 'auto_install': True, 'assets': { 'web.assets_tests': [ 'website_event_booth_sale_exhibitor/static/tests/tours/website_event_booth_sale_exhibitor.js', ], }, 'license': 'LGPL-3', }
30.210526
574
956
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 EventBoothRegistration(models.Model): _inherit = 'event.booth.registration' sponsor_name = fields.Char(string='Sponsor Name') sponsor_email = fields.Char(string='Sponsor Email') sponsor_mobile = fields.Char(string='Sponsor Mobile') sponsor_phone = fields.Char(string='Sponsor Phone') sponsor_subtitle = fields.Char(string='Sponsor Slogan') sponsor_website_description = fields.Html(string='Sponsor Description') sponsor_image_512 = fields.Image(string='Sponsor Logo') def _get_fields_for_booth_confirmation(self): return super(EventBoothRegistration, self)._get_fields_for_booth_confirmation() + \ ['sponsor_name', 'sponsor_email', 'sponsor_mobile', 'sponsor_phone', 'sponsor_subtitle', 'sponsor_website_description', 'sponsor_image_512']
45.52381
956
603
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "snailmail_account", 'description': """ Allows users to send invoices by post ===================================================== """, 'category': 'Hidden/Tools', 'version': '0.1', 'depends': ['account', 'snailmail'], 'data': [ 'views/res_config_settings_views.xml', 'wizard/account_invoice_send_views.xml', 'security/ir.model.access.csv', ], 'auto_install': True, 'assets': { 'web.assets_backend': [ 'snailmail_account/static/**/*', ], }, 'license': 'LGPL-3', }
26.217391
603
3,108
py
PYTHON
15.0
import requests import json import base64 import logging from odoo.tests.common import HttpCase from odoo.tests import tagged _logger = logging.getLogger(__name__) @tagged('post_install', '-at_install', '-standard', 'external') class TestPingenSend(HttpCase): def setUp(self): super(TestPingenSend, self).setUp() self.pingen_url = "https://stage-api.pingen.com/document/upload/token/30fc3947dbea4792eb12548b41ec8117/" self.sample_invoice = self.create_invoice() self.sample_invoice.partner_id.vat = "BE000000000" self.letter = self.env['snailmail.letter'].create({ 'partner_id': self.sample_invoice.partner_id.id, 'model': 'account.move', 'res_id': self.sample_invoice.id, 'user_id': self.env.user.id, 'company_id': self.sample_invoice.company_id.id, 'report_template': self.env.ref('account.account_invoices').id }) self.data = { 'data': json.dumps({ 'speed': 1, 'color': 1, 'duplex': 0, 'send': True, }) } def create_invoice(self): """ Create a sample invoice """ invoice = self.env['account.move'].with_context(default_move_type='out_invoice').create({ 'move_type': 'out_invoice', 'partner_id': self.env.ref("base.res_partner_2").id, 'currency_id': self.env.ref('base.EUR').id, 'invoice_date': '2018-12-11', 'invoice_line_ids': [(0, 0, { 'product_id': self.env.ref("product.product_product_4").id, 'quantity': 1, 'price_unit': 42, })], }) invoice.action_post() return invoice def render_and_send(self, report_name): self.sample_invoice.company_id.external_report_layout_id = self.env.ref('web.' + report_name) self.letter.attachment_id = False attachment_id = self.letter.with_context(force_report_rendering=True)._fetch_attachment() files = { 'file': ('pingen_test_%s.pdf' % report_name, base64.b64decode(attachment_id.datas), 'application/pdf'), } response = requests.post(self.pingen_url, data=self.data, files=files) if 400 <= response.status_code <= 599 or response.json()['error']: msg = "%(code)s %(side)s Error: %(reason)s for url: %(url)s\n%(body)s" % { 'code': response.status_code, 'side': r"%s", 'reason': response.reason, 'url': self.pingen_url, 'body': response.text} if response.status_code <= 499 or response.json()['error']: raise requests.HTTPError(msg % "Client") else: _logger.warning(msg % "Server") def test_pingen_send_invoice(self): self.render_and_send('external_layout_standard') self.render_and_send('external_layout_striped') self.render_and_send('external_layout_boxed') self.render_and_send('external_layout_bold')
38.37037
3,108
4,445
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, Command, _ from odoo.exceptions import UserError class AccountInvoiceSend(models.TransientModel): _name = 'account.invoice.send' _inherit = 'account.invoice.send' _description = 'Account Invoice Send' partner_id = fields.Many2one('res.partner', compute='_get_partner', string='Partner') snailmail_is_letter = fields.Boolean('Send by Post', help='Allows to send the document by Snailmail (conventional posting delivery service)', default=lambda self: self.env.company.invoice_is_snailmail) snailmail_cost = fields.Float(string='Stamp(s)', compute='_compute_snailmail_cost', readonly=True) invalid_addresses = fields.Integer('Invalid Addresses Count', compute='_compute_invalid_addresses') invalid_invoices = fields.Integer('Invalid Invoices Count', compute='_compute_invalid_addresses') invalid_partner_ids = fields.Many2many('res.partner', string='Invalid Addresses', compute='_compute_invalid_addresses') @api.depends('invoice_ids') def _compute_invalid_addresses(self): for wizard in self: if any(not invoice.partner_id for invoice in wizard.invoice_ids): raise UserError(_('You cannot send an invoice which has no partner assigned.')) invalid_invoices = wizard.invoice_ids.filtered(lambda i: not self.env['snailmail.letter']._is_valid_address(i.partner_id)) wizard.invalid_invoices = len(invalid_invoices) invalid_partner_ids = invalid_invoices.partner_id.ids wizard.invalid_addresses = len(invalid_partner_ids) wizard.invalid_partner_ids = [Command.set(invalid_partner_ids)] @api.depends('invoice_ids') def _get_partner(self): self.partner_id = self.env['res.partner'] for wizard in self: if wizard.invoice_ids and len(wizard.invoice_ids) == 1: wizard.partner_id = wizard.invoice_ids.partner_id.id @api.depends('snailmail_is_letter') def _compute_snailmail_cost(self): for wizard in self: wizard.snailmail_cost = len(wizard.invoice_ids.ids) def snailmail_print_action(self): self.ensure_one() letters = self.env['snailmail.letter'] for invoice in self.invoice_ids: letter = self.env['snailmail.letter'].create({ 'partner_id': invoice.partner_id.id, 'model': 'account.move', 'res_id': invoice.id, 'user_id': self.env.user.id, 'company_id': invoice.company_id.id, 'report_template': self.env.ref('account.account_invoices').id }) letters |= letter self.invoice_ids.filtered(lambda inv: not inv.is_move_sent).write({'is_move_sent': True}) if len(self.invoice_ids) == 1: letters._snailmail_print() else: letters._snailmail_print(immediate=False) def send_and_print_action(self): if self.snailmail_is_letter: if self.env['snailmail.confirm.invoice'].show_warning(): wizard = self.env['snailmail.confirm.invoice'].create({'model_name': _('Invoice'), 'invoice_send_id': self.id}) return wizard.action_open() self._print_action() return self.send_and_print() def _print_action(self): if not self.snailmail_is_letter: return if self.invalid_addresses and self.composition_mode == "mass_mail": self.notify_invalid_addresses() self.snailmail_print_action() def send_and_print(self): res = super(AccountInvoiceSend, self).send_and_print_action() return res def notify_invalid_addresses(self): self.ensure_one() self.env['bus.bus']._sendone(self.env.user.partner_id, 'snailmail_invalid_address', { 'title': _("Invalid Addresses"), 'message': _("%s of the selected invoice(s) had an invalid address and were not sent", self.invalid_invoices), }) def invalid_addresses_action(self): return { 'name': _('Invalid Addresses'), 'type': 'ir.actions.act_window', 'view_mode': 'kanban,tree,form', 'res_model': 'res.partner', 'domain': [('id', 'in', self.invalid_partner_ids.ids)], }
44.89899
4,445
585
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 SnailmailConfirmInvoiceSend(models.TransientModel): _name = 'snailmail.confirm.invoice' _inherit = ['snailmail.confirm'] _description = 'Snailmail Confirm Invoice' invoice_send_id = fields.Many2one('account.invoice.send') def _confirm(self): self.ensure_one() self.invoice_send_id._print_action() def _continue(self): self.ensure_one() return self.invoice_send_id.send_and_print()
29.25
585
273
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 Company(models.Model): _inherit = "res.company" invoice_is_snailmail = fields.Boolean(string='Send by Post', default=False)
27.3
273
349
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' invoice_is_snailmail = fields.Boolean(string='Send by Post', related='company_id.invoice_is_snailmail', readonly=False)
34.9
349
594
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Margins in Sales Orders', 'version':'1.0', 'category': 'Sales/Sales', 'description': """ This module adds the 'Margin' on sales order. ============================================= This gives the profitability by calculating the difference between the Unit Price and Cost Price. """, 'depends':['sale_management'], 'demo':['data/sale_margin_demo.xml'], 'data':['security/ir.model.access.csv','views/sale_margin_view.xml'], 'license': 'LGPL-3', }
31.263158
594
8,068
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common from datetime import datetime class TestSaleMargin(common.TransactionCase): def setUp(self): super(TestSaleMargin, self).setUp() self.SaleOrder = self.env['sale.order'] self.product_uom_id = self.ref('uom.product_uom_unit') self.product = self.env['product.product'].create({'name': 'Individual Workplace'}) self.product_id = self.product.id self.partner_id = self.env['res.partner'].create({'name': 'A test partner'}).id self.partner_invoice_address_id = self.env['res.partner'].create({ 'name': 'A test partner address', 'parent_id': self.partner_id, }).id self.pricelist_id = self.ref('product.list0') self.pricelist = self.env.ref('product.list0') def test_sale_margin(self): """ Test the sale_margin module in Odoo. """ self.pricelist.currency_id = self.env.company.currency_id self.product.standard_price = 700.0 sale_order_so11 = self.SaleOrder.create({ 'date_order': datetime.today(), 'name': 'Test_SO011', 'order_line': [ (0, 0, { 'name': '[CARD] Individual Workplace', 'price_unit': 1000.0, 'product_uom': self.product_uom_id, 'product_uom_qty': 10.0, 'state': 'draft', 'product_id': self.product_id}), (0, 0, { 'name': 'Line without product_uom', 'price_unit': 1000.0, 'product_uom_qty': 10.0, 'state': 'draft', 'product_id': self.product_id})], 'partner_id': self.partner_id, 'partner_invoice_id': self.partner_invoice_address_id, 'partner_shipping_id': self.partner_invoice_address_id, 'pricelist_id': self.pricelist_id}) # Confirm the sales order. sale_order_so11.action_confirm() # Verify that margin field gets bind with the value. self.assertEqual(sale_order_so11.margin, 6000.00, "Sales order profit should be 6000.00") self.assertEqual(sale_order_so11.margin_percent, 0.3, "Sales order margin should be 30%") sale_order_so11.order_line[1].purchase_price = 800 self.assertEqual(sale_order_so11.margin, 5000.00, "Sales order margin should be 5000.00") def test_sale_margin1(self): """ Test the margin when sales price is less then cost.""" sale_order_so12 = self.SaleOrder.create({ 'date_order': datetime.today(), 'name': 'Test_SO012', 'order_line': [ (0, 0, { 'name': '[CARD] Individual Workplace', 'purchase_price': 40.0, 'price_unit': 20.0, 'product_uom': self.product_uom_id, 'product_uom_qty': 1.0, 'state': 'draft', 'product_id': self.product_id}), (0, 0, { 'name': 'Line without product_uom', 'price_unit': -100.0, 'purchase_price': 0.0, 'product_uom_qty': 1.0, 'state': 'draft', 'product_id': self.product_id})], 'partner_id': self.partner_id, 'partner_invoice_id': self.partner_invoice_address_id, 'partner_shipping_id': self.partner_invoice_address_id, 'pricelist_id': self.pricelist_id}) # Confirm the sales order. sale_order_so12.action_confirm() # Verify that margin field of Sale Order Lines gets bind with the value. self.assertEqual(sale_order_so12.order_line[0].margin, -20.00, "Sales order profit should be -20.00") self.assertEqual(sale_order_so12.order_line[0].margin_percent, -1, "Sales order margin percentage should be -100%") self.assertEqual(sale_order_so12.order_line[1].margin, -100.00, "Sales order profit should be -100.00") self.assertEqual(sale_order_so12.order_line[1].margin_percent, 1.00, "Sales order margin should be 100% when the cost is zero and price defined") # Verify that margin field gets bind with the value. self.assertEqual(sale_order_so12.margin, -120.00, "Sales order margin should be -120.00") self.assertEqual(sale_order_so12.margin_percent, 1.5, "Sales order margin should be 150%") def test_sale_margin2(self): """ Test the margin when cost is 0 margin percentage should always be 100%.""" sale_order_so13 = self.SaleOrder.create({ 'date_order': datetime.today(), 'name': 'Test_SO013', 'order_line': [ (0, 0, { 'name': '[CARD] Individual Workplace', 'purchase_price': 0.0, 'price_unit': 70.0, 'product_uom': self.product_uom_id, 'product_uom_qty': 1.0, 'state': 'draft', 'product_id': self.product_id})], 'partner_id': self.partner_id, 'partner_invoice_id': self.partner_invoice_address_id, 'partner_shipping_id': self.partner_invoice_address_id, 'pricelist_id': self.pricelist_id}) # Verify that margin field of Sale Order Lines gets bind with the value. self.assertEqual(sale_order_so13.order_line[0].margin, 70.00, "Sales order profit should be 70.00") self.assertEqual(sale_order_so13.order_line[0].margin_percent, 1.0, "Sales order margin percentage should be 100.00") # Verify that margin field gets bind with the value. self.assertEqual(sale_order_so13.margin, 70.00, "Sales order profit should be 70.00") self.assertEqual(sale_order_so13.margin_percent, 1.00, "Sales order margin percentage should be 100.00") def test_sale_margin3(self): """ Test the margin and margin percentage when product with multiple quantity""" sale_order_so14 = self.SaleOrder.create({ 'date_order': datetime.today(), 'name': 'Test_SO014', 'order_line': [ (0, 0, { 'name': '[CARD] Individual Workplace', 'purchase_price': 50.0, 'price_unit': 100.0, 'product_uom': self.product_uom_id, 'product_uom_qty': 3.0, 'state': 'draft', 'product_id': self.product_id}), (0, 0, { 'name': 'Line without product_uom', 'price_unit': -50.0, 'purchase_price': 0.0, 'product_uom_qty': 1.0, 'state': 'draft', 'product_id': self.product_id})], 'partner_id': self.partner_id, 'partner_invoice_id': self.partner_invoice_address_id, 'partner_shipping_id': self.partner_invoice_address_id, 'pricelist_id': self.pricelist_id}) # Confirm the sales order. sale_order_so14.action_confirm() # Verify that margin field of Sale Order Lines gets bind with the value. self.assertEqual(sale_order_so14.order_line[0].margin, 150.00, "Sales order profit should be 150.00") self.assertEqual(sale_order_so14.order_line[0].margin_percent, 0.5, "Sales order margin should be 100%") self.assertEqual(sale_order_so14.order_line[1].margin, -50.00, "Sales order profit should be -50.00") self.assertEqual(sale_order_so14.order_line[1].margin_percent, 1.0, "Sales order margin should be 100%") # Verify that margin field gets bind with the value. self.assertEqual(sale_order_so14.margin, 100.00, "Sales order profit should be 100.00") self.assertEqual(sale_order_so14.margin_percent, 0.4, "Sales order margin should be 40%")
52.732026
8,068
3,975
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 SaleOrderLine(models.Model): _inherit = "sale.order.line" margin = fields.Float( "Margin", compute='_compute_margin', digits='Product Price', store=True, groups="base.group_user") margin_percent = fields.Float( "Margin (%)", compute='_compute_margin', store=True, groups="base.group_user", group_operator="avg") purchase_price = fields.Float( string='Cost', compute="_compute_purchase_price", digits='Product Price', store=True, readonly=False, groups="base.group_user") @api.depends('product_id', 'company_id', 'currency_id', 'product_uom') def _compute_purchase_price(self): for line in self: if not line.product_id: line.purchase_price = 0.0 continue line = line.with_company(line.company_id) product_cost = line.product_id.standard_price line.purchase_price = line._convert_price(product_cost, line.product_id.uom_id) @api.depends('price_subtotal', 'product_uom_qty', 'purchase_price') def _compute_margin(self): for line in self: line.margin = line.price_subtotal - (line.purchase_price * line.product_uom_qty) line.margin_percent = line.price_subtotal and line.margin/line.price_subtotal def _convert_price(self, product_cost, from_uom): self.ensure_one() if not product_cost: # If the standard_price is 0 # Avoid unnecessary computations # and currency conversions if not self.purchase_price: return product_cost from_currency = self.product_id.cost_currency_id to_cur = self.currency_id or self.order_id.currency_id to_uom = self.product_uom if to_uom and to_uom != from_uom: product_cost = from_uom._compute_price( product_cost, to_uom, ) return from_currency._convert( from_amount=product_cost, to_currency=to_cur, company=self.company_id or self.env.company, date=self.order_id.date_order or fields.Date.today(), round=False, ) if to_cur and product_cost else product_cost # The pricelist may not have been set, therefore no conversion # is needed because we don't know the target currency.. class SaleOrder(models.Model): _inherit = "sale.order" margin = fields.Monetary("Margin", compute='_compute_margin', store=True) margin_percent = fields.Float( "Margin (%)", compute='_compute_margin', store=True, group_operator='avg' ) @api.depends('order_line.margin', 'amount_untaxed') def _compute_margin(self): if not all(self._ids): for order in self: order.margin = sum(order.order_line.mapped('margin')) order.margin_percent = order.amount_untaxed and order.margin/order.amount_untaxed else: self.env["sale.order.line"].flush(['margin']) # On batch records recomputation (e.g. at install), compute the margins # with a single read_group query for better performance. # This isn't done in an onchange environment because (part of) the data # may not be stored in database (new records or unsaved modifications). grouped_order_lines_data = self.env['sale.order.line'].read_group( [ ('order_id', 'in', self.ids), ], ['margin', 'order_id'], ['order_id']) mapped_data = {m['order_id'][0]: m['margin'] for m in grouped_order_lines_data} for order in self: order.margin = mapped_data.get(order.id, 0.0) order.margin_percent = order.amount_untaxed and order.margin/order.amount_untaxed
45.170455
3,975
471
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 SaleReport(models.Model): _inherit = 'sale.report' margin = fields.Float('Margin') def _select_additional_fields(self, fields): fields['margin'] = ", SUM(l.margin / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) AS margin" return super()._select_additional_fields(fields)
33.642857
471
2,686
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Expenses', 'version': '2.0', 'category': 'Human Resources/Expenses', 'sequence': 70, 'summary': 'Submit, validate and reinvoice employee expenses', 'description': """ Manage expenses by Employees ============================ This application allows you to manage your employees' daily expenses. It gives you access to your employees’ fee notes and give you the right to complete and validate or refuse the notes. After validation it creates an invoice for the employee. Employee can encode their own expenses and the validation flow puts it automatically in the accounting after validation by managers. The whole flow is implemented as: --------------------------------- * Draft expense * Submitted by the employee to his manager * Approved by his manager * Validation by the accountant and accounting entries creation This module also uses analytic accounting and is compatible with the invoice on timesheet module so that you are able to automatically re-invoice your customers' expenses if your work by project. """, 'website': 'https://www.odoo.com/app/expenses', 'depends': ['hr_contract', 'account', 'web_tour'], 'data': [ 'security/hr_expense_security.xml', 'security/ir.model.access.csv', 'data/digest_data.xml', 'data/mail_data.xml', 'data/mail_templates.xml', 'data/hr_expense_sequence.xml', 'data/hr_expense_data.xml', 'wizard/hr_expense_refuse_reason_views.xml', 'wizard/hr_expense_approve_duplicate_views.xml', 'views/hr_expense_views.xml', 'views/mail_activity_views.xml', 'security/ir_rule.xml', 'report/hr_expense_report.xml', 'views/hr_department_views.xml', 'views/res_config_settings_views.xml', 'views/account_journal_dashboard.xml', ], 'demo': ['data/hr_expense_demo.xml'], 'installable': True, 'application': True, 'assets': { 'web.assets_backend': [ 'hr_expense/static/src/js/expense_views.js', 'hr_expense/static/src/js/expense_form_view.js', 'hr_expense/static/src/js/expense_qr_code_action.js', 'hr_expense/static/src/js/upload_mixin.js', 'hr_expense/static/src/scss/hr_expense.scss', ], 'web.assets_tests': [ 'hr_expense/static/src/js/tours/hr_expense.js', 'hr_expense/static/tests/tours/expense_upload_tours.js', ], 'web.assets_qweb': [ 'hr_expense/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
39.470588
2,684
5,585
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestExpensesMailImport(TestExpenseCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.product_a.default_code = 'product_a' cls.product_b.default_code = 'product_b' def test_import_expense_from_email(self): message_parsed = { 'message_id': "the-world-is-a-ghetto", 'subject': '%s %s' % (self.product_a.default_code, self.product_a.standard_price), 'email_from': self.expense_user_employee.email, 'to': '[email protected]', 'body': "Don't you know, that for me, and for you", 'attachments': [], } expense = self.env['hr.expense'].message_new(message_parsed) self.assertRecordValues(expense, [{ 'product_id': self.product_a.id, 'total_amount': 800.0, 'employee_id': self.expense_employee.id, }]) def test_import_expense_from_email_no_product(self): message_parsed = { 'message_id': "the-world-is-a-ghetto", 'subject': 'no product code 800', 'email_from': self.expense_user_employee.email, 'to': '[email protected]', 'body': "Don't you know, that for me, and for you", 'attachments': [], } expense = self.env['hr.expense'].message_new(message_parsed) self.assertRecordValues(expense, [{ 'product_id': False, 'total_amount': 800.0, 'employee_id': self.expense_employee.id, }]) def test_import_expense_from_mail_parsing_subjects(self): def assertParsedValues(subject, currencies, exp_description, exp_amount, exp_product): product, amount, currency_id, description = self.env['hr.expense']\ .with_user(self.expense_user_employee)\ ._parse_expense_subject(subject, currencies) self.assertEqual(product, exp_product) self.assertAlmostEqual(amount, exp_amount) self.assertEqual(description, exp_description) # Without Multi currency access assertParsedValues( "product_a bar $1205.91 electro wizard", self.company_data['currency'], "bar electro wizard", 1205.91, self.product_a, ) # subject having other currency then company currency, it should ignore other currency then company currency assertParsedValues( "foo bar %s1406.91 royal giant" % self.currency_data['currency'].symbol, self.company_data['currency'], "foo bar %s royal giant" % self.currency_data['currency'].symbol, 1406.91, self.env['product.product'], ) # With Multi currency access self.expense_user_employee.groups_id |= self.env.ref('base.group_multi_currency') assertParsedValues( "product_a foo bar $2205.92 elite barbarians", self.company_data['currency'], "foo bar elite barbarians", 2205.92, self.product_a, ) # subject having other currency then company currency, it should accept other currency because multi currency is activated assertParsedValues( "product_a %s2510.90 chhota bheem" % self.currency_data['currency'].symbol, self.company_data['currency'] + self.currency_data['currency'], "chhota bheem", 2510.90, self.product_a, ) # subject without product and currency, should take company currency and default product assertParsedValues( "foo bar 109.96 spear goblins", self.company_data['currency'] + self.currency_data['currency'], "foo bar spear goblins", 109.96, self.env['product.product'], ) # subject with currency symbol at end assertParsedValues( "product_a foo bar 2910.94$ inferno dragon", self.company_data['currency'] + self.currency_data['currency'], "foo bar inferno dragon", 2910.94, self.product_a, ) # subject with no amount and product assertParsedValues( "foo bar mega knight", self.company_data['currency'] + self.currency_data['currency'], "foo bar mega knight", 0.0, self.env['product.product'], ) # price with a comma assertParsedValues( "foo bar 291,56$ mega knight", self.company_data['currency'] + self.currency_data['currency'], "foo bar mega knight", 291.56, self.env['product.product'], ) # price without decimals assertParsedValues( "foo bar 291$ mega knight", self.company_data['currency'] + self.currency_data['currency'], "foo bar mega knight", 291.0, self.env['product.product'], ) assertParsedValues( "product_a foo bar 291.5$ mega knight", self.company_data['currency'] + self.currency_data['currency'], "foo bar mega knight", 291.5, self.product_a, )
36.503268
5,585
23,392
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.tests import tagged, Form from odoo.tools.misc import formatLang from odoo import fields @tagged('-at_install', 'post_install') class TestExpenses(TestExpenseCommon): def test_expense_sheet_payment_state(self): ''' Test expense sheet payment states when partially paid, in payment and paid. ''' def get_payment(expense_sheet, amount): ctx = {'active_model': 'account.move', 'active_ids': expense_sheet.account_move_id.ids} payment_register = self.env['account.payment.register'].with_context(**ctx).create({ 'amount': amount, 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, }) return payment_register._create_payments() expense_sheet = self.env['hr.expense.sheet'].create({ 'name': 'Expense for John Smith', 'employee_id': self.expense_employee.id, 'accounting_date': '2021-01-01', 'expense_line_ids': [(0, 0, { 'name': 'Car Travel Expenses', 'employee_id': self.expense_employee.id, 'product_id': self.product_a.id, 'unit_amount': 350.00, })] }) expense_sheet.action_submit_sheet() expense_sheet.approve_expense_sheets() expense_sheet.action_sheet_move_create() payment = get_payment(expense_sheet, 100.0) liquidity_lines1 = payment._seek_for_lines()[0] self.assertEqual(expense_sheet.payment_state, 'partial', 'payment_state should be partial') payment = get_payment(expense_sheet, 250.0) liquidity_lines2 = payment._seek_for_lines()[0] in_payment_state = expense_sheet.account_move_id._get_invoice_in_payment_state() self.assertEqual(expense_sheet.payment_state, in_payment_state, 'payment_state should be ' + in_payment_state) statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [ (0, 0, { 'payment_ref': 'pay_ref', 'amount': -350.0, 'partner_id': self.expense_employee.address_home_id.id, }), ], }) statement.button_post() statement.line_ids.reconcile([{'id': liquidity_lines1.id}, {'id': liquidity_lines2.id}]) self.assertEqual(expense_sheet.payment_state, 'paid', 'payment_state should be paid') def test_expense_values(self): """ Checking accounting move entries and analytic entries when submitting expense """ # The expense employee is able to a create an expense sheet. # The total should be 1500.0 because: # - first line: 1000.0 (unit amount), 130.43 (tax). But taxes are included in total thus - 1000 # - second line: (1500.0 (unit amount), 195.652 (tax)) - 65.22 (tax in company currency). total 1500.0 * 1/3 (rate) = 500 expense_sheet = self.env['hr.expense.sheet'].create({ 'name': 'First Expense for employee', 'employee_id': self.expense_employee.id, 'journal_id': self.company_data['default_journal_purchase'].id, 'accounting_date': '2017-01-01', 'expense_line_ids': [ (0, 0, { # Expense without foreign currency. 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1000.0, 'tax_ids': [(6, 0, self.company_data['default_tax_purchase'].ids)], 'analytic_account_id': self.analytic_account_1.id, 'employee_id': self.expense_employee.id, }), (0, 0, { # Expense with foreign currency (rate 1:3). 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_b.id, 'unit_amount': 1500.0, 'tax_ids': [(6, 0, self.company_data['default_tax_purchase'].ids)], 'analytic_account_id': self.analytic_account_2.id, 'currency_id': self.currency_data['currency'].id, 'employee_id': self.expense_employee.id, }), ], }) # Check expense sheet values. self.assertRecordValues(expense_sheet, [{'state': 'draft', 'total_amount': 1500.0}]) expense_sheet.action_submit_sheet() expense_sheet.approve_expense_sheets() expense_sheet.action_sheet_move_create() # Check expense sheet journal entry values. self.assertRecordValues(expense_sheet.account_move_id.line_ids.sorted('balance'), [ # Receivable line (company currency): { 'debit': 0.0, 'credit': 1000.0, 'amount_currency': -1000.0, 'account_id': self.company_data['default_account_payable'].id, 'product_id': False, 'currency_id': self.company_data['currency'].id, 'tax_line_id': False, 'analytic_account_id': False, }, # Receivable line (foreign currency): { 'debit': 0.0, 'credit': 500.0, 'amount_currency': -1500.0, 'account_id': self.company_data['default_account_payable'].id, 'product_id': False, 'currency_id': self.currency_data['currency'].id, 'tax_line_id': False, 'analytic_account_id': False, }, # Tax line (foreign currency): { 'debit': 65.22, 'credit': 0.0, 'amount_currency': 195.652, 'account_id': self.company_data['default_account_tax_purchase'].id, 'product_id': False, 'currency_id': self.currency_data['currency'].id, 'tax_line_id': self.company_data['default_tax_purchase'].id, 'analytic_account_id': False, }, # Tax line (company currency): { 'debit': 130.43, 'credit': 0.0, 'amount_currency': 130.43, 'account_id': self.company_data['default_account_tax_purchase'].id, 'product_id': False, 'currency_id': self.company_data['currency'].id, 'tax_line_id': self.company_data['default_tax_purchase'].id, 'analytic_account_id': False, }, # Product line (foreign currency): { 'debit': 434.78, 'credit': 0.0, 'amount_currency': 1304.348, # untaxed amount 'account_id': self.company_data['default_account_expense'].id, 'product_id': self.product_b.id, 'currency_id': self.currency_data['currency'].id, 'tax_line_id': False, 'analytic_account_id': self.analytic_account_2.id, }, # Product line (company currency): { 'debit': 869.57, 'credit': 0.0, 'amount_currency': 869.57, 'account_id': self.company_data['default_account_expense'].id, 'product_id': self.product_a.id, 'currency_id': self.company_data['currency'].id, 'tax_line_id': False, 'analytic_account_id': self.analytic_account_1.id, }, ]) # Check expense analytic lines. self.assertRecordValues(expense_sheet.account_move_id.line_ids.analytic_line_ids.sorted('amount'), [ { 'amount': -869.57, 'date': fields.Date.from_string('2017-01-01'), 'account_id': self.analytic_account_1.id, 'currency_id': self.company_data['currency'].id, }, { 'amount': -434.78, 'date': fields.Date.from_string('2017-01-01'), 'account_id': self.analytic_account_2.id, 'currency_id': self.company_data['currency'].id, }, ]) def test_account_entry_multi_currency(self): """ Checking accounting move entries and analytic entries when submitting expense. With multi-currency. And taxes. """ # Clean-up the rates self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", [self.env.ref('base.USD').id, self.env.company.id]) self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'currency_id': self.env.ref('base.EUR').id, 'company_id': self.env.company.id, 'rate': 2.0, 'name': '2010-01-01', }) expense = self.env['hr.expense.sheet'].create({ 'name': 'Expense for Dick Tracy', 'employee_id': self.expense_employee.id, }) tax = self.env['account.tax'].create({ 'name': 'Expense 10%', 'amount': 10, 'amount_type': 'percent', 'type_tax_use': 'purchase', 'price_include': True, }) self.env['hr.expense'].create({ 'name': 'Choucroute Saucisse', 'employee_id': self.expense_employee.id, 'product_id': self.product_a.id, 'unit_amount': 700.00, 'tax_ids': [(6, 0, tax.ids)], 'sheet_id': expense.id, 'analytic_account_id': self.analytic_account_1.id, 'currency_id': self.env.ref('base.EUR').id, }) # State should default to draft self.assertEqual(expense.state, 'draft', 'Expense should be created in Draft state') # Submitted to Manager expense.action_submit_sheet() self.assertEqual(expense.state, 'submit', 'Expense is not in Reported state') # Approve expense.approve_expense_sheets() self.assertEqual(expense.state, 'approve', 'Expense is not in Approved state') # Create Expense Entries expense.action_sheet_move_create() self.assertEqual(expense.state, 'post', 'Expense is not in Waiting Payment state') self.assertTrue(expense.account_move_id.id, 'Expense Journal Entry is not created') # Should get this result [(0.0, 350.0, -700.0), (318.18, 0.0, 636.36), (31.82, 0.0, 63.64)] for line in expense.account_move_id.line_ids: if line.credit: self.assertAlmostEqual(line.credit, 350.0) self.assertAlmostEqual(line.amount_currency, -700.0) self.assertEqual(len(line.analytic_line_ids), 0, "The credit move line should not have analytic lines") self.assertFalse(line.product_id, "Product of credit move line should be false") else: if not line.tax_line_id == tax: self.assertAlmostEqual(line.debit, 318.18) self.assertAlmostEqual(line.amount_currency, 636.36) self.assertEqual(len(line.analytic_line_ids), 1, "The debit move line should have 1 analytic lines") self.assertEqual(line.product_id, self.product_a, "Product of debit move line should be the one from the expense") else: self.assertEqual(line.tax_base_amount, 318.18) self.assertAlmostEqual(line.debit, 31.82) self.assertAlmostEqual(line.amount_currency, 63.64) self.assertEqual(len(line.analytic_line_ids), 0, "The tax move line should not have analytic lines") self.assertFalse(line.product_id, "Product of tax move line should be false") def test_expenses_with_tax_and_lockdate(self): ''' Test creating a journal entry for multiple expenses using taxes. A lock date is set in order to trigger the recomputation of the taxes base amount. ''' self.env.company.tax_lock_date = '2020-02-01' expense = self.env['hr.expense.sheet'].create({ 'name': 'Expense for John Smith', 'employee_id': self.expense_employee.id, 'accounting_date': '2020-01-01' }) for i in range(2): expense_line = self.env['hr.expense'].create({ 'name': 'Car Travel Expenses', 'employee_id': self.expense_employee.id, 'product_id': self.product_a.id, 'unit_amount': 350.00, 'tax_ids': [(6, 0, [self.tax_purchase_a.id])], 'sheet_id': expense.id, 'analytic_account_id': self.analytic_account_1.id, }) expense_line._onchange_product_id_date_account_id() expense.action_submit_sheet() expense.approve_expense_sheets() # Assert not "Cannot create unbalanced journal entry" error. expense.action_sheet_move_create() def test_reconcile_payment(self): tax = self.env['account.tax'].create({ 'name': 'tax abc', 'type_tax_use': 'purchase', 'amount_type': 'percent', 'amount': 15, 'price_include': False, 'include_base_amount': False, 'tax_exigibility': 'on_payment' }) current_assets_type = self.env.ref('account.data_account_type_current_assets') company = self.env.company.id tax.cash_basis_transition_account_id = self.env['account.account'].create({ 'name': "test", 'code': 999991, 'reconcile': True, 'user_type_id': current_assets_type.id, 'company_id': company, }).id sheet = self.env['hr.expense.sheet'].create({ 'company_id': company, 'employee_id': self.expense_employee.id, 'name': 'test sheet', 'expense_line_ids': [ (0, 0, { 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 10.0, 'employee_id': self.expense_employee.id, 'tax_ids': tax }), (0, 0, { 'name': 'expense_2', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1.0, 'employee_id': self.expense_employee.id, 'tax_ids': tax }), ], }) #actions sheet.action_submit_sheet() sheet.approve_expense_sheets() sheet.action_sheet_move_create() action_data = sheet.action_register_payment() wizard = Form(self.env['account.payment.register'].with_context(action_data['context'])).save() action = wizard.action_create_payments() self.assertEqual(sheet.state, 'done', 'all account.move.line linked to expenses must be reconciled after payment') move = self.env['account.payment'].browse(action['res_id']).move_id move.button_cancel() self.assertEqual(sheet.state, 'cancel', 'Sheet state must be cancel when the payment linked to that sheet is canceled') def test_expense_amount_total_signed_compute(self): sheet = self.env['hr.expense.sheet'].create({ 'company_id': self.env.company.id, 'employee_id': self.expense_employee.id, 'name': 'test sheet', 'expense_line_ids': [ (0, 0, { 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 10.0, 'employee_id': self.expense_employee.id }), ], }) #actions sheet.action_submit_sheet() sheet.approve_expense_sheets() sheet.action_sheet_move_create() action_data = sheet.action_register_payment() wizard = Form(self.env['account.payment.register'].with_context(action_data['context'])).save() action = wizard.action_create_payments() move = self.env['account.payment'].browse(action['res_id']).move_id self.assertEqual(move.amount_total_signed, 10.0, 'The total amount of the payment move is not correct') def test_print_expense_check(self): """ Test the check content when printing a check that comes from an expense """ sheet = self.env['hr.expense.sheet'].create({ 'company_id': self.env.company.id, 'employee_id': self.expense_employee.id, 'name': 'test sheet', 'expense_line_ids': [ (0, 0, { 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 10.0, 'employee_id': self.expense_employee.id, }), (0, 0, { 'name': 'expense_2', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1.0, 'employee_id': self.expense_employee.id, }), ], }) #actions sheet.action_submit_sheet() sheet.approve_expense_sheets() sheet.action_sheet_move_create() action_data = sheet.action_register_payment() payment_method_line = self.env.company.bank_journal_ids.outbound_payment_method_line_ids.filtered(lambda m: m.code == 'check_printing') with Form(self.env[action_data['res_model']].with_context(action_data['context'])) as wiz_form: wiz_form.payment_method_line_id = payment_method_line wizard = wiz_form.save() action = wizard.action_create_payments() self.assertEqual(sheet.state, 'done', 'all account.move.line linked to expenses must be reconciled after payment') payment = self.env[action['res_model']].browse(action['res_id']) pages = payment._check_get_pages() stub_line = pages[0]['stub_lines'][:1] self.assertTrue(stub_line) move = self.env[action_data['context']['active_model']].browse(action_data['context']['active_ids']) self.assertDictEqual(stub_line[0], { 'due_date': '', 'number': ' - '.join([move.name, move.ref] if move.ref else [move.name]), 'amount_total': formatLang(self.env, 11.0, currency_obj=self.env.company.currency_id), 'amount_residual': '-', 'amount_paid': formatLang(self.env, 11.0, currency_obj=self.env.company.currency_id), 'currency': self.env.company.currency_id }) def test_reset_move_to_draft(self): """ Test the state of an expense and its report after resetting the paid move to draft """ expense_sheet = self.env['hr.expense.sheet'].create({ 'company_id': self.env.company.id, 'employee_id': self.expense_employee.id, 'name': 'test sheet', 'expense_line_ids': [ (0, 0, { 'name': 'expense_1', 'employee_id': self.expense_employee.id, 'product_id': self.product_a.id, 'unit_amount': 1000.00, }), ], }) expense = expense_sheet.expense_line_ids self.assertEqual(expense.state, 'draft', 'Expense state must be draft before sheet submission') self.assertEqual(expense_sheet.state, 'draft', 'Sheet state must be draft before submission') # Submit report expense_sheet.action_submit_sheet() self.assertEqual(expense.state, 'reported', 'Expense state must be reported after sheet submission') self.assertEqual(expense_sheet.state, 'submit', 'Sheet state must be submit after submission') # Approve report expense_sheet.approve_expense_sheets() self.assertEqual(expense.state, 'approved', 'Expense state must be draft after sheet approval') self.assertEqual(expense_sheet.state, 'approve', 'Sheet state must be draft after approval') # Create move expense_sheet.action_sheet_move_create() self.assertEqual(expense.state, 'approved', 'Expense state must be draft after posting move') self.assertEqual(expense_sheet.state, 'post', 'Sheet state must be draft after posting move') # Pay move move = expense_sheet.account_move_id self.env['account.payment.register'].with_context(active_model='account.move', active_ids=move.ids).create({ 'amount': 1000.0, })._create_payments() self.assertEqual(expense.state, 'done', 'Expense state must be done after payment') self.assertEqual(expense_sheet.state, 'done', 'Sheet state must be done after payment') # Reset move to draft move.button_draft() self.assertEqual(expense.state, 'approved', 'Expense state must be approved after resetting move to draft') self.assertEqual(expense_sheet.state, 'post', 'Sheet state must be done after resetting move to draft') # Post and pay move again move.action_post() self.env['account.payment.register'].with_context(active_model='account.move', active_ids=move.ids).create({ 'amount': 1000.0, })._create_payments() self.assertEqual(expense.state, 'done', 'Expense state must be done after payment') self.assertEqual(expense_sheet.state, 'done', 'Sheet state must be done after payment') def test_expense_from_attachments(self): # avoid passing through extraction when installed if 'hr.expense.extract.words' in self.env: self.env.company.expense_extract_show_ocr_option_selection = 'no_send' self.env.user.employee_id = self.expense_employee.id attachment = self.env['ir.attachment'].create({ 'datas': b"R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=", 'name': 'file.png', 'res_model': 'hr.expense', }) product = self.env['product.product'].search([('can_be_expensed', '=', True)]) # reproduce the same way we get the product by default if product: product = product.filtered(lambda p: p.default_code == "EXP_GEN") or product[0] product.property_account_expense_id = self.company_data['default_account_payable'] self.env['hr.expense'].create_expense_from_attachments(attachment.id) expense = self.env['hr.expense'].search([], order='id desc', limit=1) self.assertEqual(expense.account_id, product.property_account_expense_id, "The expense account should be the default one of the product")
44.984615
23,392
2,337
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.addons.mail.tests.common import mail_new_test_user class TestExpenseCommon(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) group_expense_manager = cls.env.ref('hr_expense.group_hr_expense_manager') cls.expense_user_employee = mail_new_test_user( cls.env, name='expense_user_employee', login='expense_user_employee', email='[email protected]', notification_type='email', groups='base.group_user', company_ids=[(6, 0, cls.env.companies.ids)], ) cls.expense_user_manager = mail_new_test_user( cls.env, name='Expense manager', login='expense_manager_1', email='[email protected]', notification_type='email', groups='base.group_user,hr_expense.group_hr_expense_manager', company_ids=[(6, 0, cls.env.companies.ids)], ) cls.expense_employee = cls.env['hr.employee'].create({ 'name': 'expense_employee', 'user_id': cls.expense_user_employee.id, 'address_home_id': cls.expense_user_employee.partner_id.id, 'address_id': cls.expense_user_employee.partner_id.id, }) # Allow the current accounting user to access the expenses. cls.env.user.groups_id |= group_expense_manager # Create analytic account cls.analytic_account_1 = cls.env['account.analytic.account'].create({ 'name': 'analytic_account_1', }) cls.analytic_account_2 = cls.env['account.analytic.account'].create({ 'name': 'analytic_account_2', }) # Ensure products can be expensed. (cls.product_a + cls.product_b).write({'can_be_expensed': True}) # Taxes on the products are included in price (cls.product_a.supplier_taxes_id + cls.product_b.supplier_taxes_id).write({'price_include': True}) cls.company_data['default_tax_purchase'].write({'price_include': True})
41
2,337
4,928
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.exceptions import AccessError, UserError from odoo.tests import tagged @tagged('-at_install', 'post_install') class TestExpensesAccessRights(TestExpenseCommon): def test_expense_access_rights(self): ''' The expense employee can't be able to create an expense for someone else.''' expense_employee_2 = self.env['hr.employee'].create({ 'name': 'expense_employee_2', 'user_id': self.env.user.id, 'address_home_id': self.env.user.partner_id.id, 'address_id': self.env.user.partner_id.id, }) with self.assertRaises(AccessError): self.env['hr.expense'].with_user(self.expense_user_employee).create({ 'name': "Superboy costume washing", 'employee_id': expense_employee_2.id, 'product_id': self.product_a.id, 'quantity': 1, 'unit_amount': 1, }) def test_expense_sheet_access_rights_approve(self): # The expense employee is able to a create an expense sheet. expense_sheet = self.env['hr.expense.sheet'].with_user(self.expense_user_employee).create({ 'name': 'First Expense for employee', 'employee_id': self.expense_employee.id, 'journal_id': self.company_data['default_journal_purchase'].id, 'accounting_date': '2017-01-01', 'expense_line_ids': [ (0, 0, { # Expense without foreign currency but analytic account. 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1000.0, 'employee_id': self.expense_employee.id, }), ], }) self.assertRecordValues(expense_sheet, [{'state': 'draft'}]) # The expense employee is able to submit the expense sheet. expense_sheet.with_user(self.expense_user_employee).action_submit_sheet() self.assertRecordValues(expense_sheet, [{'state': 'submit'}]) # The expense employee is not able to approve itself the expense sheet. with self.assertRaises(UserError): expense_sheet.with_user(self.expense_user_employee).approve_expense_sheets() self.assertRecordValues(expense_sheet, [{'state': 'submit'}]) # An expense manager is required for this step. expense_sheet.with_user(self.expense_user_manager).approve_expense_sheets() self.assertRecordValues(expense_sheet, [{'state': 'approve'}]) # An expense manager is not able to create the journal entry. with self.assertRaises(UserError): expense_sheet.with_user(self.expense_user_manager).action_sheet_move_create() self.assertRecordValues(expense_sheet, [{'state': 'approve'}]) # An expense manager having accounting access rights is able to create the journal entry. expense_sheet.with_user(self.env.user).action_sheet_move_create() self.assertRecordValues(expense_sheet, [{'state': 'post'}]) def test_expense_sheet_access_rights_refuse(self): # The expense employee is able to a create an expense sheet. expense_sheet = self.env['hr.expense.sheet'].with_user(self.expense_user_employee).create({ 'name': 'First Expense for employee', 'employee_id': self.expense_employee.id, 'journal_id': self.company_data['default_journal_purchase'].id, 'accounting_date': '2017-01-01', 'expense_line_ids': [ (0, 0, { # Expense without foreign currency but analytic account. 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1000.0, 'employee_id': self.expense_employee.id, }), ], }) self.assertRecordValues(expense_sheet, [{'state': 'draft'}]) # The expense employee is able to submit the expense sheet. expense_sheet.with_user(self.expense_user_employee).action_submit_sheet() self.assertRecordValues(expense_sheet, [{'state': 'submit'}]) # The expense employee is not able to refuse itself the expense sheet. with self.assertRaises(UserError): expense_sheet.with_user(self.expense_user_employee).refuse_sheet('') self.assertRecordValues(expense_sheet, [{'state': 'submit'}]) # An expense manager is required for this step. expense_sheet.with_user(self.expense_user_manager).refuse_sheet('') self.assertRecordValues(expense_sheet, [{'state': 'cancel'}])
42.852174
4,928
4,997
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr_expense.tests.common import TestExpenseCommon from odoo.tests import tagged from odoo.exceptions import UserError @tagged('post_install', '-at_install') class TestExpenseMultiCompany(TestExpenseCommon): def test_expense_sheet_multi_company_approve(self): self.expense_employee.company_id = self.company_data_2['company'] # The expense employee is able to a create an expense sheet for company_2. expense_sheet = self.env['hr.expense.sheet']\ .with_user(self.expense_user_employee)\ .with_context(allowed_company_ids=self.company_data_2['company'].ids)\ .create({ 'name': 'First Expense for employee', 'employee_id': self.expense_employee.id, 'journal_id': self.company_data_2['default_journal_purchase'].id, 'accounting_date': '2017-01-01', 'expense_line_ids': [ (0, 0, { # Expense without foreign currency but analytic account. 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1000.0, 'employee_id': self.expense_employee.id, }), ], }) self.assertRecordValues(expense_sheet, [{'company_id': self.company_data_2['company'].id}]) # The expense employee is able to submit the expense sheet. expense_sheet.with_user(self.expense_user_employee).action_submit_sheet() # An expense manager is not able to approve without access to company_2. with self.assertRaises(UserError): expense_sheet\ .with_user(self.expense_user_manager)\ .with_context(allowed_company_ids=self.company_data['company'].ids)\ .approve_expense_sheets() # An expense manager is able to approve with access to company_2. expense_sheet\ .with_user(self.expense_user_manager)\ .with_context(allowed_company_ids=self.company_data_2['company'].ids)\ .approve_expense_sheets() # An expense manager having accounting access rights is not able to create the journal entry without access # to company_2. with self.assertRaises(UserError): expense_sheet\ .with_user(self.env.user)\ .with_context(allowed_company_ids=self.company_data['company'].ids)\ .action_sheet_move_create() # An expense manager having accounting access rights is able to create the journal entry with access to # company_2. expense_sheet\ .with_user(self.env.user)\ .with_context(allowed_company_ids=self.company_data_2['company'].ids)\ .action_sheet_move_create() def test_expense_sheet_multi_company_refuse(self): self.expense_employee.company_id = self.company_data_2['company'] # The expense employee is able to a create an expense sheet for company_2. expense_sheet = self.env['hr.expense.sheet']\ .with_user(self.expense_user_employee)\ .with_context(allowed_company_ids=self.company_data_2['company'].ids)\ .create({ 'name': 'First Expense for employee', 'employee_id': self.expense_employee.id, 'journal_id': self.company_data_2['default_journal_purchase'].id, 'accounting_date': '2017-01-01', 'expense_line_ids': [ (0, 0, { # Expense without foreign currency but analytic account. 'name': 'expense_1', 'date': '2016-01-01', 'product_id': self.product_a.id, 'unit_amount': 1000.0, 'employee_id': self.expense_employee.id, }), ], }) self.assertRecordValues(expense_sheet, [{'company_id': self.company_data_2['company'].id}]) # The expense employee is able to submit the expense sheet. expense_sheet.with_user(self.expense_user_employee).action_submit_sheet() # An expense manager is not able to approve without access to company_2. with self.assertRaises(UserError): expense_sheet\ .with_user(self.expense_user_manager)\ .with_context(allowed_company_ids=self.company_data['company'].ids)\ .refuse_sheet('') # An expense manager is able to approve with access to company_2. expense_sheet\ .with_user(self.expense_user_manager)\ .with_context(allowed_company_ids=self.company_data_2['company'].ids)\ .refuse_sheet('')
43.077586
4,997
1,651
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 HrExpenseRefuseWizard(models.TransientModel): """This wizard can be launched from an he.expense (an expense line) or from an hr.expense.sheet (En expense report) 'hr_expense_refuse_model' must be passed in the context to differentiate the right model to use. """ _name = "hr.expense.refuse.wizard" _description = "Expense Refuse Reason Wizard" reason = fields.Char(string='Reason', required=True) hr_expense_ids = fields.Many2many('hr.expense') hr_expense_sheet_id = fields.Many2one('hr.expense.sheet') @api.model def default_get(self, fields): res = super(HrExpenseRefuseWizard, self).default_get(fields) active_ids = self.env.context.get('active_ids', []) refuse_model = self.env.context.get('hr_expense_refuse_model') if refuse_model == 'hr.expense': res.update({ 'hr_expense_ids': active_ids, 'hr_expense_sheet_id': False, }) elif refuse_model == 'hr.expense.sheet': res.update({ 'hr_expense_sheet_id': active_ids[0] if active_ids else False, 'hr_expense_ids': [], }) return res def expense_refuse_reason(self): self.ensure_one() if self.hr_expense_ids: self.hr_expense_ids.refuse_expense(self.reason) if self.hr_expense_sheet_id: self.hr_expense_sheet_id.refuse_sheet(self.reason) return {'type': 'ir.actions.act_window_close'}
36.688889
1,651
1,107
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 HrExpenseApproveDuplicate(models.TransientModel): """ This wizard is shown whenever an approved expense is similar to one being approved. The user has the opportunity to still validate it or decline. """ _name = "hr.expense.approve.duplicate" _description = "Expense Approve Duplicate" sheet_ids = fields.Many2many('hr.expense.sheet') expense_ids = fields.Many2many('hr.expense', readonly=True) @api.model def default_get(self, fields): res = super().default_get(fields) if 'sheet_ids' in fields: res['sheet_ids'] = [(6, 0, self.env.context.get('default_sheet_ids', []))] if 'duplicate_expense_ids' in fields: res['expense_ids'] = [(6, 0, self.env.context.get('default_expense_ids', []))] return res def action_approve(self): self.sheet_ids._do_approve() def action_refuse(self): self.sheet_ids.refuse_sheet(_('Duplicate Expense'))
32.558824
1,107
1,963
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ class AccountPaymentRegister(models.TransientModel): _inherit = 'account.payment.register' # ------------------------------------------------------------------------- # BUSINESS METHODS # ------------------------------------------------------------------------- @api.model def _get_line_batch_key(self, line): # OVERRIDE to set the bank account defined on the employee res = super()._get_line_batch_key(line) expense_sheet = self.env['hr.expense.sheet'].search([('payment_mode', '=', 'own_account'), ('account_move_id', 'in', line.move_id.ids)]) if expense_sheet and not line.move_id.partner_bank_id: res['partner_bank_id'] = expense_sheet.employee_id.sudo().bank_account_id.id or line.partner_id.bank_ids and line.partner_id.bank_ids.ids[0] return res def _init_payments(self, to_process, edit_mode=False): # OVERRIDE payments = super()._init_payments(to_process, edit_mode=edit_mode) for payment, vals in zip(payments, to_process): expenses = vals['batch']['lines'].expense_id if expenses: payment.line_ids.write({'expense_id': expenses[0].id}) receivable_lines = payment.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) receivable_lines.write({'exclude_from_invoice_tab': True}) return payments def _reconcile_payments(self, to_process, edit_mode=False): # OVERRIDE res = super()._reconcile_payments(to_process, edit_mode=edit_mode) for vals in to_process: expense_sheets = vals['batch']['lines'].expense_id.sheet_id for expense_sheet in expense_sheets: if expense_sheet.currency_id.is_zero(expense_sheet.amount_residual): expense_sheet.state = 'done' return res
47.878049
1,963
597
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ class AccountMove(models.Model): _inherit = "account.move" def button_cancel(self): for l in self.line_ids: if l.expense_id: l.expense_id.refuse_expense(reason=_("Payment Cancelled")) return super().button_cancel() def button_draft(self): for line in self.line_ids: if line.expense_id: line.expense_id.sheet_id.write({'state': 'post'}) return super().button_draft()
29.85
597
64,206
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from markupsafe import Markup from odoo import api, fields, Command, models, _ from odoo.exceptions import UserError, ValidationError from odoo.tools import email_split, float_is_zero, float_repr from odoo.tools.misc import clean_context, format_date from odoo.addons.account.models.account_move import PAYMENT_STATE_SELECTION class HrExpense(models.Model): _name = "hr.expense" _inherit = ['mail.thread', 'mail.activity.mixin'] _description = "Expense" _order = "date desc, id desc" _check_company_auto = True @api.model def _default_employee_id(self): employee = self.env.user.employee_id if not employee and not self.env.user.has_group('hr_expense.group_hr_expense_team_approver'): raise ValidationError(_('The current user has no related employee. Please, create one.')) return employee @api.model def _default_product_uom_id(self): return self.env['uom.uom'].search([], limit=1, order='id') @api.model def _default_account_id(self): return self.env['ir.property']._get('property_account_expense_categ_id', 'product.category') @api.model def _get_employee_id_domain(self): res = [('id', '=', 0)] # Nothing accepted by domain, by default if self.user_has_groups('hr_expense.group_hr_expense_user') or self.user_has_groups('account.group_account_user'): res = "['|', ('company_id', '=', False), ('company_id', '=', company_id)]" # Then, domain accepts everything elif self.user_has_groups('hr_expense.group_hr_expense_team_approver') and self.env.user.employee_ids: user = self.env.user employee = self.env.user.employee_id res = [ '|', '|', '|', ('department_id.manager_id', '=', employee.id), ('parent_id', '=', employee.id), ('id', '=', employee.id), ('expense_manager_id', '=', user.id), '|', ('company_id', '=', False), ('company_id', '=', employee.company_id.id), ] elif self.env.user.employee_id: employee = self.env.user.employee_id res = [('id', '=', employee.id), '|', ('company_id', '=', False), ('company_id', '=', employee.company_id.id)] return res name = fields.Char('Description', compute='_compute_from_product_id_company_id', store=True, required=True, copy=True, states={'draft': [('readonly', False)], 'reported': [('readonly', False)], 'approved': [('readonly', False)], 'refused': [('readonly', False)]}) date = fields.Date(readonly=True, states={'draft': [('readonly', False)], 'reported': [('readonly', False)], 'approved': [('readonly', False)], 'refused': [('readonly', False)]}, default=fields.Date.context_today, string="Expense Date") accounting_date = fields.Date(string="Accounting Date", related='sheet_id.accounting_date', store=True, groups='account.group_account_invoice,account.group_account_readonly') employee_id = fields.Many2one('hr.employee', compute='_compute_employee_id', string="Employee", store=True, required=True, readonly=False, tracking=True, states={'approved': [('readonly', True)], 'done': [('readonly', True)]}, default=_default_employee_id, domain=lambda self: self._get_employee_id_domain(), check_company=True) # product_id not required to allow create an expense without product via mail alias, but should be required on the view. product_id = fields.Many2one('product.product', string='Product', readonly=True, tracking=True, states={'draft': [('readonly', False)], 'reported': [('readonly', False)], 'approved': [('readonly', False)], 'refused': [('readonly', False)]}, domain="[('can_be_expensed', '=', True), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", ondelete='restrict') product_uom_id = fields.Many2one('uom.uom', string='Unit of Measure', compute='_compute_from_product_id_company_id', store=True, copy=True, readonly=True, default=_default_product_uom_id, domain="[('category_id', '=', product_uom_category_id)]") product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id', readonly=True, string="UoM Category") unit_amount = fields.Float("Unit Price", compute='_compute_from_product_id_company_id', store=True, required=True, copy=True, states={'draft': [('readonly', False)], 'reported': [('readonly', False)], 'approved': [('readonly', False)], 'refused': [('readonly', False)]}, digits='Product Price') quantity = fields.Float(required=True, readonly=True, states={'draft': [('readonly', False)], 'reported': [('readonly', False)], 'approved': [('readonly', False)], 'refused': [('readonly', False)]}, digits='Product Unit of Measure', default=1) tax_ids = fields.Many2many('account.tax', 'expense_tax', 'expense_id', 'tax_id', compute='_compute_from_product_id_company_id', store=True, readonly=False, domain="[('company_id', '=', company_id), ('type_tax_use', '=', 'purchase'), ('price_include', '=', True)]", string='Taxes', help="The taxes should be \"Included In Price\"") # TODO SGV can be removed untaxed_amount = fields.Float("Subtotal", store=True, compute='_compute_amount_tax', digits='Account', copy=True) amount_residual = fields.Monetary(string='Amount Due', compute='_compute_amount_residual') total_amount = fields.Monetary("Total In Currency", compute='_compute_amount', store=True, currency_field='currency_id', tracking=True, readonly=False) company_currency_id = fields.Many2one('res.currency', string="Report Company Currency", related='company_id.currency_id', readonly=True) total_amount_company = fields.Monetary("Total", compute='_compute_total_amount_company', store=True, currency_field='company_currency_id') company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.company) currency_id = fields.Many2one('res.currency', string='Currency', required=True, readonly=False, store=True, states={'reported': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)]}, compute='_compute_currency_id', default=lambda self: self.env.company.currency_id) analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', check_company=True) analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags', states={'post': [('readonly', True)], 'done': [('readonly', True)]}, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") account_id = fields.Many2one('account.account', compute='_compute_from_product_id_company_id', store=True, readonly=False, string='Account', default=_default_account_id, domain="[('internal_type', '=', 'other'), ('company_id', '=', company_id)]", help="An expense account is expected") description = fields.Text('Notes...', readonly=True, states={'draft': [('readonly', False)], 'reported': [('readonly', False)], 'refused': [('readonly', False)]}) payment_mode = fields.Selection([ ("own_account", "Employee (to reimburse)"), ("company_account", "Company") ], default='own_account', tracking=True, states={'done': [('readonly', True)], 'approved': [('readonly', True)], 'reported': [('readonly', True)]}, string="Paid By") attachment_number = fields.Integer('Number of Attachments', compute='_compute_attachment_number') state = fields.Selection([ ('draft', 'To Submit'), ('reported', 'Submitted'), ('approved', 'Approved'), ('done', 'Paid'), ('refused', 'Refused') ], compute='_compute_state', string='Status', copy=False, index=True, readonly=True, store=True, default='draft', help="Status of the expense.") sheet_id = fields.Many2one('hr.expense.sheet', string="Expense Report", domain="[('employee_id', '=', employee_id), ('company_id', '=', company_id)]", readonly=True, copy=False) sheet_is_editable = fields.Boolean(compute='_compute_sheet_is_editable') approved_by = fields.Many2one('res.users', string='Approved By', related='sheet_id.user_id') approved_on = fields.Datetime(string='Approved On', related='sheet_id.approval_date') reference = fields.Char("Bill Reference") is_refused = fields.Boolean("Explicitly Refused by manager or accountant", readonly=True, copy=False) is_editable = fields.Boolean("Is Editable By Current User", compute='_compute_is_editable') is_ref_editable = fields.Boolean("Reference Is Editable By Current User", compute='_compute_is_ref_editable') product_has_cost = fields.Boolean("Is product with non zero cost selected", compute='_compute_product_has_cost') same_currency = fields.Boolean("Is currency_id different from the company_currency_id", compute='_compute_same_currency') duplicate_expense_ids = fields.Many2many('hr.expense', compute='_compute_duplicate_expense_ids') sample = fields.Boolean() label_total_amount_company = fields.Char(compute='_compute_label_total_amount_company') label_convert_rate = fields.Char(compute='_compute_label_convert_rate') @api.depends("product_has_cost") def _compute_currency_id(self): for expense in self.filtered("product_has_cost"): expense.currency_id = expense.company_currency_id @api.depends_context('lang') @api.depends("company_currency_id") def _compute_label_total_amount_company(self): for expense in self: expense.label_total_amount_company = _("Total %s", expense.company_currency_id.name) if expense.company_currency_id else _("Total") @api.depends('currency_id', 'company_currency_id') def _compute_same_currency(self): for expense in self: expense.same_currency = bool(not expense.company_id or (expense.currency_id and expense.currency_id == expense.company_currency_id)) @api.depends('product_id') def _compute_product_has_cost(self): for expense in self: expense.product_has_cost = bool(expense.product_id and expense.unit_amount) @api.depends('sheet_id', 'sheet_id.account_move_id', 'sheet_id.state') def _compute_state(self): for expense in self: if not expense.sheet_id or expense.sheet_id.state == 'draft': expense.state = "draft" elif expense.sheet_id.state == "cancel": expense.state = "refused" elif expense.sheet_id.state == "approve" or expense.sheet_id.state == "post": expense.state = "approved" elif not expense.sheet_id.account_move_id: expense.state = "reported" else: expense.state = "done" @api.depends('quantity', 'unit_amount', 'tax_ids', 'currency_id') def _compute_amount(self): for expense in self: if expense.unit_amount: taxes = expense.tax_ids.compute_all(expense.unit_amount, expense.currency_id, expense.quantity, expense.product_id, expense.employee_id.user_id.partner_id) expense.total_amount = taxes.get('total_included') @api.depends('total_amount', 'tax_ids', 'currency_id') def _compute_amount_tax(self): for expense in self: # the taxes should be "Included In Price", as the entered # total_amount includes all the taxes already # for the cases with total price, the quantity is always 1 amount = expense.total_amount quantity = 1 taxes = expense.tax_ids.compute_all(amount, expense.currency_id, quantity, expense.product_id, expense.employee_id.user_id.partner_id) expense.untaxed_amount = taxes.get('total_excluded') @api.depends("sheet_id.account_move_id.line_ids") def _compute_amount_residual(self): for expense in self: if not expense.sheet_id: expense.amount_residual = expense.total_amount continue if not expense.currency_id or expense.currency_id == expense.company_id.currency_id: residual_field = 'amount_residual' else: residual_field = 'amount_residual_currency' payment_term_lines = expense.sheet_id.account_move_id.sudo().line_ids \ .filtered(lambda line: line.expense_id == expense and line.account_internal_type in ('receivable', 'payable')) expense.amount_residual = -sum(payment_term_lines.mapped(residual_field)) @api.depends('date', 'total_amount', 'currency_id', 'company_currency_id') def _compute_total_amount_company(self): for expense in self: amount = 0 if expense.same_currency: amount = expense.total_amount else: date_expense = expense.date or fields.Date.today() amount = expense.currency_id._convert( expense.total_amount, expense.company_currency_id, expense.company_id, date_expense) expense.total_amount_company = amount @api.depends('date', 'total_amount', 'currency_id', 'company_currency_id') def _compute_label_convert_rate(self): records_with_diff_currency = self.filtered(lambda x: not x.same_currency and x.currency_id) (self - records_with_diff_currency).label_convert_rate = False for expense in records_with_diff_currency: date_expense = expense.date or fields.Date.today() rate = expense.currency_id._get_conversion_rate( expense.currency_id, expense.company_currency_id, expense.company_id, date_expense) rate_txt = _('1 %(exp_cur)s = %(rate)s %(comp_cur)s', exp_cur=expense.currency_id.name, rate=float_repr(rate, 6), comp_cur=expense.company_currency_id.name) expense.label_convert_rate = rate_txt def _compute_attachment_number(self): attachment_data = self.env['ir.attachment'].read_group([('res_model', '=', 'hr.expense'), ('res_id', 'in', self.ids)], ['res_id'], ['res_id']) attachment = dict((data['res_id'], data['res_id_count']) for data in attachment_data) for expense in self: expense.attachment_number = attachment.get(expense._origin.id, 0) @api.depends('employee_id') def _compute_is_editable(self): is_account_manager = self.env.user.has_group('account.group_account_user') or self.env.user.has_group('account.group_account_manager') for expense in self: if expense.state == 'draft' or expense.sheet_id.state in ['draft', 'submit']: expense.is_editable = True elif expense.sheet_id.state == 'approve': expense.is_editable = is_account_manager else: expense.is_editable = False @api.depends('sheet_id.is_editable', 'sheet_id') def _compute_sheet_is_editable(self): for expense in self: expense.sheet_is_editable = not expense.sheet_id or expense.sheet_id.is_editable @api.depends('employee_id') def _compute_is_ref_editable(self): is_account_manager = self.env.user.has_group('account.group_account_user') or self.env.user.has_group('account.group_account_manager') for expense in self: if expense.state == 'draft' or expense.sheet_id.state in ['draft', 'submit']: expense.is_ref_editable = True else: expense.is_ref_editable = is_account_manager @api.depends('product_id', 'company_id') def _compute_from_product_id_company_id(self): for expense in self.filtered('product_id'): expense = expense.with_company(expense.company_id) expense.name = expense.name or expense.product_id.display_name if not expense.attachment_number or (expense.attachment_number and not expense.unit_amount) or (expense.attachment_number and expense.unit_amount and not expense.product_id.standard_price): expense.unit_amount = expense.product_id.price_compute('standard_price')[expense.product_id.id] expense.product_uom_id = expense.product_id.uom_id expense.tax_ids = expense.product_id.supplier_taxes_id.filtered(lambda tax: tax.price_include and tax.company_id == expense.company_id) # taxes only from the same company account = expense.product_id.product_tmpl_id._get_product_accounts()['expense'] if account: expense.account_id = account @api.depends('company_id') def _compute_employee_id(self): if not self.env.context.get('default_employee_id'): for expense in self: expense.employee_id = self.env.user.with_company(expense.company_id).employee_id @api.depends('employee_id', 'product_id', 'total_amount') def _compute_duplicate_expense_ids(self): self.duplicate_expense_ids = [(5, 0, 0)] expenses = self.filtered(lambda e: e.employee_id and e.product_id and e.total_amount) if expenses.ids: duplicates_query = """ SELECT ARRAY_AGG(DISTINCT he.id) FROM hr_expense AS he JOIN hr_expense AS ex ON he.employee_id = ex.employee_id AND he.product_id = ex.product_id AND he.date = ex.date AND he.total_amount = ex.total_amount AND he.company_id = ex.company_id AND he.currency_id = ex.currency_id WHERE ex.id in %(expense_ids)s GROUP BY he.employee_id, he.product_id, he.date, he.total_amount, he.company_id, he.currency_id HAVING COUNT(he.id) > 1 """ self.env.cr.execute(duplicates_query, { 'expense_ids': tuple(expenses.ids), }) duplicates = [x[0] for x in self.env.cr.fetchall()] for ids in duplicates: exp = expenses.filtered(lambda e: e.id in ids) exp.duplicate_expense_ids = [(6, 0, ids)] expenses = expenses - exp @api.onchange('product_id', 'date', 'account_id') def _onchange_product_id_date_account_id(self): rec = self.env['account.analytic.default'].sudo().account_get( product_id=self.product_id.id, account_id=self.account_id.id, company_id=self.company_id.id, date=self.date ) self.analytic_account_id = self.analytic_account_id or rec.analytic_id.id self.analytic_tag_ids = self.analytic_tag_ids or rec.analytic_tag_ids.ids @api.constrains('payment_mode') def _check_payment_mode(self): self.sheet_id._check_payment_mode() @api.constrains('product_id', 'product_uom_id') def _check_product_uom_category(self): for expense in self: if expense.product_id and expense.product_uom_id.category_id != expense.product_id.uom_id.category_id: raise UserError(_( 'Selected Unit of Measure for expense %(expense)s does not belong to the same category as the Unit of Measure of product %(product)s.', expense=expense.name, product=expense.product_id.name, )) def create_expense_from_attachments(self, attachment_ids=None, view_type='tree'): ''' Create the expenses from files. :return: An action redirecting to hr.expense tree view. ''' if attachment_ids is None: attachment_ids = [] attachments = self.env['ir.attachment'].browse(attachment_ids) if not attachments: raise UserError(_("No attachment was provided")) expenses = self.env['hr.expense'] if any(attachment.res_id or attachment.res_model != 'hr.expense' for attachment in attachments): raise UserError(_("Invalid attachments!")) product = self.env['product.product'].search([('can_be_expensed', '=', True)]) if product: product = product.filtered(lambda p: p.default_code == "EXP_GEN") or product[0] else: raise UserError(_("You need to have at least one category that can be expensed in your database to proceed!")) for attachment in attachments: vals = { 'name': attachment.name.split('.')[0], 'unit_amount': 0, 'product_id': product.id, } if product.property_account_expense_id: vals['account_id'] = product.property_account_expense_id.id expense = self.env['hr.expense'].create(vals) attachment.write({ 'res_model': 'hr.expense', 'res_id': expense.id, }) attachment.register_as_main_attachment() expenses += expense return { 'name': _('Generated Expenses'), 'res_model': 'hr.expense', 'type': 'ir.actions.act_window', 'views': [[False, view_type], [False, "form"]], 'context': {'search_default_my_expenses': 1, 'search_default_no_report': 1}, } def attach_document(self, **kwargs): pass # ---------------------------------------- # ORM Overrides # ---------------------------------------- @api.ondelete(at_uninstall=False) def _unlink_except_posted_or_approved(self): for expense in self: if expense.state in ['done', 'approved']: raise UserError(_('You cannot delete a posted or approved expense.')) def write(self, vals): if 'sheet_id' in vals: self.env['hr.expense.sheet'].browse(vals['sheet_id']).check_access_rule('write') if 'tax_ids' in vals or 'analytic_account_id' in vals or 'account_id' in vals: if any(not expense.is_editable for expense in self): raise UserError(_('You are not authorized to edit this expense report.')) if 'reference' in vals: if any(not expense.is_ref_editable for expense in self): raise UserError(_('You are not authorized to edit the reference of this expense report.')) return super(HrExpense, self).write(vals) @api.model def get_empty_list_help(self, help_message): return super(HrExpense, self).get_empty_list_help(help_message or '' + self._get_empty_list_mail_alias()) @api.model def _get_empty_list_mail_alias(self): use_mailgateway = self.env['ir.config_parameter'].sudo().get_param('hr_expense.use_mailgateway') alias_record = use_mailgateway and self.env.ref('hr_expense.mail_alias_expense') or False if alias_record and alias_record.alias_domain and alias_record.alias_name: return Markup(""" <p> Or send your receipts at <a href="mailto:%(email)s?subject=Lunch%%20with%%20customer%%3A%%20%%2412.32">%(email)s</a>. </p>""") % {'email': '%s@%s' % (alias_record.alias_name, alias_record.alias_domain)} return "" # ---------------------------------------- # Actions # ---------------------------------------- def action_view_sheet(self): self.ensure_one() return { 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'hr.expense.sheet', 'target': 'current', 'res_id': self.sheet_id.id } def _get_default_expense_sheet_values(self): if any(expense.state != 'draft' or expense.sheet_id for expense in self): raise UserError(_("You cannot report twice the same line!")) if len(self.mapped('employee_id')) != 1: raise UserError(_("You cannot report expenses for different employees in the same report.")) if any(not expense.product_id for expense in self): raise UserError(_("You can not create report without category.")) todo = self.filtered(lambda x: x.payment_mode=='own_account') or self.filtered(lambda x: x.payment_mode=='company_account') if len(todo) == 1: expense_name = todo.name else: dates = todo.mapped('date') min_date = format_date(self.env, min(dates)) max_date = format_date(self.env, max(dates)) expense_name = min_date if max_date == min_date else "%s - %s" % (min_date, max_date) values = { 'default_company_id': self.company_id.id, 'default_employee_id': self[0].employee_id.id, 'default_name': expense_name, 'default_expense_line_ids': [Command.set(todo.ids)], 'default_state': 'draft', 'create': False } return values def action_submit_expenses(self): context_vals = self._get_default_expense_sheet_values() return { 'name': _('New Expense Report'), 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'hr.expense.sheet', 'target': 'current', 'context': context_vals, } def action_get_attachment_view(self): self.ensure_one() res = self.env['ir.actions.act_window']._for_xml_id('base.action_attachment') res['domain'] = [('res_model', '=', 'hr.expense'), ('res_id', 'in', self.ids)] res['context'] = {'default_res_model': 'hr.expense', 'default_res_id': self.id} return res def action_approve_duplicates(self): root = self.env['ir.model.data']._xmlid_to_res_id("base.partner_root") for expense in self.duplicate_expense_ids: expense.message_post( body=_('%(user)s confirms this expense is not a duplicate with similar expense.', user=self.env.user.name), author_id=root ) # ---------------------------------------- # Business # ---------------------------------------- def _prepare_move_values(self): """ This function prepares move values related to an expense """ self.ensure_one() journal = self.sheet_id.bank_journal_id if self.payment_mode == 'company_account' else self.sheet_id.journal_id account_date = self.sheet_id.accounting_date or self.date move_values = { 'journal_id': journal.id, 'company_id': self.sheet_id.company_id.id, 'date': account_date, 'ref': self.sheet_id.name, # force the name to the default value, to avoid an eventual 'default_name' in the context # to set it to '' which cause no number to be given to the account.move when posted. 'name': '/', } return move_values def _get_account_move_by_sheet(self): """ Return a mapping between the expense sheet of current expense and its account move :returns dict where key is a sheet id, and value is an account move record """ move_grouped_by_sheet = {} for expense in self: # create the move that will contain the accounting entries if expense.sheet_id.id not in move_grouped_by_sheet: move_vals = expense._prepare_move_values() move = self.env['account.move'].with_context(default_journal_id=move_vals['journal_id']).create(move_vals) move_grouped_by_sheet[expense.sheet_id.id] = move else: move = move_grouped_by_sheet[expense.sheet_id.id] return move_grouped_by_sheet def _get_expense_account_source(self): self.ensure_one() if self.account_id: account = self.account_id elif self.product_id: account = self.product_id.product_tmpl_id.with_company(self.company_id)._get_product_accounts()['expense'] if not account: raise UserError( _("No Expense account found for the product %s (or for its category), please configure one.") % (self.product_id.name)) else: account = self.env['ir.property'].with_company(self.company_id)._get('property_account_expense_categ_id', 'product.category') if not account: raise UserError(_('Please configure Default Expense account for Category expense: `property_account_expense_categ_id`.')) return account def _get_expense_account_destination(self): self.ensure_one() account_dest = self.env['account.account'] if self.payment_mode == 'company_account': journal = self.sheet_id.bank_journal_id account_dest = ( journal.outbound_payment_method_line_ids[0].payment_account_id or journal.company_id.account_journal_payment_credit_account_id ) else: if not self.employee_id.sudo().address_home_id: raise UserError(_("No Home Address found for the employee %s, please configure one.") % (self.employee_id.name)) partner = self.employee_id.sudo().address_home_id.with_company(self.company_id) account_dest = partner.property_account_payable_id or partner.parent_id.property_account_payable_id return account_dest.id def _get_account_move_line_values(self): move_line_values_by_expense = {} for expense in self: move_line_name = expense.employee_id.name + ': ' + expense.name.split('\n')[0][:64] account_src = expense._get_expense_account_source() account_dst = expense._get_expense_account_destination() account_date = expense.date or expense.sheet_id.accounting_date or fields.Date.context_today(expense) company_currency = expense.company_id.currency_id move_line_values = [] unit_amount = expense.unit_amount or expense.total_amount quantity = expense.quantity if expense.unit_amount else 1 taxes = expense.tax_ids.with_context(round=True).compute_all(unit_amount, expense.currency_id,quantity,expense.product_id) total_amount = 0.0 total_amount_currency = 0.0 partner_id = expense.employee_id.sudo().address_home_id.commercial_partner_id.id # source move line balance = expense.currency_id._convert(taxes['total_excluded'], company_currency, expense.company_id, account_date) amount_currency = taxes['total_excluded'] move_line_src = { 'name': move_line_name, 'quantity': expense.quantity or 1, 'debit': balance if balance > 0 else 0, 'credit': -balance if balance < 0 else 0, 'amount_currency': amount_currency, 'account_id': account_src.id, 'product_id': expense.product_id.id, 'product_uom_id': expense.product_uom_id.id, 'analytic_account_id': expense.analytic_account_id.id, 'analytic_tag_ids': [(6, 0, expense.analytic_tag_ids.ids)], 'expense_id': expense.id, 'partner_id': partner_id, 'tax_ids': [(6, 0, expense.tax_ids.ids)], 'tax_tag_ids': [(6, 0, taxes['base_tags'])], 'currency_id': expense.currency_id.id, } move_line_values.append(move_line_src) total_amount -= balance total_amount_currency -= move_line_src['amount_currency'] # taxes move lines for tax in taxes['taxes']: balance = expense.currency_id._convert(tax['amount'], company_currency, expense.company_id, account_date) amount_currency = tax['amount'] if tax['tax_repartition_line_id']: rep_ln = self.env['account.tax.repartition.line'].browse(tax['tax_repartition_line_id']) base_amount = self.env['account.move']._get_base_amount_to_display(tax['base'], rep_ln) base_amount = expense.currency_id._convert(base_amount, company_currency, expense.company_id, account_date) else: base_amount = None move_line_tax_values = { 'name': tax['name'], 'quantity': 1, 'debit': balance if balance > 0 else 0, 'credit': -balance if balance < 0 else 0, 'amount_currency': amount_currency, 'account_id': tax['account_id'] or move_line_src['account_id'], 'tax_repartition_line_id': tax['tax_repartition_line_id'], 'tax_tag_ids': tax['tag_ids'], 'tax_base_amount': base_amount, 'expense_id': expense.id, 'partner_id': partner_id, 'currency_id': expense.currency_id.id, 'analytic_account_id': expense.analytic_account_id.id if tax['analytic'] else False, 'analytic_tag_ids': [(6, 0, expense.analytic_tag_ids.ids)] if tax['analytic'] else False, } total_amount -= balance total_amount_currency -= move_line_tax_values['amount_currency'] move_line_values.append(move_line_tax_values) # destination move line move_line_dst = { 'name': move_line_name, 'debit': total_amount > 0 and total_amount, 'credit': total_amount < 0 and -total_amount, 'account_id': account_dst, 'date_maturity': account_date, 'amount_currency': total_amount_currency, 'currency_id': expense.currency_id.id, 'expense_id': expense.id, 'partner_id': partner_id, 'exclude_from_invoice_tab': True, } move_line_values.append(move_line_dst) move_line_values_by_expense[expense.id] = move_line_values return move_line_values_by_expense def action_move_create(self): ''' main function that is called when trying to create the accounting entries related to an expense ''' move_group_by_sheet = self._get_account_move_by_sheet() move_line_values_by_expense = self._get_account_move_line_values() for expense in self: # get the account move of the related sheet move = move_group_by_sheet[expense.sheet_id.id] # get move line values move_line_values = move_line_values_by_expense.get(expense.id) # link move lines to move, and move to expense sheet move.write({'line_ids': [(0, 0, line) for line in move_line_values]}) expense.sheet_id.write({'account_move_id': move.id}) if expense.payment_mode == 'company_account': expense.sheet_id.paid_expense_sheets() # post the moves for move in move_group_by_sheet.values(): move._post() return move_group_by_sheet def refuse_expense(self, reason): self.write({'is_refused': True}) self.sheet_id.write({'state': 'cancel'}) self.sheet_id.message_post_with_view('hr_expense.hr_expense_template_refuse_reason', values={'reason': reason, 'is_sheet': False, 'name': self.name}) @api.model def get_expense_dashboard(self): expense_state = { 'draft': { 'description': _('to report'), 'amount': 0.0, 'currency': self.env.company.currency_id.id, }, 'reported': { 'description': _('under validation'), 'amount': 0.0, 'currency': self.env.company.currency_id.id, }, 'approved': { 'description': _('to be reimbursed'), 'amount': 0.0, 'currency': self.env.company.currency_id.id, } } if not self.env.user.employee_ids: return expense_state target_currency = self.env.company.currency_id expenses = self.read_group( [ ('employee_id', 'in', self.env.user.employee_ids.ids), ('payment_mode', '=', 'own_account'), ('state', 'in', ['draft', 'reported', 'approved']) ], ['total_amount', 'currency_id', 'state'], ['state', 'currency_id'], lazy=False) for expense in expenses: state = expense['state'] currency = self.env['res.currency'].browse(expense['currency_id'][0]) if expense['currency_id'] else target_currency amount = currency._convert( expense['total_amount'], target_currency, self.env.company, fields.Date.today()) expense_state[state]['amount'] += amount return expense_state # ---------------------------------------- # Mail Thread # ---------------------------------------- @api.model def message_new(self, msg_dict, custom_values=None): email_address = email_split(msg_dict.get('email_from', False))[0] employee = self.env['hr.employee'].search([ '|', ('work_email', 'ilike', email_address), ('user_id.email', 'ilike', email_address) ], limit=1) if not employee: return super().message_new(msg_dict, custom_values=custom_values) expense_description = msg_dict.get('subject', '') if employee.user_id: company = employee.user_id.company_id currencies = company.currency_id | employee.user_id.company_ids.mapped('currency_id') else: company = employee.company_id currencies = company.currency_id if not company: # ultimate fallback, since company_id is required on expense company = self.env.company # The expenses alias is the same for all companies, we need to set the proper context # To select the product account self = self.with_company(company) product, price, currency_id, expense_description = self._parse_expense_subject(expense_description, currencies) vals = { 'employee_id': employee.id, 'name': expense_description, 'unit_amount': price, 'product_id': product.id if product else None, 'product_uom_id': product.uom_id.id, 'tax_ids': [(4, tax.id, False) for tax in product.supplier_taxes_id.filtered(lambda r: r.company_id == company)], 'quantity': 1, 'company_id': company.id, 'currency_id': currency_id.id } account = product.product_tmpl_id._get_product_accounts()['expense'] if account: vals['account_id'] = account.id expense = super(HrExpense, self).message_new(msg_dict, dict(custom_values or {}, **vals)) self._send_expense_success_mail(msg_dict, expense) return expense @api.model def _parse_product(self, expense_description): """ Parse the subject to find the product. Product code should be the first word of expense_description Return product.product and updated description """ product_code = expense_description.split(' ')[0] product = self.env['product.product'].search([('can_be_expensed', '=', True), ('default_code', '=ilike', product_code)], limit=1) if product: expense_description = expense_description.replace(product_code, '', 1) return product, expense_description @api.model def _parse_price(self, expense_description, currencies): """ Return price, currency and updated description """ symbols, symbols_pattern, float_pattern = [], '', '[+-]?(\d+[.,]?\d*)' price = 0.0 for currency in currencies: symbols.append(re.escape(currency.symbol)) symbols.append(re.escape(currency.name)) symbols_pattern = '|'.join(symbols) price_pattern = "((%s)?\s?%s\s?(%s)?)" % (symbols_pattern, float_pattern, symbols_pattern) matches = re.findall(price_pattern, expense_description) currency = currencies and currencies[0] if matches: match = max(matches, key=lambda match: len([group for group in match if group])) # get the longuest match. e.g. "2 chairs 120$" -> the price is 120$, not 2 full_str = match[0] currency_str = match[1] or match[3] price = match[2].replace(',', '.') if currency_str and currencies: currencies = currencies.filtered(lambda c: currency_str in [c.symbol, c.name]) currency = (currencies and currencies[0]) or currency expense_description = expense_description.replace(full_str, ' ') # remove price from description expense_description = re.sub(' +', ' ', expense_description.strip()) price = float(price) return price, currency, expense_description @api.model def _parse_expense_subject(self, expense_description, currencies): """ Fetch product, price and currency info from mail subject. Product can be identified based on product name or product code. It can be passed between [] or it can be placed at start. When parsing, only consider currencies passed as parameter. This will fetch currency in symbol($) or ISO name (USD). Some valid examples: Travel by Air [TICKET] USD 1205.91 TICKET $1205.91 Travel by Air Extra expenses 29.10EUR [EXTRA] """ product, expense_description = self._parse_product(expense_description) price, currency_id, expense_description = self._parse_price(expense_description, currencies) return product, price, currency_id, expense_description # TODO: Make api.multi def _send_expense_success_mail(self, msg_dict, expense): mail_template_id = 'hr_expense.hr_expense_template_register' if expense.employee_id.user_id else 'hr_expense.hr_expense_template_register_no_user' expense_template = self.env.ref(mail_template_id) rendered_body = expense_template._render({'expense': expense}, engine='ir.qweb') body = self.env['mail.render.mixin']._replace_local_links(rendered_body) # TDE TODO: seems louche, check to use notify if expense.employee_id.user_id.partner_id: expense.message_post( partner_ids=expense.employee_id.user_id.partner_id.ids, subject='Re: %s' % msg_dict.get('subject', ''), body=body, subtype_id=self.env.ref('mail.mt_note').id, email_layout_xmlid='mail.mail_notification_light', ) else: self.env['mail.mail'].sudo().create({ 'email_from': self.env.user.email_formatted, 'author_id': self.env.user.partner_id.id, 'body_html': body, 'subject': 'Re: %s' % msg_dict.get('subject', ''), 'email_to': msg_dict.get('email_from', False), 'auto_delete': True, 'references': msg_dict.get('message_id'), }).send() class HrExpenseSheet(models.Model): """ Here are the rights associated with the expense flow Action Group Restriction ================================================================================= Submit Employee Only his own Officer If he is expense manager of the employee, manager of the employee or the employee is in the department managed by the officer Manager Always Approve Officer Not his own and he is expense manager of the employee, manager of the employee or the employee is in the department managed by the officer Manager Always Post Anybody State = approve and journal_id defined Done Anybody State = approve and journal_id defined Cancel Officer Not his own and he is expense manager of the employee, manager of the employee or the employee is in the department managed by the officer Manager Always ================================================================================= """ _name = "hr.expense.sheet" _inherit = ['mail.thread', 'mail.activity.mixin'] _description = "Expense Report" _order = "accounting_date desc, id desc" _check_company_auto = True @api.model def _default_employee_id(self): return self.env.user.employee_id @api.model def _default_journal_id(self): """ The journal is determining the company of the accounting entries generated from expense. We need to force journal company and expense sheet company to be the same. """ default_company_id = self.default_get(['company_id'])['company_id'] journal = self.env['account.journal'].search([('type', '=', 'purchase'), ('company_id', '=', default_company_id)], limit=1) return journal.id @api.model def _default_bank_journal_id(self): default_company_id = self.default_get(['company_id'])['company_id'] return self.env['account.journal'].search([('type', 'in', ['cash', 'bank']), ('company_id', '=', default_company_id)], limit=1) name = fields.Char('Expense Report Summary', required=True, tracking=True) expense_line_ids = fields.One2many('hr.expense', 'sheet_id', string='Expense Lines', copy=False) is_editable = fields.Boolean("Expense Lines Are Editable By Current User", compute='_compute_is_editable') state = fields.Selection([ ('draft', 'Draft'), ('submit', 'Submitted'), ('approve', 'Approved'), ('post', 'Posted'), ('done', 'Done'), ('cancel', 'Refused') ], string='Status', index=True, readonly=True, tracking=True, copy=False, default='draft', required=True, help='Expense Report State') payment_state = fields.Selection(selection=PAYMENT_STATE_SELECTION, string="Payment Status", store=True, readonly=True, copy=False, tracking=True, compute='_compute_payment_state') employee_id = fields.Many2one('hr.employee', string="Employee", required=True, readonly=True, tracking=True, states={'draft': [('readonly', False)]}, default=_default_employee_id, check_company=True, domain= lambda self: self.env['hr.expense']._get_employee_id_domain()) address_id = fields.Many2one('res.partner', compute='_compute_from_employee_id', store=True, readonly=False, copy=True, string="Employee Home Address", check_company=True) payment_mode = fields.Selection(related='expense_line_ids.payment_mode', readonly=True, string="Paid By", tracking=True) user_id = fields.Many2one('res.users', 'Manager', compute='_compute_from_employee_id', store=True, readonly=True, copy=False, states={'draft': [('readonly', False)]}, tracking=True, domain=lambda self: [('groups_id', 'in', self.env.ref('hr_expense.group_hr_expense_team_approver').id)]) total_amount = fields.Monetary('Total Amount', currency_field='currency_id', compute='_compute_amount', store=True, tracking=True) amount_residual = fields.Monetary( string="Amount Due", store=True, currency_field='currency_id', related='account_move_id.amount_residual') company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.company) currency_id = fields.Many2one('res.currency', string='Currency', readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.company.currency_id) attachment_number = fields.Integer(compute='_compute_attachment_number', string='Number of Attachments') journal_id = fields.Many2one('account.journal', string='Expense Journal', states={'done': [('readonly', True)], 'post': [('readonly', True)]}, check_company=True, domain="[('type', '=', 'purchase'), ('company_id', '=', company_id)]", default=_default_journal_id, help="The journal used when the expense is done.") bank_journal_id = fields.Many2one('account.journal', string='Bank Journal', states={'done': [('readonly', True)], 'post': [('readonly', True)]}, check_company=True, domain="[('type', 'in', ['cash', 'bank']), ('company_id', '=', company_id)]", default=_default_bank_journal_id, help="The payment method used when the expense is paid by the company.") accounting_date = fields.Date("Accounting Date") account_move_id = fields.Many2one('account.move', string='Journal Entry', ondelete='restrict', copy=False, readonly=True) department_id = fields.Many2one('hr.department', compute='_compute_from_employee_id', store=True, readonly=False, copy=False, string='Department', states={'post': [('readonly', True)], 'done': [('readonly', True)]}) is_multiple_currency = fields.Boolean("Handle lines with different currencies", compute='_compute_is_multiple_currency') can_reset = fields.Boolean('Can Reset', compute='_compute_can_reset') can_approve = fields.Boolean('Can Approve', compute='_compute_can_approve') approval_date = fields.Datetime('Approval Date', readonly=True) _sql_constraints = [ ('journal_id_required_posted', "CHECK((state IN ('post', 'done') AND journal_id IS NOT NULL) OR (state NOT IN ('post', 'done')))", 'The journal must be set on posted expense'), ] @api.depends('expense_line_ids.total_amount_company') def _compute_amount(self): for sheet in self: sheet.total_amount = sum(sheet.expense_line_ids.mapped('total_amount_company')) @api.depends('account_move_id.payment_state') def _compute_payment_state(self): for sheet in self: sheet.payment_state = sheet.account_move_id.payment_state or 'not_paid' def _compute_attachment_number(self): for sheet in self: sheet.attachment_number = sum(sheet.expense_line_ids.mapped('attachment_number')) @api.depends('expense_line_ids.currency_id') def _compute_is_multiple_currency(self): for sheet in self: sheet.is_multiple_currency = len(sheet.expense_line_ids.mapped('currency_id')) > 1 @api.depends('employee_id') def _compute_can_reset(self): is_expense_user = self.user_has_groups('hr_expense.group_hr_expense_team_approver') for sheet in self: sheet.can_reset = is_expense_user if is_expense_user else sheet.employee_id.user_id == self.env.user @api.depends_context('uid') @api.depends('employee_id') def _compute_can_approve(self): is_approver = self.user_has_groups('hr_expense.group_hr_expense_team_approver, hr_expense.group_hr_expense_user') is_manager = self.user_has_groups('hr_expense.group_hr_expense_manager') for sheet in self: sheet.can_approve = is_manager or (is_approver and sheet.employee_id.user_id != self.env.user) @api.depends('employee_id') def _compute_from_employee_id(self): for sheet in self: sheet.address_id = sheet.employee_id.sudo().address_home_id sheet.department_id = sheet.employee_id.department_id sheet.user_id = sheet.employee_id.expense_manager_id or sheet.employee_id.parent_id.user_id @api.depends_context('uid') @api.depends('employee_id', 'state') def _compute_is_editable(self): is_manager = self.user_has_groups('hr_expense.group_hr_expense_manager') is_approver = self.user_has_groups('hr_expense.group_hr_expense_user') for report in self: # Employee can edit his own expense in draft only is_editable = (report.employee_id.user_id == self.env.user and report.state == 'draft') or (is_manager and report.state in ['draft', 'submit', 'approve']) if not is_editable and report.state in ['draft', 'submit', 'approve']: # expense manager can edit, unless it's own expense current_managers = report.employee_id.expense_manager_id | report.employee_id.parent_id.user_id | report.employee_id.department_id.manager_id.user_id is_editable = (is_approver or self.env.user in current_managers) and report.employee_id.user_id != self.env.user report.is_editable = is_editable @api.constrains('expense_line_ids') def _check_payment_mode(self): for sheet in self: expense_lines = sheet.mapped('expense_line_ids') if expense_lines and any(expense.payment_mode != expense_lines[0].payment_mode for expense in expense_lines): raise ValidationError(_("Expenses must be paid by the same entity (Company or employee).")) @api.constrains('expense_line_ids', 'employee_id') def _check_employee(self): for sheet in self: employee_ids = sheet.expense_line_ids.mapped('employee_id') if len(employee_ids) > 1 or (len(employee_ids) == 1 and employee_ids != sheet.employee_id): raise ValidationError(_('You cannot add expenses of another employee.')) @api.constrains('expense_line_ids', 'company_id') def _check_expense_lines_company(self): for sheet in self: if any(expense.company_id != sheet.company_id for expense in sheet.expense_line_ids): raise ValidationError(_('An expense report must contain only lines from the same company.')) @api.model def create(self, vals): context = clean_context(self.env.context) context.update({ 'mail_create_nosubscribe': True, 'mail_auto_subscribe_no_notify': True }) sheet = super(HrExpenseSheet, self.with_context(context)).create(vals) sheet.activity_update() return sheet @api.ondelete(at_uninstall=False) def _unlink_except_posted_or_paid(self): for expense in self: if expense.state in ['post', 'done']: raise UserError(_('You cannot delete a posted or paid expense.')) # -------------------------------------------- # Mail Thread # -------------------------------------------- def _track_subtype(self, init_values): self.ensure_one() if 'state' in init_values and self.state == 'approve': return self.env.ref('hr_expense.mt_expense_approved') elif 'state' in init_values and self.state == 'cancel': return self.env.ref('hr_expense.mt_expense_refused') elif 'state' in init_values and self.state == 'done': return self.env.ref('hr_expense.mt_expense_paid') return super(HrExpenseSheet, self)._track_subtype(init_values) def _message_auto_subscribe_followers(self, updated_values, subtype_ids): res = super(HrExpenseSheet, self)._message_auto_subscribe_followers(updated_values, subtype_ids) if updated_values.get('employee_id'): employee = self.env['hr.employee'].browse(updated_values['employee_id']) if employee.user_id: res.append((employee.user_id.partner_id.id, subtype_ids, False)) return res # -------------------------------------------- # Actions # -------------------------------------------- def action_sheet_move_create(self): samples = self.mapped('expense_line_ids.sample') if samples.count(True): if samples.count(False): raise UserError(_("You can't mix sample expenses and regular ones")) self.write({'state': 'post'}) return if any(sheet.state != 'approve' for sheet in self): raise UserError(_("You can only generate accounting entry for approved expense(s).")) if any(not sheet.journal_id for sheet in self): raise UserError(_("Specify expense journal to generate accounting entries.")) expense_line_ids = self.mapped('expense_line_ids')\ .filtered(lambda r: not float_is_zero(r.total_amount, precision_rounding=(r.currency_id or self.env.company.currency_id).rounding)) res = expense_line_ids.with_context(clean_context(self.env.context)).action_move_create() for sheet in self.filtered(lambda s: not s.accounting_date): sheet.accounting_date = sheet.account_move_id.date to_post = self.filtered(lambda sheet: sheet.payment_mode == 'own_account' and sheet.expense_line_ids) to_post.write({'state': 'post'}) (self - to_post).write({'state': 'done'}) self.activity_update() return res def action_unpost(self): self = self.with_context(clean_context(self.env.context)) moves = self.account_move_id self.write({ 'account_move_id': False, 'state': 'draft', }) draft_moves = moves.filtered(lambda m: m.state == 'draft') draft_moves.unlink() (moves - draft_moves)._reverse_moves(cancel=True) def action_get_attachment_view(self): res = self.env['ir.actions.act_window']._for_xml_id('base.action_attachment') res['domain'] = [('res_model', '=', 'hr.expense'), ('res_id', 'in', self.expense_line_ids.ids)] res['context'] = { 'default_res_model': 'hr.expense.sheet', 'default_res_id': self.id, 'create': False, 'edit': False, } return res def action_open_account_move(self): self.ensure_one() return { 'name': self.account_move_id.name, 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.move', 'res_id': self.account_move_id.id } # -------------------------------------------- # Business # -------------------------------------------- def set_to_paid(self): self.write({'state': 'done'}) def action_submit_sheet(self): self.write({'state': 'submit'}) self.activity_update() def _check_can_approve(self): if not self.user_has_groups('hr_expense.group_hr_expense_team_approver'): raise UserError(_("Only Managers and HR Officers can approve expenses")) elif not self.user_has_groups('hr_expense.group_hr_expense_manager'): current_managers = self.employee_id.expense_manager_id | self.employee_id.parent_id.user_id | self.employee_id.department_id.manager_id.user_id if self.employee_id.user_id == self.env.user: raise UserError(_("You cannot approve your own expenses")) if not self.env.user in current_managers and not self.user_has_groups('hr_expense.group_hr_expense_user') and self.employee_id.expense_manager_id != self.env.user: raise UserError(_("You can only approve your department expenses")) def approve_expense_sheets(self): self._check_can_approve() duplicates = self.expense_line_ids.duplicate_expense_ids.filtered(lambda exp: exp.state in ['approved', 'done']) if duplicates: action = self.env["ir.actions.act_window"]._for_xml_id('hr_expense.hr_expense_approve_duplicate_action') action['context'] = {'default_sheet_ids': self.ids, 'default_expense_ids': duplicates.ids} return action self._do_approve() def _do_approve(self): self._check_can_approve() notification = { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'title': _('There are no expense reports to approve.'), 'type': 'warning', 'sticky': False, #True/False will display for few seconds if false }, } filtered_sheet = self.filtered(lambda s: s.state in ['submit', 'draft']) if not filtered_sheet: return notification for sheet in filtered_sheet: sheet.write({ 'state': 'approve', 'user_id': sheet.user_id.id or self.env.user.id, 'approval_date': fields.Date.context_today(sheet), }) notification['params'].update({ 'title': _('The expense reports were successfully approved.'), 'type': 'success', 'next': {'type': 'ir.actions.act_window_close'}, }) self.activity_update() return notification def paid_expense_sheets(self): self.write({'state': 'done'}) def refuse_sheet(self, reason): if not self.user_has_groups('hr_expense.group_hr_expense_team_approver'): raise UserError(_("Only Managers and HR Officers can approve expenses")) elif not self.user_has_groups('hr_expense.group_hr_expense_manager'): current_managers = self.employee_id.expense_manager_id | self.employee_id.parent_id.user_id | self.employee_id.department_id.manager_id.user_id if self.employee_id.user_id == self.env.user: raise UserError(_("You cannot refuse your own expenses")) if not self.env.user in current_managers and not self.user_has_groups('hr_expense.group_hr_expense_user') and self.employee_id.expense_manager_id != self.env.user: raise UserError(_("You can only refuse your department expenses")) self.write({'state': 'cancel'}) for sheet in self: sheet.message_post_with_view('hr_expense.hr_expense_template_refuse_reason', values={'reason': reason, 'is_sheet': True, 'name': sheet.name}) self.activity_update() def reset_expense_sheets(self): if not self.can_reset: raise UserError(_("Only HR Officers or the concerned employee can reset to draft.")) self.mapped('expense_line_ids').write({'is_refused': False}) self.write({'state': 'draft', 'approval_date': False}) self.activity_update() return True def _get_responsible_for_approval(self): if self.user_id: return self.user_id elif self.employee_id.parent_id.user_id: return self.employee_id.parent_id.user_id elif self.employee_id.department_id.manager_id.user_id: return self.employee_id.department_id.manager_id.user_id return self.env['res.users'] def activity_update(self): for expense_report in self.filtered(lambda hol: hol.state == 'submit'): self.activity_schedule( 'hr_expense.mail_act_expense_approval', user_id=expense_report.sudo()._get_responsible_for_approval().id or self.env.user.id) self.filtered(lambda hol: hol.state == 'approve').activity_feedback(['hr_expense.mail_act_expense_approval']) self.filtered(lambda hol: hol.state in ('draft', 'cancel')).activity_unlink(['hr_expense.mail_act_expense_approval']) def action_register_payment(self): ''' Open the account.payment.register wizard to pay the selected journal entries. :return: An action opening the account.payment.register wizard. ''' return { 'name': _('Register Payment'), 'res_model': 'account.payment.register', 'view_mode': 'form', 'context': { 'active_model': 'account.move', 'active_ids': self.account_move_id.ids, 'default_partner_bank_id': self.employee_id.sudo().bank_account_id.id, }, 'target': 'new', 'type': 'ir.actions.act_window', }
52.757601
64,206
1,585
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 AccountMove(models.Model): _inherit = "account.move" def _payment_state_matters(self): self.ensure_one() if self.line_ids.expense_id: return True return super()._payment_state_matters() class AccountMoveLine(models.Model): _inherit = "account.move.line" expense_id = fields.Many2one('hr.expense', string='Expense', copy=False, help="Expense where the move line come from") def reconcile(self): # OVERRIDE not_paid_expenses = self.expense_id.filtered(lambda expense: expense.state != 'done') res = super().reconcile() # Do not consider expense sheet states if account_move_id is False, it means it has been just canceled not_paid_expense_sheets = not_paid_expenses.sheet_id.filtered(lambda sheet: sheet.account_move_id) paid_expenses = not_paid_expenses.filtered(lambda expense: expense.currency_id.is_zero(expense.amount_residual)) paid_expenses.write({'state': 'done'}) not_paid_expense_sheets.filtered(lambda sheet: all(expense.state == 'done' for expense in sheet.expense_line_ids)).set_to_paid() return res def _get_attachment_domains(self): attachment_domains = super(AccountMoveLine, self)._get_attachment_domains() if self.expense_id: attachment_domains.append([('res_model', '=', 'hr.expense'), ('res_id', '=', self.expense_id.id)]) return attachment_domains
44.027778
1,585
786
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 HrDepartment(models.Model): _inherit = 'hr.department' def _compute_expense_sheets_to_approve(self): expense_sheet_data = self.env['hr.expense.sheet'].read_group([('department_id', 'in', self.ids), ('state', '=', 'submit')], ['department_id'], ['department_id']) result = dict((data['department_id'][0], data['department_id_count']) for data in expense_sheet_data) for department in self: department.expense_sheets_to_approve_count = result.get(department.id, 0) expense_sheets_to_approve_count = fields.Integer(compute='_compute_expense_sheets_to_approve', string='Expenses Reports to Approve')
49.125
786
829
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 ProductTemplate(models.Model): _inherit = "product.template" @api.model def default_get(self, fields): result = super(ProductTemplate, self).default_get(fields) if self.env.context.get('default_can_be_expensed'): result['supplier_taxes_id'] = False return result can_be_expensed = fields.Boolean(string="Can be Expensed", compute='_compute_can_be_expensed', store=True, readonly=False, help="Specify whether the product can be selected in an expense.") @api.depends('type') def _compute_can_be_expensed(self): self.filtered(lambda p: p.type not in ['consu', 'service']).update({'can_be_expensed': False})
37.681818
829
2,017
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models from odoo.tools.misc import formatLang class AccountJournal(models.Model): _inherit = "account.journal" def _get_expenses_to_pay_query(self): """ Returns a tuple containing as it's first element the SQL query used to gather the expenses in reported state data, and the arguments dictionary to use to run it as it's second. """ query = """SELECT total_amount as amount_total, currency_id AS currency FROM hr_expense_sheet WHERE state IN ('approve', 'post') and journal_id = %(journal_id)s""" return (query, {'journal_id': self.id}) def get_journal_dashboard_datas(self): res = super(AccountJournal, self).get_journal_dashboard_datas() #add the number and sum of expenses to pay to the json defining the accounting dashboard data (query, query_args) = self._get_expenses_to_pay_query() self.env.cr.execute(query, query_args) query_results_to_pay = self.env.cr.dictfetchall() (number_to_pay, sum_to_pay) = self._count_results_and_sum_amounts(query_results_to_pay, self.company_id.currency_id) res['number_expenses_to_pay'] = number_to_pay res['sum_expenses_to_pay'] = formatLang(self.env, sum_to_pay or 0.0, currency_obj=self.currency_id or self.company_id.currency_id) return res def open_expenses_action(self): action = self.env['ir.actions.act_window']._for_xml_id('hr_expense.action_hr_expense_sheet_all_all') action['context'] = { 'search_default_approved': 1, 'search_default_to_post': 1, 'search_default_journal_id': self.id, 'default_journal_id': self.id, } action['view_mode'] = 'tree,form' action['views'] = [(k,v) for k,v in action['views'] if v in ['tree', 'form']] return action
45.840909
2,017
2,467
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class Employee(models.Model): _inherit = 'hr.employee' def _group_hr_expense_user_domain(self): # We return the domain only if the group exists for the following reason: # When a group is created (at module installation), the `res.users` form view is # automatically modifiedto add application accesses. When modifiying the view, it # reads the related field `expense_manager_id` of `res.users` and retrieve its domain. # This is a problem because the `group_hr_expense_user` record has already been created but # not its associated `ir.model.data` which makes `self.env.ref(...)` fail. group = self.env.ref('hr_expense.group_hr_expense_team_approver', raise_if_not_found=False) return [('groups_id', 'in', group.ids)] if group else [] expense_manager_id = fields.Many2one( 'res.users', string='Expense', domain=_group_hr_expense_user_domain, compute='_compute_expense_manager', store=True, readonly=False, help='Select the user responsible for approving "Expenses" of this employee.\n' 'If empty, the approval is done by an Administrator or Approver (determined in settings/users).') @api.depends('parent_id') def _compute_expense_manager(self): for employee in self: previous_manager = employee._origin.parent_id.user_id manager = employee.parent_id.user_id if manager and manager.has_group('hr_expense.group_hr_expense_user') and (employee.expense_manager_id == previous_manager or not employee.expense_manager_id): employee.expense_manager_id = manager elif not employee.expense_manager_id: employee.expense_manager_id = False def _get_user_m2o_to_empty_on_archived_employees(self): return super()._get_user_m2o_to_empty_on_archived_employees() + ['expense_manager_id'] class EmployeePublic(models.Model): _inherit = 'hr.employee.public' expense_manager_id = fields.Many2one('res.users', readonly=True) class User(models.Model): _inherit = ['res.users'] expense_manager_id = fields.Many2one(related='employee_id.expense_manager_id', readonly=False) @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + ['expense_manager_id']
45.685185
2,467
1,260
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' expense_alias_prefix = fields.Char('Default Alias Name for Expenses', compute='_compute_expense_alias_prefix', store=True, readonly=False) use_mailgateway = fields.Boolean(string='Let your employees record expenses by email', config_parameter='hr_expense.use_mailgateway') module_hr_payroll_expense = fields.Boolean(string='Reimburse Expenses in Payslip') module_hr_expense_extract = fields.Boolean(string='Send bills to OCR to generate expenses') @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res.update( expense_alias_prefix=self.env.ref('hr_expense.mail_alias_expense').alias_name, ) return res def set_values(self): super(ResConfigSettings, self).set_values() self.env.ref('hr_expense.mail_alias_expense').write({'alias_name': self.expense_alias_prefix}) @api.depends('use_mailgateway') def _compute_expense_alias_prefix(self): self.filtered(lambda w: not w.use_mailgateway).update({'expense_alias_prefix': False})
39.375
1,260
549
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Send SMS to Visitor', 'category': 'Website/Website', 'sequence': 54, 'summary': 'Allows to send sms to website visitor', 'version': '1.0', 'description': """Allows to send sms to website visitor if the visitor is linked to a partner.""", 'depends': ['website', 'sms'], 'data': [ 'views/website_visitor_views.xml', ], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
32.294118
549
1,530
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 WebsiteVisitor(models.Model): _inherit = 'website.visitor' def _check_for_sms_composer(self): """ Purpose of this method is to actualize visitor model prior to contacting him. Used notably for inheritance purpose, when dealing with leads that could update the visitor model. """ return bool(self.partner_id and (self.partner_id.mobile or self.partner_id.phone)) def _prepare_sms_composer_context(self): return { 'default_res_model': 'res.partner', 'default_res_id': self.partner_id.id, 'default_composition_mode': 'comment', 'default_number_field_name': 'mobile' if self.partner_id.mobile else 'phone', } def action_send_sms(self): self.ensure_one() if not self._check_for_sms_composer(): raise UserError(_("There are no contact and/or no phone or mobile numbers linked to this visitor.")) visitor_composer_ctx = self._prepare_sms_composer_context() compose_ctx = dict(self.env.context) compose_ctx.update(**visitor_composer_ctx) return { "name": _("Send SMS Text Message"), "type": "ir.actions.act_window", "res_model": "sms.composer", "view_mode": 'form', "context": compose_ctx, "target": "new", }
38.25
1,530
681
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Website Mail', 'category': 'Hidden', 'summary': 'Website Module for Mail', 'version': '0.1', 'description': """ Module holding mail improvements for website. It holds the follow widget. """, 'depends': ['website', 'mail'], 'data': [ 'views/website_mail_templates.xml', ], 'installable': True, 'auto_install': True, 'assets': { 'web.assets_frontend': [ 'website_mail/static/src/js/follow.js', 'website_mail/static/src/css/website_mail.scss', ], }, 'license': 'LGPL-3', }
27.24
681
392
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 PublisherWarrantyContract(models.AbstractModel): _inherit = "publisher_warranty.contract" @api.model def _get_message(self): msg = super(PublisherWarrantyContract, self)._get_message() msg['website'] = True return msg
28
392
3,308
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request class WebsiteMail(http.Controller): @http.route(['/website_mail/follow'], type='json', auth="public", website=True) def website_message_subscribe(self, id=0, object=None, message_is_follower="on", email=False, **post): # TDE FIXME: check this method with new followers res_id = int(id) is_follower = message_is_follower == 'on' record = request.env[object].browse(res_id).exists() if not record: return False record.check_access_rights('read') record.check_access_rule('read') # search partner_id if request.env.user != request.website.user_id: partner_ids = request.env.user.partner_id.ids else: # mail_thread method partner_ids = [p.id for p in request.env['mail.thread'].sudo()._mail_find_partner_from_emails([email], records=record.sudo()) if p] if not partner_ids or not partner_ids[0]: name = email.split('@')[0] partner_ids = request.env['res.partner'].sudo().create({'name': name, 'email': email}).ids # add or remove follower if is_follower: record.sudo().message_unsubscribe(partner_ids) return False else: # add partner to session request.session['partner_id'] = partner_ids[0] record.sudo().message_subscribe(partner_ids) return True @http.route(['/website_mail/is_follower'], type='json', auth="public", website=True) def is_follower(self, records, **post): """ Given a list of `models` containing a list of res_ids, return the res_ids for which the user is follower and some practical info. :param records: dict of models containing record IDS, eg: { 'res.model': [1, 2, 3..], 'res.model2': [1, 2, 3..], .. } :returns: [ {'is_user': True/False, 'email': '[email protected]'}, {'res.model': [1, 2], 'res.model2': [1]} ] """ user = request.env.user partner = None public_user = request.website.user_id if user != public_user: partner = request.env.user.partner_id elif request.session.get('partner_id'): partner = request.env['res.partner'].sudo().browse(request.session.get('partner_id')) res = {} if partner: for model in records: mail_followers_ids = request.env['mail.followers'].sudo().read_group([ ('res_model', '=', model), ('res_id', 'in', records[model]), ('partner_id', '=', partner.id) ], ['res_id', 'follow_count:count(id)'], ['res_id']) # `read_group` will filter out the ones without count result for m in mail_followers_ids: res.setdefault(model, []).append(m['res_id']) return [{ 'is_user': user != public_user, 'email': partner.email if partner else "", }, res]
41.873418
3,308
541
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Lead Livechat Sessions', 'category': 'Website/Website', 'summary': 'View livechat sessions for leads', 'version': '1.0', 'description': """ Adds a stat button on lead form view to access their livechat sessions.""", 'depends': ['website_crm', 'website_livechat'], 'data': [ 'views/website_crm_lead_views.xml', ], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
33.8125
541
874
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 Lead(models.Model): _inherit = 'crm.lead' visitor_sessions_count = fields.Integer('# Sessions', compute="_compute_visitor_sessions_count", groups="im_livechat.im_livechat_group_user") @api.depends('visitor_ids.mail_channel_ids') def _compute_visitor_sessions_count(self): for lead in self: lead.visitor_sessions_count = len(lead.visitor_ids.mail_channel_ids) def action_redirect_to_livechat_sessions(self): visitors = self.visitor_ids action = self.env["ir.actions.actions"]._for_xml_id("website_livechat.website_visitor_livechat_session_action") action['domain'] = [('livechat_visitor_id', 'in', visitors.ids), ('has_message', '=', True)] return action
41.619048
874
777
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class MailChannel(models.Model): _inherit = 'mail.channel' def _convert_visitor_to_lead(self, partner, key): """ When website is installed, we can link the created lead from /lead command to the current website_visitor. We do not use the lead name as it does not correspond to the lead contact name.""" lead = super(MailChannel, self)._convert_visitor_to_lead(partner, key) visitor_sudo = self.livechat_visitor_id.sudo() if visitor_sudo: visitor_sudo.write({'lead_ids': [(4, lead.id)]}) lead.country_id = lead.country_id or visitor_sudo.country_id return lead
40.894737
777
409
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "account_qr_code_sepa", 'description': """ This module adds support for SEPA Credit Transfer QR-code generation. """, 'category': 'Accounting/Payment', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['account', 'base_iban'], 'data': [ ], 'auto_install': True, 'license': 'LGPL-3', }
20.45
409
3,432
py
PYTHON
15.0
# -*- coding:utf-8 -*- from odoo.exceptions import UserError from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo import fields @tagged('post_install', '-at_install') class TestSEPAQRCode(AccountTestInvoicingCommon): """ Tests the generation of Swiss QR-codes on invoices """ @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company_data['company'].qr_code = True cls.acc_sepa_iban = cls.env['res.partner.bank'].create({ 'acc_number': 'BE15001559627230', 'partner_id': cls.company_data['company'].partner_id.id, }) cls.acc_non_sepa_iban = cls.env['res.partner.bank'].create({ 'acc_number': 'SA4420000001234567891234', 'partner_id': cls.company_data['company'].partner_id.id, }) cls.sepa_qr_invoice = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': cls.partner_a.id, 'currency_id': cls.env.ref('base.EUR').id, 'partner_bank_id': cls.acc_sepa_iban.id, 'company_id': cls.company_data['company'].id, 'invoice_line_ids': [ (0, 0, {'quantity': 1, 'price_unit': 100}) ], }) def test_sepa_qr_code_generation(self): """ Check different cases of SEPA QR-code generation, when qr_method is specified beforehand. """ self.sepa_qr_invoice.qr_code_method = 'sct_qr' # Using a SEPA IBAN should work self.sepa_qr_invoice.generate_qr_code() # Using a non-SEPA IBAN shouldn't self.sepa_qr_invoice.partner_bank_id = self.acc_non_sepa_iban with self.assertRaises(UserError, msg="It shouldn't be possible to generate a SEPA QR-code for IBAN of countries outside SEPA zone."): self.sepa_qr_invoice.generate_qr_code() # Changing the currency should break it as well self.sepa_qr_invoice.partner_bank_id = self.acc_sepa_iban self.sepa_qr_invoice.currency_id = self.env.ref('base.USD').id with self.assertRaises(UserError, msg="It shouldn't be possible to generate a SEPA QR-code for another currency as EUR."): self.sepa_qr_invoice.generate_qr_code() def test_sepa_qr_code_detection(self): """ Checks SEPA QR-code auto-detection when no specific QR-method is given to the invoice. """ self.sepa_qr_invoice.generate_qr_code() self.assertEqual(self.sepa_qr_invoice.qr_code_method, 'sct_qr', "SEPA QR-code generator should have been chosen for this invoice.") def test_out_invoice_create_refund_qr_code(self): self.sepa_qr_invoice.generate_qr_code() self.sepa_qr_invoice.action_post() move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.sepa_qr_invoice.ids).create({ 'date': fields.Date.from_string('2019-02-01'), 'reason': 'no reason', 'refund_method': 'refund', 'journal_id': self.sepa_qr_invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertFalse(reverse_move.qr_code_method, "qr_code_method for credit note should be None")
44
3,432
3,939
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' def _get_qr_vals(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): if qr_method == 'sct_qr': comment = (free_communication or '') if not structured_communication else '' qr_code_vals = [ 'BCD', # Service Tag '002', # Version '1', # Character Set 'SCT', # Identification Code self.bank_bic or '', # BIC of the Beneficiary Bank (self.acc_holder_name or self.partner_id.name)[:71], # Name of the Beneficiary self.sanitized_acc_number, # Account Number of the Beneficiary currency.name + str(amount), # Currency + Amount of the Transfer in EUR '', # Purpose of the Transfer (structured_communication or '')[:36], # Remittance Information (Structured) comment[:141], # Remittance Information (Unstructured) (can't be set if there is a structured one) '', # Beneficiary to Originator Information ] return qr_code_vals return super()._get_qr_vals(qr_method, amount, currency, debtor_partner, free_communication, structured_communication) def _get_qr_code_generation_params(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): if qr_method == 'sct_qr': return { 'barcode_type': 'QR', 'width': 128, 'height': 128, 'humanreadable': 1, 'value': '\n'.join(self._get_qr_vals(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)), } return super()._get_qr_code_generation_params(qr_method, amount, currency, debtor_partner, free_communication, structured_communication) def _eligible_for_qr_code(self, qr_method, debtor_partner, currency): if qr_method == 'sct_qr': # Some countries share the same IBAN country code # (e.g. Åland Islands and Finland IBANs are 'FI', but Åland Islands' code is 'AX'). sepa_country_codes = self.env.ref('base.sepa_zone').country_ids.mapped('code') non_iban_codes = {'AX', 'NC', 'YT', 'TF', 'BL', 'RE', 'MF', 'GP', 'PM', 'PF', 'GF', 'MQ', 'JE', 'GG', 'IM'} sepa_iban_codes = {code for code in sepa_country_codes if code not in non_iban_codes} return currency.name == 'EUR' and self.acc_type == 'iban' and self.sanitized_acc_number[:2] in sepa_iban_codes return super()._eligible_for_qr_code(qr_method, debtor_partner, currency) def _check_for_qr_code_errors(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): if qr_method == 'sct_qr': if not self.acc_holder_name and not self.partner_id.name: return _("The account receiving the payment must have an account holder name or partner name set.") return super()._check_for_qr_code_errors(qr_method, amount, currency, debtor_partner, free_communication, structured_communication) @api.model def _get_available_qr_methods(self): rslt = super()._get_available_qr_methods() rslt.append(('sct_qr', _("SEPA Credit Transfer QR"), 20)) return rslt
60.569231
3,937
695
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Website Sale Gift Card", 'summary': "Use gift card in eCommerce", 'description': """Integrate gift card mechanism in your ecommerce.""", 'category': 'Website/Website', 'version': '1.0', 'depends': ['website_sale', 'sale_gift_card'], 'data': [ 'views/template.xml', 'views/gift_card_views.xml', 'views/gift_card_menus.xml', ], 'demo': [ 'data/product_demo.xml', ], 'assets': { 'web.assets_frontend': [ 'website_sale_gift_card/static/**/*', ], }, 'license': 'LGPL-3', }
27.8
695
1,195
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class SaleOrder(models.Model): _inherit = "sale.order" def _compute_website_order_line(self): super()._compute_website_order_line() for order in self: order.website_order_line = order.website_order_line.sorted(lambda ol: ol.gift_card_id.id) def _compute_cart_info(self): super()._compute_cart_info() for order in self: gift_card_payment_lines = order.website_order_line.filtered('gift_card_id') order.cart_quantity -= int(sum(gift_card_payment_lines.mapped('product_uom_qty'))) def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs): res = super()._cart_update(product_id=product_id, line_id=line_id, add_qty=add_qty, set_qty=set_qty, **kwargs) self._recompute_gift_card_lines() return res class SaleOrderLine(models.Model): _inherit = "sale.order.line" def _build_gift_card(self): gift_card = super()._build_gift_card() gift_card['website_id'] = self.order_id.website_id.id return gift_card
36.212121
1,195
541
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 GiftCard(models.Model): _name = "gift.card" _inherit = ['website.multi.mixin', 'gift.card'] website_id = fields.Many2one('website', related='buy_line_id.order_id.website_id', store=True, readonly=False) def can_be_used(self): website = self.env['website'].get_current_website() return super(GiftCard, self).can_be_used() and self.website_id.id in [website.id, False]
36.066667
541
1,440
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http from odoo.http import request from odoo.addons.website_sale.controllers import main class GiftCardController(main.WebsiteSale): @http.route('/shop/pay_with_gift_card', type='http', methods=['POST'], website=True, auth='public') def add_gift_card(self, gift_card_code, **post): gift_card = request.env["gift.card"].sudo().search([('code', '=', gift_card_code.strip())], limit=1) order = request.env['website'].get_current_website().sale_get_order() gift_card_status = order._pay_with_gift_card(gift_card) return request.redirect('/shop/payment' + '?keep_carrier=1' + ('&gift_card_error=%s' % gift_card_status if gift_card_status else '')) @http.route() def shop_payment(self, **post): order = request.website.sale_get_order() res = super().shop_payment(**post) order._recompute_gift_card_lines() return res @http.route(['/shop/cart'], type='http', auth="public", website=True) def cart(self, **post): order = request.website.sale_get_order() order._recompute_gift_card_lines() return super().cart(**post) def _get_shop_payment_values(self, order, **kwargs): values = super()._get_shop_payment_values(order, **kwargs) values['allow_pay_with_gift_card'] = True return values
42.352941
1,440
551
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Account Sale Timesheet', 'version': '1.0', 'category': 'Account/sale/timesheet', 'summary': 'Account sale timesheet', 'description': 'Bridge created to add the number of invoices linked to an AA to a project form', 'depends': ['account', 'sale_timesheet'], 'data': [ 'views/project_project_views.xml', ], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
29
551
987
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _lt class Project(models.Model): _inherit = 'project.project' invoice_count = fields.Integer(related='analytic_account_id.invoice_count', groups='account.group_account_readonly') # ---------------------------- # Project Updates # ---------------------------- def _get_stat_buttons(self): buttons = super(Project, self)._get_stat_buttons() if self.user_has_groups('account.group_account_readonly'): buttons.append({ 'icon': 'pencil-square-o', 'text': _lt('Invoices'), 'number': self.invoice_count, 'action_type': 'object', 'action': 'action_open_project_invoices', 'show': bool(self.analytic_account_id) and self.invoice_count > 0, 'sequence': 11, }) return buttons
36.555556
987
745
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Saudi Arabia - Point of Sale', 'author': 'Odoo S.A', 'category': 'Accounting/Localizations/Point of Sale', 'description': """ K.S.A. POS Localization ======================================================= """, 'license': 'LGPL-3', 'depends': ['l10n_gcc_pos', 'l10n_sa_invoice'], 'data': [ ], 'assets': { 'web.assets_qweb': [ 'l10n_sa_pos/static/src/xml/OrderReceipt.xml', ], 'point_of_sale.assets': [ 'web/static/lib/zxing-library/zxing-library.js', 'l10n_sa_pos/static/src/js/models.js', ] }, 'auto_install': True, }
29.8
745
497
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 from odoo.tools.translate import _ class pos_config(models.Model): _inherit = 'pos.config' def open_ui(self): for config in self: if not config.company_id.country_id: raise UserError(_("You have to set a country in your company setting.")) return super(pos_config, self).open_ui()
33.133333
497
443
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 from odoo import fields, api, models class POSOrder(models.Model): _inherit = 'pos.order' def _prepare_invoice_vals(self): vals = super()._prepare_invoice_vals() if self.company_id.country_id.code == 'SA': vals.update({'l10n_sa_confirmation_datetime': self.date_order}) return vals
29.533333
443
679
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Hong Kong - Accounting', 'version': '1.0', 'category': 'Accounting/Localizations/Account Charts', 'description': """ This is the base module to manage chart of accounting and localization for Hong Kong """, 'author': 'Odoo SA', 'depends': ['account'], 'data': [ 'data/account_chart_template_data.xml', 'data/account.account.template.csv', 'data/l10n_hk_chart_data.xml', 'data/account_chart_template_configure_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
32.333333
679
517
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'SMS in CRM', 'version': '1.1', 'category': 'Sales/CRM', 'summary': 'Add SMS capabilities to CRM', 'description': "", 'depends': ['crm', 'sms'], 'data': [ 'views/crm_lead_views.xml', 'security/ir.model.access.csv', 'security/sms_security.xml', ], 'installable': True, 'application': False, 'auto_install': True, 'license': 'LGPL-3', }
25.85
517
1,222
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.crm.tests.common import TestCrmCommon from odoo.tests.common import users class TestCRMLead(TestCrmCommon): @users('user_sales_manager') def test_phone_mobile_update(self): lead = self.env['crm.lead'].create({ 'name': 'Lead 1', 'country_id': self.env.ref('base.us').id, 'phone': self.test_phone_data[0], }) self.assertEqual(lead.phone, self.test_phone_data[0]) self.assertFalse(lead.mobile) self.assertEqual(lead.phone_sanitized, self.test_phone_data_sanitized[0]) lead.write({'phone': False, 'mobile': self.test_phone_data[1]}) self.assertFalse(lead.phone) self.assertEqual(lead.mobile, self.test_phone_data[1]) self.assertEqual(lead.phone_sanitized, self.test_phone_data_sanitized[1]) lead.write({'phone': self.test_phone_data[1], 'mobile': self.test_phone_data[2]}) self.assertEqual(lead.phone, self.test_phone_data[1]) self.assertEqual(lead.mobile, self.test_phone_data[2]) self.assertEqual(lead.phone_sanitized, self.test_phone_data_sanitized[2])
42.137931
1,222
576
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Purchase and Subcontracting Management', 'version': '0.1', 'category': 'Manufacturing/Purchase', 'description': """ This bridge module adds some smart buttons between Purchase and Subcontracting """, 'depends': ['mrp_subcontracting', 'purchase_mrp'], 'data': [ 'views/purchase_order_views.xml', 'views/stock_picking_views.xml', ], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
30.315789
576
8,328
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import Command from odoo.exceptions import UserError from odoo.tests import Form from odoo.addons.mrp_subcontracting.tests.common import TestMrpSubcontractingCommon class MrpSubcontractingPurchaseTest(TestMrpSubcontractingCommon): def setUp(self): super().setUp() # todo 15.0: move in `mrp_subcontracting_purchase` if 'purchase.order' not in self.env: self.skipTest('`purchase` is not installed') self.finished2, self.comp3 = self.env['product.product'].create([{ 'name': 'SuperProduct', 'type': 'product', }, { 'name': 'Component', 'type': 'consu', }]) self.bom_finished2 = self.env['mrp.bom'].create({ 'product_tmpl_id': self.finished2.product_tmpl_id.id, 'type': 'subcontract', 'subcontractor_ids': [(6, 0, self.subcontractor_partner1.ids)], 'bom_line_ids': [(0, 0, { 'product_id': self.comp3.id, 'product_qty': 1, })], }) def test_count_smart_buttons(self): resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')]) (self.comp1 + self.comp2).write({'route_ids': [Command.link(resupply_sub_on_order_route.id)]}) # I create a draft Purchase Order for first in move for 10 kg at 50 euro po = self.env['purchase.order'].create({ 'partner_id': self.subcontractor_partner1.id, 'order_line': [Command.create({ 'name': 'finished', 'product_id': self.finished.id, 'product_qty': 1.0, 'product_uom': self.finished.uom_id.id, 'price_unit': 50.0} )], }) po.button_confirm() self.assertEqual(po.subcontracting_resupply_picking_count, 1) action1 = po.action_view_subcontracting_resupply() picking = self.env[action1['res_model']].browse(action1['res_id']) self.assertEqual(picking.subcontracting_source_purchase_count, 1) action2 = picking.action_view_subcontracting_source_purchase() po_action2 = self.env[action2['res_model']].browse(action2['res_id']) self.assertEqual(po_action2, po) def test_decrease_qty(self): """ Tests when a PO for a subcontracted product has its qty decreased after confirmation """ product_qty = 5.0 po = self.env['purchase.order'].create({ 'partner_id': self.subcontractor_partner1.id, 'order_line': [Command.create({ 'name': 'finished', 'product_id': self.finished.id, 'product_qty': product_qty, 'product_uom': self.finished.uom_id.id, 'price_unit': 50.0} )], }) po.button_confirm() receipt = po.picking_ids sub_mo = receipt._get_subcontract_production() self.assertEqual(len(receipt), 1, "A receipt should have been created") self.assertEqual(receipt.move_lines.product_qty, product_qty, "Qty of subcontracted product to receive is incorrect") self.assertEqual(len(sub_mo), 1, "A subcontracting MO should have been created") self.assertEqual(sub_mo.product_qty, product_qty, "Qty of subcontracted product to produce is incorrect") # create a neg qty to proprogate to receipt lower_qty = product_qty - 1.0 po.order_line.product_qty = lower_qty sub_mos = receipt._get_subcontract_production() self.assertEqual(receipt.move_lines.product_qty, lower_qty, "Qty of subcontracted product to receive should update (not validated yet)") self.assertEqual(len(sub_mos), 1, "Original subcontract MO should have absorbed qty change") self.assertEqual(sub_mo.product_qty, lower_qty, "Qty of subcontract MO should update (none validated yet)") # increase qty again po.order_line.product_qty = product_qty sub_mos = receipt._get_subcontract_production() self.assertEqual(sum(receipt.move_lines.mapped('product_qty')), product_qty, "Qty of subcontracted product to receive should update (not validated yet)") self.assertEqual(len(sub_mos), 2, "A new subcontracting MO should have been created") # check that a neg qty can't proprogate once receipt is done for move in receipt.move_lines: move.move_line_ids.qty_done = move.product_qty receipt.button_validate() self.assertEqual(receipt.state, 'done') self.assertEqual(sub_mos[0].state, 'done') self.assertEqual(sub_mos[1].state, 'done') with self.assertRaises(UserError): po.order_line.product_qty = lower_qty def test_purchase_and_return01(self): """ The user buys 10 x a subcontracted product P. He receives the 10 products and then does a return with 3 x P. The test ensures that the final received quantity is correctly computed """ po = self.env['purchase.order'].create({ 'partner_id': self.subcontractor_partner1.id, 'order_line': [(0, 0, { 'name': self.finished2.name, 'product_id': self.finished2.id, 'product_uom_qty': 10, 'product_uom': self.finished2.uom_id.id, 'price_unit': 1, })], }) po.button_confirm() mo = self.env['mrp.production'].search([('bom_id', '=', self.bom_finished2.id)]) self.assertTrue(mo) receipt = po.picking_ids receipt.move_lines.quantity_done = 10 receipt.button_validate() return_form = Form(self.env['stock.return.picking'].with_context(active_id=receipt.id, active_model='stock.picking')) with return_form.product_return_moves.edit(0) as line: line.quantity = 3 line.to_refund = True return_wizard = return_form.save() return_id, _ = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_id) return_picking.move_lines.quantity_done = 3 return_picking.button_validate() self.assertEqual(self.finished2.qty_available, 7.0) self.assertEqual(po.order_line.qty_received, 7.0) def test_purchase_and_return02(self): """ The user buys 10 x a subcontracted product P. He receives the 10 products and then does a return with 3 x P (with the flag to_refund disabled and the subcontracting location as return location). The test ensures that the final received quantity is correctly computed """ grp_multi_loc = self.env.ref('stock.group_stock_multi_locations') self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]}) po = self.env['purchase.order'].create({ 'partner_id': self.subcontractor_partner1.id, 'order_line': [(0, 0, { 'name': self.finished2.name, 'product_id': self.finished2.id, 'product_uom_qty': 10, 'product_uom': self.finished2.uom_id.id, 'price_unit': 1, })], }) po.button_confirm() mo = self.env['mrp.production'].search([('bom_id', '=', self.bom_finished2.id)]) self.assertTrue(mo) receipt = po.picking_ids receipt.move_lines.quantity_done = 10 receipt.button_validate() return_form = Form(self.env['stock.return.picking'].with_context(active_id=receipt.id, active_model='stock.picking')) return_form.location_id = self.env.company.subcontracting_location_id with return_form.product_return_moves.edit(0) as line: line.quantity = 3 line.to_refund = False return_wizard = return_form.save() return_id, _ = return_wizard._create_returns() return_picking = self.env['stock.picking'].browse(return_id) return_picking.move_lines.quantity_done = 3 return_picking.button_validate() self.assertEqual(self.finished2.qty_available, 7.0) self.assertEqual(po.order_line.qty_received, 10.0)
43.375
8,328
1,415
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 PurchaseOrder(models.Model): _inherit = 'purchase.order' subcontracting_resupply_picking_count = fields.Integer( "Count of Subcontracting Resupply", compute='_compute_subcontracting_resupply_picking_count', help="Count of Subcontracting Resupply for component") @api.depends('order_line.move_ids') def _compute_subcontracting_resupply_picking_count(self): for purchase in self: purchase.subcontracting_resupply_picking_count = len(purchase._get_subcontracting_resupplies()) def action_view_subcontracting_resupply(self): return self._get_action_view_picking(self._get_subcontracting_resupplies()) def _get_subcontracting_resupplies(self): moves_subcontracted = self.order_line.move_ids.filtered(lambda m: m.is_subcontract) subcontracted_productions = moves_subcontracted.move_orig_ids.production_id return subcontracted_productions.picking_ids def _get_mrp_productions(self, **kwargs): productions = super()._get_mrp_productions(**kwargs) if kwargs.get('remove_archived_picking_types', True): productions = productions.filtered(lambda production: production.with_context(active_test=False).picking_type_id.active) return productions
45.645161
1,415
1,637
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 StockPicking(models.Model): _inherit = 'stock.picking' subcontracting_source_purchase_count = fields.Integer( "Number of subcontracting PO Source", compute='_compute_subcontracting_source_purchase_count', help="Number of subcontracting Purchase Order Source") @api.depends('move_lines.move_dest_ids.raw_material_production_id') def _compute_subcontracting_source_purchase_count(self): for picking in self: picking.subcontracting_source_purchase_count = len(picking._get_subcontracting_source_purchase()) def action_view_subcontracting_source_purchase(self): purchase_order_ids = self._get_subcontracting_source_purchase().ids action = { 'res_model': 'purchase.order', 'type': 'ir.actions.act_window', } if len(purchase_order_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': purchase_order_ids[0], }) else: action.update({ 'name': _("Source PO of %s", self.name), 'domain': [('id', 'in', purchase_order_ids)], 'view_mode': 'tree,form', }) return action def _get_subcontracting_source_purchase(self): moves_subcontracted = self.move_lines.move_dest_ids.raw_material_production_id.move_finished_ids.move_dest_ids.filtered(lambda m: m.is_subcontract) return moves_subcontracted.purchase_line_id.order_id
40.925
1,637
904
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Unsplash Image Library', 'category': 'Hidden', 'summary': 'Find free high-resolution images from Unsplash', 'version': '1.1', 'description': """Explore the free high-resolution image library of Unsplash.com and find images to use in Odoo. An Unsplash search bar is added to the image library modal.""", 'depends': ['base_setup', 'web_editor'], 'data': [ 'views/res_config_settings_view.xml', ], 'auto_install': True, 'assets': { 'web_editor.assets_wysiwyg': [ 'web_unsplash/static/src/js/unsplashapi.js', 'web_unsplash/static/src/js/unsplash_image_widget.js', ], 'web.assets_frontend': [ 'web_unsplash/static/src/js/unsplash_beacon.js', ], }, 'license': 'LGPL-3', }
37.666667
904
977
py
PYTHON
15.0
from werkzeug import urls from odoo import models, api class Image(models.AbstractModel): _inherit = 'ir.qweb.field.image' @api.model def from_html(self, model, field, element): if element.find('.//img') is None: return False url = element.find('.//img').get('src') url_object = urls.url_parse(url) if url_object.path.startswith('/unsplash/'): res_id = element.get('data-oe-id') if res_id: res_id = int(res_id) res_model = model._name attachment = self.env['ir.attachment'].search([ '&', '|', '&', ('res_model', '=', res_model), ('res_id', '=', res_id), ('public', '=', True), ('url', '=', url_object.path), ], limit=1) return attachment.datas return super(Image, self).from_html(model, field, element)
32.566667
977
804
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ResUsers(models.Model): _inherit = 'res.users' def _has_unsplash_key_rights(self, mode='write'): self.ensure_one() # Website has no dependency to web_unsplash, we cannot warranty the order of the execution # of the overwrite done in 5ef8300. # So to avoid to create a new module bridge, with a lot of code, we prefer to make a check # here for website's user. assert mode in ('read', 'write') website_group_required = (mode == 'write') and 'website.group_website_designer' or 'website.group_website_publisher' return self.has_group('base.group_erp_manager') or self.has_group(website_group_required)
47.294118
804
311
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' unsplash_access_key = fields.Char("Access Key", config_parameter='unsplash.access_key')
34.555556
311
6,147
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import logging import mimetypes import requests import werkzeug.utils from odoo import http, tools, _ from odoo.http import request from odoo.tools.mimetypes import guess_mimetype from werkzeug.urls import url_encode logger = logging.getLogger(__name__) class Web_Unsplash(http.Controller): def _get_access_key(self): if request.env.user._has_unsplash_key_rights(mode='read'): return request.env['ir.config_parameter'].sudo().get_param('unsplash.access_key') raise werkzeug.exceptions.NotFound() def _notify_download(self, url): ''' Notifies Unsplash from an image download. (API requirement) :param url: the download_url of the image to be notified This method won't return anything. This endpoint should just be pinged with a simple GET request for Unsplash to increment the image view counter. ''' try: if not url.startswith('https://api.unsplash.com/photos/') and not request.env.registry.in_test_mode(): raise Exception(_("ERROR: Unknown Unsplash notify URL!")) access_key = self._get_access_key() requests.get(url, params=url_encode({'client_id': access_key})) except Exception as e: logger.exception("Unsplash download notification failed: " + str(e)) # ------------------------------------------------------ # add unsplash image url # ------------------------------------------------------ @http.route('/web_unsplash/attachment/add', type='json', auth='user', methods=['POST']) def save_unsplash_url(self, unsplashurls=None, **kwargs): """ unsplashurls = { image_id1: { url: image_url, download_url: download_url, }, image_id2: { url: image_url, download_url: download_url, }, ..... } """ def slugify(s): ''' Keeps only alphanumeric characters, hyphens and spaces from a string. The string will also be truncated to 1024 characters max. :param s: the string to be filtered :return: the sanitized string ''' return "".join([c for c in s if c.isalnum() or c in list("- ")])[:1024] if not unsplashurls: return [] uploads = [] Attachments = request.env['ir.attachment'] query = kwargs.get('query', '') query = slugify(query) res_model = kwargs.get('res_model', 'ir.ui.view') if res_model != 'ir.ui.view' and kwargs.get('res_id'): res_id = int(kwargs['res_id']) else: res_id = None for key, value in unsplashurls.items(): url = value.get('url') try: if not url.startswith(('https://images.unsplash.com/', 'https://plus.unsplash.com/')) and not request.env.registry.in_test_mode(): logger.exception("ERROR: Unknown Unsplash URL!: " + url) raise Exception(_("ERROR: Unknown Unsplash URL!")) req = requests.get(url) if req.status_code != requests.codes.ok: continue # get mime-type of image url because unsplash url dosn't contains mime-types in url image_base64 = base64.b64encode(req.content) except requests.exceptions.ConnectionError as e: logger.exception("Connection Error: " + str(e)) continue except requests.exceptions.Timeout as e: logger.exception("Timeout: " + str(e)) continue image_base64 = tools.image_process(image_base64, verify_resolution=True) mimetype = guess_mimetype(base64.b64decode(image_base64)) # append image extension in name query += mimetypes.guess_extension(mimetype) or '' # /unsplash/5gR788gfd/lion url_frags = ['unsplash', key, query] attachment = Attachments.create({ 'name': '_'.join(url_frags), 'url': '/' + '/'.join(url_frags), 'mimetype': mimetype, 'datas': image_base64, 'public': res_model == 'ir.ui.view', 'res_id': res_id, 'res_model': res_model, 'description': value.get('description'), }) attachment.generate_access_token() uploads.append(attachment._get_media_info()) # Notifies Unsplash from an image download. (API requirement) self._notify_download(value.get('download_url')) return uploads @http.route("/web_unsplash/fetch_images", type='json', auth="user") def fetch_unsplash_images(self, **post): access_key = self._get_access_key() app_id = self.get_unsplash_app_id() if not access_key or not app_id: return {'error': 'key_not_found'} post['client_id'] = access_key response = requests.get('https://api.unsplash.com/search/photos/', params=url_encode(post)) if response.status_code == requests.codes.ok: return response.json() else: return {'error': response.status_code} @http.route("/web_unsplash/get_app_id", type='json', auth="public") def get_unsplash_app_id(self, **post): return request.env['ir.config_parameter'].sudo().get_param('unsplash.app_id') @http.route("/web_unsplash/save_unsplash", type='json', auth="user") def save_unsplash(self, **post): if request.env.user._has_unsplash_key_rights(mode='write'): request.env['ir.config_parameter'].sudo().set_param('unsplash.app_id', post.get('appId')) request.env['ir.config_parameter'].sudo().set_param('unsplash.access_key', post.get('key')) return True raise werkzeug.exceptions.NotFound()
40.98
6,147
1,295
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Website Sale Product Configurator", 'summary': """ Bridge module for website_sale / sale_product_configurator""", 'description': """ Bridge module to make the website e-commerce compatible with the product configurator """, 'category': 'Hidden', 'version': '0.1', 'depends': ['website_sale', 'sale_product_configurator'], 'auto_install': True, 'data': [ 'views/website_sale_product_configurator_templates.xml', ], 'demo': [ 'data/demo.xml', ], 'assets': { 'web.assets_frontend': [ ('before', 'website_sale/static/src/js/website_sale.js', 'sale_product_configurator/static/src/js/product_configurator_modal.js'), ('before', 'website_sale/static/src/js/website_sale.js', 'website_sale_product_configurator/static/src/js/product_configurator_modal.js'), 'sale/static/src/scss/product_configurator.scss', 'website_sale_product_configurator/static/src/scss/website_sale_options.scss', 'website_sale_product_configurator/static/src/js/website_sale_options.js', ], 'web.assets_tests': [ 'website_sale_product_configurator/static/tests/**/*', ], }, 'license': 'LGPL-3', }
40.46875
1,295
6,138
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.sale_product_configurator.tests.common import TestProductConfiguratorCommon from odoo.addons.base.tests.common import HttpCaseWithUserPortal @tagged('post_install', '-at_install') class TestWebsiteSaleProductConfigurator(TestProductConfiguratorCommon, HttpCaseWithUserPortal): @classmethod def setUpClass(cls): super().setUpClass() cls.product_product_custo_desk.write({ 'optional_product_ids': [(4, cls.product_product_conf_chair.id)], 'website_published': True, }) cls.product_product_conf_chair.website_published = True ptav_ids = cls.product_product_custo_desk.attribute_line_ids.product_template_value_ids ptav_ids.filtered(lambda ptav: ptav.name == 'Aluminium').price_extra = 50.4 def test_01_product_configurator_variant_price(self): product = self.product_product_conf_chair.with_user(self.user_portal) ptav_ids = self.product_product_custo_desk.attribute_line_ids.product_template_value_ids parent_combination = ptav_ids.filtered(lambda ptav: ptav.name in ('Aluminium', 'White')) self.assertEqual(product._is_add_to_cart_possible(parent_combination), True) # This is a regression test. The product configurator menu is proposed # whenever a product has optional products. However, as the end user # already picked a variant, the variant configuration menu is omitted # in this case. However, we still want to make sure that the correct # variant attributes are taken into account when calculating the price. url = self.product_product_custo_desk.website_url self.start_tour(url, 'website_sale_product_configurator_optional_products_tour', login='portal') def test_02_variants_modal_window(self): """ The objective is to verify that the data concerning the variants are well transmitted even when passing through a modal window (product configurator). We create a product with the different attributes and we will modify them. If the information is not correctly transmitted, the default values of the variants will be used (the first one). """ always_attribute, dynamic_attribute, never_attribute, never_attribute_custom = self.env['product.attribute'].create([ { 'name': 'Always attribute size', 'display_type': 'radio', 'create_variant': 'always' }, { 'name': 'Dynamic attribute size', 'display_type': 'radio', 'create_variant': 'dynamic' }, { 'name': 'Never attribute size', 'display_type': 'radio', 'create_variant': 'no_variant' }, { 'name': 'Never attribute size custom', 'display_type': 'radio', 'create_variant': 'no_variant' } ]) always_S, always_M, dynamic_S, dynamic_M, never_S, never_M, never_custom_no, never_custom_yes = self.env['product.attribute.value'].create([ { 'name': 'S always', 'attribute_id': always_attribute.id, }, { 'name': 'M always', 'attribute_id': always_attribute.id, }, { 'name': 'S dynamic', 'attribute_id': dynamic_attribute.id, }, { 'name': 'M dynamic', 'attribute_id': dynamic_attribute.id, }, { 'name': 'S never', 'attribute_id': never_attribute.id, }, { 'name': 'M never', 'attribute_id': never_attribute.id, }, { 'name': 'No never custom', 'attribute_id': never_attribute_custom.id, }, { 'name': 'Yes never custom', 'attribute_id': never_attribute_custom.id, 'is_custom': True, } ]) product_short = self.env['product.template'].create({ 'name': 'Short (TEST)', 'website_published': True, }) self.env['product.template.attribute.line'].create([ { 'product_tmpl_id': product_short.id, 'attribute_id': always_attribute.id, 'value_ids': [(4, always_S.id), (4, always_M.id)], }, { 'product_tmpl_id': product_short.id, 'attribute_id': dynamic_attribute.id, 'value_ids': [(4, dynamic_S.id), (4, dynamic_M.id)], }, { 'product_tmpl_id': product_short.id, 'attribute_id': never_attribute.id, 'value_ids': [(4, never_S.id), (4, never_M.id)], }, { 'product_tmpl_id': product_short.id, 'attribute_id': never_attribute_custom.id, 'value_ids': [(4, never_custom_no.id), (4, never_custom_yes.id)], }, ]) # Add an optional product to trigger the modal window optional_product = self.env['product.template'].create({ 'name': 'Optional product (TEST)', 'website_published': True, }) product_short.optional_product_ids = [(4, optional_product.id)] old_sale_order = self.env['sale.order'].search([]) self.start_tour("/", 'tour_variants_modal_window', login="demo") # Check the name of the created sale order line new_sale_order = self.env['sale.order'].search([]) - old_sale_order new_order_line = new_sale_order.order_line self.assertEqual(new_order_line.name, 'Short (TEST) (M always, M dynamic)\n\nNever attribute size: M never\nNever attribute size custom: Yes never custom: TEST')
42.331034
6,138
716
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import HttpCase from odoo.addons.sale_product_configurator.tests.common import TestProductConfiguratorCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestUi(HttpCase, TestProductConfiguratorCommon): def test_01_admin_shop_custom_attribute_value_tour(self): # fix runbot, sometimes one pricelist is chosen, sometimes the other... pricelists = self.env['website'].get_current_website().get_current_pricelist() | self.env.ref('product.list0') self._create_pricelist(pricelists) self.start_tour("/", 'a_shop_custom_attribute_value', login="admin")
47.733333
716
1,077
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 SaleOrder(models.Model): _inherit = "sale.order" def _cart_find_product_line(self, product_id=None, line_id=None, **kwargs): lines = super(SaleOrder, self)._cart_find_product_line(product_id, line_id, **kwargs) if line_id: # in this case we get the exact line we want, so filtering below would be wrong return lines linked_line_id = kwargs.get('linked_line_id', False) optional_product_ids = set(kwargs.get('optional_product_ids', [])) lines = lines.filtered(lambda line: line.linked_line_id.id == linked_line_id) if optional_product_ids: # only match the lines with the same chosen optional products on the existing lines lines = lines.filtered(lambda line: optional_product_ids == set(line.mapped('option_line_ids.product_id.id'))) else: lines = lines.filtered(lambda line: not line.option_line_ids) return lines
43.08
1,077
4,983
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from odoo import http from odoo.http import request from odoo.addons.sale_product_configurator.controllers.main import ProductConfiguratorController from odoo.addons.website_sale.controllers import main class WebsiteSaleProductConfiguratorController(ProductConfiguratorController): @http.route(['/sale_product_configurator/show_advanced_configurator_website'], type='json', auth="public", methods=['POST'], website=True) def show_advanced_configurator_website(self, product_id, variant_values, **kw): """Special route to use website logic in get_combination_info override. This route is called in JS by appending _website to the base route. """ kw.pop('pricelist_id') product = request.env['product.product'].browse(int(product_id)) combination = request.env['product.template.attribute.value'].browse(variant_values) has_optional_products = product.optional_product_ids.filtered(lambda p: p._is_add_to_cart_possible(combination)) if not has_optional_products and (product.product_variant_count <= 1 or variant_values): # The modal is not shown if there are no optional products and # the main product either has no variants or is already configured return False if variant_values: kw["already_configured"] = True return self.show_advanced_configurator(product_id, variant_values, request.website.get_current_pricelist(), **kw) @http.route(['/sale_product_configurator/optional_product_items_website'], type='json', auth="public", methods=['POST'], website=True) def optional_product_items_website(self, product_id, **kw): """Special route to use website logic in get_combination_info override. This route is called in JS by appending _website to the base route. """ kw.pop('pricelist_id') return self.optional_product_items(product_id, request.website.get_current_pricelist(), **kw) class WebsiteSale(main.WebsiteSale): def _prepare_product_values(self, product, category, search, **kwargs): values = super(WebsiteSale, self)._prepare_product_values(product, category, search, **kwargs) values['optional_product_ids'] = [p.with_context(active_id=p.id) for p in product.optional_product_ids] return values @http.route(['/shop/cart/update_option'], type='http', auth="public", methods=['POST'], website=True, multilang=False) def cart_options_update_json(self, product_and_options, goto_shop=None, lang=None, **kwargs): """This route is called when submitting the optional product modal. The product without parent is the main product, the other are options. Options need to be linked to their parents with a unique ID. The main product is the first product in the list and the options need to be right after their parent. product_and_options { 'product_id', 'product_template_id', 'quantity', 'parent_unique_id', 'unique_id', 'product_custom_attribute_values', 'no_variant_attribute_values' } """ if lang: request.website = request.website.with_context(lang=lang) order = request.website.sale_get_order(force_create=True) if order.state != 'draft': request.session['sale_order_id'] = None order = request.website.sale_get_order(force_create=True) product_and_options = json.loads(product_and_options) if product_and_options: # The main product is the first, optional products are the rest main_product = product_and_options[0] value = order._cart_update( product_id=main_product['product_id'], add_qty=main_product['quantity'], product_custom_attribute_values=main_product['product_custom_attribute_values'], no_variant_attribute_values=main_product['no_variant_attribute_values'], ) # Link option with its parent. option_parent = {main_product['unique_id']: value['line_id']} for option in product_and_options[1:]: parent_unique_id = option['parent_unique_id'] option_value = order._cart_update( product_id=option['product_id'], set_qty=option['quantity'], linked_line_id=option_parent[parent_unique_id], product_custom_attribute_values=option['product_custom_attribute_values'], no_variant_attribute_values=option['no_variant_attribute_values'], ) option_parent[option['unique_id']] = option_value['line_id'] return str(order.cart_quantity)
52.452632
4,983
714
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Online Members Directory', 'category': 'Website/Website', 'summary': 'Publish your members directory', 'version': '1.0', 'description': """ Publish your members/association directory publicly. """, 'depends': ['website_partner', 'website_google_map', 'association', 'website_sale'], 'data': [ 'views/product_template_views.xml', 'views/website_membership_templates.xml', 'security/ir.model.access.csv', 'security/website_membership.xml', ], 'demo': ['data/membership_demo.xml'], 'installable': True, 'license': 'LGPL-3', }
32.454545
714
499
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((_('Members'), url_for('/members'), 'website_membership')) return suggested_controllers
35.642857
499
716
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class MembershipLine(models.Model): _inherit = 'membership.membership_line' def _get_published_companies(self, limit=None): if not self.ids: return [] limit_clause = '' if limit is None else ' LIMIT %d' % limit self.env.cr.execute(""" SELECT DISTINCT p.id FROM res_partner p INNER JOIN membership_membership_line m ON p.id = m.partner WHERE is_published AND is_company AND m.id IN %s """ + limit_clause, (tuple(self.ids),)) return [partner_id[0] for partner_id in self.env.cr.fetchall()]
37.684211
716
8,315
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import werkzeug.urls from odoo import fields from odoo import http from odoo.http import request from odoo.addons.http_routing.models.ir_http import unslug from odoo.tools.translate import _ class WebsiteMembership(http.Controller): _references_per_page = 20 @http.route([ '/members', '/members/page/<int:page>', '/members/association/<membership_id>', '/members/association/<membership_id>/page/<int:page>', '/members/country/<int:country_id>', '/members/country/<country_name>-<int:country_id>', '/members/country/<int:country_id>/page/<int:page>', '/members/country/<country_name>-<int:country_id>/page/<int:page>', '/members/association/<membership_id>/country/<country_name>-<int:country_id>', '/members/association/<membership_id>/country/<int:country_id>', '/members/association/<membership_id>/country/<country_name>-<int:country_id>/page/<int:page>', '/members/association/<membership_id>/country/<int:country_id>/page/<int:page>', ], type='http', auth="public", website=True, sitemap=True) def members(self, membership_id=None, country_name=None, country_id=0, page=1, **post): Product = request.env['product.product'] Country = request.env['res.country'] MembershipLine = request.env['membership.membership_line'] Partner = request.env['res.partner'] post_name = post.get('search') or post.get('name', '') current_country = None today = fields.Date.today() # base domain for groupby / searches base_line_domain = [ ("partner.website_published", "=", True), ('state', '=', 'paid'), ('date_to', '>=', today), ('date_from', '<=', today) ] if membership_id and membership_id != 'free': membership_id = int(membership_id) base_line_domain.append(('membership_id', '=', membership_id)) if post_name: base_line_domain += ['|', ('partner.name', 'ilike', post_name), ('partner.website_description', 'ilike', post_name)] # group by country, based on all customers (base domain) if membership_id != 'free': membership_lines = MembershipLine.sudo().search(base_line_domain) country_domain = [('member_lines', 'in', membership_lines.ids)] if not membership_id: country_domain = ['|', country_domain[0], ('membership_state', '=', 'free')] else: country_domain = [('membership_state', '=', 'free')] if post_name: country_domain += ['|', ('name', 'ilike', post_name), ('website_description', 'ilike', post_name)] countries = Partner.sudo().read_group(country_domain + [("website_published", "=", True)], ["id", "country_id"], groupby="country_id", orderby="country_id") countries_total = sum(country_dict['country_id_count'] for country_dict in countries) line_domain = list(base_line_domain) if country_id: line_domain.append(('partner.country_id', '=', country_id)) current_country = Country.browse(country_id).read(['id', 'name'])[0] if not any(x['country_id'][0] == country_id for x in countries if x['country_id']): countries.append({ 'country_id_count': 0, 'country_id': (country_id, current_country["name"]) }) countries = [d for d in countries if d['country_id']] countries.sort(key=lambda d: d['country_id'][1]) countries.insert(0, { 'country_id_count': countries_total, 'country_id': (0, _("All Countries")) }) # format domain for group_by and memberships memberships = Product.search([('membership', '=', True)], order="website_sequence") # make sure we don't access to lines with unpublished membershipts line_domain.append(('membership_id', 'in', memberships.ids)) limit = self._references_per_page offset = limit * (page - 1) count_members = 0 membership_lines = MembershipLine.sudo() # displayed non-free membership lines if membership_id != 'free': count_members = MembershipLine.sudo().search_count(line_domain) if offset <= count_members: membership_lines = MembershipLine.sudo().search(line_domain, offset, limit) page_partner_ids = set(m.partner.id for m in membership_lines) # get google maps localization of partners google_map_partner_ids = [] if request.website.is_view_active('website_membership.opt_index_google_map'): google_map_partner_ids = MembershipLine.search(line_domain)._get_published_companies(limit=2000) search_domain = [('membership_state', '=', 'free'), ('website_published', '=', True)] if post_name: search_domain += ['|', ('name', 'ilike', post_name), ('website_description', 'ilike', post_name)] if country_id: search_domain += [('country_id', '=', country_id)] free_partners = Partner.sudo().search(search_domain) memberships_data = [] for membership_record in memberships: memberships_data.append({'id': membership_record.id, 'name': membership_record.name}) memberships_partner_ids = {} for line in membership_lines: memberships_partner_ids.setdefault(line.membership_id.id, []).append(line.partner.id) if free_partners: memberships_data.append({'id': 'free', 'name': _('Free Members')}) if not membership_id or membership_id == 'free': if count_members < offset + limit: free_start = max(offset - count_members, 0) free_end = max(offset + limit - count_members, 0) memberships_partner_ids['free'] = free_partners.ids[free_start:free_end] page_partner_ids |= set(memberships_partner_ids['free']) google_map_partner_ids += free_partners.ids[:2000-len(google_map_partner_ids)] count_members += len(free_partners) google_map_partner_ids = ",".join(str(it) for it in google_map_partner_ids) google_maps_api_key = request.website.google_maps_api_key partners = {p.id: p for p in Partner.sudo().browse(list(page_partner_ids))} base_url = '/members%s%s' % ('/association/%s' % membership_id if membership_id else '', '/country/%s' % country_id if country_id else '') # request pager for lines pager = request.website.pager(url=base_url, total=count_members, page=page, step=limit, scope=7, url_args=post) values = { 'partners': partners, 'memberships_data': memberships_data, 'memberships_partner_ids': memberships_partner_ids, 'membership_id': membership_id, 'countries': countries, 'current_country': current_country and [current_country['id'], current_country['name']] or None, 'current_country_id': current_country and current_country['id'] or 0, 'google_map_partner_ids': google_map_partner_ids, 'pager': pager, 'post': post, 'search': "?%s" % werkzeug.urls.url_encode(post), 'search_count': count_members, 'google_maps_api_key': google_maps_api_key, } return request.render("website_membership.index", values) # Do not use semantic controller due to SUPERUSER_ID @http.route(['/members/<partner_id>'], type='http', auth="public", website=True) def partners_detail(self, partner_id, **post): _, partner_id = unslug(partner_id) if partner_id: partner = request.env['res.partner'].sudo().browse(partner_id) if partner.exists() and partner.website_published: # TODO should be done with access rules values = {} values['main_object'] = values['partner'] = partner return request.render("website_membership.partner", values) return self.members(**post)
48.063584
8,315
1,700
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Events Sales', 'version': '1.2', 'category': 'Marketing/Events', 'website': 'https://www.odoo.com/app/events', 'description': """ Creating registration with sales orders. ======================================== This module allows you to automate and connect your registration creation with your main sale flow and therefore, to enable the invoicing feature of registrations. It defines a new kind of service products that offers you the possibility to choose an event category associated with it. When you encode a sales order for that product, you will be able to choose an existing event of that category and when you confirm your sales order it will automatically create a registration for this event. """, 'depends': ['event', 'sale_management'], 'data': [ 'views/event_ticket_views.xml', 'views/event_registration_views.xml', 'views/event_views.xml', 'views/sale_order_views.xml', 'data/event_sale_data.xml', 'data/mail_data.xml', 'report/event_event_templates.xml', 'security/ir.model.access.csv', 'security/event_security.xml', 'wizard/event_edit_registration.xml', 'wizard/event_configurator_views.xml', ], 'demo': ['data/event_demo.xml'], 'installable': True, 'auto_install': True, 'assets': { 'web.assets_backend': [ 'event_sale/static/src/**/*', ], 'web.assets_tests': [ 'event_sale/static/tests/tours/**/*', ], 'web.qunit_suite_tests': [ 'event_sale/static/tests/event_configurator.test.js', ], }, 'license': 'LGPL-3', }
34
1,700
12,071
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.event_sale.tests.common import TestEventSaleCommon from odoo.addons.mail.tests.common import mail_new_test_user from odoo.tests import tagged from odoo.tests.common import users @tagged('event_flow') class TestEventSale(TestEventSaleCommon): @classmethod def setUpClass(cls): super(TestEventSale, cls).setUpClass() product = cls.env['product.product'].create({ 'name': 'Event', 'detailed_type': 'event', }) cls.user_salesperson = mail_new_test_user(cls.env, login='user_salesman', groups='sales_team.group_sale_salesman') cls.ticket = cls.env['event.event.ticket'].create({ 'name': 'First Ticket', 'product_id': cls.event_product.id, 'seats_max': 30, 'event_id': cls.event_0.id, }) cls.event_0.write({ 'event_ticket_ids': [ (6, 0, cls.ticket.ids), (0, 0, { 'name': 'Second Ticket', 'product_id': cls.event_product.id, }) ], }) cls.sale_order = cls.env['sale.order'].create({ 'partner_id': cls.env.ref('base.res_partner_2').id, 'note': 'Invoice after delivery', 'payment_term_id': cls.env.ref('account.account_payment_term_end_following_month').id }) # In the sales order I add some sales order lines. i choose event product cls.env['sale.order.line'].create({ 'product_id': product.id, 'price_unit': 190.50, 'product_uom': cls.env.ref('uom.product_uom_unit').id, 'product_uom_qty': 1.0, 'order_id': cls.sale_order.id, 'name': 'sales order line', 'event_id': cls.event_0.id, 'event_ticket_id': cls.ticket.id, }) cls.register_person = cls.env['registration.editor'].create({ 'sale_order_id': cls.sale_order.id, 'event_registration_ids': [(0, 0, { 'event_id': cls.event_0.id, 'name': 'Administrator', 'email': '[email protected]', 'sale_order_line_id': cls.sale_order.order_line.id, })], }) # make a SO for a customer, selling some tickets cls.customer_so = cls.env['sale.order'].with_user(cls.user_sales_salesman).create({ 'partner_id': cls.event_customer.id, }) @users('user_sales_salesman') def test_event_crm_sale(self): TICKET1_COUNT, TICKET2_COUNT = 3, 1 customer_so = self.customer_so.with_user(self.env.user) ticket1 = self.event_0.event_ticket_ids[0] ticket2 = self.event_0.event_ticket_ids[1] # PREPARE SO DATA # ------------------------------------------------------------ # adding some tickets to SO customer_so.write({ 'order_line': [ (0, 0, { 'event_id': self.event_0.id, 'event_ticket_id': ticket1.id, 'product_id': ticket1.product_id.id, 'product_uom_qty': TICKET1_COUNT, 'price_unit': 10, }), (0, 0, { 'event_id': self.event_0.id, 'event_ticket_id': ticket2.id, 'product_id': ticket2.product_id.id, 'product_uom_qty': TICKET2_COUNT, 'price_unit': 50, }) ] }) ticket1_line = customer_so.order_line.filtered(lambda line: line.event_ticket_id == ticket1) ticket2_line = customer_so.order_line.filtered(lambda line: line.event_ticket_id == ticket2) self.assertEqual(customer_so.amount_untaxed, TICKET1_COUNT * 10 + TICKET2_COUNT * 50) # one existing registration for first ticket ticket1_reg1 = self.env['event.registration'].create({ 'event_id': self.event_0.id, 'event_ticket_id': ticket1.id, 'partner_id': self.event_customer2.id, 'sale_order_id': customer_so.id, 'sale_order_line_id': ticket1_line.id, }) self.assertEqual(ticket1_reg1.partner_id, self.event_customer) for field in ['name', 'email', 'phone', 'mobile']: self.assertEqual(ticket1_reg1[field], self.event_customer[field]) # EVENT REGISTRATION EDITOR # ------------------------------------------------------------ # use event registration editor to create missing lines and update details editor = self.env['registration.editor'].with_context({ 'default_sale_order_id': customer_so.id }).create({}) self.assertEqual(len(editor.event_registration_ids), TICKET1_COUNT + TICKET2_COUNT) self.assertEqual(editor.sale_order_id, customer_so) self.assertEqual(editor.event_registration_ids.sale_order_line_id, ticket1_line | ticket2_line) # check line linked to existing registration (ticket1_reg1) ticket1_editor_reg1 = editor.event_registration_ids.filtered(lambda line: line.registration_id) for field in ['name', 'email', 'phone', 'mobile']: self.assertEqual(ticket1_editor_reg1[field], ticket1_reg1[field]) # check new lines ticket1_editor_other = editor.event_registration_ids.filtered(lambda line: not line.registration_id and line.event_ticket_id == ticket1) self.assertEqual(len(ticket1_editor_other), 2) ticket2_editor_other = editor.event_registration_ids.filtered(lambda line: not line.registration_id and line.event_ticket_id == ticket2) self.assertEqual(len(ticket2_editor_other), 1) # update lines in editor and save them ticket1_editor_other[0].write({ 'name': 'ManualEntry1', 'email': '[email protected]', 'phone': '+32456111111', }) ticket1_editor_other[1].write({ 'name': 'ManualEntry2', 'email': '[email protected]', 'mobile': '+32456222222', }) editor.action_make_registration() # check editor correctly created new registrations with information coming from it or SO as fallback self.assertEqual(len(self.event_0.registration_ids), TICKET1_COUNT + TICKET2_COUNT) new_registrations = self.event_0.registration_ids - ticket1_reg1 self.assertEqual(new_registrations.sale_order_id, customer_so) ticket1_new_reg = new_registrations.filtered(lambda reg: reg.event_ticket_id == ticket1) ticket2_new_reg = new_registrations.filtered(lambda reg: reg.event_ticket_id == ticket2) self.assertEqual(len(ticket1_new_reg), 2) self.assertEqual(len(ticket2_new_reg), 1) self.assertEqual( set(ticket1_new_reg.mapped('name')), set(['ManualEntry1', 'ManualEntry2']) ) self.assertEqual( set(ticket1_new_reg.mapped('email')), set(['[email protected]', '[email protected]']) ) self.assertEqual( set(ticket1_new_reg.mapped('phone')), set(['+32456111111', self.event_customer.phone]) ) self.assertEqual( set(ticket1_new_reg.mapped('mobile')), set(['+32456222222', self.event_customer.mobile]) ) for field in ['name', 'email', 'phone', 'mobile']: self.assertEqual(ticket2_new_reg[field], self.event_customer[field]) # ADDING MANUAL LINES ON SO # ------------------------------------------------------------ ticket2_line.write({'product_uom_qty': 3}) editor_action = customer_so.action_confirm() self.assertEqual(customer_so.state, 'sale') self.assertEqual(customer_so.amount_untaxed, TICKET1_COUNT * 10 + (TICKET2_COUNT + 2) * 50) # check confirm of SO correctly created new registrations with information coming from SO self.assertEqual(len(self.event_0.registration_ids), 6) # 3 for each ticket now new_registrations = self.event_0.registration_ids - (ticket1_reg1 | ticket1_new_reg | ticket2_new_reg) self.assertEqual(new_registrations.event_ticket_id, ticket2) self.assertEqual(new_registrations.partner_id, self.customer_so.partner_id) self.assertEqual(editor_action['type'], 'ir.actions.act_window') self.assertEqual(editor_action['res_model'], 'registration.editor') def test_ticket_price_with_pricelist_and_tax(self): self.env.user.partner_id.country_id = False pricelist = self.env['product.pricelist'].search([], limit=1) tax = self.env['account.tax'].create({ 'name': "Tax 10", 'amount': 10, }) event_product = self.env['product.template'].create({ 'name': 'Event Product', 'list_price': 10.0, }) event_product.taxes_id = tax event = self.env['event.event'].create({ 'name': 'New Event', 'date_begin': '2020-02-02', 'date_end': '2020-04-04', }) event_ticket = self.env['event.event.ticket'].create({ 'name': 'VIP', 'price': 1000.0, 'event_id': event.id, 'product_id': event_product.product_variant_id.id, }) pricelist.item_ids = self.env['product.pricelist.item'].create({ 'applied_on': "1_product", 'base': "list_price", 'compute_price': "fixed", 'fixed_price': 6.0, 'product_tmpl_id': event_product.id, }) pricelist.discount_policy = 'without_discount' so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, 'pricelist_id': pricelist.id, }) sol = self.env['sale.order.line'].create({ 'name': event.name, 'product_id': event_product.product_variant_id.id, 'product_uom_qty': 1, 'product_uom': event_product.uom_id.id, 'price_unit': event_product.list_price, 'order_id': so.id, 'event_id': event.id, 'event_ticket_id': event_ticket.id, }) sol.product_id_change() self.assertEqual(so.amount_total, 660.0, "Ticket is $1000 but the event product is on a pricelist 10 -> 6. So, $600 + a 10% tax.") @users('user_salesman') def test_unlink_so(self): """ This test ensures that when deleting a sale order, if the latter is linked to an event registration, the number of expected seats will be correctly updated """ event = self.env['event.event'].browse(self.event_0.ids) self.register_person.action_make_registration() self.assertEqual(event.seats_expected, 1) self.sale_order.unlink() self.assertEqual(event.seats_expected, 0) @users('user_salesman') def test_unlink_soline(self): """ This test ensures that when deleting a sale order line, if the latter is linked to an event registration, the number of expected seats will be correctly updated """ event = self.env['event.event'].browse(self.event_0.ids) self.register_person.action_make_registration() self.assertEqual(event.seats_expected, 1) self.sale_order.order_line.unlink() self.assertEqual(event.seats_expected, 0) @users('user_salesman') def test_cancel_so(self): """ This test ensures that when canceling a sale order, if the latter is linked to an event registration, the number of expected seats will be correctly updated """ event = self.env['event.event'].browse(self.event_0.ids) self.register_person.action_make_registration() self.assertEqual(event.seats_expected, 1) self.sale_order.action_cancel() self.assertEqual(event.seats_expected, 0)
42.957295
12,071
2,465
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from dateutil.relativedelta import relativedelta from odoo.addons.event_sale.tests.common import TestEventSaleCommon from odoo.tests.common import Form class TestEventSpecific(TestEventSaleCommon): def test_event_change_max_seat_no_side_effect(self): """ Test that changing the Maximum (seats_max), the seats_reserved of all the ticket do not change """ # Enable "sell tickets with sales orders" so that we have a price column on the tickets # Event template with Form(self.env['event.type']) as event_type_form: event_type_form.name = "Pastafarian Event Template" # Edit the default line with event_type_form.event_type_ticket_ids.new() as ticket_line: ticket_line.name = 'Pastafarian Registration' ticket_line.price = 0 event_type = event_type_form.save() with Form(self.env['event.event']) as event_event_form: event_event_form.name = 'Annual Pastafarian Reunion (APR)' event_event_form.date_begin = datetime.datetime.now() + relativedelta(days=2) event_event_form.date_end = datetime.datetime.now() + relativedelta(days=3) event_event_form.event_type_id = event_type # Set the template event_event_form.auto_confirm = True # Create second ticket (VIP) with event_event_form.event_ticket_ids.new() as ticket_line: ticket_line.name = 'VIP (Very Important Pastafarian)' ticket_line.price = 10 event_event = event_event_form.save() # Add two registrations for the event, one registration for each ticket type for ticket in event_event.event_ticket_ids: self.env['event.registration'].create({ 'event_id': event_event.id, 'event_ticket_id': ticket.id }) # Edit the maximum before_confirmed = [t.seats_reserved for t in event_event.event_ticket_ids] with Form(event_event) as event_event_form: with event_event_form.event_ticket_ids.edit(0) as ticket_line: ticket_line.seats_max = ticket_line.seats_max + 1 after_confirmed = [t.seats_reserved for t in event_event.event_ticket_ids] self.assertEqual(before_confirmed, after_confirmed)
46.509434
2,465
665
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.addons.sales_team.tests.common import TestSalesCommon class TestEventSaleCommon(TestEventCommon, TestSalesCommon): @classmethod def setUpClass(cls): super(TestEventSaleCommon, cls).setUpClass() cls.event_product = cls.env['product.product'].create({ 'name': 'Test Registration Product', 'description_sale': 'Mighty Description', 'list_price': 10, 'standard_price': 30.0, 'detailed_type': 'event', })
33.25
665
6,404
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime, timedelta from unittest.mock import patch from odoo.addons.event_sale.tests.common import TestEventSaleCommon from odoo.fields import Datetime as FieldsDatetime, Date as FieldsDate from odoo.tests.common import users class TestEventData(TestEventSaleCommon): @users('user_eventmanager') def test_event_configuration_from_type(self): """ In addition to event test, also test tickets configuration coming from event_sale capabilities. """ event_type = self.event_type_complex.with_user(self.env.user) event = self.env['event.event'].create({ 'name': 'Event Update Type', 'event_type_id': event_type.id, 'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)), 'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)), }) event_type.write({ 'event_type_ticket_ids': [(5, 0), (0, 0, { 'name': 'First Ticket', 'product_id': self.event_product.id, 'seats_max': 5, })] }) self.assertEqual(event_type.event_type_ticket_ids.description, self.event_product.description_sale) # synchronize event event.write({'event_type_id': event_type.id}) self.assertEqual(event.event_ticket_ids.name, event.event_type_id.event_type_ticket_ids.name) self.assertTrue(event.event_ticket_ids.seats_limited) self.assertEqual(event.event_ticket_ids.seats_max, 5) self.assertEqual(event.event_ticket_ids.product_id, self.event_product) self.assertEqual(event.event_ticket_ids.price, self.event_product.list_price) self.assertEqual(event.event_ticket_ids.description, self.event_product.description_sale) def test_event_registrable(self): """Test if `_compute_event_registrations_open` works properly with additional product active conditions compared to base tests (see event) """ event = self.event_0.with_user(self.env.user) self.assertTrue(event.event_registrations_open) # ticket without dates boundaries -> ok ticket = self.env['event.event.ticket'].create({ 'name': 'TestTicket', 'event_id': event.id, 'product_id': self.event_product.id, }) self.assertTrue(event.event_registrations_open) # ticket has inactive product -> ko ticket.product_id.action_archive() self.assertFalse(event.event_registrations_open) # at least one valid ticket -> ok is back event_product = self.env['product.product'].create({'name': 'Test Registration Product New',}) new_ticket = self.env['event.event.ticket'].create({ 'name': 'TestTicket 2', 'event_id': event.id, 'product_id': event_product.id, 'end_sale_datetime': FieldsDatetime.to_string(datetime.now() + timedelta(days=2)), }) self.assertTrue(new_ticket.sale_available) self.assertTrue(event.event_registrations_open) class TestEventTicketData(TestEventSaleCommon): def setUp(self): super(TestEventTicketData, self).setUp() self.ticket_date_patcher = patch('odoo.addons.event.models.event_ticket.fields.Date', wraps=FieldsDate) self.ticket_date_patcher_mock = self.ticket_date_patcher.start() self.ticket_date_patcher_mock.context_today.return_value = date(2020, 1, 31) self.ticket_datetime_patcher = patch('odoo.addons.event.models.event_event.fields.Datetime', wraps=FieldsDatetime) self.mock_datetime = self.ticket_datetime_patcher.start() self.mock_datetime.now.return_value = datetime(2020, 1, 31, 10, 0, 0) def tearDown(self): super(TestEventTicketData, self).tearDown() self.ticket_date_patcher.stop() self.ticket_datetime_patcher.stop() @users('user_eventmanager') def test_event_ticket_fields(self): """ Test event ticket fields synchronization """ event = self.event_0.with_user(self.env.user) event.write({ 'event_ticket_ids': [ (5, 0), (0, 0, { 'name': 'First Ticket', 'product_id': self.event_product.id, 'seats_max': 30, }), (0, 0, { # limited in time, available (01/10 (start) < 01/31 (today) < 02/10 (end)) 'name': 'Second Ticket', 'product_id': self.event_product.id, 'start_sale_datetime': datetime(2020, 1, 10, 0, 0, 0), 'end_sale_datetime': datetime(2020, 2, 10, 23, 59, 59), }) ], }) first_ticket = event.event_ticket_ids.filtered(lambda t: t.name == 'First Ticket') second_ticket = event.event_ticket_ids.filtered(lambda t: t.name == 'Second Ticket') # force second ticket price, after calling the onchange second_ticket.write({'price': 8.0}) # price coming from product self.assertEqual(first_ticket.price, self.event_product.list_price) self.assertEqual(second_ticket.price, 8.0) # default availability self.assertTrue(first_ticket.seats_limited) self.assertTrue(first_ticket.sale_available) self.assertFalse(first_ticket.is_expired) self.assertFalse(second_ticket.seats_limited) self.assertTrue(second_ticket.sale_available) self.assertFalse(second_ticket.is_expired) # product archived self.event_product.action_archive() self.assertFalse(first_ticket.sale_available) self.assertFalse(second_ticket.sale_available) # sale is ended self.event_product.action_unarchive() second_ticket.write({'end_sale_datetime': datetime(2020, 1, 20, 23, 59, 59)}) self.assertFalse(second_ticket.sale_available) self.assertTrue(second_ticket.is_expired) # sale has not started second_ticket.write({ 'start_sale_datetime': datetime(2020, 2, 10, 0, 0, 0), 'end_sale_datetime': datetime(2020, 2, 20, 23, 59, 59), }) self.assertFalse(second_ticket.sale_available) self.assertFalse(second_ticket.is_expired)
45.098592
6,404
950
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from odoo.fields import Datetime from odoo.tests import HttpCase, tagged @tagged('post_install', '-at_install') class TestUi(HttpCase): def test_event_configurator(self): event = self.env['event.event'].create({ 'name': 'Design Fair Los Angeles', 'date_begin': Datetime.now() + timedelta(days=1), 'date_end': Datetime.now() + timedelta(days=5), }) self.env['event.event.ticket'].create([{ 'name': 'Standard', 'event_id': event.id, 'product_id': self.env.ref('event_sale.product_product_event').id, }, { 'name': 'VIP', 'event_id': event.id, 'product_id': self.env.ref('event_sale.product_product_event').id, }]) self.start_tour("/web", 'event_configurator_tour', login="admin")
32.758621
950
4,573
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api class RegistrationEditor(models.TransientModel): _name = "registration.editor" _description = 'Edit Attendee Details on Sales Confirmation' sale_order_id = fields.Many2one('sale.order', 'Sales Order', required=True, ondelete='cascade') event_registration_ids = fields.One2many('registration.editor.line', 'editor_id', string='Registrations to Edit') @api.model def default_get(self, fields): res = super(RegistrationEditor, self).default_get(fields) if not res.get('sale_order_id'): sale_order_id = res.get('sale_order_id', self._context.get('active_id')) res['sale_order_id'] = sale_order_id sale_order = self.env['sale.order'].browse(res.get('sale_order_id')) registrations = self.env['event.registration'].search([ ('sale_order_id', '=', sale_order.id), ('event_ticket_id', 'in', sale_order.mapped('order_line.event_ticket_id').ids), ('state', '!=', 'cancel')]) attendee_list = [] for so_line in [l for l in sale_order.order_line if l.event_ticket_id]: existing_registrations = [r for r in registrations if r.event_ticket_id == so_line.event_ticket_id] for reg in existing_registrations: attendee_list.append([0, 0, { 'event_id': reg.event_id.id, 'event_ticket_id': reg.event_ticket_id.id, 'registration_id': reg.id, 'name': reg.name, 'email': reg.email, 'phone': reg.phone, 'mobile': reg.mobile, 'sale_order_line_id': so_line.id, }]) for count in range(int(so_line.product_uom_qty) - len(existing_registrations)): attendee_list.append([0, 0, { 'event_id': so_line.event_id.id, 'event_ticket_id': so_line.event_ticket_id.id, 'sale_order_line_id': so_line.id, 'name': so_line.order_partner_id.name, 'email': so_line.order_partner_id.email, 'phone': so_line.order_partner_id.phone, 'mobile': so_line.order_partner_id.mobile, }]) res['event_registration_ids'] = attendee_list res = self._convert_to_write(res) return res def action_make_registration(self): self.ensure_one() registrations_to_create = [] for registration_line in self.event_registration_ids: values = registration_line.get_registration_data() if registration_line.registration_id: registration_line.registration_id.write(values) else: registrations_to_create.append(values) self.env['event.registration'].create(registrations_to_create) self.sale_order_id.order_line._update_registrations(confirm=self.sale_order_id.amount_total == 0) return {'type': 'ir.actions.act_window_close'} class RegistrationEditorLine(models.TransientModel): """Event Registration""" _name = "registration.editor.line" _description = 'Edit Attendee Line on Sales Confirmation' _order = "id desc" editor_id = fields.Many2one('registration.editor') sale_order_line_id = fields.Many2one('sale.order.line', string='Sales Order Line') event_id = fields.Many2one('event.event', string='Event', required=True) registration_id = fields.Many2one('event.registration', 'Original Registration') event_ticket_id = fields.Many2one('event.event.ticket', string='Event Ticket') email = fields.Char(string='Email') phone = fields.Char(string='Phone') mobile = fields.Char(string='Mobile') name = fields.Char(string='Name', index=True) def get_registration_data(self): self.ensure_one() return { 'event_id': self.event_id.id, 'event_ticket_id': self.event_ticket_id.id, 'partner_id': self.editor_id.sale_order_id.partner_id.id, 'name': self.name or self.editor_id.sale_order_id.partner_id.name, 'phone': self.phone or self.editor_id.sale_order_id.partner_id.phone, 'mobile': self.mobile or self.editor_id.sale_order_id.partner_id.mobile, 'email': self.email or self.editor_id.sale_order_id.partner_id.email, 'sale_order_id': self.editor_id.sale_order_id.id, 'sale_order_line_id': self.sale_order_line_id.id, }
47.14433
4,573
492
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 EventConfigurator(models.TransientModel): _name = 'event.event.configurator' _description = 'Event Configurator' product_id = fields.Many2one('product.product', string="Product", readonly=True) event_id = fields.Many2one('event.event', string="Event") event_ticket_id = fields.Many2one('event.event.ticket', string="Event Ticket")
37.846154
492
594
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 AccountMove(models.Model): _inherit = 'account.move' def action_invoice_paid(self): """ When an invoice linked to a sales order selling registrations is paid confirm attendees. Attendees should indeed not be confirmed before full payment. """ res = super(AccountMove, self).action_invoice_paid() self.mapped('line_ids.sale_line_ids')._update_registrations(confirm=True, mark_as_paid=True) return res
37.125
594
7,878
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ class SaleOrder(models.Model): _inherit = "sale.order" attendee_count = fields.Integer('Attendee Count', compute='_compute_attendee_count') def write(self, vals): """ Synchronize partner from SO to registrations. This is done notably in website_sale controller shop/address that updates customer, but not only. """ result = super(SaleOrder, self).write(vals) if vals.get('partner_id'): registrations_toupdate = self.env['event.registration'].search([('sale_order_id', 'in', self.ids)]) registrations_toupdate.write({'partner_id': vals['partner_id']}) return result def action_confirm(self): res = super(SaleOrder, self).action_confirm() for so in self: # confirm registration if it was free (otherwise it will be confirmed once invoice fully paid) so.order_line._update_registrations(confirm=so.amount_total == 0, cancel_to_draft=False) if any(line.event_ok for line in so.order_line): return self.env['ir.actions.act_window'] \ .with_context(default_sale_order_id=so.id) \ ._for_xml_id('event_sale.action_sale_order_event_registration') return res def _action_cancel(self): self.order_line._cancel_associated_registrations() return super()._action_cancel() def action_view_attendee_list(self): action = self.env["ir.actions.actions"]._for_xml_id("event.event_registration_action_tree") action['domain'] = [('sale_order_id', 'in', self.ids)] return action def _compute_attendee_count(self): sale_orders_data = self.env['event.registration'].read_group( [('sale_order_id', 'in', self.ids), ('state', '!=', 'cancel')], ['sale_order_id'], ['sale_order_id'] ) attendee_count_data = { sale_order_data['sale_order_id'][0]: sale_order_data['sale_order_id_count'] for sale_order_data in sale_orders_data } for sale_order in self: sale_order.attendee_count = attendee_count_data.get(sale_order.id, 0) def unlink(self): self.order_line._unlink_associated_registrations() return super(SaleOrder, self).unlink() class SaleOrderLine(models.Model): _inherit = 'sale.order.line' event_id = fields.Many2one( 'event.event', string='Event', help="Choose an event and it will automatically create a registration for this event.") event_ticket_id = fields.Many2one( 'event.event.ticket', string='Event Ticket', help="Choose an event ticket and it will automatically create a registration for this event ticket.") event_ok = fields.Boolean(compute='_compute_event_ok') @api.depends('product_id.detailed_type') def _compute_event_ok(self): for record in self: record.event_ok = record.product_id.detailed_type == 'event' @api.depends('state', 'event_id') def _compute_product_uom_readonly(self): event_lines = self.filtered(lambda line: line.event_id) event_lines.update({'product_uom_readonly': True}) super(SaleOrderLine, self - event_lines)._compute_product_uom_readonly() def _update_registrations(self, confirm=True, cancel_to_draft=False, registration_data=None, mark_as_paid=False): """ Create or update registrations linked to a sales order line. A sale order line has a product_uom_qty attribute that will be the number of registrations linked to this line. This method update existing registrations and create new one for missing one. """ RegistrationSudo = self.env['event.registration'].sudo() registrations = RegistrationSudo.search([('sale_order_line_id', 'in', self.ids)]) registrations_vals = [] for so_line in self.filtered('event_ok'): existing_registrations = registrations.filtered(lambda self: self.sale_order_line_id.id == so_line.id) if confirm: existing_registrations.filtered(lambda self: self.state not in ['open', 'cancel']).action_confirm() if mark_as_paid: existing_registrations.filtered(lambda self: not self.is_paid)._action_set_paid() if cancel_to_draft: existing_registrations.filtered(lambda self: self.state == 'cancel').action_set_draft() for count in range(int(so_line.product_uom_qty) - len(existing_registrations)): values = { 'sale_order_line_id': so_line.id, 'sale_order_id': so_line.order_id.id } # TDE CHECK: auto confirmation if registration_data: values.update(registration_data.pop()) registrations_vals.append(values) if registrations_vals: RegistrationSudo.create(registrations_vals) return True @api.onchange('product_id') def _onchange_product_id(self): # We reset the event when keeping it would lead to an inconstitent state. # We need to do it this way because the only relation between the product and the event is through the corresponding tickets. if self.event_id and (not self.product_id or self.product_id.id not in self.event_id.mapped('event_ticket_ids.product_id.id')): self.event_id = None @api.onchange('event_id') def _onchange_event_id(self): # We reset the ticket when keeping it would lead to an inconstitent state. if self.event_ticket_id and (not self.event_id or self.event_id != self.event_ticket_id.event_id): self.event_ticket_id = None @api.onchange('product_uom', 'product_uom_qty') def product_uom_change(self): if not self.event_ticket_id: super(SaleOrderLine, self).product_uom_change() @api.onchange('event_ticket_id') def _onchange_event_ticket_id(self): # we call this to force update the default name self.product_id_change() def unlink(self): self._unlink_associated_registrations() return super(SaleOrderLine, self).unlink() def _cancel_associated_registrations(self): self.env['event.registration'].search([('sale_order_line_id', 'in', self.ids)]).action_cancel() def _unlink_associated_registrations(self): self.env['event.registration'].search([('sale_order_line_id', 'in', self.ids)]).unlink() def get_sale_order_line_multiline_description_sale(self, product): """ We override this method because we decided that: The default description of a sales order line containing a ticket must be different than the default description when no ticket is present. So in that case we use the description computed from the ticket, instead of the description computed from the product. We need this override to be defined here in sales order line (and not in product) because here is the only place where the event_ticket_id is referenced. """ if self.event_ticket_id: ticket = self.event_ticket_id.with_context( lang=self.order_id.partner_id.lang, ) return ticket._get_ticket_multiline_description() + self._get_sale_order_line_multiline_description_variants() else: return super(SaleOrderLine, self).get_sale_order_line_multiline_description_sale(product) def _get_display_price(self, product): if self.event_ticket_id and self.event_id: return self.event_ticket_id.with_context(pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id).price_reduce else: return super()._get_display_price(product)
47.457831
7,878
6,102
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_is_zero class EventRegistration(models.Model): _inherit = 'event.registration' is_paid = fields.Boolean('Is Paid') # TDE FIXME: maybe add an onchange on sale_order_id sale_order_id = fields.Many2one('sale.order', string='Sales Order', ondelete='cascade', copy=False) sale_order_line_id = fields.Many2one('sale.order.line', string='Sales Order Line', ondelete='cascade', copy=False) payment_status = fields.Selection(string="Payment Status", selection=[ ('to_pay', 'Not Paid'), ('paid', 'Paid'), ('free', 'Free'), ], compute="_compute_payment_status", compute_sudo=True) utm_campaign_id = fields.Many2one(compute='_compute_utm_campaign_id', readonly=False, store=True) utm_source_id = fields.Many2one(compute='_compute_utm_source_id', readonly=False, store=True) utm_medium_id = fields.Many2one(compute='_compute_utm_medium_id', readonly=False, store=True) @api.depends('is_paid', 'sale_order_id.currency_id', 'sale_order_line_id.price_total') def _compute_payment_status(self): for record in self: so = record.sale_order_id so_line = record.sale_order_line_id if not so or float_is_zero(so_line.price_total, precision_digits=so.currency_id.rounding): record.payment_status = 'free' elif record.is_paid: record.payment_status = 'paid' else: record.payment_status = 'to_pay' @api.depends('sale_order_id') def _compute_utm_campaign_id(self): for registration in self: if registration.sale_order_id.campaign_id: registration.utm_campaign_id = registration.sale_order_id.campaign_id elif not registration.utm_campaign_id: registration.utm_campaign_id = False @api.depends('sale_order_id') def _compute_utm_source_id(self): for registration in self: if registration.sale_order_id.source_id: registration.utm_source_id = registration.sale_order_id.source_id elif not registration.utm_source_id: registration.utm_source_id = False @api.depends('sale_order_id') def _compute_utm_medium_id(self): for registration in self: if registration.sale_order_id.medium_id: registration.utm_medium_id = registration.sale_order_id.medium_id elif not registration.utm_medium_id: registration.utm_medium_id = False def action_view_sale_order(self): action = self.env["ir.actions.actions"]._for_xml_id("sale.action_orders") action['views'] = [(False, 'form')] action['res_id'] = self.sale_order_id.id return action @api.model_create_multi def create(self, vals_list): for vals in vals_list: if vals.get('sale_order_line_id'): so_line_vals = self._synchronize_so_line_values( self.env['sale.order.line'].browse(vals['sale_order_line_id']) ) vals.update(so_line_vals) registrations = super(EventRegistration, self).create(vals_list) for registration in registrations: if registration.sale_order_id: registration.message_post_with_view( 'mail.message_origin_link', values={'self': registration, 'origin': registration.sale_order_id}, subtype_id=self.env.ref('mail.mt_note').id) return registrations def write(self, vals): if vals.get('sale_order_line_id'): so_line_vals = self._synchronize_so_line_values( self.env['sale.order.line'].browse(vals['sale_order_line_id']) ) vals.update(so_line_vals) if vals.get('event_ticket_id'): self.filtered( lambda registration: registration.event_ticket_id and registration.event_ticket_id.id != vals['event_ticket_id'] )._sale_order_ticket_type_change_notify(self.env['event.event.ticket'].browse(vals['event_ticket_id'])) return super(EventRegistration, self).write(vals) def _synchronize_so_line_values(self, so_line): if so_line: return { 'partner_id': False if self.env.user._is_public() else so_line.order_id.partner_id.id, 'event_id': so_line.event_id.id, 'event_ticket_id': so_line.event_ticket_id.id, 'sale_order_id': so_line.order_id.id, 'sale_order_line_id': so_line.id, } return {} def _sale_order_ticket_type_change_notify(self, new_event_ticket): fallback_user_id = self.env.user.id if not self.env.user._is_public() else self.env.ref("base.user_admin").id for registration in self: render_context = { 'registration': registration, 'old_ticket_name': registration.event_ticket_id.name, 'new_ticket_name': new_event_ticket.name } user_id = registration.event_id.user_id.id or registration.sale_order_id.user_id.id or fallback_user_id registration.sale_order_id._activity_schedule_with_view( 'mail.mail_activity_data_warning', user_id=user_id, views_or_xmlid='event_sale.event_ticket_id_change_exception', render_context=render_context) def _action_set_paid(self): self.write({'is_paid': True}) def _get_registration_summary(self): res = super(EventRegistration, self)._get_registration_summary() res.update({ 'payment_status': self.payment_status, 'payment_status_value': dict(self._fields['payment_status']._description_selection(self.env))[self.payment_status], 'has_to_pay': self.payment_status == 'to_pay', }) return res
45.879699
6,102
3,705
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' sale_order_lines_ids = fields.One2many( 'sale.order.line', 'event_id', groups='sales_team.group_sale_salesman', string='All sale order lines pointing to this event') sale_price_subtotal = fields.Monetary( string='Sales (Tax Excluded)', compute='_compute_sale_price_subtotal', groups='sales_team.group_sale_salesman') currency_id = fields.Many2one( 'res.currency', string='Currency', related='company_id.currency_id', readonly=True) @api.depends('company_id.currency_id', 'sale_order_lines_ids.price_subtotal', 'sale_order_lines_ids.currency_id', 'sale_order_lines_ids.company_id', 'sale_order_lines_ids.order_id.date_order') def _compute_sale_price_subtotal(self): """ Takes all the sale.order.lines related to this event and converts amounts from the currency of the sale order to the currency of the event company. To avoid extra overhead, we use conversion rates as of 'today'. Meaning we have a number that can change over time, but using the conversion rates at the time of the related sale.order would mean thousands of extra requests as we would have to do one conversion per sale.order (and a sale.order is created every time we sell a single event ticket). """ date_now = fields.Datetime.now() sale_price_by_event = {} if self.ids: event_subtotals = self.env['sale.order.line'].read_group( [('event_id', 'in', self.ids), ('price_subtotal', '!=', 0)], ['event_id', 'currency_id', 'price_subtotal:sum'], ['event_id', 'currency_id'], lazy=False ) company_by_event = { event._origin.id or event.id: event.company_id for event in self } currency_by_event = { event._origin.id or event.id: event.currency_id for event in self } currency_by_id = { currency.id: currency for currency in self.env['res.currency'].browse( [event_subtotal['currency_id'][0] for event_subtotal in event_subtotals] ) } for event_subtotal in event_subtotals: price_subtotal = event_subtotal['price_subtotal'] event_id = event_subtotal['event_id'][0] currency_id = event_subtotal['currency_id'][0] sale_price = currency_by_event[event_id]._convert( price_subtotal, currency_by_id[currency_id], company_by_event[event_id], date_now) if event_id in sale_price_by_event: sale_price_by_event[event_id] += sale_price else: sale_price_by_event[event_id] = sale_price for event in self: event.sale_price_subtotal = sale_price_by_event.get(event._origin.id or event.id, 0) def action_view_linked_orders(self): """ Redirects to the orders linked to the current events """ sale_order_action = self.env["ir.actions.actions"]._for_xml_id("sale.action_orders") sale_order_action.update({ 'domain': [('state', '!=', 'cancel'), ('order_line.event_id', 'in', self.ids)], 'context': {'create': 0}, }) return sale_order_action
43.588235
3,705
221
py
PYTHON
15.0
from odoo import fields, models class SaleOrderTemplateLine(models.Model): _inherit = "sale.order.template.line" product_id = fields.Many2one(domain="[('sale_ok', '=', True), ('detailed_type', '!=', 'event')]")
36.833333
221
751
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = 'product.template' detailed_type = fields.Selection(selection_add=[ ('event', 'Event Ticket'), ], ondelete={'event': 'set service'}) @api.onchange('detailed_type') def _onchange_type_event(self): if self.detailed_type == 'event': self.invoice_policy = 'order' def _detailed_type_mapping(self): type_mapping = super()._detailed_type_mapping() type_mapping['event'] = 'service' return type_mapping class Product(models.Model): _inherit = 'product.product' event_ticket_ids = fields.One2many('event.event.ticket', 'product_id', string='Event Tickets')
27.814815
751
225
py
PYTHON
15.0
from odoo import fields, models class SaleOrderTemplateOption(models.Model): _inherit = "sale.order.template.option" product_id = fields.Many2one(domain="[('sale_ok', '=', True), ('detailed_type', '!=', 'event')]")
37.5
225
5,454
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) class EventTemplateTicket(models.Model): _inherit = 'event.type.ticket' def _default_product_id(self): return self.env.ref('event_sale.product_product_event', raise_if_not_found=False) description = fields.Text(compute='_compute_description', readonly=False, store=True) # product product_id = fields.Many2one( 'product.product', string='Product', required=True, domain=[("detailed_type", "=", "event")], default=_default_product_id) price = fields.Float( string='Price', compute='_compute_price', digits='Product Price', readonly=False, store=True) price_reduce = fields.Float( string="Price Reduce", compute="_compute_price_reduce", compute_sudo=True, digits='Product Price') @api.depends('product_id') def _compute_price(self): for ticket in self: if ticket.product_id and ticket.product_id.lst_price: ticket.price = ticket.product_id.lst_price or 0 elif not ticket.price: ticket.price = 0 @api.depends('product_id') def _compute_description(self): for ticket in self: if ticket.product_id and ticket.product_id.description_sale: ticket.description = ticket.product_id.description_sale # initialize, i.e for embedded tree views if not ticket.description: ticket.description = False @api.depends_context('pricelist', 'quantity') @api.depends('product_id', 'price') def _compute_price_reduce(self): for ticket in self: product = ticket.product_id pricelist = self.env['product.pricelist'].browse(self._context.get('pricelist')) lst_price = product.currency_id._convert( product.lst_price, pricelist.currency_id, self.env.company, fields.Datetime.now() ) discount = (lst_price - product.price) / lst_price if lst_price else 0.0 ticket.price_reduce = (1.0 - discount) * ticket.price def _init_column(self, column_name): if column_name != "product_id": return super(EventTemplateTicket, self)._init_column(column_name) # fetch void columns self.env.cr.execute("SELECT id FROM %s WHERE product_id IS NULL" % self._table) ticket_type_ids = self.env.cr.fetchall() if not ticket_type_ids: return # update existing columns _logger.debug("Table '%s': setting default value of new column %s to unique values for each row", self._table, column_name) default_event_product = self.env.ref('event_sale.product_product_event', raise_if_not_found=False) if default_event_product: product_id = default_event_product.id else: product_id = self.env['product.product'].create({ 'name': 'Generic Registration Product', 'list_price': 0, 'standard_price': 0, 'type': 'service', }).id self.env['ir.model.data'].create({ 'name': 'product_product_event', 'module': 'event_sale', 'model': 'product.product', 'res_id': product_id, }) self.env.cr._obj.execute( f'UPDATE {self._table} SET product_id = %s WHERE id IN %s;', (product_id, tuple(ticket_type_ids)) ) @api.model def _get_event_ticket_fields_whitelist(self): """ Add sale specific fields to copy from template to ticket """ return super(EventTemplateTicket, self)._get_event_ticket_fields_whitelist() + ['product_id', 'price'] class EventTicket(models.Model): _inherit = 'event.event.ticket' _order = "event_id, price" # product price_reduce_taxinc = fields.Float( string='Price Reduce Tax inc', compute='_compute_price_reduce_taxinc', compute_sudo=True) def _compute_price_reduce_taxinc(self): for event in self: # sudo necessary here since the field is most probably accessed through the website tax_ids = event.product_id.taxes_id.filtered(lambda r: r.company_id == event.event_id.company_id) taxes = tax_ids.compute_all(event.price_reduce, event.event_id.company_id.currency_id, 1.0, product=event.product_id) event.price_reduce_taxinc = taxes['total_included'] @api.depends('product_id.active') def _compute_sale_available(self): inactive_product_tickets = self.filtered(lambda ticket: not ticket.product_id.active) for ticket in inactive_product_tickets: ticket.sale_available = False super(EventTicket, self - inactive_product_tickets)._compute_sale_available() def _get_ticket_multiline_description(self): """ If people set a description on their product it has more priority than the ticket name itself for the SO description. """ self.ensure_one() if self.product_id.description_sale: return '%s\n%s' % (self.product_id.description_sale, self.event_id.display_name) return super(EventTicket, self)._get_ticket_multiline_description()
41.953846
5,454
850
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Sales - Project", 'summary': "Task Generation from Sales Orders", 'description': """ Allows to create task from your sales order ============================================= This module allows to generate a project/task from sales orders. """, 'category': 'Hidden', 'depends': ['sale_management', 'project'], 'data': [ 'security/ir.model.access.csv', 'security/sale_project_security.xml', 'report/project_report_views.xml', 'views/product_views.xml', 'views/project_task_views.xml', 'views/sale_order_views.xml', 'views/sale_project_portal_templates.xml', 'views/project_sharing_views.xml', ], 'auto_install': True, 'license': 'LGPL-3', }
34
850
12,340
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import Command from odoo.tests.common import TransactionCase, users class TestSaleProject(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.analytic_account_sale = cls.env['account.analytic.account'].create({ 'name': 'Project for selling timesheet - AA', 'code': 'AA-2030' }) # Create projects cls.project_global = cls.env['project.project'].create({ 'name': 'Global Project', 'analytic_account_id': cls.analytic_account_sale.id, }) cls.project_template = cls.env['project.project'].create({ 'name': 'Project TEMPLATE for services', }) cls.project_template_state = cls.env['project.task.type'].create({ 'name': 'Only stage in project template', 'sequence': 1, 'project_ids': [(4, cls.project_template.id)] }) # Create service products uom_hour = cls.env.ref('uom.product_uom_hour') cls.product_order_service1 = cls.env['product.product'].create({ 'name': "Service Ordered, create no task", 'standard_price': 11, 'list_price': 13, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED1', 'service_tracking': 'no', 'project_id': False, }) cls.product_order_service2 = cls.env['product.product'].create({ 'name': "Service Ordered, create task in global project", 'standard_price': 30, 'list_price': 90, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED2', 'service_tracking': 'task_global_project', 'project_id': cls.project_global.id, }) cls.product_order_service3 = cls.env['product.product'].create({ 'name': "Service Ordered, create task in new project", 'standard_price': 10, 'list_price': 20, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED3', 'service_tracking': 'task_in_project', 'project_id': False, # will create a project }) cls.product_order_service4 = cls.env['product.product'].create({ 'name': "Service Ordered, create project only", 'standard_price': 15, 'list_price': 30, 'type': 'service', 'invoice_policy': 'order', 'uom_id': uom_hour.id, 'uom_po_id': uom_hour.id, 'default_code': 'SERV-ORDERED4', 'service_tracking': 'project_only', 'project_id': False, }) # Create partner cls.partner = cls.env['res.partner'].create({'name': "Mur en béton"}) def test_sale_order_with_project_task(self): SaleOrder = self.env['sale.order'].with_context(tracking_disable=True) SaleOrderLine = self.env['sale.order.line'].with_context(tracking_disable=True) sale_order = SaleOrder.create({ 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, }) so_line_order_no_task = SaleOrderLine.create({ 'name': self.product_order_service1.name, 'product_id': self.product_order_service1.id, 'product_uom_qty': 10, 'product_uom': self.product_order_service1.uom_id.id, 'price_unit': self.product_order_service1.list_price, 'order_id': sale_order.id, }) so_line_order_task_in_global = SaleOrderLine.create({ 'name': self.product_order_service2.name, 'product_id': self.product_order_service2.id, 'product_uom_qty': 10, 'product_uom': self.product_order_service2.uom_id.id, 'price_unit': self.product_order_service2.list_price, 'order_id': sale_order.id, }) so_line_order_new_task_new_project = SaleOrderLine.create({ 'name': self.product_order_service3.name, 'product_id': self.product_order_service3.id, 'product_uom_qty': 10, 'product_uom': self.product_order_service3.uom_id.id, 'price_unit': self.product_order_service3.list_price, 'order_id': sale_order.id, }) so_line_order_only_project = SaleOrderLine.create({ 'name': self.product_order_service4.name, 'product_id': self.product_order_service4.id, 'product_uom_qty': 10, 'product_uom': self.product_order_service4.uom_id.id, 'price_unit': self.product_order_service4.list_price, 'order_id': sale_order.id, }) sale_order.action_confirm() # service_tracking 'no' self.assertFalse(so_line_order_no_task.project_id, "The project should not be linked to no task product") self.assertFalse(so_line_order_no_task.task_id, "The task should not be linked to no task product") # service_tracking 'task_global_project' self.assertFalse(so_line_order_task_in_global.project_id, "Only task should be created, project should not be linked") self.assertEqual(self.project_global.tasks.sale_line_id, so_line_order_task_in_global, "Global project's task should be linked to so line") # service_tracking 'task_in_project' self.assertTrue(so_line_order_new_task_new_project.project_id, "Sales order line should be linked to newly created project") self.assertTrue(so_line_order_new_task_new_project.task_id, "Sales order line should be linked to newly created task") # service_tracking 'project_only' self.assertFalse(so_line_order_only_project.task_id, "Task should not be created") self.assertTrue(so_line_order_only_project.project_id, "Sales order line should be linked to newly created project") self.assertEqual(self.project_global._get_sale_order_items(), self.project_global.sale_line_id | self.project_global.tasks.sale_line_id, 'The _get_sale_order_items should returns all the SOLs linked to the project and its active tasks.') sale_order_2 = SaleOrder.create({ 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, }) sale_line_1_order_2 = SaleOrderLine.create({ 'product_id': self.product_order_service1.id, 'product_uom_qty': 10, 'product_uom': self.product_order_service1.uom_id.id, 'price_unit': self.product_order_service1.list_price, 'order_id': sale_order_2.id, }) task = self.env['project.task'].create({ 'name': 'Task', 'sale_line_id': sale_line_1_order_2.id, 'project_id': self.project_global.id, }) self.assertEqual(task.sale_line_id, sale_line_1_order_2) self.assertIn(task.sale_line_id, self.project_global._get_sale_order_items()) self.assertEqual(self.project_global._get_sale_orders(), sale_order | sale_order_2) def test_sol_product_type_update(self): sale_order = self.env['sale.order'].with_context(tracking_disable=True).create({ 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, }) self.product_order_service3.type = 'consu' sale_order_line = self.env['sale.order.line'].create({ 'order_id': sale_order.id, 'name': self.product_order_service3.name, 'product_id': self.product_order_service3.id, 'product_uom_qty': 5, 'product_uom': self.product_order_service3.uom_id.id, 'price_unit': self.product_order_service3.list_price }) self.assertFalse(sale_order_line.is_service, "As the product is consumable, the SOL should not be a service") self.product_order_service3.type = 'service' self.assertTrue(sale_order_line.is_service, "As the product is a service, the SOL should be a service") @users('demo') def test_cancel_so_linked_to_project(self): """ Test that cancelling a SO linked to a project will not raise an error """ # Ensure user don't have edit right access to the project group_sale_manager = self.env.ref('sales_team.group_sale_manager') group_project_user = self.env.ref('project.group_project_user') self.env.user.write({'groups_id': [(6, 0, [group_sale_manager.id, group_project_user.id])]}) sale_order = self.env['sale.order'].with_context(tracking_disable=True).create({ 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner.id, 'project_id': self.project_global.id, }) sale_order_line = self.env['sale.order.line'].create({ 'name': self.product_order_service2.name, 'product_id': self.product_order_service2.id, 'order_id': sale_order.id, }) self.assertFalse(self.project_global.tasks.sale_line_id, "The project tasks should not be linked to the SOL") sale_order.action_confirm() self.assertEqual(self.project_global.tasks.sale_line_id.id, sale_order_line.id, "The project tasks should be linked to the SOL from the SO") self.project_global.sale_line_id = sale_order_line sale_order.action_cancel() self.assertFalse(self.project_global.sale_line_id, "The project should not be linked to the SOL anymore") def test_create_task_from_template_line(self): """ When we add an SOL from a template that is a service that has a service_policy that will generate a task, even if default_task_id is present in the context, a new task should be created when confirming the SO. """ default_task = self.env['project.task'].with_context(tracking_disable=True).create({ 'name': 'Task', 'project_id': self.project_global.id }) sale_order = self.env['sale.order'].with_context(tracking_disable=True, default_task_id=default_task.id).create({ 'partner_id': self.partner.id, }) quotation_template = self.env['sale.order.template'].create({ 'name': 'Test quotation', }) quotation_template.write({ 'sale_order_template_line_ids': [ Command.set( self.env['sale.order.template.line'].create([{ 'name': self.product_order_service2.display_name, 'sale_order_template_id': quotation_template.id, 'product_id': self.product_order_service2.id, 'product_uom_id': self.product_order_service2.uom_id.id, }, { 'name': self.product_order_service3.display_name, 'sale_order_template_id': quotation_template.id, 'product_id': self.product_order_service3.id, 'product_uom_id': self.product_order_service3.uom_id.id, }]).ids ) ] }) sale_order.with_context(default_task_id=default_task.id).write({ 'sale_order_template_id': quotation_template.id, }) sale_order.with_context(default_task_id=default_task.id).onchange_sale_order_template_id() self.assertFalse(sale_order.order_line.mapped('task_id'), "SOL should have no related tasks, because they are from services that generates a task") sale_order.action_confirm() self.assertEqual(sale_order.tasks_count, 2, "SO should have 2 related tasks") self.assertNotIn(default_task, sale_order.tasks_ids, "SO should link to the default task from the context")
48.011673
12,339
12,517
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, new_test_user class TestNestedTaskUpdate(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env['res.partner'].create({'name': "Mur en béton"}) sale_order = cls.env['sale.order'].with_context(tracking_disable=True).create({ 'partner_id': cls.partner.id, 'partner_invoice_id': cls.partner.id, 'partner_shipping_id': cls.partner.id, }) product = cls.env['product.product'].create({ 'name': "Prepaid Consulting", 'type': 'service', }) cls.order_line = cls.env['sale.order.line'].create({ 'name': "Order line", 'product_id': product.id, 'order_id': sale_order.id, }) cls.user = new_test_user(cls.env, login='mla') #---------------------------------- # # When creating tasks that have a parent_id, they pick some values from their parent # #---------------------------------- def test_creating_subtask_user_id_on_parent_dont_go_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'user_ids': [(4, self.user.id)]}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id, 'user_ids': False}) self.assertFalse(child.user_ids) def test_creating_subtask_partner_id_on_parent_goes_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.user.partner_id.id}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id}) child._compute_partner_id() # the compute will be triggered since the user set the parent_id. self.assertEqual(child.partner_id, self.user.partner_id) # Another case, it is the parent as a default value child = self.env['project.task'].with_context(default_parent_id=parent.id).create({'name': 'child'}) self.assertEqual(child.partner_id, self.user.partner_id) def test_creating_subtask_email_from_on_parent_goes_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'email_from': '[email protected]'}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id}) self.assertEqual(child.email_from, '[email protected]') def test_creating_subtask_sale_line_id_on_parent_goes_on_child_if_same_partner_in_values(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': self.partner.id, 'parent_id': parent.id}) self.assertEqual(child.sale_line_id, parent.sale_line_id) parent.write({'sale_line_id': False}) self.assertEqual(child.sale_line_id, self.order_line) def test_creating_subtask_sale_line_id_on_parent_goes_on_child_with_partner_if_not_in_values(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id}) self.assertEqual(child.partner_id, parent.partner_id) self.assertEqual(child.sale_line_id, parent.sale_line_id) def test_creating_subtask_sale_line_id_on_parent_dont_go_on_child_if_other_partner(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': self.user.partner_id.id, 'parent_id': parent.id}) self.assertFalse(child.sale_line_id) self.assertNotEqual(child.partner_id, parent.partner_id) def test_creating_subtask_sale_line_id_on_parent_go_on_child_if_same_commercial_partner(self): commercial_partner = self.env['res.partner'].create({'name': "Jémémy"}) self.partner.parent_id = commercial_partner self.user.partner_id.parent_id = commercial_partner parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': self.user.partner_id.id, 'parent_id': parent.id}) self.assertEqual(child.sale_line_id, self.order_line, "Sale order line on parent should be transfered to child") self.assertNotEqual(child.partner_id, parent.partner_id) #---------------------------------------- # # When writing on a parent task, some values adapt on their children # #---------------------------------------- def test_write_user_id_on_parent_dont_write_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'user_ids': False}) child = self.env['project.task'].create({'name': 'child', 'user_ids': False, 'parent_id': parent.id}) self.assertFalse(child.user_ids) parent.write({'user_ids': [(4, self.user.id)]}) self.assertFalse(child.user_ids) parent.write({'user_ids': False}) self.assertFalse(child.user_ids) def test_write_partner_id_on_parent_write_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': False}) child = self.env['project.task'].create({'name': 'child', 'partner_id': False, 'parent_id': parent.id}) self.assertFalse(child.partner_id) parent.write({'partner_id': self.user.partner_id.id}) self.assertNotEqual(child.partner_id, parent.partner_id) parent.write({'partner_id': False}) self.assertNotEqual(child.partner_id, self.user.partner_id) def test_write_email_from_on_parent_write_on_child(self): parent = self.env['project.task'].create({'name': 'parent'}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id}) self.assertFalse(child.email_from) parent.write({'email_from': '[email protected]'}) self.assertEqual(child.email_from, parent.email_from) parent.write({'email_from': ''}) self.assertEqual(child.email_from, '[email protected]') def test_write_sale_line_id_on_parent_write_on_child_if_same_partner(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id, 'partner_id': self.partner.id}) self.assertFalse(child.sale_line_id) parent.write({'sale_line_id': self.order_line.id}) self.assertEqual(child.sale_line_id, parent.sale_line_id) parent.write({'sale_line_id': False}) self.assertEqual(child.sale_line_id, self.order_line) def test_write_sale_line_id_on_parent_write_on_child_with_partner_if_not_set(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id}) child._compute_partner_id() self.assertFalse(child.sale_line_id) parent.write({'sale_line_id': self.order_line.id}) self.assertEqual(child.sale_line_id, parent.sale_line_id) self.assertEqual(child.partner_id, self.partner) parent.write({'sale_line_id': False}) self.assertEqual(child.sale_line_id, self.order_line) def test_write_sale_line_id_on_parent_dont_write_on_child_if_other_partner(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id}) child = self.env['project.task'].create({'name': 'child', 'parent_id': parent.id, 'partner_id': self.user.partner_id.id}) self.assertFalse(child.sale_line_id) parent.write({'sale_line_id': self.order_line.id}) self.assertFalse(child.sale_line_id) #---------------------------------- # # When linking two existent task, some values go on the child # #---------------------------------- def test_linking_user_id_on_parent_dont_write_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'user_ids': [(4, self.user.id)]}) child = self.env['project.task'].create({'name': 'child', 'user_ids': False}) self.assertFalse(child.user_ids) child.write({'parent_id': parent.id}) self.assertFalse(child.user_ids) def test_linking_partner_id_on_parent_write_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.user.partner_id.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': False}) self.assertFalse(child.partner_id) child.write({'parent_id': parent.id}) self.assertEqual(child.partner_id, self.user.partner_id) def test_linking_email_from_on_parent_write_on_child(self): parent = self.env['project.task'].create({'name': 'parent', 'email_from': '[email protected]'}) child = self.env['project.task'].create({'name': 'child', 'email_from': False}) self.assertFalse(child.email_from) child.write({'parent_id': parent.id}) self.assertEqual(child.email_from, '[email protected]') def test_linking_sale_line_id_on_parent_write_on_child_if_same_partner(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': self.partner.id}) self.assertFalse(child.sale_line_id) child.write({'parent_id': parent.id}) self.assertEqual(child.sale_line_id, parent.sale_line_id) parent.write({'sale_line_id': False}) self.assertEqual(child.sale_line_id, self.order_line) def test_linking_sale_line_id_on_parent_write_on_child_with_partner_if_not_set(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': False}) self.assertFalse(child.sale_line_id) self.assertFalse(child.partner_id) child.write({'parent_id': parent.id}) self.assertEqual(child.partner_id, parent.partner_id) self.assertEqual(child.sale_line_id, parent.sale_line_id) def test_linking_sale_line_id_on_parent_write_dont_child_if_other_partner(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id}) child = self.env['project.task'].create({'name': 'child', 'partner_id': self.user.partner_id.id}) self.assertFalse(child.sale_line_id) self.assertNotEqual(child.partner_id, parent.partner_id) child.write({'parent_id': parent.id}) self.assertFalse(child.sale_line_id) def test_writing_on_parent_with_multiple_tasks(self): parent = self.env['project.task'].create({'name': 'parent', 'user_ids': False, 'partner_id': self.partner.id}) children_values = [{'name': 'child%s' % i, 'user_ids': False, 'parent_id': parent.id} for i in range(5)] children = self.env['project.task'].create(children_values) children._compute_partner_id() # test writing sale_line_id for child in children: self.assertFalse(child.sale_line_id) parent.write({'sale_line_id': self.order_line.id}) for child in children: self.assertEqual(child.sale_line_id, self.order_line) def test_linking_on_parent_with_multiple_tasks(self): parent = self.env['project.task'].create({'name': 'parent', 'partner_id': self.partner.id, 'sale_line_id': self.order_line.id, 'user_ids': [(4, self.user.id)]}) children_values = [{'name': 'child%s' % i, 'user_ids': False} for i in range(5)] children = self.env['project.task'].create(children_values) # test writing user_ids and sale_line_id for child in children: self.assertFalse(child.user_ids) self.assertFalse(child.sale_line_id) children.write({'parent_id': parent.id}) for child in children: self.assertEqual(child.sale_line_id, self.order_line) self.assertFalse(child.user_ids)
56.116592
12,514
21,125
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, Command, fields, models, _ from odoo.tools.safe_eval import safe_eval from odoo.tools.sql import column_exists, create_column class SaleOrder(models.Model): _inherit = 'sale.order' tasks_ids = fields.Many2many('project.task', compute='_compute_tasks_ids', string='Tasks associated to this sale') tasks_count = fields.Integer(string='Tasks', compute='_compute_tasks_ids', groups="project.group_project_user") visible_project = fields.Boolean('Display project', compute='_compute_visible_project', readonly=True) project_id = fields.Many2one( 'project.project', 'Project', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help='Select a non billable project on which tasks can be created.') project_ids = fields.Many2many('project.project', compute="_compute_project_ids", string='Projects', copy=False, groups="project.group_project_manager", help="Projects used in this sales order.") project_count = fields.Integer(string='Number of Projects', compute='_compute_project_ids', groups='project.group_project_manager') @api.depends('order_line.product_id.project_id') def _compute_tasks_ids(self): for order in self: order.tasks_ids = self.env['project.task'].search(['&', ('display_project_id', '!=', False), '|', ('sale_line_id', 'in', order.order_line.ids), ('sale_order_id', '=', order.id)]) order.tasks_count = len(order.tasks_ids) @api.depends('order_line.product_id.service_tracking') def _compute_visible_project(self): """ Users should be able to select a project_id on the SO if at least one SO line has a product with its service tracking configured as 'task_in_project' """ for order in self: order.visible_project = any( service_tracking == 'task_in_project' for service_tracking in order.order_line.mapped('product_id.service_tracking') ) @api.depends('order_line.product_id', 'order_line.project_id') def _compute_project_ids(self): for order in self: projects = order.order_line.mapped('product_id.project_id') projects |= order.order_line.mapped('project_id') projects |= order.project_id order.project_ids = projects order.project_count = len(projects) @api.onchange('project_id') def _onchange_project_id(self): """ Set the SO analytic account to the selected project's analytic account """ if self.project_id.analytic_account_id: self.analytic_account_id = self.project_id.analytic_account_id def _action_confirm(self): """ On SO confirmation, some lines should generate a task or a project. """ result = super()._action_confirm() if len(self.company_id) == 1: # All orders are in the same company self.order_line.sudo().with_company(self.company_id)._timesheet_service_generation() else: # Orders from different companies are confirmed together for order in self: order.order_line.sudo().with_company(order.company_id)._timesheet_service_generation() return result def action_view_task(self): self.ensure_one() list_view_id = self.env.ref('project.view_task_tree2').id form_view_id = self.env.ref('project.view_task_form2').id action = {'type': 'ir.actions.act_window_close'} task_projects = self.tasks_ids.mapped('project_id') if len(task_projects) == 1 and len(self.tasks_ids) > 1: # redirect to task of the project (with kanban stage, ...) action = self.with_context(active_id=task_projects.id).env['ir.actions.actions']._for_xml_id( 'project.act_project_project_2_project_task_all') action['domain'] = [('id', 'in', self.tasks_ids.ids)] if action.get('context'): eval_context = self.env['ir.actions.actions']._get_eval_context() eval_context.update({'active_id': task_projects.id}) action_context = safe_eval(action['context'], eval_context) action_context.update(eval_context) action['context'] = action_context else: action = self.env["ir.actions.actions"]._for_xml_id("project.action_view_task") action['context'] = {} # erase default context to avoid default filter if len(self.tasks_ids) > 1: # cross project kanban task action['views'] = [[False, 'kanban'], [list_view_id, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'calendar'], [False, 'pivot']] elif len(self.tasks_ids) == 1: # single task -> form view action['views'] = [(form_view_id, 'form')] action['res_id'] = self.tasks_ids.id # filter on the task of the current SO action.setdefault('context', {}) action['context'].update({'search_default_sale_order_id': self.id}) return action def action_view_project_ids(self): self.ensure_one() view_form_id = self.env.ref('project.edit_project').id view_kanban_id = self.env.ref('project.view_project_kanban').id action = { 'type': 'ir.actions.act_window', 'domain': [('id', 'in', self.project_ids.ids)], 'view_mode': 'kanban,form', 'name': _('Projects'), 'res_model': 'project.project', } if len(self.project_ids) == 1: action.update({'views': [(view_form_id, 'form')], 'res_id': self.project_ids.id}) else: action['views'] = [(view_kanban_id, 'kanban'), (view_form_id, 'form')] return action def write(self, values): if 'state' in values and values['state'] == 'cancel': self.project_id.sudo().sale_line_id = False return super(SaleOrder, self).write(values) def _compute_line_data_for_template_change(self, line): data = super()._compute_line_data_for_template_change(line) # prevent the association of a related task on the SOL if a task would be generated when confirming the SO. if 'default_task_id' in self.env.context and line.product_id.service_tracking in ['task_in_project', 'task_global_project']: data['task_id'] = False return data class SaleOrderLine(models.Model): _inherit = "sale.order.line" project_id = fields.Many2one( 'project.project', 'Generated Project', index=True, copy=False, help="Project generated by the sales order item") task_id = fields.Many2one( 'project.task', 'Generated Task', index=True, copy=False, help="Task generated by the sales order item") is_service = fields.Boolean("Is a Service", compute='_compute_is_service', store=True, compute_sudo=True, help="Sales Order item should generate a task and/or a project, depending on the product settings.") @api.depends('product_id.type') def _compute_is_service(self): for so_line in self: so_line.is_service = so_line.product_id.type == 'service' @api.depends('product_id.type') def _compute_product_updatable(self): for line in self: if line.product_id.type == 'service' and line.state == 'sale': line.product_updatable = False else: super(SaleOrderLine, line)._compute_product_updatable() def _auto_init(self): """ Create column to stop ORM from computing it himself (too slow) """ if not column_exists(self.env.cr, 'sale_order_line', 'is_service'): create_column(self.env.cr, 'sale_order_line', 'is_service', 'bool') self.env.cr.execute(""" UPDATE sale_order_line line SET is_service = (pt.type = 'service') FROM product_product pp LEFT JOIN product_template pt ON pt.id = pp.product_tmpl_id WHERE pp.id = line.product_id """) return super()._auto_init() @api.model_create_multi def create(self, vals_list): lines = super().create(vals_list) # Do not generate task/project when expense SO line, but allow # generate task with hours=0. for line in lines: if line.state == 'sale' and not line.is_expense: line.sudo()._timesheet_service_generation() # if the SO line created a task, post a message on the order if line.task_id: msg_body = _("Task Created (%s): <a href=# data-oe-model=project.task data-oe-id=%d>%s</a>") % (line.product_id.name, line.task_id.id, line.task_id.name) line.order_id.message_post(body=msg_body) return lines def write(self, values): result = super().write(values) # changing the ordered quantity should change the planned hours on the # task, whatever the SO state. It will be blocked by the super in case # of a locked sale order. if 'product_uom_qty' in values and not self.env.context.get('no_update_planned_hours', False): for line in self: if line.task_id and line.product_id.type == 'service': planned_hours = line._convert_qty_company_hours(line.task_id.company_id) line.task_id.write({'planned_hours': planned_hours}) return result ########################################### # Service : Project and task generation ########################################### def _convert_qty_company_hours(self, dest_company): return self.product_uom_qty def _timesheet_create_project_prepare_values(self): """Generate project values""" account = self.order_id.analytic_account_id if not account: self.order_id._create_analytic_account(prefix=self.product_id.default_code or None) account = self.order_id.analytic_account_id # create the project or duplicate one return { 'name': '%s - %s' % (self.order_id.client_order_ref, self.order_id.name) if self.order_id.client_order_ref else self.order_id.name, 'analytic_account_id': account.id, 'partner_id': self.order_id.partner_id.id, 'sale_line_id': self.id, 'active': True, 'company_id': self.company_id.id, } def _timesheet_create_project(self): """ Generate project for the given so line, and link it. :param project: record of project.project in which the task should be created :return task: record of the created task """ self.ensure_one() values = self._timesheet_create_project_prepare_values() if self.product_id.project_template_id: values['name'] = "%s - %s" % (values['name'], self.product_id.project_template_id.name) project = self.product_id.project_template_id.copy(values) project.tasks.write({ 'sale_line_id': self.id, 'partner_id': self.order_id.partner_id.id, 'email_from': self.order_id.partner_id.email, }) # duplicating a project doesn't set the SO on sub-tasks project.tasks.filtered(lambda task: task.parent_id != False).write({ 'sale_line_id': self.id, 'sale_order_id': self.order_id, }) else: project = self.env['project.project'].create(values) # Avoid new tasks to go to 'Undefined Stage' if not project.type_ids: project.type_ids = self.env['project.task.type'].create({'name': _('New')}) # link project as generated by current so line self.write({'project_id': project.id}) return project def _timesheet_create_task_prepare_values(self, project): self.ensure_one() planned_hours = self._convert_qty_company_hours(self.company_id) sale_line_name_parts = self.name.split('\n') title = sale_line_name_parts[0] or self.product_id.name description = '<br/>'.join(sale_line_name_parts[1:]) return { 'name': title if project.sale_line_id else '%s: %s' % (self.order_id.name or '', title), 'planned_hours': planned_hours, 'partner_id': self.order_id.partner_id.id, 'email_from': self.order_id.partner_id.email, 'description': description, 'project_id': project.id, 'sale_line_id': self.id, 'sale_order_id': self.order_id.id, 'company_id': project.company_id.id, 'user_ids': False, # force non assigned task, as created as sudo() } def _timesheet_create_task(self, project): """ Generate task for the given so line, and link it. :param project: record of project.project in which the task should be created :return task: record of the created task """ values = self._timesheet_create_task_prepare_values(project) task = self.env['project.task'].sudo().create(values) self.write({'task_id': task.id}) # post message on task task_msg = _("This task has been created from: <a href=# data-oe-model=sale.order data-oe-id=%d>%s</a> (%s)") % (self.order_id.id, self.order_id.name, self.product_id.name) task.message_post(body=task_msg) return task def _timesheet_service_generation(self): """ For service lines, create the task or the project. If already exists, it simply links the existing one to the line. Note: If the SO was confirmed, cancelled, set to draft then confirmed, avoid creating a new project/task. This explains the searches on 'sale_line_id' on project/task. This also implied if so line of generated task has been modified, we may regenerate it. """ so_line_task_global_project = self.filtered(lambda sol: sol.is_service and sol.product_id.service_tracking == 'task_global_project') so_line_new_project = self.filtered(lambda sol: sol.is_service and sol.product_id.service_tracking in ['project_only', 'task_in_project']) # search so lines from SO of current so lines having their project generated, in order to check if the current one can # create its own project, or reuse the one of its order. map_so_project = {} if so_line_new_project: order_ids = self.mapped('order_id').ids so_lines_with_project = self.search([('order_id', 'in', order_ids), ('project_id', '!=', False), ('product_id.service_tracking', 'in', ['project_only', 'task_in_project']), ('product_id.project_template_id', '=', False)]) map_so_project = {sol.order_id.id: sol.project_id for sol in so_lines_with_project} so_lines_with_project_templates = self.search([('order_id', 'in', order_ids), ('project_id', '!=', False), ('product_id.service_tracking', 'in', ['project_only', 'task_in_project']), ('product_id.project_template_id', '!=', False)]) map_so_project_templates = {(sol.order_id.id, sol.product_id.project_template_id.id): sol.project_id for sol in so_lines_with_project_templates} # search the global project of current SO lines, in which create their task map_sol_project = {} if so_line_task_global_project: map_sol_project = {sol.id: sol.product_id.with_company(sol.company_id).project_id for sol in so_line_task_global_project} def _can_create_project(sol): if not sol.project_id: if sol.product_id.project_template_id: return (sol.order_id.id, sol.product_id.project_template_id.id) not in map_so_project_templates elif sol.order_id.id not in map_so_project: return True return False def _determine_project(so_line): """Determine the project for this sale order line. Rules are different based on the service_tracking: - 'project_only': the project_id can only come from the sale order line itself - 'task_in_project': the project_id comes from the sale order line only if no project_id was configured on the parent sale order""" if so_line.product_id.service_tracking == 'project_only': return so_line.project_id elif so_line.product_id.service_tracking == 'task_in_project': return so_line.order_id.project_id or so_line.project_id return False # task_global_project: create task in global project for so_line in so_line_task_global_project: if not so_line.task_id: if map_sol_project.get(so_line.id) and so_line.product_uom_qty > 0: so_line._timesheet_create_task(project=map_sol_project[so_line.id]) # project_only, task_in_project: create a new project, based or not on a template (1 per SO). May be create a task too. # if 'task_in_project' and project_id configured on SO, use that one instead for so_line in so_line_new_project: project = _determine_project(so_line) if not project and _can_create_project(so_line): project = so_line._timesheet_create_project() if so_line.product_id.project_template_id: map_so_project_templates[(so_line.order_id.id, so_line.product_id.project_template_id.id)] = project else: map_so_project[so_line.order_id.id] = project elif not project: # Attach subsequent SO lines to the created project so_line.project_id = ( map_so_project_templates.get((so_line.order_id.id, so_line.product_id.project_template_id.id)) or map_so_project.get(so_line.order_id.id) ) if so_line.product_id.service_tracking == 'task_in_project': if not project: if so_line.product_id.project_template_id: project = map_so_project_templates[(so_line.order_id.id, so_line.product_id.project_template_id.id)] else: project = map_so_project[so_line.order_id.id] if not so_line.task_id: so_line._timesheet_create_task(project=project) def _prepare_invoice_line(self, **optional_values): """ If the sale order line isn't linked to a sale order which already have a default analytic account, this method allows to retrieve the analytic account which is linked to project or task directly linked to this sale order line, or the analytic account of the project which uses this sale order line, if it exists. """ values = super(SaleOrderLine, self)._prepare_invoice_line(**optional_values) if not values.get('analytic_account_id'): task_analytic_account = self.task_id._get_task_analytic_account_id() if self.task_id else False if task_analytic_account: values['analytic_account_id'] = task_analytic_account.id elif self.project_id.analytic_account_id: values['analytic_account_id'] = self.project_id.analytic_account_id.id elif self.is_service and not self.is_expense: task_analytic_account_id = self.env['project.task'].read_group([ ('sale_line_id', '=', self.id), ('analytic_account_id', '!=', False), ], ['analytic_account_id'], ['analytic_account_id']) project_analytic_account_id = self.env['project.project'].read_group([ ('analytic_account_id', '!=', False), '|', ('sale_line_id', '=', self.id), '&', ('tasks.sale_line_id', '=', self.id), ('tasks.analytic_account_id', '=', False) ], ['analytic_account_id'], ['analytic_account_id']) analytic_account_ids = {rec['analytic_account_id'][0] for rec in (task_analytic_account_id + project_analytic_account_id)} if len(analytic_account_ids) == 1: values['analytic_account_id'] = analytic_account_ids.pop() analytic_tag_ids = [Command.link(tag_id.id) for tag_id in self.task_id.analytic_tag_ids] if self.is_service and not self.is_expense: tag_ids = self.env['account.analytic.tag'].search([ ('task_ids.sale_line_id', '=', self.id) ]) analytic_tag_ids += [Command.link(tag_id.id) for tag_id in tag_ids] if analytic_tag_ids: values['analytic_tag_ids'] = values.get('analytic_tag_ids', []) + analytic_tag_ids return values
53.616751
21,125
5,985
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class ProductTemplate(models.Model): _inherit = 'product.template' service_tracking = fields.Selection( selection=[ ('no', 'Nothing'), ('task_global_project', 'Task'), ('task_in_project', 'Project & Task'), ('project_only', 'Project'), ], string="Create on Order", default="no", help="On Sales order confirmation, this product can generate a project and/or task. \ From those, you can track the service you are selling.\n \ 'In sale order\'s project': Will use the sale order\'s configured project if defined or fallback to \ creating a new project based on the selected template.") project_id = fields.Many2one( 'project.project', 'Project', company_dependent=True, domain="[('company_id', '=', current_company_id)]", help='Select a billable project on which tasks can be created. This setting must be set for each company.') project_template_id = fields.Many2one( 'project.project', 'Project Template', company_dependent=True, copy=True, domain="[('company_id', '=', current_company_id)]", help='Select a billable project to be the skeleton of the new created project when selling the current product. Its stages and tasks will be duplicated.') @api.depends('service_tracking', 'type') def _compute_product_tooltip(self): super()._compute_product_tooltip() for record in self.filtered(lambda record: record.type == 'service'): if record.service_tracking == 'no': record.product_tooltip = _( "Invoice ordered quantities as soon as this service is sold." ) elif record.service_tracking == 'task_global_project': record.product_tooltip = _( "Invoice as soon as this service is sold, and create a task in an existing " "project to track the time spent." ) elif record.service_tracking == 'task_in_project': record.product_tooltip = _( "Invoice ordered quantities as soon as this service is sold, and create a " "project for the order with a task for each sales order line to track the time" " spent." ) elif record.service_tracking == 'project_only': record.product_tooltip = _( "Invoice ordered quantities as soon as this service is sold, and create an " "empty project for the order to track the time spent." ) @api.constrains('project_id', 'project_template_id') def _check_project_and_template(self): """ NOTE 'service_tracking' should be in decorator parameters but since ORM check constraints twice (one after setting stored fields, one after setting non stored field), the error is raised when company-dependent fields are not set. So, this constraints does cover all cases and inconsistent can still be recorded until the ORM change its behavior. """ for product in self: if product.service_tracking == 'no' and (product.project_id or product.project_template_id): raise ValidationError(_('The product %s should not have a project nor a project template since it will not generate project.') % (product.name,)) elif product.service_tracking == 'task_global_project' and product.project_template_id: raise ValidationError(_('The product %s should not have a project template since it will generate a task in a global project.') % (product.name,)) elif product.service_tracking in ['task_in_project', 'project_only'] and product.project_id: raise ValidationError(_('The product %s should not have a global project since it will generate a project.') % (product.name,)) @api.onchange('service_tracking') def _onchange_service_tracking(self): if self.service_tracking == 'no': self.project_id = False self.project_template_id = False elif self.service_tracking == 'task_global_project': self.project_template_id = False elif self.service_tracking in ['task_in_project', 'project_only']: self.project_id = False @api.onchange('type') def _onchange_type(self): res = super(ProductTemplate, self)._onchange_type() if self.type != 'service': self.service_tracking = 'no' return res def write(self, vals): if 'type' in vals and vals['type'] != 'service': vals.update({ 'service_tracking': 'no', 'project_id': False }) return super(ProductTemplate, self).write(vals) class ProductProduct(models.Model): _inherit = 'product.product' @api.onchange('service_tracking') def _onchange_service_tracking(self): if self.service_tracking == 'no': self.project_id = False self.project_template_id = False elif self.service_tracking == 'task_global_project': self.project_template_id = False elif self.service_tracking in ['task_in_project', 'project_only']: self.project_id = False @api.onchange('type') def _onchange_type(self): res = super(ProductProduct, self)._onchange_type() if self.type != 'service': self.service_tracking = 'no' return res def write(self, vals): if 'type' in vals and vals['type'] != 'service': vals.update({ 'service_tracking': 'no', 'project_id': False }) return super(ProductProduct, self).write(vals)
48.658537
5,985
12,605
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from ast import literal_eval from odoo import api, fields, models, _, _lt from odoo.exceptions import ValidationError, UserError from odoo.osv import expression from odoo.osv.query import Query class Project(models.Model): _inherit = 'project.project' sale_line_id = fields.Many2one( 'sale.order.line', 'Sales Order Item', copy=False, compute="_compute_sale_line_id", store=True, readonly=False, index=True, domain="[('is_service', '=', True), ('is_expense', '=', False), ('state', 'in', ['sale', 'done']), ('order_partner_id', '=?', partner_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", help="Sales order item to which the project is linked. Link the timesheet entry to the sales order item defined on the project. " "Only applies on tasks without sale order item defined, and if the employee is not in the 'Employee/Sales Order Item Mapping' of the project.") sale_order_id = fields.Many2one(string='Sales Order', related='sale_line_id.order_id', help="Sales order to which the project is linked.") has_any_so_to_invoice = fields.Boolean('Has SO to Invoice', compute='_compute_has_any_so_to_invoice') @api.model def _map_tasks_default_valeus(self, task, project): defaults = super()._map_tasks_default_valeus(task, project) defaults['sale_line_id'] = False return defaults @api.depends('partner_id') def _compute_sale_line_id(self): self.filtered( lambda p: p.sale_line_id and ( not p.partner_id or p.sale_line_id.order_partner_id.commercial_partner_id != p.partner_id.commercial_partner_id ) ).update({'sale_line_id': False}) @api.depends('sale_order_id.invoice_status', 'tasks.sale_order_id.invoice_status') def _compute_has_any_so_to_invoice(self): """Has any Sale Order whose invoice_status is set as To Invoice""" if not self.ids: self.has_any_so_to_invoice = False return self.env.cr.execute(""" SELECT id FROM project_project pp WHERE pp.active = true AND ( EXISTS(SELECT 1 FROM sale_order so JOIN project_task pt ON pt.sale_order_id = so.id WHERE pt.project_id = pp.id AND pt.active = true AND so.invoice_status = 'to invoice') OR EXISTS(SELECT 1 FROM sale_order so JOIN sale_order_line sol ON sol.order_id = so.id WHERE sol.id = pp.sale_line_id AND so.invoice_status = 'to invoice')) AND id in %s""", (tuple(self.ids),)) project_to_invoice = self.env['project.project'].browse([x[0] for x in self.env.cr.fetchall()]) project_to_invoice.has_any_so_to_invoice = True (self - project_to_invoice).has_any_so_to_invoice = False def action_view_so(self): self.ensure_one() action_window = { "type": "ir.actions.act_window", "res_model": "sale.order", "name": "Sales Order", "views": [[False, "form"]], "context": {"create": False, "show_sale": True}, "res_id": self.sale_order_id.id } return action_window def action_create_invoice(self): if not self.has_any_so_to_invoice: raise UserError(_("There is nothing to invoice in this project.")) action = self.env["ir.actions.actions"]._for_xml_id("sale.action_view_sale_advance_payment_inv") so_ids = (self.sale_order_id | self.task_ids.sale_order_id).filtered(lambda so: so.invoice_status == 'to invoice').ids action['context'] = { 'active_id': so_ids[0] if len(so_ids) == 1 else False, 'active_ids': so_ids } return action # ---------------------------- # Project Updates # ---------------------------- def _get_sale_order_stat_button(self): self.ensure_one() return { 'icon': 'dollar', 'text': _lt('Sales Order'), 'action_type': 'object', 'action': 'action_view_so', 'show': bool(self.sale_order_id), 'sequence': 1, } def _fetch_sale_order_items(self, domain_per_model=None, limit=None, offset=None): return self.env['sale.order.line'].browse(self._fetch_sale_order_item_ids(domain_per_model, limit, offset)) def _fetch_sale_order_item_ids(self, domain_per_model=None, limit=None, offset=None): if not self: return [] query = self._get_sale_order_items_query(domain_per_model) query.limit = limit query.offset = offset query_str, params = query.select('DISTINCT sale_line_id') self._cr.execute(query_str, params) return [row[0] for row in self._cr.fetchall()] def _get_sale_orders(self): return self._get_sale_order_items().order_id def _get_sale_order_items(self): return self._fetch_sale_order_items() def _get_sale_order_items_query(self, domain_per_model=None): if domain_per_model is None: domain_per_model = {} project_domain = [('id', 'in', self.ids), ('sale_line_id', '!=', False)] if 'project.project' in domain_per_model: project_domain = expression.AND([project_domain, domain_per_model['project.project']]) project_query = self.env['project.project']._where_calc(project_domain) self._apply_ir_rules(project_query, 'read') project_query_str, project_params = project_query.select('id', 'sale_line_id') Task = self.env['project.task'] task_domain = [('project_id', 'in', self.ids), ('sale_line_id', '!=', False)] if Task._name in domain_per_model: task_domain = expression.AND([task_domain, domain_per_model[Task._name]]) task_query = Task._where_calc(task_domain) Task._apply_ir_rules(task_query, 'read') task_query_str, task_params = task_query.select(f'{Task._table}.project_id AS id', f'{Task._table}.sale_line_id') query = Query(self._cr, 'project_sale_order_item', ' UNION '.join([project_query_str, task_query_str])) query._where_params = project_params + task_params return query def _get_stat_buttons(self): buttons = super(Project, self)._get_stat_buttons() if self.user_has_groups('sales_team.group_sale_salesman_all_leads'): buttons.append(self._get_sale_order_stat_button()) return buttons class ProjectTask(models.Model): _inherit = "project.task" sale_order_id = fields.Many2one('sale.order', 'Sales Order', compute='_compute_sale_order_id', store=True, help="Sales order to which the task is linked.") sale_line_id = fields.Many2one( 'sale.order.line', 'Sales Order Item', domain="[('company_id', '=', company_id), ('is_service', '=', True), ('order_partner_id', 'child_of', commercial_partner_id), ('is_expense', '=', False), ('state', 'in', ['sale', 'done'])]", compute='_compute_sale_line', recursive=True, store=True, readonly=False, copy=False, tracking=True, index=True, help="Sales Order Item to which the time spent on this task will be added, in order to be invoiced to your customer.") project_sale_order_id = fields.Many2one('sale.order', string="Project's sale order", related='project_id.sale_order_id') invoice_count = fields.Integer("Number of invoices", related='sale_order_id.invoice_count') task_to_invoice = fields.Boolean("To invoice", compute='_compute_task_to_invoice', search='_search_task_to_invoice', groups='sales_team.group_sale_salesman_all_leads') @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS | {'sale_order_id', 'sale_line_id'} @api.depends('sale_line_id', 'project_id', 'commercial_partner_id') def _compute_sale_order_id(self): for task in self: sale_order_id = task.sale_order_id or self.env["sale.order"] if task.sale_line_id: sale_order_id = task.sale_line_id.sudo().order_id elif task.project_id.sale_order_id: sale_order_id = task.project_id.sale_order_id if task.commercial_partner_id != sale_order_id.partner_id.commercial_partner_id: sale_order_id = False if sale_order_id and not task.partner_id: task.partner_id = sale_order_id.partner_id task.sale_order_id = sale_order_id @api.depends('commercial_partner_id', 'sale_line_id.order_partner_id.commercial_partner_id', 'parent_id.sale_line_id', 'project_id.sale_line_id') def _compute_sale_line(self): for task in self: if not task.sale_line_id: # if the display_project_id is set then it means the task is classic task or a subtask with another project than its parent. task.sale_line_id = task.display_project_id.sale_line_id or task.parent_id.sale_line_id or task.project_id.sale_line_id # check sale_line_id and customer are coherent if task.sale_line_id.order_partner_id.commercial_partner_id != task.partner_id.commercial_partner_id: task.sale_line_id = False @api.constrains('sale_line_id') def _check_sale_line_type(self): for task in self.sudo(): if task.sale_line_id: if not task.sale_line_id.is_service or task.sale_line_id.is_expense: raise ValidationError(_( 'You cannot link the order item %(order_id)s - %(product_id)s to this task because it is a re-invoiced expense.', order_id=task.sale_line_id.order_id.name, product_id=task.sale_line_id.product_id.display_name, )) @api.ondelete(at_uninstall=False) def _unlink_except_linked_so(self): if any(task.sale_line_id for task in self): raise ValidationError(_('You have to unlink the task from the sale order item in order to delete it.')) # --------------------------------------------------- # Actions # --------------------------------------------------- def _get_action_view_so_ids(self): return self.sale_order_id.ids def action_view_so(self): self.ensure_one() so_ids = self._get_action_view_so_ids() action_window = { "type": "ir.actions.act_window", "res_model": "sale.order", "name": "Sales Order", "views": [[False, "tree"], [False, "form"]], "context": {"create": False, "show_sale": True}, "domain": [["id", "in", so_ids]], } if len(so_ids) == 1: action_window["views"] = [[False, "form"]] action_window["res_id"] = so_ids[0] return action_window def rating_get_partner_id(self): partner = self.partner_id or self.sale_line_id.order_id.partner_id if partner: return partner return super().rating_get_partner_id() @api.depends('sale_order_id.invoice_status', 'sale_order_id.order_line') def _compute_task_to_invoice(self): for task in self: if task.sale_order_id: task.task_to_invoice = bool(task.sale_order_id.invoice_status not in ('no', 'invoiced')) else: task.task_to_invoice = False @api.model def _search_task_to_invoice(self, operator, value): query = """ SELECT so.id FROM sale_order so WHERE so.invoice_status != 'invoiced' AND so.invoice_status != 'no' """ operator_new = 'inselect' if(bool(operator == '=') ^ bool(value)): operator_new = 'not inselect' return [('sale_order_id', operator_new, (query, ()))] class ProjectTaskRecurrence(models.Model): _inherit = 'project.task.recurrence' def _new_task_values(self, task): values = super(ProjectTaskRecurrence, self)._new_task_values(task) task = self.sudo().task_ids[0] values['sale_line_id'] = self._get_sale_line_id(task) return values def _get_sale_line_id(self, task): return task.sale_line_id.id
46.858736
12,605
469
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 ReportProjectTaskUser(models.Model): _inherit = "report.project.task.user" sale_order_id = fields.Many2one('sale.order', string='Sales Order', readonly=True) def _select(self): return super()._select() + ", t.sale_order_id" def _group_by(self): return super()._group_by() + ", t.sale_order_id"
29.3125
469
2,011
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from operator import itemgetter from odoo import _ from odoo.http import request from odoo.tools import groupby as groupbyelem from odoo.osv.expression import OR from odoo.addons.project.controllers.portal import ProjectCustomerPortal class SaleProjectCustomerPortal(ProjectCustomerPortal): def _task_get_searchbar_groupby(self): values = super()._task_get_searchbar_groupby() values['sale_order'] = {'input': 'sale_order', 'label': _('Sales Order'), 'order': 7} values['sale_line'] = {'input': 'sale_line', 'label': _('Sales Order Item'), 'order': 8} return dict(sorted(values.items(), key=lambda item: item[1]["order"])) def _task_get_groupby_mapping(self): groupby_mapping = super()._task_get_groupby_mapping() groupby_mapping.update(sale_order='sale_order_id', sale_line='sale_line_id') return groupby_mapping def _task_get_searchbar_inputs(self): values = super()._task_get_searchbar_inputs() values['sale_order'] = {'input': 'sale_order', 'label': _('Search in Sales Order'), 'order': 7} values['sale_line'] = {'input': 'sale_line', 'label': _('Search in Sales Order Item'), 'order': 8} values['invoice'] = {'input': 'invoice', 'label': _('Search in Invoice'), 'order': 9} return dict(sorted(values.items(), key=lambda item: item[1]["order"])) def _task_get_search_domain(self, search_in, search): search_domain = [super()._task_get_search_domain(search_in, search)] if search_in in ('sale_order', 'all'): search_domain.append([('sale_order_id.name', 'ilike', search)]) if search_in in ('sale_line', 'all'): search_domain.append([('sale_line_id.name', 'ilike', search)]) if search_in in ('invoice', 'all'): search_domain.append([('sale_order_id.invoice_ids.name', 'ilike', search)]) return OR(search_domain)
46.767442
2,011