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
|
|---|---|---|---|---|---|---|
2,818 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.addons.http_routing.models.ir_http import slug
class EventEvent(models.Model):
_inherit = "event.event"
# sponsors
sponsor_ids = fields.One2many('event.sponsor', 'event_id', 'Sponsors')
sponsor_count = fields.Integer('Sponsor Count', compute='_compute_sponsor_count')
# frontend menu management
exhibitor_menu = fields.Boolean(
string='Showcase Exhibitors', compute='_compute_exhibitor_menu',
readonly=False, store=True)
exhibitor_menu_ids = fields.One2many(
'website.event.menu', 'event_id', string='Exhibitors Menus',
domain=[('menu_type', '=', 'exhibitor')])
def _compute_sponsor_count(self):
data = self.env['event.sponsor'].read_group([], ['event_id'], ['event_id'])
result = dict((data['event_id'][0], data['event_id_count']) for data in data)
for event in self:
event.sponsor_count = result.get(event.id, 0)
@api.depends('event_type_id', 'website_menu', 'exhibitor_menu')
def _compute_exhibitor_menu(self):
for event in self:
if event.event_type_id and event.event_type_id != event._origin.event_type_id:
event.exhibitor_menu = event.event_type_id.exhibitor_menu
elif event.website_menu and (event.website_menu != event._origin.website_menu or not event.exhibitor_menu):
event.exhibitor_menu = True
elif not event.website_menu:
event.exhibitor_menu = False
# ------------------------------------------------------------
# WEBSITE MENU MANAGEMENT
# ------------------------------------------------------------
def toggle_exhibitor_menu(self, val):
self.exhibitor_menu = val
def _get_menu_update_fields(self):
return super(EventEvent, self)._get_menu_update_fields() + ['exhibitor_menu']
def _update_website_menus(self, menus_update_by_field=None):
super(EventEvent, self)._update_website_menus(menus_update_by_field=menus_update_by_field)
for event in self:
if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('exhibitor_menu')):
event._update_website_menu_entry('exhibitor_menu', 'exhibitor_menu_ids', 'exhibitor')
def _get_menu_type_field_matching(self):
res = super(EventEvent, self)._get_menu_type_field_matching()
res['exhibitor'] = 'exhibitor_menu'
return res
def _get_website_menu_entries(self):
self.ensure_one()
return super(EventEvent, self)._get_website_menu_entries() + [
(_('Exhibitors'), '/event/%s/exhibitors' % slug(self), False, 60, 'exhibitor')
]
| 44.730159 | 2,818 |
338 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class EventMenu(models.Model):
_inherit = "website.event.menu"
menu_type = fields.Selection(
selection_add=[('exhibitor', 'Exhibitors Menus')],
ondelete={'exhibitor': 'cascade'})
| 28.166667 | 338 |
11,175 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from pytz import timezone, utc
from odoo import api, fields, models, _
from odoo.addons.http_routing.models.ir_http import slug
from odoo.addons.resource.models.resource import float_to_time
from odoo.modules.module import get_resource_path
from odoo.tools import is_html_empty
from odoo.tools.translate import html_translate
class Sponsor(models.Model):
_name = "event.sponsor"
_description = 'Event Sponsor'
_order = "sequence, sponsor_type_id"
# _order = 'sponsor_type_id, sequence' TDE FIXME
_rec_name = 'name'
_inherit = [
'mail.thread',
'mail.activity.mixin',
'website.published.mixin',
'chat.room.mixin'
]
def _default_sponsor_type_id(self):
return self.env['event.sponsor.type'].search([], order="sequence desc", limit=1).id
event_id = fields.Many2one('event.event', 'Event', required=True)
sponsor_type_id = fields.Many2one(
'event.sponsor.type', 'Sponsoring Level',
default=lambda self: self._default_sponsor_type_id(), required=True, auto_join=True)
url = fields.Char('Sponsor Website', compute='_compute_url', readonly=False, store=True)
sequence = fields.Integer('Sequence')
active = fields.Boolean(default=True)
# description
subtitle = fields.Char('Slogan', help='Catchy marketing sentence for promote')
exhibitor_type = fields.Selection(
[('sponsor', 'Sponsor'), ('exhibitor', 'Exhibitor'), ('online', 'Online Exhibitor')],
string="Sponsor Type", default="sponsor")
website_description = fields.Html(
'Description', compute='_compute_website_description',
sanitize_attributes=False, sanitize_form=True, translate=html_translate,
readonly=False, store=True)
# contact information
partner_id = fields.Many2one('res.partner', 'Partner', required=True, auto_join=True)
partner_name = fields.Char('Name', related='partner_id.name')
partner_email = fields.Char('Email', related='partner_id.email')
partner_phone = fields.Char('Phone', related='partner_id.phone')
partner_mobile = fields.Char('Mobile', related='partner_id.mobile')
name = fields.Char('Sponsor Name', compute='_compute_name', readonly=False, store=True)
email = fields.Char('Sponsor Email', compute='_compute_email', readonly=False, store=True)
phone = fields.Char('Sponsor Phone', compute='_compute_phone', readonly=False, store=True)
mobile = fields.Char('Sponsor Mobile', compute='_compute_mobile', readonly=False, store=True)
# image
image_512 = fields.Image(
string="Logo", max_width=512, max_height=512,
compute='_compute_image_512', readonly=False, store=True)
image_256 = fields.Image("Image 256", related="image_512", max_width=256, max_height=256, store=False)
image_128 = fields.Image("Image 128", related="image_512", max_width=128, max_height=128, store=False)
website_image_url = fields.Char(
string='Image URL',
compute='_compute_website_image_url', compute_sudo=True, store=False)
# live mode
hour_from = fields.Float('Opening hour', default=8.0)
hour_to = fields.Float('End hour', default=18.0)
event_date_tz = fields.Selection(string='Timezone', related='event_id.date_tz', readonly=True)
is_in_opening_hours = fields.Boolean(
'Within opening hours', compute='_compute_is_in_opening_hours')
# chat room
chat_room_id = fields.Many2one(readonly=False)
room_name = fields.Char(readonly=False)
# country information (related to ease frontend templates)
country_id = fields.Many2one(
'res.country', string='Country',
related='partner_id.country_id', readonly=True)
country_flag_url = fields.Char(
string='Country Flag',
compute='_compute_country_flag_url', compute_sudo=True)
@api.depends('partner_id')
def _compute_url(self):
for sponsor in self:
if sponsor.partner_id.website or not sponsor.url:
sponsor.url = sponsor.partner_id.website
@api.depends('partner_id')
def _compute_name(self):
self._synchronize_with_partner('name')
@api.depends('partner_id')
def _compute_email(self):
self._synchronize_with_partner('email')
@api.depends('partner_id')
def _compute_phone(self):
self._synchronize_with_partner('phone')
@api.depends('partner_id')
def _compute_mobile(self):
self._synchronize_with_partner('mobile')
@api.depends('partner_id')
def _compute_image_512(self):
self._synchronize_with_partner('image_512')
@api.depends('image_512', 'partner_id.image_256')
def _compute_website_image_url(self):
for sponsor in self:
if sponsor.image_512:
# image_512 is stored, image_256 is derived from it dynamically
sponsor.website_image_url = self.env['website'].image_url(sponsor, 'image_256', size=256)
elif sponsor.partner_id.image_256:
sponsor.website_image_url = self.env['website'].image_url(sponsor.partner_id, 'image_256', size=256)
else:
sponsor.website_image_url = get_resource_path('website_event_exhibitor', 'static/src/img', 'event_sponsor_default_%d.png' % (sponsor.id % 1))
def _synchronize_with_partner(self, fname):
""" Synchronize with partner if not set. Setting a value does not write
on partner as this may be event-specific information. """
for sponsor in self:
if not sponsor[fname]:
sponsor[fname] = sponsor.partner_id[fname]
@api.onchange('exhibitor_type')
def _onchange_exhibitor_type(self):
""" Keep an explicit onchange to allow configuration of room names, even
if this field is normally a related on chat_room_id.name. It is not a real
computed field, an onchange used in form view is sufficient. """
for sponsor in self:
if sponsor.exhibitor_type == 'online' and not sponsor.room_name:
if sponsor.name:
room_name = "odoo-exhibitor-%s" % sponsor.name
else:
room_name = self.env['chat.room']._default_name(objname='exhibitor')
sponsor.room_name = self._jitsi_sanitize_name(room_name)
if sponsor.exhibitor_type == 'online' and not sponsor.room_max_capacity:
sponsor.room_max_capacity = '8'
@api.depends('partner_id')
def _compute_website_description(self):
for sponsor in self:
if is_html_empty(sponsor.website_description):
sponsor.website_description = sponsor.partner_id.website_description
@api.depends('event_id.is_ongoing', 'hour_from', 'hour_to', 'event_id.date_begin', 'event_id.date_end')
def _compute_is_in_opening_hours(self):
""" Opening hours: hour_from and hour_to are given within event TZ or UTC.
Now() must therefore be computed based on that TZ. """
for sponsor in self:
if not sponsor.event_id.is_ongoing:
sponsor.is_in_opening_hours = False
elif not sponsor.hour_from or not sponsor.hour_to:
sponsor.is_in_opening_hours = True
else:
event_tz = timezone(sponsor.event_id.date_tz)
# localize now, begin and end datetimes in event tz
dt_begin = sponsor.event_id.date_begin.astimezone(event_tz)
dt_end = sponsor.event_id.date_end.astimezone(event_tz)
now_utc = utc.localize(fields.Datetime.now().replace(microsecond=0))
now_tz = now_utc.astimezone(event_tz)
# compute opening hours
opening_from_tz = event_tz.localize(datetime.combine(now_tz.date(), float_to_time(sponsor.hour_from)))
opening_to_tz = event_tz.localize(datetime.combine(now_tz.date(), float_to_time(sponsor.hour_to)))
opening_from = max([dt_begin, opening_from_tz])
opening_to = min([dt_end, opening_to_tz])
sponsor.is_in_opening_hours = opening_from <= now_tz < opening_to
@api.depends('partner_id.country_id.image_url')
def _compute_country_flag_url(self):
for sponsor in self:
if sponsor.partner_id.country_id:
sponsor.country_flag_url = sponsor.partner_id.country_id.image_url
else:
sponsor.country_flag_url = False
# ------------------------------------------------------------
# MIXINS
# ---------------------------------------------------------
@api.depends('name', 'event_id.name')
def _compute_website_url(self):
super(Sponsor, self)._compute_website_url()
for sponsor in self:
if sponsor.id: # avoid to perform a slug on a not yet saved record in case of an onchange.
base_url = sponsor.event_id.get_base_url()
sponsor.website_url = '%s/event/%s/exhibitor/%s' % (base_url, slug(sponsor.event_id), slug(sponsor))
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
@api.model_create_multi
def create(self, values_list):
for values in values_list:
if values.get('is_exhibitor') and not values.get('room_name'):
exhibitor_name = values['name'] if values.get('name') else self.env['res.partner'].browse(values['partner_id']).name
name = 'odoo-exhibitor-%s' % exhibitor_name or 'sponsor'
values['room_name'] = name
return super(Sponsor, self).create(values_list)
def write(self, values):
toupdate = self.env['event.sponsor']
if values.get('is_exhibitor') and not values.get('chat_room_id') and not values.get('room_name'):
toupdate = self.filtered(lambda exhibitor: not exhibitor.chat_room_id)
# go into sequential update in order to create a custom room name for each sponsor
for exhibitor in toupdate:
values['room_name'] = 'odoo-exhibitor-%s' % exhibitor.name
super(Sponsor, exhibitor).write(values)
return super(Sponsor, self - toupdate).write(values)
# ------------------------------------------------------------
# ACTIONS
# ---------------------------------------------------------
def get_backend_menu_id(self):
return self.env.ref('event.event_main_menu').id
# ------------------------------------------------------------
# MESSAGING
# ------------------------------------------------------------
def _message_get_suggested_recipients(self):
recipients = super(Sponsor, self)._message_get_suggested_recipients()
for sponsor in self:
if sponsor.partner_id:
sponsor._message_add_suggested_recipient(
recipients,
partner=sponsor.partner_id,
reason=_('Sponsor')
)
return recipients
| 47.151899 | 11,175 |
729 |
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 SponsorType(models.Model):
_name = "event.sponsor.type"
_description = 'Event Sponsor Level'
_order = "sequence"
def _default_sequence(self):
return (self.search([], order="sequence desc", limit=1).sequence or 0) + 1
name = fields.Char('Sponsor Level', required=True, translate=True)
sequence = fields.Integer('Sequence', default=_default_sequence)
display_ribbon_style = fields.Selection(
[('no_ribbon', 'No Ribbon'), ('Gold', 'Gold'),
('Silver', 'Silver'), ('Bronze', 'Bronze')],
string='Ribbon Style', default='no_ribbon')
| 36.45 | 729 |
11,008 |
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 collections import OrderedDict
from random import randint, sample
from werkzeug.exceptions import NotFound, Forbidden
from odoo import exceptions, http
from odoo.addons.website_event.controllers.main import WebsiteEventController
from odoo.http import request
from odoo.osv import expression
from odoo.tools import format_duration
class ExhibitorController(WebsiteEventController):
def _get_event_sponsors_base_domain(self, event):
search_domain_base = [
('event_id', '=', event.id),
('exhibitor_type', 'in', ['exhibitor', 'online']),
]
if not request.env.user.has_group('event.group_event_registration_desk'):
search_domain_base = expression.AND([search_domain_base, [('is_published', '=', True)]])
return search_domain_base
# ------------------------------------------------------------
# MAIN PAGE
# ------------------------------------------------------------
@http.route([
# TDE BACKWARD: exhibitors is actually a typo
'/event/<model("event.event"):event>/exhibitors',
# TDE BACKWARD: matches event/event-1/exhibitor/exhib-1 sub domain
'/event/<model("event.event"):event>/exhibitor'
], type='http', auth="public", website=True, sitemap=False, methods=['GET', 'POST'])
def event_exhibitors(self, event, **searches):
return request.render(
"website_event_exhibitor.event_exhibitors",
self._event_exhibitors_get_values(event, **searches)
)
def _event_exhibitors_get_values(self, event, **searches):
# init and process search terms
searches.setdefault('search', '')
searches.setdefault('countries', '')
searches.setdefault('sponsorships', '')
search_domain_base = self._get_event_sponsors_base_domain(event)
search_domain = search_domain_base
# search on content
if searches.get('search'):
search_domain = expression.AND([
search_domain,
['|', ('name', 'ilike', searches['search']), ('website_description', 'ilike', searches['search'])]
])
# search on countries
search_countries = self._get_search_countries(searches['countries'])
if search_countries:
search_domain = expression.AND([
search_domain,
[('partner_id.country_id', 'in', search_countries.ids)]
])
# search on sponsor types
search_sponsorships = self._get_search_sponsorships(searches['sponsorships'])
if search_sponsorships:
search_domain = expression.AND([
search_domain,
[('sponsor_type_id', 'in', search_sponsorships.ids)]
])
# fetch data to display; use sudo to allow reading partner info, be sure domain is correct
event = event.with_context(tz=event.date_tz or 'UTC')
sponsors = request.env['event.sponsor'].sudo().search(
search_domain
).sorted(lambda sponsor: (sponsor.sponsor_type_id.sequence, sponsor.sequence))
sponsors_all = request.env['event.sponsor'].sudo().search(search_domain_base)
sponsor_types = sponsors_all.mapped('sponsor_type_id')
sponsor_countries = sponsors_all.mapped('partner_id.country_id').sorted('name')
# organize sponsors into categories to help display
sponsor_categories_dict = OrderedDict()
sponsor_categories = []
is_event_user = request.env.user.has_group('event.group_event_registration_desk')
for sponsor in sponsors:
if not sponsor_categories_dict.get(sponsor.sponsor_type_id):
sponsor_categories_dict[sponsor.sponsor_type_id] = request.env['event.sponsor'].sudo()
sponsor_categories_dict[sponsor.sponsor_type_id] |= sponsor
for sponsor_category, sponsors in sponsor_categories_dict.items():
# To display random published sponsors first and random unpublished sponsors last
if is_event_user:
published_sponsors = sponsors.filtered(lambda s: s.website_published)
unpublished_sponsors = sponsors - published_sponsors
random_sponsors = sample(published_sponsors, len(published_sponsors)) + sample(unpublished_sponsors, len(unpublished_sponsors))
else:
random_sponsors = sample(sponsors, len(sponsors))
sponsor_categories.append({
'sponsorship': sponsor_category,
'sponsors': random_sponsors,
})
# return rendering values
return {
# event information
'event': event,
'main_object': event,
'sponsor_categories': sponsor_categories,
'hide_sponsors': True,
# search information
'searches': searches,
'search_key': searches['search'],
'search_countries': search_countries,
'search_sponsorships': search_sponsorships,
'sponsor_types': sponsor_types,
'sponsor_countries': sponsor_countries,
# environment
'hostname': request.httprequest.host.split(':')[0],
'is_event_user': is_event_user,
}
# ------------------------------------------------------------
# FRONTEND FORM
# ------------------------------------------------------------
@http.route(['''/event/<model("event.event", "[('exhibitor_menu', '=', True)]"):event>/exhibitor/<model("event.sponsor", "[('event_id', '=', event.id)]"):sponsor>'''],
type='http', auth="public", website=True, sitemap=True)
def event_exhibitor(self, event, sponsor, **options):
try:
sponsor.check_access_rule('read')
except exceptions.AccessError:
raise Forbidden()
sponsor = sponsor.sudo()
if 'widescreen' not in options and sponsor.chat_room_id and sponsor.is_in_opening_hours:
options['widescreen'] = True
return request.render(
"website_event_exhibitor.event_exhibitor_main",
self._event_exhibitor_get_values(event, sponsor, **options)
)
def _event_exhibitor_get_values(self, event, sponsor, **options):
# search for exhibitor list
search_domain_base = self._get_event_sponsors_base_domain(event)
search_domain_base = expression.AND([
search_domain_base,
[('id', '!=', sponsor.id)]
])
sponsors_other = request.env['event.sponsor'].sudo().search(search_domain_base)
current_country = sponsor.partner_id.country_id
sponsors_other = sponsors_other.sorted(key=lambda sponsor: (
sponsor.website_published,
sponsor.is_in_opening_hours,
sponsor.partner_id.country_id == current_country,
-1 * sponsor.sponsor_type_id.sequence,
randint(0, 20)
), reverse=True)
option_widescreen = options.get('widescreen', False)
option_widescreen = bool(option_widescreen) if option_widescreen != '0' else False
return {
# event information
'event': event,
'main_object': sponsor,
'sponsor': sponsor,
'hide_sponsors': True,
# sidebar
'sponsors_other': sponsors_other[:30],
# options
'option_widescreen': option_widescreen,
'option_can_edit': request.env.user.has_group('event.group_event_user'),
# environment
'hostname': request.httprequest.host.split(':')[0],
'is_event_user': request.env.user.has_group('event.group_event_registration_desk'),
}
# ------------------------------------------------------------
# BUSINESS / MISC
# ------------------------------------------------------------
@http.route('/event_sponsor/<int:sponsor_id>/read', type='json', auth='public', website=True)
def event_sponsor_read(self, sponsor_id):
""" Marshmalling data for "event not started / sponsor not available" modal """
sponsor = request.env['event.sponsor'].browse(sponsor_id)
sponsor_data = sponsor.read([
'name', 'subtitle',
'url', 'email', 'phone',
'website_description', 'website_image_url',
'hour_from', 'hour_to', 'is_in_opening_hours',
'event_date_tz', 'country_flag_url',
])[0]
if sponsor.country_id:
sponsor_data['country_name'] = sponsor.country_id.name
sponsor_data['country_id'] = sponsor.country_id.id
else:
sponsor_data['country_name'] = False
sponsor_data['country_id'] = False
if sponsor.sponsor_type_id:
sponsor_data['sponsor_type_name'] = sponsor.sponsor_type_id.name
sponsor_data['sponsor_type_id'] = sponsor.sponsor_type_id.id
else:
sponsor_data['sponsor_type_name'] = False
sponsor_data['sponsor_type_id'] = False
sponsor_data['event_name'] = sponsor.event_id.name
sponsor_data['event_is_ongoing'] = sponsor.event_id.is_ongoing
sponsor_data['event_is_done'] = sponsor.event_id.is_done
sponsor_data['event_start_today'] = sponsor.event_id.start_today
sponsor_data['event_start_remaining'] = sponsor.event_id.start_remaining
sponsor_data['event_date_begin_located'] = sponsor.event_id.date_begin_located
sponsor_data['event_date_end_located'] = sponsor.event_id.date_end_located
sponsor_data['hour_from_str'] = format_duration(sponsor_data['hour_from'])
sponsor_data['hour_to_str'] = format_duration(sponsor_data['hour_to'])
return sponsor_data
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
def _get_search_countries(self, country_search):
# TDE FIXME: make me generic (slides, event, ...)
country_ids = set(request.httprequest.form.getlist('sponsor_country'))
try:
country_ids.update(literal_eval(country_search))
except Exception:
pass
# perform a search to filter on existing / valid tags implicitly
return request.env['res.country'].sudo().search([('id', 'in', list(country_ids))])
def _get_search_sponsorships(self, sponsorship_search):
# TDE FIXME: make me generic (slides, event, ...)
sponsorship_ids = set(request.httprequest.form.getlist('sponsor_type'))
try:
sponsorship_ids.update(literal_eval(sponsorship_search))
except Exception:
pass
# perform a search to filter on existing / valid tags implicitly
return request.env['event.sponsor.type'].sudo().search([('id', 'in', list(sponsorship_ids))])
| 45.487603 | 11,008 |
1,018 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from babel.dates import format_datetime
from odoo import _
from odoo.http import request
from odoo.addons.website_event.controllers import main
class WebsiteEventController(main.WebsiteEventController):
def _prepare_event_register_values(self, event, **post):
values = super(WebsiteEventController, self)._prepare_event_register_values(event, **post)
if "from_sponsor_id" in post and not event.is_ongoing:
sponsor = request.env["event.sponsor"].browse(int(post["from_sponsor_id"])).exists()
if sponsor:
date_begin = format_datetime(event.with_context(tz=event.date_tz).date_begin, format="medium")
values["toast_message"] = (
_('The event %s starts on %s (%s). \nJoin us there to meet %s !')
% (event.name, date_begin, event.date_tz, sponsor.partner_name)
)
return values
| 40.72 | 1,018 |
2,779 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Sales',
'version': '1.2',
'category': 'Sales/Sales',
'summary': 'Sales internal machinery',
'description': """
This module contains all the common features of Sales Management and eCommerce.
""",
'depends': ['sales_team', 'payment', 'portal', 'utm'],
'data': [
'security/sale_security.xml',
'security/ir.model.access.csv',
'report/sale_report.xml',
'report/sale_report_views.xml',
'report/sale_report_templates.xml',
'report/invoice_report_templates.xml',
'report/report_all_channels_sales_views.xml',
'data/ir_sequence_data.xml',
'data/mail_data_various.xml',
'data/mail_template_data.xml',
'data/mail_templates.xml',
'data/sale_data.xml',
'wizard/sale_make_invoice_advance_views.xml',
'views/sale_views.xml',
'views/crm_team_views.xml',
'views/res_partner_views.xml',
'views/mail_activity_views.xml',
'views/variant_templates.xml',
'views/sale_portal_templates.xml',
'views/sale_onboarding_views.xml',
'views/res_config_settings_views.xml',
'views/payment_templates.xml',
'views/payment_views.xml',
'views/product_views.xml',
'views/product_packaging_views.xml',
'views/utm_campaign_views.xml',
'wizard/sale_order_cancel_views.xml',
'wizard/sale_payment_link_views.xml',
],
'demo': [
'data/product_product_demo.xml',
'data/sale_demo.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'web.assets_backend': [
'sale/static/src/scss/sale_onboarding.scss',
'sale/static/src/scss/product_configurator.scss',
'sale/static/src/js/sale.js',
'sale/static/src/js/tours/sale.js',
'sale/static/src/js/product_configurator_widget.js',
'sale/static/src/js/sale_order_view.js',
'sale/static/src/js/product_discount_widget.js',
],
'web.report_assets_common': [
'sale/static/src/scss/sale_report.scss',
],
'web.assets_frontend': [
'sale/static/src/scss/sale_portal.scss',
'sale/static/src/js/sale_portal_sidebar.js',
'sale/static/src/js/payment_form.js',
],
'web.assets_tests': [
'sale/static/tests/tours/**/*',
],
'web.qunit_suite_tests': [
'sale/static/tests/product_configurator_tests.js',
'sale/static/tests/sales_team_dashboard_tests.js',
],
},
'post_init_hook': '_synchronize_cron',
'license': 'LGPL-3',
}
| 35.628205 | 2,779 |
4,335 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import models
from odoo.tools import populate, groupby
_logger = logging.getLogger(__name__)
class SaleOrder(models.Model):
_inherit = "sale.order"
_populate_sizes = {"small": 100, "medium": 2_000, "large": 20_000}
_populate_dependencies = ["res.partner", "res.company", "res.users", "product.pricelist"]
def _populate_factories(self):
company_ids = self.env.registry.populated_models["res.company"]
def x_ids_by_company(recordset, with_false=True):
x_by_company = dict(groupby(recordset, key=lambda x_record: x_record.company_id.id))
if with_false:
x_inter_company = self.env[recordset._name].concat(*x_by_company.get(False, []))
else:
x_inter_company = self.env[recordset._name]
return {com: (self.env[recordset._name].concat(*x_records) | x_inter_company).ids for com, x_records in x_by_company.items() if com}
partners_ids_by_company = x_ids_by_company(self.env["res.partner"].browse(self.env.registry.populated_models["res.partner"]))
pricelist_ids_by_company = x_ids_by_company(self.env["product.pricelist"].browse(self.env.registry.populated_models["product.pricelist"]))
user_ids_by_company = x_ids_by_company(self.env["res.users"].browse(self.env.registry.populated_models["res.users"]), with_false=False)
def get_company_info(iterator, field_name, model_name):
random = populate.Random("sale_order_company")
for values in iterator:
cid = values.get("company_id")
valid_partner_ids = partners_ids_by_company[cid]
valid_user_ids = user_ids_by_company[cid]
valid_pricelist_ids = pricelist_ids_by_company[cid]
values.update({
"partner_id": random.choice(valid_partner_ids),
"user_id": random.choice(valid_user_ids),
"pricelist_id": random.choice(valid_pricelist_ids),
})
yield values
return [
("company_id", populate.randomize(company_ids)),
("_company_limited_fields", get_company_info),
("require_payment", populate.randomize([True, False])),
("require_signature", populate.randomize([True, False])),
]
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
_populate_sizes = {"small": 1_000, "medium": 50_000, "large": 100_000}
_populate_dependencies = ["sale.order", "product.product"]
def _populate(self, size):
so_line = super()._populate(size)
def confirm_sale_order(sample_ratio):
# Confirm sample_ratio * 100 % of picking
random = populate.Random('confirm_sale_order')
order_ids = so_line.order_id.ids
orders_to_confirm = self.env['sale.order'].browse(random.sample(order_ids, int(len(order_ids) * sample_ratio)))
_logger.info("Confirm %d sale orders", len(orders_to_confirm))
orders_to_confirm.action_confirm()
return orders_to_confirm
confirm_sale_order(0.50)
return so_line
def _populate_factories(self):
order_ids = self.env.registry.populated_models["sale.order"]
product_ids = self.env.registry.populated_models["product.product"]
# If we want more advanced products with multiple variants
# add a populate dependency on product template and the following lines
product_ids += self.env["product.product"].search([
('product_tmpl_id', 'in', self.env.registry.populated_models["product.template"])
]).ids
self.env['product.product'].browse(product_ids).read(['uom_id']) # prefetch all uom_id
def get_product_uom(values, counter, random):
return self.env['product.product'].browse(values['product_id']).uom_id.id
# TODO sections & notes (display_type & name)
return [
("order_id", populate.randomize(order_ids)),
("product_id", populate.randomize(product_ids)),
("product_uom", populate.compute(get_product_uom)),
("product_uom_qty", populate.randint(1, 200)),
]
| 45.631579 | 4,335 |
507 |
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.tools import populate
class ProductProduct(models.Model):
_inherit = "product.product"
def _populate_get_product_factories(self):
"""Populate the invoice_policy of product.product & product.template models."""
return super()._populate_get_product_factories() + [
("invoice_policy", populate.randomize(['order', 'delivery'], [5, 5]))]
| 36.214286 | 507 |
1,493 |
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.tools import populate
class ProductAttribute(models.Model):
_inherit = "product.attribute"
def _populate_factories(self):
return super()._populate_factories() + [
("display_type", populate.randomize(['radio', 'select', 'color'], [6, 3, 1])),
]
class ProductAttributeValue(models.Model):
_inherit = "product.attribute.value"
def _populate_factories(self):
attribute_ids = self.env.registry.populated_models["product.attribute"]
color_attribute_ids = self.env["product.attribute"].search([
("id", "in", attribute_ids),
("display_type", "=", "color"),
]).ids
def get_custom_values(iterator, field_group, model_name):
r = populate.Random('%s+fields+%s' % (model_name, field_group))
for _, values in enumerate(iterator):
attribute_id = values.get("attribute_id")
if attribute_id in color_attribute_ids:
values["html_color"] = r.choice(
["#FFFFFF", "#000000", "#FFC300", "#1BC56D", "#FFFF00", "#FF0000"],
)
elif not r.getrandbits(4):
values["is_custom"] = True
yield values
return super()._populate_factories() + [
("_custom_values", get_custom_values),
]
| 35.547619 | 1,493 |
16,611 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from .common import TestSaleCommon
from odoo.tests import tagged
from odoo.tests.common import Form
@tagged('post_install', '-at_install')
class TestSaleOrder(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
Pricelist = cls.env['product.pricelist']
PricelistItem = cls.env['product.pricelist.item']
SaleOrder = cls.env['sale.order'].with_context(tracking_disable=True)
SaleOrderLine = cls.env['sale.order.line'].with_context(tracking_disable=True)
# Create a product category
cls.product_category_1 = cls.env['product.category'].create({
'name': 'Product Category for pricelist',
})
# Create a pricelist with discount policy: percentage on services, fixed price for product_order
cls.pricelist_discount_incl = Pricelist.create({
'name': 'Pricelist A',
'discount_policy': 'with_discount',
'company_id': cls.company_data['company'].id,
})
PricelistItem.create({
'pricelist_id': cls.pricelist_discount_incl.id,
'applied_on': '1_product',
'product_tmpl_id': cls.company_data['product_service_order'].product_tmpl_id.id,
'compute_price': 'percentage',
'percent_price': 10
})
PricelistItem.create({
'pricelist_id': cls.pricelist_discount_incl.id,
'applied_on': '1_product',
'product_tmpl_id': cls.company_data['product_service_delivery'].product_tmpl_id.id,
'compute_price': 'percentage',
'percent_price': 20,
})
cls.pricelist_discount_incl_item3 = PricelistItem.create({
'pricelist_id': cls.pricelist_discount_incl.id,
'applied_on': '1_product',
'product_tmpl_id': cls.company_data['product_order_no'].product_tmpl_id.id,
'compute_price': 'fixed',
'fixed_price': 211,
})
# Create a pricelist without discount policy: formula for product_category_1 category, percentage for service_order
cls.pricelist_discount_excl = Pricelist.create({
'name': 'Pricelist B',
'discount_policy': 'without_discount',
'company_id': cls.company_data['company'].id,
})
PricelistItem.create({
'pricelist_id': cls.pricelist_discount_excl.id,
'applied_on': '2_product_category',
'categ_id': cls.product_category_1.id,
'compute_price': 'formula',
'base': 'standard_price',
'price_discount': 10,
})
PricelistItem.create({
'pricelist_id': cls.pricelist_discount_excl.id,
'applied_on': '1_product',
'product_tmpl_id': cls.company_data['product_service_order'].product_tmpl_id.id,
'compute_price': 'percentage',
'percent_price': 20,
})
# Create a pricelist without discount policy: percentage on all products
cls.pricelist_discount_excl_global = cls.env['product.pricelist'].create({
'name': 'Pricelist C',
'discount_policy': 'without_discount',
'company_id': cls.env.company.id,
'item_ids': [(0, 0, {
'applied_on': '3_global',
'compute_price': 'percentage',
'percent_price': 54,
})],
})
# create a generic Sale Order with all classical products and empty pricelist
cls.sale_order = SaleOrder.create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
cls.sol_product_order = SaleOrderLine.create({
'name': cls.company_data['product_order_no'].name,
'product_id': cls.company_data['product_order_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_order_no'].uom_id.id,
'price_unit': cls.company_data['product_order_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_deliver = SaleOrderLine.create({
'name': cls.company_data['product_service_delivery'].name,
'product_id': cls.company_data['product_service_delivery'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_service_delivery'].uom_id.id,
'price_unit': cls.company_data['product_service_delivery'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_order = SaleOrderLine.create({
'name': cls.company_data['product_service_order'].name,
'product_id': cls.company_data['product_service_order'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_service_order'].uom_id.id,
'price_unit': cls.company_data['product_service_order'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_prod_deliver = SaleOrderLine.create({
'name': cls.company_data['product_delivery_no'].name,
'product_id': cls.company_data['product_delivery_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_delivery_no'].uom_id.id,
'price_unit': cls.company_data['product_delivery_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
def test_sale_with_pricelist_discount_included(self):
""" Test SO with the pricelist and check unit price appeared on its lines """
# Change the pricelist
self.sale_order.write({'pricelist_id': self.pricelist_discount_incl.id})
# Trigger onchange to reset discount, unit price, subtotal, ...
for line in self.sale_order.order_line:
line.product_id_change()
line._onchange_discount()
# Check that pricelist of the SO has been applied on the sale order lines or not
for line in self.sale_order.order_line:
if line.product_id == self.company_data['product_order_no']:
self.assertEqual(line.price_unit, self.pricelist_discount_incl_item3.fixed_price, 'Price of product_order should be %s applied on the order line' % (self.pricelist_discount_incl_item3.fixed_price,))
else: # only services (service_order and service_deliver)
for item in self.sale_order.pricelist_id.item_ids.filtered(lambda l: l.product_tmpl_id == line.product_id.product_tmpl_id):
price = item.percent_price
self.assertEqual(price, (line.product_id.list_price - line.price_unit) / line.product_id.list_price * 100, 'Pricelist of the SO should be applied on an order line %s' % (line.product_id.name,))
def test_sale_with_pricelist_discount_excluded(self):
""" Test SO with the pricelist 'discount displayed' and check discount and unit price appeared on its lines """
# Add group 'Discount on Lines' to the user
self.env.user.write({'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)]})
# Set product category on consumable products (for the pricelist item applying on this category)
self.company_data['product_order_no'].write({'categ_id': self.product_category_1.id})
self.company_data['product_delivery_no'].write({'categ_id': self.product_category_1.id})
# Change the pricelist
self.sale_order.write({'pricelist_id': self.pricelist_discount_excl.id})
# Trigger onchange to reset discount, unit price, subtotal, ...
for line in self.sale_order.order_line:
line.product_id_change()
line._onchange_discount()
# Check pricelist of the SO apply or not on order lines where pricelist contains formula that add 15% on the cost price
for line in self.sale_order.order_line:
if line.product_id.categ_id in self.sale_order.pricelist_id.item_ids.mapped('categ_id'): # reduction per category (consummable only)
for item in self.sale_order.pricelist_id.item_ids.filtered(lambda l: l.categ_id == line.product_id.categ_id):
self.assertEqual(line.discount, item.price_discount, "Discount should be displayed on order line %s since its category get some discount" % (line.name,))
self.assertEqual(line.price_unit, line.product_id.standard_price, "Price unit should be the cost price for product %s" % (line.name,))
else:
if line.product_id == self.company_data['product_service_order']: # reduction for this product
self.assertEqual(line.discount, 20.0, "Discount for product %s should be 20 percent with pricelist %s" % (line.name, self.pricelist_discount_excl.name))
self.assertEqual(line.price_unit, line.product_id.list_price, 'Unit price of order line should be a sale price as the pricelist not applied on the other category\'s product')
else: # no discount for the rest
self.assertEqual(line.discount, 0.0, 'Pricelist of SO should not be applied on an order line')
self.assertEqual(line.price_unit, line.product_id.list_price, 'Unit price of order line should be a sale price as the pricelist not applied on the other category\'s product')
def test_sale_change_of_pricelists_excluded_value_discount(self):
""" Test SO with the pricelist 'discount displayed' and check displayed percentage value after multiple changes of pricelist """
self.env.user.write({'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)]})
# Create a product with a very low price
amazing_product = self.env['product.product'].create({
'name': 'Amazing Product',
'lst_price': 0.03,
})
# create a simple Sale Order with a unique line
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
'order_line': [(0, 0, {
'name': amazing_product.name,
'product_id': amazing_product.id,
'product_uom_qty': 1,
'product_uom': amazing_product.uom_id.id,
'price_unit': 0.03,
'tax_id': False,
})],
})
# Change the pricelist
sale_order.write({'pricelist_id': self.pricelist_discount_excl_global.id})
# Update Prices
sale_order.update_prices()
# Check that the discount displayed is the correct one
self.assertEqual(
sale_order.order_line.discount, 54,
"Wrong discount computed for specified product & pricelist"
)
# Additional to check for overall consistency
self.assertEqual(
sale_order.order_line.price_unit, 0.03,
"Wrong unit price computed for specified product & pricelist"
)
self.assertEqual(
sale_order.order_line.price_subtotal, 0.01,
"Wrong subtotal price computed for specified product & pricelist"
)
self.assertFalse(
sale_order.order_line.tax_id,
"Wrong tax applied for specified product & pricelist"
)
def test_sale_change_of_pricelists_excluded_value_discount_on_tax_included_price_mapped_to_tax_excluded_price(self):
self.env.user.write({'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)]})
# setting up the taxes:
tax_a = self.tax_sale_a.copy()
tax_b = self.tax_sale_a.copy()
tax_a.price_include = True
tax_b.amount = 6
# setting up fiscal position:
fiscal_pos = self.fiscal_pos_a.copy()
fiscal_pos.auto_apply = True
country = self.env["res.country"].search([('name', '=', 'Belgium')], limit=1)
fiscal_pos.country_id = country
fiscal_pos.tax_ids = [
(0, None,
{
'tax_src_id': tax_a.id,
'tax_dest_id': tax_b.id
})
]
# setting up partner:
self.partner_a.country_id = country
# creating product:
my_product = self.env['product.product'].create({
'name': 'my Product',
'lst_price': 115,
'taxes_id': [tax_a.id]
})
# creating SO
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
'order_line': [(0, 0, {
'name': my_product.name,
'product_id': my_product.id,
'product_uom_qty': 1,
'product_uom': my_product.uom_id.id,
})],
})
# Apply fiscal position
sale_order.fiscal_position_id = fiscal_pos.id
# Change the pricelist
sale_order.write({'pricelist_id': self.pricelist_discount_excl_global.id})
# Update Prices
sale_order.update_prices()
# Check that the discount displayed is the correct one
self.assertEqual(
sale_order.order_line.discount, 54,
"Wrong discount computed for specified product & pricelist"
)
# Additional to check for overall consistency
self.assertEqual(
sale_order.order_line.price_unit, 100,
"Wrong unit price computed for specified product & pricelist"
)
self.assertEqual(
sale_order.order_line.price_subtotal, 46,
"Wrong subtotal price computed for specified product & pricelist"
)
self.assertEqual(
sale_order.order_line.tax_id.id, tax_b.id,
"Wrong tax applied for specified product & pricelist"
)
def test_sale_with_pricelist_discount_excluded_2(self):
""" Test SO with the pricelist 'discount displayed' and check discount and unit price appeared on its lines
When product are added after pricelist and the onchange should be trigger automatically.
"""
# Add group 'Discount on Lines' to the user
self.env.user.write({'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)]})
product_order = self.company_data['product_order_no']
service_order = self.company_data['product_service_order']
# Set product category on consumable products (for the pricelist item applying on this category)
product_order.write({'categ_id': self.product_category_1.id})
# Remove current SO lines
self.sale_order.write({'order_line': [(5,)]})
# Change the pricelist
self.sale_order.write({'pricelist_id': self.pricelist_discount_excl.id})
self.env['sale.order.line'].create({
'order_id': self.sale_order.id,
'name': 'Dummy1',
'product_id': 1,
})
with Form(self.sale_order) as so_form:
sol_form = so_form.order_line.edit(0)
sol_form.product_id = service_order
self.assertEqual(sol_form.product_id, service_order)
self.assertEqual(sol_form.price_unit, service_order.list_price,
"Unit price of order line should be a sale price as the pricelist not applied on the other category\'s product")
self.assertEqual(sol_form.discount, 20,
"Discount should be displayed on order line since the product get some discount")
sol_form.product_id = product_order
self.assertEqual(sol_form.product_id, product_order)
self.assertEqual(sol_form.price_unit, product_order.standard_price,
"Price unit should be the cost price for product")
self.assertEqual(sol_form.discount, 10,
"Discount should be displayed on order line since its category get some discount")
| 48.428571 | 16,611 |
1,216 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.base.tests.common import HttpCaseWithUserPortal
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestSaleSignature(HttpCaseWithUserPortal):
def test_01_portal_sale_signature_tour(self):
"""The goal of this test is to make sure the portal user can sign SO."""
portal_user = self.partner_portal
# create a SO to be signed
sales_order = self.env['sale.order'].create({
'name': 'test SO',
'partner_id': portal_user.id,
'state': 'sent',
'require_payment': False,
})
self.env['sale.order.line'].create({
'order_id': sales_order.id,
'product_id': self.env['product.product'].create({'name': 'A product'}).id,
})
# must be sent to the user so he can see it
email_act = sales_order.action_quotation_send()
email_ctx = email_act.get('context', {})
sales_order.with_context(**email_ctx).message_post_with_template(email_ctx.get('default_template_id'))
self.start_tour("/", 'sale_signature', login="portal")
| 39.225806 | 1,216 |
8,366 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale.tests.common import TestSaleCommon
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.tests import HttpCase, tagged
@tagged('post_install', '-at_install')
class TestAccessRights(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.company_data['default_user_salesman_2'] = cls.env['res.users'].with_context(no_reset_password=True).create({
'name': 'default_user_salesman_2',
'login': 'default_user_salesman_2.comp%s' % cls.company_data['company'].id,
'email': '[email protected]',
'signature': '--\nMark',
'notification_type': 'email',
'groups_id': [(6, 0, cls.env.ref('sales_team.group_sale_salesman').ids)],
'company_ids': [(6, 0, cls.company_data['company'].ids)],
'company_id': cls.company_data['company'].id,
})
# Create the SO with a specific salesperson
cls.order = cls.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': cls.partner_a.id,
'user_id': cls.company_data['default_user_salesman'].id
})
def test_access_sales_manager(self):
""" Test sales manager's access rights """
SaleOrder = self.env['sale.order'].with_context(tracking_disable=True)
# Manager can see the SO which is assigned to another salesperson
self.order.read()
# Manager can change a salesperson of the SO
self.order.write({'user_id': self.company_data['default_user_salesman'].id})
# Manager can create the SO for other salesperson
sale_order = SaleOrder.create({
'partner_id': self.partner_a.id,
'user_id': self.company_data['default_user_salesman'].id
})
self.assertIn(sale_order.id, SaleOrder.search([]).ids, 'Sales manager should be able to create the SO of other salesperson')
# Manager can confirm the SO
sale_order.action_confirm()
# Manager can not delete confirmed SO
with self.assertRaises(UserError):
sale_order.unlink()
# Manager can delete the SO of other salesperson if SO is in 'draft' or 'cancel' state
self.order.unlink()
self.assertNotIn(self.order.id, SaleOrder.search([]).ids, 'Sales manager should be able to delete the SO')
# Manager can create a Sales Team
india_channel = self.env['crm.team'].with_context(tracking_disable=True).create({
'name': 'India',
})
self.assertIn(india_channel.id, self.env['crm.team'].search([]).ids, 'Sales manager should be able to create a Sales Team')
# Manager can edit a Sales Team
india_channel.write({'name': 'new_india'})
self.assertEqual(india_channel.name, 'new_india', 'Sales manager should be able to edit a Sales Team')
# Manager can delete a Sales Team
india_channel.unlink()
self.assertNotIn(india_channel.id, self.env['crm.team'].search([]).ids, 'Sales manager should be able to delete a Sales Team')
def test_access_sales_person(self):
""" Test Salesperson's access rights """
# Salesperson can see only their own sales order
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_salesman_2']).read()
# Now assign the SO to themselves
self.order.write({'user_id': self.company_data['default_user_salesman_2'].id})
self.order.with_user(self.company_data['default_user_salesman_2']).read()
# Salesperson can change a Sales Team of SO
self.order.with_user(self.company_data['default_user_salesman_2']).write({'team_id': self.company_data['default_sale_team'].id})
# Salesperson can't create the SO of other salesperson
with self.assertRaises(AccessError):
self.env['sale.order'].with_user(self.company_data['default_user_salesman_2']).create({
'partner_id': self.partner_a.id,
'user_id': self.company_data['default_user_salesman'].id
})
# Salesperson can't delete the SO
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_salesman_2']).unlink()
# Salesperson can confirm the SO
self.order.with_user(self.company_data['default_user_salesman_2']).action_confirm()
def test_access_portal_user(self):
""" Test portal user's access rights """
# Portal user can see the confirmed SO for which they are assigned as a customer
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_portal']).read()
self.order.partner_id = self.company_data['default_user_portal'].partner_id
self.order.action_confirm()
# Portal user can't edit the SO
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_portal']).write({'team_id': self.company_data['default_sale_team'].id})
# Portal user can't create the SO
with self.assertRaises(AccessError):
self.env['sale.order'].with_user(self.company_data['default_user_portal']).create({
'partner_id': self.partner_a.id,
})
# Portal user can't delete the SO which is in 'draft' or 'cancel' state
self.order.action_cancel()
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_portal']).unlink()
def test_access_employee(self):
""" Test classic employee's access rights """
# Employee can't see any SO
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_employee']).read()
# Employee can't edit the SO
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_employee']).write({'team_id': self.company_data['default_sale_team'].id})
# Employee can't create the SO
with self.assertRaises(AccessError):
self.env['sale.order'].with_user(self.company_data['default_user_employee']).create({
'partner_id': self.partner_a.id,
})
# Employee can't delete the SO
with self.assertRaises(AccessError):
self.order.with_user(self.company_data['default_user_employee']).unlink()
@tagged('post_install', '-at_install')
class TestAccessRightsControllers(HttpCase):
def test_access_controller(self):
portal_so = self.env.ref("sale.portal_sale_order_2").sudo()
portal_so._portal_ensure_token()
token = portal_so.access_token
private_so = self.env.ref("sale.sale_order_1")
self.authenticate(None, None)
# Test public user can't print an order without a token
req = self.url_open(
url='/my/orders/%s?report_type=pdf' % portal_so.id,
allow_redirects=False,
)
self.assertEqual(req.status_code, 303)
# or with a random token
req = self.url_open(
url='/my/orders/%s?access_token=%s&report_type=pdf' % (
portal_so.id,
"foo",
),
allow_redirects=False,
)
self.assertEqual(req.status_code, 303)
# but works fine with the right token
req = self.url_open(
url='/my/orders/%s?access_token=%s&report_type=pdf' % (
portal_so.id,
token,
),
allow_redirects=False,
)
self.assertEqual(req.status_code, 200)
self.authenticate("portal", "portal")
# do not need the token when logged in
req = self.url_open(
url='/my/orders/%s?report_type=pdf' % portal_so.id,
allow_redirects=False,
)
self.assertEqual(req.status_code, 200)
# but still can't access another order
req = self.url_open(
url='/my/orders/%s?report_type=pdf' % private_so.id,
allow_redirects=False,
)
self.assertEqual(req.status_code, 303)
| 46.477778 | 8,366 |
9,226 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.fields import Command
from odoo.tests import tagged
from odoo.tools import mute_logger
from odoo.addons.payment.tests.common import PaymentCommon
from odoo.addons.payment.tests.http_common import PaymentHttpCommon
@tagged('-at_install', 'post_install')
class TestSalePayment(PaymentCommon, PaymentHttpCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.pricelist = cls.env['product.pricelist'].search([
('currency_id', '=', cls.currency.id)], limit=1)
if not cls.pricelist:
cls.pricelist = cls.env['product.pricelist'].create({
'name': 'Test Pricelist (%s)' % (cls.currency.name),
'currency_id': cls.currency.id,
})
cls.sale_product = cls.env['product.product'].create({
'sale_ok': True,
'name': "Test Product",
})
cls.order = cls.env['sale.order'].create({
'partner_id': cls.partner.id,
'pricelist_id': cls.pricelist.id,
'order_line': [Command.create({
'product_id': cls.sale_product.id,
'product_uom_qty': 5,
'price_unit': 20,
})],
})
cls.partner = cls.order.partner_invoice_id
def test_11_so_payment_link(self):
# test customized /payment/pay route with sale_order_id param
self.amount = self.order.amount_total
route_values = self._prepare_pay_values()
route_values['sale_order_id'] = self.order.id
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['currency_id'], self.order.currency_id.id)
self.assertEqual(tx_context['partner_id'], self.order.partner_invoice_id.id)
self.assertEqual(tx_context['amount'], self.order.amount_total)
self.assertEqual(tx_context['sale_order_id'], self.order.id)
route_values.update({
'flow': 'direct',
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
'validation_route': False,
'reference_prefix': None, # Force empty prefix to fallback on SO reference
'landing_route': tx_context['landing_route'],
'amount': tx_context['amount'],
'currency_id': tx_context['currency_id'],
})
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**route_values)
tx_sudo = self._get_tx(processing_values['reference'])
self.assertEqual(tx_sudo.sale_order_ids, self.order)
self.assertEqual(tx_sudo.amount, self.amount)
self.assertEqual(tx_sudo.partner_id, self.order.partner_invoice_id)
self.assertEqual(tx_sudo.company_id, self.order.company_id)
self.assertEqual(tx_sudo.currency_id, self.order.currency_id)
self.assertEqual(tx_sudo.reference, self.order.name)
# Check validation of transaction correctly confirms the SO
self.assertEqual(self.order.state, 'draft')
tx_sudo._set_done()
tx_sudo._finalize_post_processing()
self.assertEqual(self.order.state, 'sale')
self.assertTrue(tx_sudo.payment_id)
self.assertEqual(tx_sudo.payment_id.state, 'posted')
def test_so_payment_link_with_different_partner_invoice(self):
# test customized /payment/pay route with sale_order_id param
# partner_id and partner_invoice_id different on the so
self.order.partner_invoice_id = self.portal_partner
self.partner = self.order.partner_invoice_id
route_values = self._prepare_pay_values()
route_values['sale_order_id'] = self.order.id
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['partner_id'], self.order.partner_invoice_id.id)
def test_12_so_partial_payment_link(self):
# test customized /payment/pay route with sale_order_id param
# partial amount specified
self.amount = self.order.amount_total / 2.0
route_values = self._prepare_pay_values()
route_values['sale_order_id'] = self.order.id
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['reference_prefix'], self.reference)
self.assertEqual(tx_context['currency_id'], self.order.currency_id.id)
self.assertEqual(tx_context['partner_id'], self.order.partner_invoice_id.id)
self.assertEqual(tx_context['amount'], self.amount)
self.assertEqual(tx_context['sale_order_id'], self.order.id)
route_values.update({
'flow': 'direct',
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
'validation_route': False,
'reference_prefix': tx_context['reference_prefix'],
'landing_route': tx_context['landing_route'],
})
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**route_values)
tx_sudo = self._get_tx(processing_values['reference'])
self.assertEqual(tx_sudo.sale_order_ids, self.order)
self.assertEqual(tx_sudo.amount, self.amount)
self.assertEqual(tx_sudo.partner_id, self.order.partner_invoice_id)
self.assertEqual(tx_sudo.company_id, self.order.company_id)
self.assertEqual(tx_sudo.currency_id, self.order.currency_id)
self.assertEqual(tx_sudo.reference, self.reference)
tx_sudo._set_done()
with mute_logger('odoo.addons.sale.models.payment_transaction'):
tx_sudo._finalize_post_processing()
self.assertEqual(self.order.state, 'draft') # Only a partial amount was paid
# Pay the remaining amount
route_values = self._prepare_pay_values()
route_values['sale_order_id'] = self.order.id
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['reference_prefix'], self.reference)
self.assertEqual(tx_context['currency_id'], self.order.currency_id.id)
self.assertEqual(tx_context['partner_id'], self.order.partner_id.id)
self.assertEqual(tx_context['amount'], self.amount)
self.assertEqual(tx_context['sale_order_id'], self.order.id)
route_values.update({
'flow': 'direct',
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
'validation_route': False,
'reference_prefix': tx_context['reference_prefix'],
'landing_route': tx_context['landing_route'],
})
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**route_values)
tx2_sudo = self._get_tx(processing_values['reference'])
self.assertEqual(tx2_sudo.sale_order_ids, self.order)
self.assertEqual(tx2_sudo.amount, self.amount)
self.assertEqual(tx2_sudo.partner_id, self.order.partner_invoice_id)
self.assertEqual(tx2_sudo.company_id, self.order.company_id)
self.assertEqual(tx2_sudo.currency_id, self.order.currency_id)
# We are paying a second time with the same reference (prefix)
# a suffix is added to respect unique reference constraint
reference = self.reference + "-1"
self.assertEqual(tx2_sudo.reference, reference)
self.assertEqual(self.order.state, 'draft')
self.assertEqual(self.order.transaction_ids, tx_sudo + tx2_sudo)
def test_13_sale_automatic_partial_payment_link_delivery(self):
"""Test that with automatic invoice and invoicing policy based on delivered quantity, a transaction for the partial
amount does not validate the SO."""
# set automatic invoice
self.env['ir.config_parameter'].sudo().set_param('sale.automatic_invoice', 'True')
# invoicing policy is based on delivered quantity
self.sale_product.invoice_policy = 'delivery'
self.amount = self.order.amount_total / 2.0
route_values = self._prepare_pay_values()
route_values['sale_order_id'] = self.order.id
tx_context = self.get_tx_checkout_context(**route_values)
route_values.update({
'flow': 'direct',
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
'validation_route': False,
'reference_prefix': tx_context['reference_prefix'],
'landing_route': tx_context['landing_route'],
})
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**route_values)
tx_sudo = self._get_tx(processing_values['reference'])
tx_sudo._set_done()
with mute_logger('odoo.addons.sale.models.payment_transaction'):
tx_sudo._finalize_post_processing()
self.assertEqual(self.order.state, 'draft', 'a partial transaction with automatic invoice and invoice_policy = delivery should not validate a quote')
| 45.22549 | 9,226 |
4,782 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from freezegun import freeze_time
from odoo import Command
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo.exceptions import UserError
@freeze_time('2022-01-01')
@tagged('post_install', '-at_install')
class TestAccruedSaleOrders(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.alt_inc_account = cls.company_data['default_account_revenue'].copy()
# set 'invoice_policy' to 'delivery' to take 'qty_delivered' into account when computing 'untaxed_amount_to_invoice'
# set 'type' to 'service' to allow manualy set 'qty_delivered' even with sale_stock installed
cls.product_a.update({
'type': 'service',
'invoice_policy': 'delivery',
})
cls.product_b.update({
'type': 'service',
'invoice_policy': 'delivery',
'property_account_income_id': cls.alt_inc_account.id,
})
cls.sale_order = cls.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': cls.partner_a.id,
'order_line': [
Command.create({
'name': cls.product_a.name,
'product_id': cls.product_a.id,
'product_uom_qty': 10.0,
'product_uom': cls.product_a.uom_id.id,
'price_unit': cls.product_a.list_price,
'tax_id': False,
}),
Command.create({
'name': cls.product_b.name,
'product_id': cls.product_b.id,
'product_uom_qty': 10.0,
'product_uom': cls.product_b.uom_id.id,
'price_unit': cls.product_b.list_price,
'tax_id': False,
})
]
})
cls.sale_order.action_confirm()
cls.account_expense = cls.company_data['default_account_expense']
cls.account_revenue = cls.company_data['default_account_revenue']
cls.wizard = cls.env['account.accrued.orders.wizard'].with_context({
'active_model': 'sale.order',
'active_ids': cls.sale_order.ids,
}).create({
'account_id': cls.account_expense.id,
})
def test_accrued_order(self):
# nothing to invoice : no entries to be created
with self.assertRaises(UserError):
self.wizard.create_entries()
# 5 qty of each product invoiceable
self.sale_order.order_line.qty_delivered = 5
self.assertRecordValues(self.env['account.move'].search(self.wizard.create_entries()['domain']).line_ids, [
# reverse move lines
{'account_id': self.account_revenue.id, 'debit': 5000, 'credit': 0},
{'account_id': self.alt_inc_account.id, 'debit': 1000, 'credit': 0},
{'account_id': self.wizard.account_id.id, 'debit': 0, 'credit': 6000},
# move lines
{'account_id': self.account_revenue.id, 'debit': 0, 'credit': 5000},
{'account_id': self.alt_inc_account.id, 'debit': 0, 'credit': 1000},
{'account_id': self.wizard.account_id.id, 'debit': 6000, 'credit': 0},
])
# delivered products invoiced, nothing to invoice left
self.sale_order.with_context(default_invoice_date=self.wizard.date)._create_invoices().action_post()
with self.assertRaises(UserError):
self.wizard.create_entries()
def test_multi_currency_accrued_order(self):
# 5 qty of each product billeable
self.sale_order.order_line.qty_delivered = 5
# self.sale_order.order_line.product_uom_qty = 5
# set currency != company currency
self.sale_order.currency_id = self.currency_data['currency']
self.assertRecordValues(self.env['account.move'].search(self.wizard.create_entries()['domain']).line_ids, [
# reverse move lines
{'account_id': self.account_revenue.id, 'debit': 5000 / 2, 'credit': 0, 'amount_currency': 5000},
{'account_id': self.alt_inc_account.id, 'debit': 1000 / 2, 'credit': 0, 'amount_currency': 1000},
{'account_id': self.account_expense.id, 'debit': 0, 'credit': 6000 / 2, 'amount_currency': 0.0},
# move lines
{'account_id': self.account_revenue.id, 'debit': 0, 'credit': 5000 / 2, 'amount_currency': -5000},
{'account_id': self.alt_inc_account.id, 'debit': 0, 'credit': 1000 / 2, 'amount_currency': -1000},
{'account_id': self.account_expense.id, 'debit': 6000 / 2, 'credit': 0, 'amount_currency': 0.0},
])
| 49.298969 | 4,782 |
18,140 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from freezegun import freeze_time
from odoo.addons.sale.tests.common import TestSaleCommon
from odoo.tests import Form, tagged
@tagged('post_install', '-at_install')
class TestReInvoice(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.analytic_account = cls.env['account.analytic.account'].create({
'name': 'Test AA',
'code': 'TESTSALE_REINVOICE',
'company_id': cls.partner_a.company_id.id,
'partner_id': cls.partner_a.id
})
cls.sale_order = cls.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'analytic_account_id': cls.analytic_account.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
cls.AccountMove = cls.env['account.move'].with_context(
default_move_type='in_invoice',
default_invoice_date=cls.sale_order.date_order,
mail_notrack=True,
mail_create_nolog=True,
)
def test_at_cost(self):
""" Test vendor bill at cost for product based on ordered and delivered quantities. """
# create SO line and confirm SO (with only one line)
sale_order_line1 = self.env['sale.order.line'].create({
'name': self.company_data['product_order_cost'].name,
'product_id': self.company_data['product_order_cost'].id,
'product_uom_qty': 2,
'qty_delivered': 1,
'product_uom': self.company_data['product_order_cost'].uom_id.id,
'price_unit': self.company_data['product_order_cost'].list_price,
'order_id': self.sale_order.id,
})
sale_order_line1.product_id_change()
sale_order_line2 = self.env['sale.order.line'].create({
'name': self.company_data['product_delivery_cost'].name,
'product_id': self.company_data['product_delivery_cost'].id,
'product_uom_qty': 4,
'qty_delivered': 1,
'product_uom': self.company_data['product_delivery_cost'].uom_id.id,
'price_unit': self.company_data['product_delivery_cost'].list_price,
'order_id': self.sale_order.id,
})
sale_order_line2.product_id_change()
self.sale_order.onchange_partner_id()
self.sale_order._compute_tax_id()
self.sale_order.action_confirm()
# create invoice lines and validate it
move_form = Form(self.AccountMove)
move_form.partner_id = self.partner_a
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_order_cost']
line_form.quantity = 3.0
line_form.analytic_account_id = self.analytic_account
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_delivery_cost']
line_form.quantity = 3.0
line_form.analytic_account_id = self.analytic_account
invoice_a = move_form.save()
invoice_a.action_post()
sale_order_line3 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol.product_id == self.company_data['product_order_cost'])
sale_order_line4 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol.product_id == self.company_data['product_delivery_cost'])
self.assertTrue(sale_order_line3, "A new sale line should have been created with ordered product")
self.assertTrue(sale_order_line4, "A new sale line should have been created with delivered product")
self.assertEqual(len(self.sale_order.order_line), 4, "There should be 4 lines on the SO (2 vendor bill lines created)")
self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 2, "There should be 4 lines on the SO (2 vendor bill lines created)")
self.assertEqual((sale_order_line3.price_unit, sale_order_line3.qty_delivered, sale_order_line3.product_uom_qty, sale_order_line3.qty_invoiced), (self.company_data['product_order_cost'].standard_price, 3, 0, 0), 'Sale line is wrong after confirming vendor invoice')
self.assertEqual((sale_order_line4.price_unit, sale_order_line4.qty_delivered, sale_order_line4.product_uom_qty, sale_order_line4.qty_invoiced), (self.company_data['product_delivery_cost'].standard_price, 3, 0, 0), 'Sale line is wrong after confirming vendor invoice')
self.assertEqual(sale_order_line3.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line should be computed by analytic amount")
self.assertEqual(sale_order_line4.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line should be computed by analytic amount")
# create second invoice lines and validate it
move_form = Form(self.AccountMove)
move_form.partner_id = self.partner_a
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_order_cost']
line_form.quantity = 2.0
line_form.analytic_account_id = self.analytic_account
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_delivery_cost']
line_form.quantity = 2.0
line_form.analytic_account_id = self.analytic_account
invoice_b = move_form.save()
invoice_b.action_post()
sale_order_line5 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol != sale_order_line3 and sol.product_id == self.company_data['product_order_cost'])
sale_order_line6 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol != sale_order_line4 and sol.product_id == self.company_data['product_delivery_cost'])
self.assertTrue(sale_order_line5, "A new sale line should have been created with ordered product")
self.assertTrue(sale_order_line6, "A new sale line should have been created with delivered product")
self.assertEqual(len(self.sale_order.order_line), 6, "There should be still 4 lines on the SO, no new created")
self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 4, "There should be still 2 expenses lines on the SO")
self.assertEqual((sale_order_line5.price_unit, sale_order_line5.qty_delivered, sale_order_line5.product_uom_qty, sale_order_line5.qty_invoiced), (self.company_data['product_order_cost'].standard_price, 2, 0, 0), 'Sale line 5 is wrong after confirming 2e vendor invoice')
self.assertEqual((sale_order_line6.price_unit, sale_order_line6.qty_delivered, sale_order_line6.product_uom_qty, sale_order_line6.qty_invoiced), (self.company_data['product_delivery_cost'].standard_price, 2, 0, 0), 'Sale line 6 is wrong after confirming 2e vendor invoice')
@freeze_time('2020-01-15')
def test_sales_team_invoiced(self):
""" Test invoiced field from sales team ony take into account the amount the sales channel has invoiced this month """
invoices = self.env['account.move'].create([
{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2020-01-10',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 1000.0})],
},
{
'move_type': 'out_refund',
'partner_id': self.partner_a.id,
'invoice_date': '2020-01-10',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 500.0})],
},
{
'move_type': 'in_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2020-01-01',
'date': '2020-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 800.0})],
},
])
invoices.action_post()
for invoice in invoices:
self.env['account.payment.register']\
.with_context(active_model='account.move', active_ids=invoice.ids)\
.create({})\
._create_payments()
invoices.flush()
self.assertRecordValues(invoices.team_id, [{'invoiced': 500.0}])
def test_sales_price(self):
""" Test invoicing vendor bill at sales price for products based on delivered and ordered quantities. Check no existing SO line is incremented, but when invoicing a
second time, increment only the delivered so line.
"""
# create SO line and confirm SO (with only one line)
sale_order_line1 = self.env['sale.order.line'].create({
'name': self.company_data['product_delivery_sales_price'].name,
'product_id': self.company_data['product_delivery_sales_price'].id,
'product_uom_qty': 2,
'qty_delivered': 1,
'product_uom': self.company_data['product_delivery_sales_price'].uom_id.id,
'price_unit': self.company_data['product_delivery_sales_price'].list_price,
'order_id': self.sale_order.id,
})
sale_order_line1.product_id_change()
sale_order_line2 = self.env['sale.order.line'].create({
'name': self.company_data['product_order_sales_price'].name,
'product_id': self.company_data['product_order_sales_price'].id,
'product_uom_qty': 3,
'qty_delivered': 1,
'product_uom': self.company_data['product_order_sales_price'].uom_id.id,
'price_unit': self.company_data['product_order_sales_price'].list_price,
'order_id': self.sale_order.id,
})
sale_order_line2.product_id_change()
self.sale_order._compute_tax_id()
self.sale_order.action_confirm()
# create invoice lines and validate it
move_form = Form(self.AccountMove)
move_form.partner_id = self.partner_a
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_delivery_sales_price']
line_form.quantity = 3.0
line_form.analytic_account_id = self.analytic_account
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_order_sales_price']
line_form.quantity = 3.0
line_form.analytic_account_id = self.analytic_account
invoice_a = move_form.save()
invoice_a.action_post()
sale_order_line3 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol.product_id == self.company_data['product_delivery_sales_price'])
sale_order_line4 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol.product_id == self.company_data['product_order_sales_price'])
self.assertTrue(sale_order_line3, "A new sale line should have been created with ordered product")
self.assertTrue(sale_order_line4, "A new sale line should have been created with delivered product")
self.assertEqual(len(self.sale_order.order_line), 4, "There should be 4 lines on the SO (2 vendor bill lines created)")
self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 2, "There should be 4 lines on the SO (2 vendor bill lines created)")
self.assertEqual((sale_order_line3.price_unit, sale_order_line3.qty_delivered, sale_order_line3.product_uom_qty, sale_order_line3.qty_invoiced), (self.company_data['product_delivery_sales_price'].list_price, 3, 0, 0), 'Sale line is wrong after confirming vendor invoice')
self.assertEqual((sale_order_line4.price_unit, sale_order_line4.qty_delivered, sale_order_line4.product_uom_qty, sale_order_line4.qty_invoiced), (self.company_data['product_order_sales_price'].list_price, 3, 0, 0), 'Sale line is wrong after confirming vendor invoice')
self.assertEqual(sale_order_line3.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line 3 should be computed by analytic amount")
self.assertEqual(sale_order_line4.qty_delivered_method, 'analytic', "Delivered quantity of 'expense' SO line 4 should be computed by analytic amount")
# create second invoice lines and validate it
move_form = Form(self.AccountMove)
move_form.partner_id = self.partner_a
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_delivery_sales_price']
line_form.quantity = 2.0
line_form.analytic_account_id = self.analytic_account
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_order_sales_price']
line_form.quantity = 2.0
line_form.analytic_account_id = self.analytic_account
invoice_b = move_form.save()
invoice_b.action_post()
sale_order_line5 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line1 and sol != sale_order_line3 and sol.product_id == self.company_data['product_delivery_sales_price'])
sale_order_line6 = self.sale_order.order_line.filtered(lambda sol: sol != sale_order_line2 and sol != sale_order_line4 and sol.product_id == self.company_data['product_order_sales_price'])
self.assertFalse(sale_order_line5, "No new sale line should have been created with delivered product !!")
self.assertTrue(sale_order_line6, "A new sale line should have been created with ordered product")
self.assertEqual(len(self.sale_order.order_line), 5, "There should be 5 lines on the SO, 1 new created and 1 incremented")
self.assertEqual(len(self.sale_order.order_line.filtered(lambda sol: sol.is_expense)), 3, "There should be 3 expenses lines on the SO")
self.assertEqual((sale_order_line6.price_unit, sale_order_line6.qty_delivered, sale_order_line4.product_uom_qty, sale_order_line6.qty_invoiced), (self.company_data['product_order_sales_price'].list_price, 2, 0, 0), 'Sale line is wrong after confirming 2e vendor invoice')
def test_no_expense(self):
""" Test invoicing vendor bill with no policy. Check nothing happen. """
# confirm SO
sale_order_line = self.env['sale.order.line'].create({
'name': self.company_data['product_delivery_no'].name,
'product_id': self.company_data['product_delivery_no'].id,
'product_uom_qty': 2,
'qty_delivered': 1,
'product_uom': self.company_data['product_delivery_no'].uom_id.id,
'price_unit': self.company_data['product_delivery_no'].list_price,
'order_id': self.sale_order.id,
})
self.sale_order._compute_tax_id()
self.sale_order.action_confirm()
# create invoice lines and validate it
move_form = Form(self.AccountMove)
move_form.partner_id = self.partner_a
with move_form.line_ids.new() as line_form:
line_form.product_id = self.company_data['product_delivery_no']
line_form.quantity = 3.0
line_form.analytic_account_id = self.analytic_account
invoice_a = move_form.save()
invoice_a.action_post()
self.assertEqual(len(self.sale_order.order_line), 1, "No SO line should have been created (or removed) when validating vendor bill")
self.assertTrue(invoice_a.mapped('line_ids.analytic_line_ids'), "Analytic lines should be generated")
def test_not_reinvoicing_invoiced_so_lines(self):
""" Test that invoiced SO lines are not re-invoiced. """
so_line1 = self.env['sale.order.line'].create({
'name': self.company_data['product_delivery_cost'].name,
'product_id': self.company_data['product_delivery_cost'].id,
'product_uom_qty': 1,
'product_uom': self.company_data['product_delivery_cost'].uom_id.id,
'price_unit': self.company_data['product_delivery_cost'].list_price,
'discount': 100.00,
'order_id': self.sale_order.id,
})
so_line1.product_id_change()
so_line2 = self.env['sale.order.line'].create({
'name': self.company_data['product_delivery_sales_price'].name,
'product_id': self.company_data['product_delivery_sales_price'].id,
'product_uom_qty': 1,
'product_uom': self.company_data['product_delivery_sales_price'].uom_id.id,
'price_unit': self.company_data['product_delivery_sales_price'].list_price,
'discount': 100.00,
'order_id': self.sale_order.id,
})
so_line2.product_id_change()
self.sale_order.onchange_partner_id()
self.sale_order._compute_tax_id()
self.sale_order.action_confirm()
for line in self.sale_order.order_line:
line.qty_delivered = 1
# create invoice and validate it
invoice = self.sale_order._create_invoices()
invoice.action_post()
so_line3 = self.sale_order.order_line.filtered(lambda sol: sol != so_line1 and sol.product_id == self.company_data['product_delivery_cost'])
so_line4 = self.sale_order.order_line.filtered(lambda sol: sol != so_line2 and sol.product_id == self.company_data['product_delivery_sales_price'])
self.assertFalse(so_line3, "No re-invoicing should have created a new sale line with product #1")
self.assertFalse(so_line4, "No re-invoicing should have created a new sale line with product #2")
self.assertEqual(so_line1.qty_delivered, 1, "No re-invoicing should have impacted exising SO line 1")
self.assertEqual(so_line2.qty_delivered, 1, "No re-invoicing should have impacted exising SO line 2")
| 59.867987 | 18,140 |
1,130 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.test_invoice_tax_totals import TestTaxTotals
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class SaleTestTaxTotals(TestTaxTotals):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.so_product = cls.env['product.product'].create({
'name': 'Odoo course',
'type': 'service',
})
def _create_document_for_tax_totals_test(self, lines_data):
# Overridden in order to run the inherited tests with sale.order's
# tax_totals_json field instead of account.move's
lines_vals = [
(0, 0, {
'name': 'test',
'product_id': self.so_product.id,
'price_unit': amount,
'product_uom_qty': 1,
'tax_id': [(6, 0, taxes.ids)],
})
for amount, taxes in lines_data]
return self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': lines_vals,
})
| 32.285714 | 1,130 |
9,107 |
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.base.tests.common import TransactionCase
class TestSaleCommonBase(TransactionCase):
''' Setup with sale test configuration. '''
@classmethod
def setup_sale_configuration_for_company(cls, company):
Users = cls.env['res.users'].with_context(no_reset_password=True)
company_data = {
# Sales Team
'default_sale_team': cls.env['crm.team'].with_context(tracking_disable=True).create({
'name': 'Test Channel',
'company_id': company.id,
}),
# Users
'default_user_salesman': Users.create({
'name': 'default_user_salesman',
'login': 'default_user_salesman.comp%s' % company.id,
'email': '[email protected]',
'signature': '--\nMark',
'notification_type': 'email',
'groups_id': [(6, 0, cls.env.ref('sales_team.group_sale_salesman').ids)],
'company_ids': [(6, 0, company.ids)],
'company_id': company.id,
}),
'default_user_portal': Users.create({
'name': 'default_user_portal',
'login': 'default_user_portal.comp%s' % company.id,
'email': '[email protected]',
'groups_id': [(6, 0, [cls.env.ref('base.group_portal').id])],
'company_ids': [(6, 0, company.ids)],
'company_id': company.id,
}),
'default_user_employee': Users.create({
'name': 'default_user_employee',
'login': 'default_user_employee.comp%s' % company.id,
'email': '[email protected]',
'groups_id': [(6, 0, [cls.env.ref('base.group_user').id])],
'company_ids': [(6, 0, company.ids)],
'company_id': company.id,
}),
# Pricelist
'default_pricelist': cls.env['product.pricelist'].with_company(company).create({
'name': 'default_pricelist',
'currency_id': company.currency_id.id,
}),
# Product category
'product_category': cls.env['product.category'].with_company(company).create({
'name': 'Test category',
}),
}
company_data.update({
# Products
'product_service_delivery': cls.env['product.product'].with_company(company).create({
'name': 'product_service_delivery',
'categ_id': company_data['product_category'].id,
'standard_price': 200.0,
'list_price': 180.0,
'type': 'service',
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'SERV_DEL',
'invoice_policy': 'delivery',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_service_order': cls.env['product.product'].with_company(company).create({
'name': 'product_service_order',
'categ_id': company_data['product_category'].id,
'standard_price': 40.0,
'list_price': 90.0,
'type': 'service',
'uom_id': cls.env.ref('uom.product_uom_hour').id,
'uom_po_id': cls.env.ref('uom.product_uom_hour').id,
'description': 'Example of product to invoice on order',
'default_code': 'PRE-PAID',
'invoice_policy': 'order',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_order_cost': cls.env['product.product'].with_company(company).create({
'name': 'product_order_cost',
'categ_id': company_data['product_category'].id,
'standard_price': 235.0,
'list_price': 280.0,
'type': 'consu',
'weight': 0.01,
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'FURN_9999',
'invoice_policy': 'order',
'expense_policy': 'cost',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_delivery_cost': cls.env['product.product'].with_company(company).create({
'name': 'product_delivery_cost',
'categ_id': company_data['product_category'].id,
'standard_price': 55.0,
'list_price': 70.0,
'type': 'consu',
'weight': 0.01,
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'FURN_7777',
'invoice_policy': 'delivery',
'expense_policy': 'cost',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_order_sales_price': cls.env['product.product'].with_company(company).create({
'name': 'product_order_sales_price',
'categ_id': company_data['product_category'].id,
'standard_price': 235.0,
'list_price': 280.0,
'type': 'consu',
'weight': 0.01,
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'FURN_9999',
'invoice_policy': 'order',
'expense_policy': 'sales_price',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_delivery_sales_price': cls.env['product.product'].with_company(company).create({
'name': 'product_delivery_sales_price',
'categ_id': company_data['product_category'].id,
'standard_price': 55.0,
'list_price': 70.0,
'type': 'consu',
'weight': 0.01,
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'FURN_7777',
'invoice_policy': 'delivery',
'expense_policy': 'sales_price',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_order_no': cls.env['product.product'].with_company(company).create({
'name': 'product_order_no',
'categ_id': company_data['product_category'].id,
'standard_price': 235.0,
'list_price': 280.0,
'type': 'consu',
'weight': 0.01,
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'FURN_9999',
'invoice_policy': 'order',
'expense_policy': 'no',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
'product_delivery_no': cls.env['product.product'].with_company(company).create({
'name': 'product_delivery_no',
'categ_id': company_data['product_category'].id,
'standard_price': 55.0,
'list_price': 70.0,
'type': 'consu',
'weight': 0.01,
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'uom_po_id': cls.env.ref('uom.product_uom_unit').id,
'default_code': 'FURN_7777',
'invoice_policy': 'delivery',
'expense_policy': 'no',
'taxes_id': [(6, 0, [])],
'supplier_taxes_id': [(6, 0, [])],
}),
})
return company_data
class TestSaleCommon(AccountTestInvoicingCommon, TestSaleCommonBase):
''' Setup to be used post-install with sale and accounting test configuration.'''
@classmethod
def setup_company_data(cls, company_name, chart_template=None, **kwargs):
company_data = super().setup_company_data(company_name, chart_template=chart_template, **kwargs)
company_data.update(cls.setup_sale_configuration_for_company(company_data['company']))
company_data['product_category'].write({
'property_account_income_categ_id': company_data['default_account_revenue'].id,
'property_account_expense_categ_id': company_data['default_account_expense'].id,
})
return company_data
| 45.763819 | 9,107 |
31,522 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from .common import TestSaleCommon
from odoo.tests import Form, tagged
@tagged('post_install', '-at_install')
class TestSaleToInvoice(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# Create the SO with four order lines
cls.sale_order = cls.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
SaleOrderLine = cls.env['sale.order.line'].with_context(tracking_disable=True)
cls.sol_prod_order = SaleOrderLine.create({
'name': cls.company_data['product_order_no'].name,
'product_id': cls.company_data['product_order_no'].id,
'product_uom_qty': 5,
'product_uom': cls.company_data['product_order_no'].uom_id.id,
'price_unit': cls.company_data['product_order_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_deliver = SaleOrderLine.create({
'name': cls.company_data['product_service_delivery'].name,
'product_id': cls.company_data['product_service_delivery'].id,
'product_uom_qty': 4,
'product_uom': cls.company_data['product_service_delivery'].uom_id.id,
'price_unit': cls.company_data['product_service_delivery'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_order = SaleOrderLine.create({
'name': cls.company_data['product_service_order'].name,
'product_id': cls.company_data['product_service_order'].id,
'product_uom_qty': 3,
'product_uom': cls.company_data['product_service_order'].uom_id.id,
'price_unit': cls.company_data['product_service_order'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_prod_deliver = SaleOrderLine.create({
'name': cls.company_data['product_delivery_no'].name,
'product_id': cls.company_data['product_delivery_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_delivery_no'].uom_id.id,
'price_unit': cls.company_data['product_delivery_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
# Confirm the SO
cls.sale_order.action_confirm()
# Create an invoice with invoiceable lines only
payment = cls.env['sale.advance.payment.inv'].with_context({
'active_model': 'sale.order',
'active_ids': [cls.sale_order.id],
'active_id': cls.sale_order.id,
'default_journal_id': cls.company_data['default_journal_sale'].id,
}).create({
'advance_payment_method': 'delivered'
})
payment.create_invoices()
cls.invoice = cls.sale_order.invoice_ids[0]
def test_refund_create(self):
# Validate invoice
self.invoice.action_post()
# Check quantity to invoice on SO lines
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered qty are not invoiced, so they should not be linked to invoice line")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 0.0, "The ordered sale line are totally invoiced (qty to invoice is zero)")
self.assertEqual(line.qty_invoiced, 5.0, "The ordered (prod) sale line are totally invoiced (qty invoiced come from the invoice lines)")
else:
self.assertEqual(line.qty_to_invoice, 0.0, "The ordered sale line are totally invoiced (qty to invoice is zero)")
self.assertEqual(line.qty_invoiced, 3.0, "The ordered (serv) sale line are totally invoiced (qty invoiced = the invoice lines)")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * line.qty_to_invoice, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * line.qty_invoiced, "Amount invoiced is now set as qty invoiced * unit price since no price change on invoice, for ordered products")
self.assertEqual(len(line.invoice_lines), 1, "The lines 'ordered' qty are invoiced, so it should be linked to 1 invoice lines")
# Make a credit note
credit_note_wizard = self.env['account.move.reversal'].with_context({'active_ids': [self.invoice.id], 'active_id': self.invoice.id, 'active_model': 'account.move'}).create({
'refund_method': 'refund', # this is the only mode for which the SO line is linked to the refund (https://github.com/odoo/odoo/commit/e680f29560ac20133c7af0c6364c6ef494662eac)
'reason': 'reason test create',
'journal_id': self.invoice.journal_id.id,
})
credit_note_wizard.reverse_moves()
invoice_refund = self.sale_order.invoice_ids.sorted(key=lambda inv: inv.id, reverse=False)[-1] # the first invoice, its refund, and the new invoice
# Check invoice's type and number
self.assertEqual(invoice_refund.move_type, 'out_refund', 'The last created invoiced should be a refund')
self.assertEqual(invoice_refund.state, 'draft', 'Last Customer invoices should be in draft')
self.assertEqual(self.sale_order.invoice_count, 2, "The SO should have 2 related invoices: the original, the new refund")
self.assertEqual(len(self.sale_order.invoice_ids.filtered(lambda inv: inv.move_type == 'out_refund')), 1, "The SO should be linked to only one refund")
self.assertEqual(len(self.sale_order.invoice_ids.filtered(lambda inv: inv.move_type == 'out_invoice')), 1, "The SO should be linked to only one customer invoices")
# At this time, the invoice 1 is opend (validated) and its refund is in draft, so the amounts invoiced are not zero for
# invoiced sale line. The amounts only take validated invoice/refund into account.
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO line based on delivered qty")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered are not invoiced, so they should not be linked to invoice line")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 5.0, "As the refund is created, the invoiced quantity cancel each other (consu ordered)")
self.assertEqual(line.qty_invoiced, 0.0, "The qty to invoice should have decreased as the refund is created for ordered consu SO line")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "Amount to invoice is zero as the refund is not validated")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * 5, "Amount invoiced is now set as unit price * ordered qty - refund qty) even if the ")
self.assertEqual(len(line.invoice_lines), 2, "The line 'ordered consumable' is invoiced, so it should be linked to 2 invoice lines (invoice and refund)")
else:
self.assertEqual(line.qty_to_invoice, 3.0, "As the refund is created, the invoiced quantity cancel each other (consu ordered)")
self.assertEqual(line.qty_invoiced, 0.0, "The qty to invoice should have decreased as the refund is created for ordered service SO line")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "Amount to invoice is zero as the refund is not validated")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * 3, "Amount invoiced is now set as unit price * ordered qty - refund qty) even if the ")
self.assertEqual(len(line.invoice_lines), 2, "The line 'ordered service' is invoiced, so it should be linked to 2 invoice lines (invoice and refund)")
# Validate the refund
invoice_refund.action_post()
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered are not invoiced, so they should not be linked to invoice line")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 5.0, "As the refund still exists, the quantity to invoice is the ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "The qty to invoice should be zero as, with the refund, the quantities cancel each other")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * 5, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, as refund is validated")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "Amount invoiced decreased as the refund is now confirmed")
self.assertEqual(len(line.invoice_lines), 2, "The line 'ordered consumable' is invoiced, so it should be linked to 2 invoice lines (invoice and refund)")
else:
self.assertEqual(line.qty_to_invoice, 3.0, "As the refund still exists, the quantity to invoice is the ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "The qty to invoice should be zero as, with the refund, the quantities cancel each other")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * 3, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, as refund is validated")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "Amount invoiced decreased as the refund is now confirmed")
self.assertEqual(len(line.invoice_lines), 2, "The line 'ordered service' is invoiced, so it should be linked to 2 invoice lines (invoice and refund)")
def test_refund_cancel(self):
""" Test invoice with a refund in 'cancel' mode, meaning a refund will be created and auto confirm to completely cancel the first
customer invoice. The SO will have 2 invoice (customer + refund) in a paid state at the end. """
# Increase quantity of an invoice lines
with Form(self.invoice) as invoice_form:
with invoice_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = 6
with invoice_form.invoice_line_ids.edit(1) as line_form:
line_form.quantity = 4
# Validate invoice
self.invoice.action_post()
# Check quantity to invoice on SO lines
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered qty are not invoiced, so they should not be linked to invoice line")
else:
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * line.qty_to_invoice, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * line.qty_invoiced, "Amount invoiced is now set as qty invoiced * unit price since no price change on invoice, for ordered products")
self.assertEqual(len(line.invoice_lines), 1, "The lines 'ordered' qty are invoiced, so it should be linked to 1 invoice lines")
self.assertEqual(line.qty_invoiced, line.product_uom_qty + 1, "The quantity invoiced is +1 unit from the one of the sale line, as we modified invoice lines (%s)" % (line.name,))
self.assertEqual(line.qty_to_invoice, -1, "The quantity to invoice is negative as we invoice more than ordered")
# Make a credit note
credit_note_wizard = self.env['account.move.reversal'].with_context({'active_ids': self.invoice.ids, 'active_id': self.invoice.id, 'active_model': 'account.move'}).create({
'refund_method': 'cancel',
'reason': 'reason test cancel',
'journal_id': self.invoice.journal_id.id,
})
invoice_refund = self.env['account.move'].browse(credit_note_wizard.reverse_moves()['res_id'])
# Check invoice's type and number
self.assertEqual(invoice_refund.move_type, 'out_refund', 'The last created invoiced should be a customer invoice')
self.assertEqual(invoice_refund.payment_state, 'paid', 'Last Customer creadit note should be in paid state')
self.assertEqual(self.sale_order.invoice_count, 2, "The SO should have 3 related invoices: the original, the refund, and the new one")
self.assertEqual(len(self.sale_order.invoice_ids.filtered(lambda inv: inv.move_type == 'out_refund')), 1, "The SO should be linked to only one refund")
self.assertEqual(len(self.sale_order.invoice_ids.filtered(lambda inv: inv.move_type == 'out_invoice')), 1, "The SO should be linked to only one customer invoices")
# At this time, the invoice 1 is opened (validated) and its refund validated too, so the amounts invoiced are zero for
# all sale line. All invoiceable Sale lines have
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO line based on delivered qty")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered are not invoiced, so they should not be linked to invoice line")
else:
self.assertEqual(line.qty_to_invoice, line.product_uom_qty, "The quantity to invoice should be the ordered quantity")
self.assertEqual(line.qty_invoiced, 0, "The quantity invoiced is zero as the refund (paid) completely cancel the first invoice")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * line.qty_to_invoice, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * line.qty_invoiced, "Amount invoiced is now set as qty invoiced * unit price since no price change on invoice, for ordered products")
self.assertEqual(len(line.invoice_lines), 2, "The lines 'ordered' qty are invoiced, so it should be linked to 1 invoice lines")
def test_refund_modify(self):
""" Test invoice with a refund in 'modify' mode, and check customer invoices credit note is created from respective invoice """
# Decrease quantity of an invoice lines
with Form(self.invoice) as invoice_form:
with invoice_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = 3
with invoice_form.invoice_line_ids.edit(1) as line_form:
line_form.quantity = 2
# Validate invoice
self.invoice.action_post()
# Check quantity to invoice on SO lines
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered qty are not invoiced, so they should not be linked to invoice line")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 2.0, "The ordered sale line are totally invoiced (qty to invoice is zero)")
self.assertEqual(line.qty_invoiced, 3.0, "The ordered (prod) sale line are totally invoiced (qty invoiced come from the invoice lines)")
else:
self.assertEqual(line.qty_to_invoice, 1.0, "The ordered sale line are totally invoiced (qty to invoice is zero)")
self.assertEqual(line.qty_invoiced, 2.0, "The ordered (serv) sale line are totally invoiced (qty invoiced = the invoice lines)")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * line.qty_to_invoice, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * line.qty_invoiced, "Amount invoiced is now set as qty invoiced * unit price since no price change on invoice, for ordered products")
self.assertEqual(len(line.invoice_lines), 1, "The lines 'ordered' qty are invoiced, so it should be linked to 1 invoice lines")
# Make a credit note
credit_note_wizard = self.env['account.move.reversal'].with_context({'active_ids': [self.invoice.id], 'active_id': self.invoice.id, 'active_model': 'account.move'}).create({
'refund_method': 'modify', # this is the only mode for which the SO line is linked to the refund (https://github.com/odoo/odoo/commit/e680f29560ac20133c7af0c6364c6ef494662eac)
'reason': 'reason test modify',
'journal_id': self.invoice.journal_id.id,
})
invoice_refund = self.env['account.move'].browse(credit_note_wizard.reverse_moves()['res_id'])
# Check invoice's type and number
self.assertEqual(invoice_refund.move_type, 'out_invoice', 'The last created invoiced should be a customer invoice')
self.assertEqual(invoice_refund.state, 'draft', 'Last Customer invoices should be in draft')
self.assertEqual(self.sale_order.invoice_count, 3, "The SO should have 3 related invoices: the original, the refund, and the new one")
self.assertEqual(len(self.sale_order.invoice_ids.filtered(lambda inv: inv.move_type == 'out_refund')), 1, "The SO should be linked to only one refund")
self.assertEqual(len(self.sale_order.invoice_ids.filtered(lambda inv: inv.move_type == 'out_invoice')), 2, "The SO should be linked to two customer invoices")
# At this time, the invoice 1 and its refund are confirmed, so the amounts invoiced are zero. The third invoice
# (2nd customer inv) is in draft state.
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered are not invoiced, so they should not be linked to invoice line")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 2.0, "The qty to invoice does not change when confirming the new invoice (2)")
self.assertEqual(line.qty_invoiced, 3.0, "The ordered (prod) sale line does not change on invoice 2 confirmation")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * 5, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "Amount invoiced is zero as the invoice 1 and its refund are reconcilied")
self.assertEqual(len(line.invoice_lines), 3, "The line 'ordered consumable' is invoiced, so it should be linked to 3 invoice lines (invoice and refund)")
else:
self.assertEqual(line.qty_to_invoice, 1.0, "The qty to invoice does not change when confirming the new invoice (2)")
self.assertEqual(line.qty_invoiced, 2.0, "The ordered (serv) sale line does not change on invoice 2 confirmation")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * 3, "Amount to invoice is now set as unit price * ordered qty - refund qty) even if the ")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "Amount invoiced is zero as the invoice 1 and its refund are reconcilied")
self.assertEqual(len(line.invoice_lines), 3, "The line 'ordered service' is invoiced, so it should be linked to 3 invoice lines (invoice and refund)")
# Change unit of ordered product on refund lines
move_form = Form(invoice_refund)
with move_form.invoice_line_ids.edit(0) as line_form:
line_form.price_unit = 100
with move_form.invoice_line_ids.edit(1) as line_form:
line_form.price_unit = 50
invoice_refund = move_form.save()
# Validate the refund
invoice_refund.action_post()
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
self.assertFalse(line.invoice_lines, "The line based on delivered are not invoiced, so they should not be linked to invoice line, even after validation")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 2.0, "The qty to invoice does not change when confirming the new invoice (3)")
self.assertEqual(line.qty_invoiced, 3.0, "The ordered sale line are totally invoiced (qty invoiced = ordered qty)")
self.assertEqual(line.untaxed_amount_to_invoice, 1100.0, "")
self.assertEqual(line.untaxed_amount_invoiced, 300.0, "")
self.assertEqual(len(line.invoice_lines), 3, "The line 'ordered consumable' is invoiced, so it should be linked to 2 invoice lines (invoice and refund), even after validation")
else:
self.assertEqual(line.qty_to_invoice, 1.0, "The qty to invoice does not change when confirming the new invoice (3)")
self.assertEqual(line.qty_invoiced, 2.0, "The ordered sale line are totally invoiced (qty invoiced = ordered qty)")
self.assertEqual(line.untaxed_amount_to_invoice, 170.0, "")
self.assertEqual(line.untaxed_amount_invoiced, 100.0, "")
self.assertEqual(len(line.invoice_lines), 3, "The line 'ordered service' is invoiced, so it should be linked to 2 invoice lines (invoice and refund), even after validation")
def test_refund_invoice_with_downpayment(self):
sale_order_refund = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
})
sol_product = self.env['sale.order.line'].create({
'name': self.company_data['product_order_no'].name,
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': 5,
'product_uom': self.company_data['product_order_no'].uom_id.id,
'price_unit': self.company_data['product_order_no'].list_price,
'order_id': sale_order_refund.id,
'tax_id': False,
})
sale_order_refund.action_confirm()
so_context = {
'active_model': 'sale.order',
'active_ids': [sale_order_refund.id],
'active_id': sale_order_refund.id,
'default_journal_id': self.company_data['default_journal_sale'].id,
}
downpayment = self.env['sale.advance.payment.inv'].with_context(so_context).create({
'advance_payment_method': 'percentage',
'amount': 50,
'deposit_account_id': self.company_data['default_account_revenue'].id
})
downpayment.create_invoices()
sale_order_refund.invoice_ids[0].action_post()
sol_downpayment = sale_order_refund.order_line[1]
payment = self.env['sale.advance.payment.inv'].with_context(so_context).create({
'deposit_account_id': self.company_data['default_account_revenue'].id
})
payment.create_invoices()
so_invoice = max(sale_order_refund.invoice_ids)
self.assertEqual(len(so_invoice.invoice_line_ids.filtered(lambda l: not (l.display_type == 'line_section' and l.name == "Down Payments"))), len(sale_order_refund.order_line), 'All lines should be invoiced')
self.assertEqual(len(so_invoice.invoice_line_ids.filtered(lambda l: l.display_type == 'line_section' and l.name == "Down Payments")), 1, 'A single section for downpayments should be present')
self.assertEqual(so_invoice.amount_total, sale_order_refund.amount_total - sol_downpayment.price_unit, 'Downpayment should be applied')
so_invoice.action_post()
credit_note_wizard = self.env['account.move.reversal'].with_context({'active_ids': [so_invoice.id], 'active_id': so_invoice.id, 'active_model': 'account.move'}).create({
'refund_method': 'refund',
'reason': 'reason test refund with downpayment',
'journal_id': so_invoice.journal_id.id,
})
credit_note_wizard.reverse_moves()
invoice_refund = sale_order_refund.invoice_ids.sorted(key=lambda inv: inv.id, reverse=False)[-1]
invoice_refund.action_post()
self.assertEqual(sol_product.qty_to_invoice, 5.0, "As the refund still exists, the quantity to invoice is the ordered quantity")
self.assertEqual(sol_product.qty_invoiced, 0.0, "The qty invoiced should be zero as, with the refund, the quantities cancel each other")
self.assertEqual(sol_product.untaxed_amount_to_invoice, sol_product.price_unit * 5, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, as refund is validated")
self.assertEqual(sol_product.untaxed_amount_invoiced, 0.0, "Amount invoiced decreased as the refund is now confirmed")
self.assertEqual(len(sol_product.invoice_lines), 2, "The product line is invoiced, so it should be linked to 2 invoice lines (invoice and refund)")
self.assertEqual(sol_downpayment.qty_to_invoice, -1.0, "As the downpayment was invoiced separately, it will still have to be deducted from the total invoice (hence -1.0), after the refund.")
self.assertEqual(sol_downpayment.qty_invoiced, 1.0, "The qty to invoice should be 1 as, with the refund, the products are not invoiced anymore, but the downpayment still is")
self.assertEqual(sol_downpayment.untaxed_amount_to_invoice, -(sol_product.price_unit * 5)/2, "Amount to invoice decreased as the refund is now confirmed")
self.assertEqual(sol_downpayment.untaxed_amount_invoiced, (sol_product.price_unit * 5)/2, "Amount invoiced is now set as half of all products' total amount to invoice, as refund is validated")
self.assertEqual(len(sol_downpayment.invoice_lines), 3, "The product line is invoiced, so it should be linked to 3 invoice lines (downpayment invoice, partial invoice and refund)")
| 81.242268 | 31,522 |
3,298 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.sale.tests.common import TestSaleCommonBase
class TestSaleFlow(TestSaleCommonBase):
''' Test running at-install to test flows independently to other modules, e.g. 'sale_stock'. '''
@classmethod
def setUpClass(cls):
super().setUpClass()
user = cls.env['res.users'].create({
'name': 'Because I am saleman!',
'login': 'saleman',
'groups_id': [(6, 0, cls.env.user.groups_id.ids), (4, cls.env.ref('account.group_account_user').id)],
})
user.partner_id.email = '[email protected]'
# Shadow the current environment/cursor with the newly created user.
cls.env = cls.env(user=user)
cls.cr = cls.env.cr
cls.company = cls.env['res.company'].create({
'name': 'Test Company',
'currency_id': cls.env.ref('base.USD').id,
})
cls.company_data = cls.setup_sale_configuration_for_company(cls.company)
cls.partner_a = cls.env['res.partner'].create({
'name': 'partner_a',
'company_id': False,
})
cls.analytic_account = cls.env['account.analytic.account'].create({
'name': 'Test analytic_account',
'code': 'analytic_account',
'company_id': cls.company.id,
'partner_id': cls.partner_a.id
})
user.company_ids |= cls.company
user.company_id = cls.company
def test_qty_delivered(self):
''' Test 'qty_delivered' at-install to avoid a change in the behavior when 'sale_stock' is installed. '''
sale_order = self.env['sale.order'].with_context(mail_notrack=True, mail_create_nolog=True).create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'analytic_account_id': self.analytic_account.id,
'pricelist_id': self.company_data['default_pricelist'].id,
'order_line': [
(0, 0, {
'name': self.company_data['product_order_cost'].name,
'product_id': self.company_data['product_order_cost'].id,
'product_uom_qty': 2,
'qty_delivered': 1,
'product_uom': self.company_data['product_order_cost'].uom_id.id,
'price_unit': self.company_data['product_order_cost'].list_price,
}),
(0, 0, {
'name': self.company_data['product_delivery_cost'].name,
'product_id': self.company_data['product_delivery_cost'].id,
'product_uom_qty': 4,
'qty_delivered': 1,
'product_uom': self.company_data['product_delivery_cost'].uom_id.id,
'price_unit': self.company_data['product_delivery_cost'].list_price,
}),
],
})
for line in sale_order.order_line:
line.product_id_change()
sale_order.onchange_partner_id()
sale_order._compute_tax_id()
sale_order.action_confirm()
self.assertRecordValues(sale_order.order_line, [
{'qty_delivered': 1.0},
{'qty_delivered': 1.0},
])
| 40.219512 | 3,298 |
23,008 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestOnchangeProductId(TransactionCase):
"""Test that when an included tax is mapped by a fiscal position, the included tax must be
subtracted to the price of the product.
"""
def setUp(self):
super(TestOnchangeProductId, self).setUp()
self.fiscal_position_model = self.env['account.fiscal.position']
self.fiscal_position_tax_model = self.env['account.fiscal.position.tax']
self.tax_model = self.env['account.tax']
self.so_model = self.env['sale.order']
self.po_line_model = self.env['sale.order.line']
self.res_partner_model = self.env['res.partner']
self.product_tmpl_model = self.env['product.template']
self.product_model = self.env['product.product']
self.product_uom_model = self.env['uom.uom']
self.supplierinfo_model = self.env["product.supplierinfo"]
self.pricelist_model = self.env['product.pricelist']
def test_onchange_product_id(self):
uom_id = self.product_uom_model.search([('name', '=', 'Units')])[0]
pricelist = self.pricelist_model.search([('name', '=', 'Public Pricelist')])[0]
partner_id = self.res_partner_model.create(dict(name="George"))
tax_include_id = self.tax_model.create(dict(name="Include tax",
amount='21.00',
price_include=True,
type_tax_use='sale'))
tax_exclude_id = self.tax_model.create(dict(name="Exclude tax",
amount='0.00',
type_tax_use='sale'))
product_tmpl_id = self.product_tmpl_model.create(dict(name="Voiture",
list_price=121,
taxes_id=[(6, 0, [tax_include_id.id])]))
product_id = product_tmpl_id.product_variant_id
fp_id = self.fiscal_position_model.create(dict(name="fiscal position", sequence=1))
fp_tax_id = self.fiscal_position_tax_model.create(dict(position_id=fp_id.id,
tax_src_id=tax_include_id.id,
tax_dest_id=tax_exclude_id.id))
# Create the SO with one SO line and apply a pricelist and fiscal position on it
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner_id
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fp_id
with order_form.order_line.new() as line:
line.name = product_id.name
line.product_id = product_id
line.product_uom_qty = 1.0
line.product_uom = uom_id
sale_order = order_form.save()
# Check the unit price of SO line
self.assertEqual(100, sale_order.order_line[0].price_unit, "The included tax must be subtracted to the price")
def test_fiscalposition_application(self):
"""Test application of a fiscal position mapping
price included to price included tax
"""
uom = self.product_uom_model.search([('name', '=', 'Units')])
pricelist = self.pricelist_model.search([('name', '=', 'Public Pricelist')])
partner = self.res_partner_model.create({
'name': "George"
})
tax_fixed_incl = self.tax_model.create({
'name': "fixed include",
'amount': '10.00',
'amount_type': 'fixed',
'price_include': True,
})
tax_fixed_excl = self.tax_model.create({
'name': "fixed exclude",
'amount': '10.00',
'amount_type': 'fixed',
'price_include': False,
})
tax_include_src = self.tax_model.create({
'name': "Include 21%",
'amount': 21.00,
'amount_type': 'percent',
'price_include': True,
})
tax_include_dst = self.tax_model.create({
'name': "Include 6%",
'amount': 6.00,
'amount_type': 'percent',
'price_include': True,
})
tax_exclude_src = self.tax_model.create({
'name': "Exclude 15%",
'amount': 15.00,
'amount_type': 'percent',
'price_include': False,
})
tax_exclude_dst = self.tax_model.create({
'name': "Exclude 21%",
'amount': 21.00,
'amount_type': 'percent',
'price_include': False,
})
product_tmpl_a = self.product_tmpl_model.create({
'name': "Voiture",
'list_price': 121,
'taxes_id': [(6, 0, [tax_include_src.id])]
})
product_tmpl_b = self.product_tmpl_model.create({
'name': "Voiture",
'list_price': 100,
'taxes_id': [(6, 0, [tax_exclude_src.id])]
})
product_tmpl_c = self.product_tmpl_model.create({
'name': "Voiture",
'list_price': 100,
'taxes_id': [(6, 0, [tax_fixed_incl.id, tax_exclude_src.id])]
})
product_tmpl_d = self.product_tmpl_model.create({
'name': "Voiture",
'list_price': 100,
'taxes_id': [(6, 0, [tax_fixed_excl.id, tax_include_src.id])]
})
fpos_incl_incl = self.fiscal_position_model.create({
'name': "incl -> incl",
'sequence': 1
})
self.fiscal_position_tax_model.create({
'position_id' :fpos_incl_incl.id,
'tax_src_id': tax_include_src.id,
'tax_dest_id': tax_include_dst.id
})
fpos_excl_incl = self.fiscal_position_model.create({
'name': "excl -> incl",
'sequence': 2,
})
self.fiscal_position_tax_model.create({
'position_id' :fpos_excl_incl.id,
'tax_src_id': tax_exclude_src.id,
'tax_dest_id': tax_include_dst.id
})
fpos_incl_excl = self.fiscal_position_model.create({
'name': "incl -> excl",
'sequence': 3,
})
self.fiscal_position_tax_model.create({
'position_id' :fpos_incl_excl.id,
'tax_src_id': tax_include_src.id,
'tax_dest_id': tax_exclude_dst.id
})
fpos_excl_excl = self.fiscal_position_model.create({
'name': "excl -> excp",
'sequence': 4,
})
self.fiscal_position_tax_model.create({
'position_id' :fpos_excl_excl.id,
'tax_src_id': tax_exclude_src.id,
'tax_dest_id': tax_exclude_dst.id
})
# Create the SO with one SO line and apply a pricelist and fiscal position on it
# Then check if price unit and price subtotal matches the expected values
# Test Mapping included to included
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fpos_incl_incl
with order_form.order_line.new() as line:
line.name = product_tmpl_a.product_variant_id.name
line.product_id = product_tmpl_a.product_variant_id
line.product_uom_qty = 1.0
line.product_uom = uom
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_unit': 106, 'price_subtotal': 100}])
# Test Mapping excluded to included
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fpos_excl_incl
with order_form.order_line.new() as line:
line.name = product_tmpl_b.product_variant_id.name
line.product_id = product_tmpl_b.product_variant_id
line.product_uom_qty = 1.0
line.product_uom = uom
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_unit': 100, 'price_subtotal': 94.34}])
# Test Mapping included to excluded
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fpos_incl_excl
with order_form.order_line.new() as line:
line.name = product_tmpl_a.product_variant_id.name
line.product_id = product_tmpl_a.product_variant_id
line.product_uom_qty = 1.0
line.product_uom = uom
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_unit': 100, 'price_subtotal': 100}])
# Test Mapping excluded to excluded
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fpos_excl_excl
with order_form.order_line.new() as line:
line.name = product_tmpl_b.product_variant_id.name
line.product_id = product_tmpl_b.product_variant_id
line.product_uom_qty = 1.0
line.product_uom = uom
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_unit': 100, 'price_subtotal': 100}])
# Test Mapping (included,excluded) to (included, included)
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fpos_excl_incl
with order_form.order_line.new() as line:
line.name = product_tmpl_c.product_variant_id.name
line.product_id = product_tmpl_c.product_variant_id
line.product_uom_qty = 1.0
line.product_uom = uom
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_unit': 100, 'price_subtotal': 84.91}])
# Test Mapping (excluded,included) to (excluded, excluded)
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.pricelist_id = pricelist
order_form.fiscal_position_id = fpos_incl_excl
with order_form.order_line.new() as line:
line.name = product_tmpl_d.product_variant_id.name
line.product_id = product_tmpl_d.product_variant_id
line.product_uom_qty = 1.0
line.product_uom = uom
sale_order = order_form.save()
self.assertRecordValues(sale_order.order_line, [{'price_unit': 100, 'price_subtotal': 100}])
def test_pricelist_application(self):
""" Test different prices are correctly applied based on dates """
support_product = self.env['product.product'].create({
'name': 'Virtual Home Staging',
'list_price': 100,
})
partner = self.res_partner_model.create(dict(name="George"))
christmas_pricelist = self.env['product.pricelist'].create({
'name': 'Christmas pricelist',
'item_ids': [(0, 0, {
'date_start': "2017-12-01",
'date_end': "2017-12-24",
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 20,
'applied_on': '3_global',
'name': 'Pre-Christmas discount'
}), (0, 0, {
'date_start': "2017-12-25",
'date_end': "2017-12-31",
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 50,
'applied_on': '3_global',
'name': 'Post-Christmas super-discount'
})]
})
# Create the SO with pricelist based on date
order_form = Form(self.env['sale.order'].with_context(tracking_disable=True))
order_form.partner_id = partner
order_form.date_order = '2017-12-20'
order_form.pricelist_id = christmas_pricelist
with order_form.order_line.new() as line:
line.product_id = support_product
so = order_form.save()
# Check the unit price and subtotal of SO line
self.assertEqual(so.order_line[0].price_unit, 80, "First date pricelist rule not applied")
self.assertEqual(so.order_line[0].price_subtotal, so.order_line[0].price_unit * so.order_line[0].product_uom_qty, 'Total of SO line should be a multiplication of unit price and ordered quantity')
# Change order date of the SO and check the unit price and subtotal of SO line
with Form(so) as order:
order.date_order = '2017-12-30'
with order.order_line.edit(0) as line:
line.product_id = support_product
self.assertEqual(so.order_line[0].price_unit, 50, "Second date pricelist rule not applied")
self.assertEqual(so.order_line[0].price_subtotal, so.order_line[0].price_unit * so.order_line[0].product_uom_qty, 'Total of SO line should be a multiplication of unit price and ordered quantity')
def test_pricelist_uom_discount(self):
""" Test prices and discounts are correctly applied based on date and uom"""
computer_case = self.env['product.product'].create({
'name': 'Drawer Black',
'list_price': 100,
})
partner = self.res_partner_model.create(dict(name="George"))
categ_unit_id = self.ref('uom.product_uom_categ_unit')
goup_discount_id = self.ref('product.group_discount_per_so_line')
self.env.user.write({'groups_id': [(4, goup_discount_id, 0)]})
new_uom = self.env['uom.uom'].create({
'name': '10 units',
'factor_inv': 10,
'uom_type': 'bigger',
'rounding': 1.0,
'category_id': categ_unit_id
})
christmas_pricelist = self.env['product.pricelist'].create({
'name': 'Christmas pricelist',
'discount_policy': 'without_discount',
'item_ids': [(0, 0, {
'date_start': "2017-12-01",
'date_end': "2017-12-30",
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 10,
'applied_on': '3_global',
'name': 'Christmas discount'
})]
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
'date_order': '2017-12-20',
'pricelist_id': christmas_pricelist.id,
})
order_line = self.env['sale.order.line'].new({
'order_id': so.id,
'product_id': computer_case.id,
})
# force compute uom and prices
order_line.product_id_change()
order_line.product_uom_change()
order_line._onchange_discount()
self.assertEqual(order_line.price_subtotal, 90, "Christmas discount pricelist rule not applied")
self.assertEqual(order_line.discount, 10, "Christmas discount not equalt to 10%")
order_line.product_uom = new_uom
order_line.product_uom_change()
order_line._onchange_discount()
self.assertEqual(order_line.price_subtotal, 900, "Christmas discount pricelist rule not applied")
self.assertEqual(order_line.discount, 10, "Christmas discount not equalt to 10%")
def test_pricelist_based_on_other(self):
""" Test price and discount are correctly applied with a pricelist based on an other one"""
computer_case = self.env['product.product'].create({
'name': 'Drawer Black',
'list_price': 100,
})
partner = self.res_partner_model.create(dict(name="George"))
goup_discount_id = self.ref('product.group_discount_per_so_line')
self.env.user.write({'groups_id': [(4, goup_discount_id, 0)]})
first_pricelist = self.env['product.pricelist'].create({
'name': 'First pricelist',
'discount_policy': 'without_discount',
'item_ids': [(0, 0, {
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 10,
'applied_on': '3_global',
'name': 'First discount'
})]
})
second_pricelist = self.env['product.pricelist'].create({
'name': 'Second pricelist',
'discount_policy': 'without_discount',
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'pricelist',
'base_pricelist_id': first_pricelist.id,
'price_discount': 10,
'applied_on': '3_global',
'name': 'Second discount'
})]
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
'date_order': '2018-07-11',
'pricelist_id': second_pricelist.id,
})
order_line = self.env['sale.order.line'].new({
'order_id': so.id,
'product_id': computer_case.id,
})
# force compute uom and prices
order_line.product_id_change()
order_line._onchange_discount()
self.assertEqual(order_line.price_subtotal, 81, "Second pricelist rule not applied")
self.assertEqual(order_line.discount, 19, "Second discount not applied")
def test_pricelist_with_other_currency(self):
""" Test prices are correctly applied with a pricelist with an other currency"""
computer_case = self.env['product.product'].create({
'name': 'Drawer Black',
'list_price': 100,
})
computer_case.list_price = 100
partner = self.res_partner_model.create(dict(name="George"))
categ_unit_id = self.ref('uom.product_uom_categ_unit')
other_currency = self.env['res.currency'].create({'name': 'other currency',
'symbol': 'other'})
self.env['res.currency.rate'].create({'name': '2018-07-11',
'rate': 2.0,
'currency_id': other_currency.id,
'company_id': self.env.company.id})
self.env['res.currency.rate'].search(
[('currency_id', '=', self.env.company.currency_id.id)]
).unlink()
new_uom = self.env['uom.uom'].create({
'name': '10 units',
'factor_inv': 10,
'uom_type': 'bigger',
'rounding': 1.0,
'category_id': categ_unit_id
})
# This pricelist doesn't show the discount
first_pricelist = self.env['product.pricelist'].create({
'name': 'First pricelist',
'currency_id': other_currency.id,
'discount_policy': 'with_discount',
'item_ids': [(0, 0, {
'compute_price': 'percentage',
'base': 'list_price',
'percent_price': 10,
'applied_on': '3_global',
'name': 'First discount'
})]
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
'date_order': '2018-07-12',
'pricelist_id': first_pricelist.id,
})
order_line = self.env['sale.order.line'].new({
'order_id': so.id,
'product_id': computer_case.id,
})
# force compute uom and prices
order_line.product_id_change()
self.assertEqual(order_line.price_unit, 180, "First pricelist rule not applied")
order_line.product_uom = new_uom
order_line.product_uom_change()
self.assertEqual(order_line.price_unit, 1800, "First pricelist rule not applied")
def test_sale_warnings(self):
"""Test warnings & SO/SOL updates when partner/products with sale warnings are used."""
partner_with_warning = self.env['res.partner'].create({
'name': 'Test', 'sale_warn': 'warning', 'sale_warn_msg': 'Highly infectious disease'})
partner_with_block_warning = self.env['res.partner'].create({
'name': 'Test2', 'sale_warn': 'block', 'sale_warn_msg': 'Cannot afford our services'})
sale_order = self.env['sale.order'].create({'partner_id': partner_with_warning.id})
warning = sale_order._onchange_partner_id_warning()
self.assertDictEqual(warning, {
'warning': {
'title': "Warning for Test",
'message': partner_with_warning.sale_warn_msg,
},
})
sale_order.partner_id = partner_with_block_warning
warning = sale_order._onchange_partner_id_warning()
self.assertDictEqual(warning, {
'warning': {
'title': "Warning for Test2",
'message': partner_with_block_warning.sale_warn_msg,
},
})
# Verify partner-related fields have been correctly reset
self.assertFalse(sale_order.partner_id.id)
self.assertFalse(sale_order.partner_invoice_id.id)
self.assertFalse(sale_order.partner_shipping_id.id)
self.assertFalse(sale_order.pricelist_id.id)
# Reuse non blocking partner for product warning tests
sale_order.partner_id = partner_with_warning
product_with_warning = self.env['product.product'].create({
'name': 'Test Product', 'sale_line_warn': 'warning', 'sale_line_warn_msg': 'Highly corrosive'})
product_with_block_warning = self.env['product.product'].create({
'name': 'Test Product (2)', 'sale_line_warn': 'block', 'sale_line_warn_msg': 'Not produced anymore'})
sale_order_line = self.env['sale.order.line'].create({
'order_id': sale_order.id,
'product_id': product_with_warning.id,
})
warning = sale_order_line.product_id_change()
self.assertDictEqual(warning, {
'warning': {
'title': "Warning for Test Product",
'message': product_with_warning.sale_line_warn_msg,
},
})
sale_order_line.product_id = product_with_block_warning
warning = sale_order_line.product_id_change()
self.assertDictEqual(warning, {
'warning': {
'title': "Warning for Test Product (2)",
'message': product_with_block_warning.sale_line_warn_msg,
},
})
self.assertFalse(sale_order_line.product_id.id)
| 42.765799 | 23,008 |
43,824 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from freezegun import freeze_time
from odoo import fields
from odoo.exceptions import UserError, AccessError
from odoo.tests import tagged, Form
from odoo.tools import float_compare
from .common import TestSaleCommon
@tagged('post_install', '-at_install')
class TestSaleOrder(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
SaleOrder = cls.env['sale.order'].with_context(tracking_disable=True)
# set up users
cls.crm_team0 = cls.env['crm.team'].create({
'name': 'crm team 0',
'company_id': cls.company_data['company'].id
})
cls.crm_team1 = cls.env['crm.team'].create({
'name': 'crm team 1',
'company_id': cls.company_data['company'].id
})
cls.user_in_team = cls.env['res.users'].sudo().create({
'email': '[email protected]',
'login': 'team0user',
'name': 'User in Team 0',
})
cls.crm_team0.sudo().write({'member_ids': [4, cls.user_in_team.id]})
cls.user_not_in_team = cls.env['res.users'].sudo().create({
'email': '[email protected]',
'login': 'noteamuser',
'name': 'User Not In Team',
})
# create a generic Sale Order with all classical products and empty pricelist
cls.sale_order = SaleOrder.create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
cls.sol_product_order = cls.env['sale.order.line'].create({
'name': cls.company_data['product_order_no'].name,
'product_id': cls.company_data['product_order_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_order_no'].uom_id.id,
'price_unit': cls.company_data['product_order_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_deliver = cls.env['sale.order.line'].create({
'name': cls.company_data['product_service_delivery'].name,
'product_id': cls.company_data['product_service_delivery'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_service_delivery'].uom_id.id,
'price_unit': cls.company_data['product_service_delivery'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_order = cls.env['sale.order.line'].create({
'name': cls.company_data['product_service_order'].name,
'product_id': cls.company_data['product_service_order'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_service_order'].uom_id.id,
'price_unit': cls.company_data['product_service_order'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_product_deliver = cls.env['sale.order.line'].create({
'name': cls.company_data['product_delivery_no'].name,
'product_id': cls.company_data['product_delivery_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_delivery_no'].uom_id.id,
'price_unit': cls.company_data['product_delivery_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
def test_sale_order(self):
""" Test the sales order flow (invoicing and quantity updates)
- Invoice repeatedly while varrying delivered quantities and check that invoice are always what we expect
"""
# TODO?: validate invoice and register payments
self.sale_order.order_line.read(['name', 'price_unit', 'product_uom_qty', 'price_total'])
self.assertEqual(self.sale_order.amount_total, 1240.0, 'Sale: total amount is wrong')
self.sale_order.order_line._compute_product_updatable()
self.assertTrue(self.sale_order.order_line[0].product_updatable)
# send quotation
email_act = self.sale_order.action_quotation_send()
email_ctx = email_act.get('context', {})
self.sale_order.with_context(**email_ctx).message_post_with_template(email_ctx.get('default_template_id'))
self.assertTrue(self.sale_order.state == 'sent', 'Sale: state after sending is wrong')
self.sale_order.order_line._compute_product_updatable()
self.assertTrue(self.sale_order.order_line[0].product_updatable)
# confirm quotation
self.sale_order.action_confirm()
self.assertTrue(self.sale_order.state == 'sale')
self.assertTrue(self.sale_order.invoice_status == 'to invoice')
# create invoice: only 'invoice on order' products are invoiced
invoice = self.sale_order._create_invoices()
self.assertEqual(len(invoice.invoice_line_ids), 2, 'Sale: invoice is missing lines')
self.assertEqual(invoice.amount_total, 740.0, 'Sale: invoice total amount is wrong')
self.assertTrue(self.sale_order.invoice_status == 'no', 'Sale: SO status after invoicing should be "nothing to invoice"')
self.assertTrue(len(self.sale_order.invoice_ids) == 1, 'Sale: invoice is missing')
self.sale_order.order_line._compute_product_updatable()
self.assertFalse(self.sale_order.order_line[0].product_updatable)
# deliver lines except 'time and material' then invoice again
for line in self.sale_order.order_line:
line.qty_delivered = 2 if line.product_id.expense_policy == 'no' else 0
self.assertTrue(self.sale_order.invoice_status == 'to invoice', 'Sale: SO status after delivery should be "to invoice"')
invoice2 = self.sale_order._create_invoices()
self.assertEqual(len(invoice2.invoice_line_ids), 2, 'Sale: second invoice is missing lines')
self.assertEqual(invoice2.amount_total, 500.0, 'Sale: second invoice total amount is wrong')
self.assertTrue(self.sale_order.invoice_status == 'invoiced', 'Sale: SO status after invoicing everything should be "invoiced"')
self.assertTrue(len(self.sale_order.invoice_ids) == 2, 'Sale: invoice is missing')
# go over the sold quantity
self.sol_serv_order.write({'qty_delivered': 10})
self.assertTrue(self.sale_order.invoice_status == 'upselling', 'Sale: SO status after increasing delivered qty higher than ordered qty should be "upselling"')
# upsell and invoice
self.sol_serv_order.write({'product_uom_qty': 10})
# There is a bug with `new` and `_origin`
# If you create a first new from a record, then change a value on the origin record, than create another new,
# this other new wont have the updated value of the origin record, but the one from the previous new
# Here the problem lies in the use of `new` in `move = self_ctx.new(new_vals)`,
# and the fact this method is called multiple times in the same transaction test case.
# Here, we update `qty_delivered` on the origin record, but the `new` records which are in cache with this order line
# as origin are not updated, nor the fields that depends on it.
self.sol_serv_order.flush()
for field in self.env['sale.order.line']._fields.values():
for res_id in list(self.env.cache._data[field]):
if not res_id:
self.env.cache._data[field].pop(res_id)
invoice3 = self.sale_order._create_invoices()
self.assertEqual(len(invoice3.invoice_line_ids), 1, 'Sale: third invoice is missing lines')
self.assertEqual(invoice3.amount_total, 720.0, 'Sale: second invoice total amount is wrong')
self.assertTrue(self.sale_order.invoice_status == 'invoiced', 'Sale: SO status after invoicing everything (including the upsel) should be "invoiced"')
def test_sale_order_send_to_self(self):
# when sender(logged in user) is also present in recipients of the mail composer,
# user should receive mail.
sale_order = self.env['sale.order'].with_user(self.company_data['default_user_salesman']).create({
'partner_id': self.company_data['default_user_salesman'].partner_id.id,
'order_line': [[0, 0, {
'name': self.company_data['product_order_no'].name,
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': 1,
'price_unit': self.company_data['product_order_no'].list_price,
}]]
})
email_ctx = sale_order.action_quotation_send().get('context', {})
# We need to prevent auto mail deletion, and so we copy the template and send the mail with
# added configuration in copied template. It will allow us to check whether mail is being
# sent to to author or not (in case author is present in 'Recipients' of composer).
mail_template = self.env['mail.template'].browse(email_ctx.get('default_template_id')).copy({'auto_delete': False})
# send the mail with same user as customer
sale_order.with_context(**email_ctx).with_user(self.company_data['default_user_salesman']).message_post_with_template(mail_template.id)
self.assertTrue(sale_order.state == 'sent', 'Sale : state should be changed to sent')
mail_message = sale_order.message_ids[0]
self.assertEqual(mail_message.author_id, sale_order.partner_id, 'Sale: author should be same as customer')
self.assertEqual(mail_message.author_id, mail_message.partner_ids, 'Sale: author should be in composer recipients thanks to "partner_to" field set on template')
self.assertEqual(mail_message.partner_ids, mail_message.sudo().mail_ids.recipient_ids, 'Sale: author should receive mail due to presence in composer recipients')
def test_invoice_state_when_ordered_quantity_is_negative(self):
"""When you invoice a SO line with a product that is invoiced on ordered quantities and has negative ordered quantity,
this test ensures that the invoicing status of the SO line is 'invoiced' (and not 'upselling')."""
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [(0, 0, {
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': -1,
})]
})
sale_order.action_confirm()
sale_order._create_invoices(final=True)
self.assertTrue(sale_order.invoice_status == 'invoiced', 'Sale: The invoicing status of the SO should be "invoiced"')
def test_sale_sequence(self):
self.env['ir.sequence'].search([
('code', '=', 'sale.order'),
]).write({
'use_date_range': True, 'prefix': 'SO/%(range_year)s/',
})
sale_order = self.sale_order.copy({'date_order': '2019-01-01'})
self.assertTrue(sale_order.name.startswith('SO/2019/'))
sale_order = self.sale_order.copy({'date_order': '2020-01-01'})
self.assertTrue(sale_order.name.startswith('SO/2020/'))
# In EU/BXL tz, this is actually already 01/01/2020
sale_order = self.sale_order.with_context(tz='Europe/Brussels').copy({'date_order': '2019-12-31 23:30:00'})
self.assertTrue(sale_order.name.startswith('SO/2020/'))
def test_unlink_cancel(self):
""" Test deleting and cancelling sales orders depending on their state and on the user's rights """
# SO in state 'draft' can be deleted
so_copy = self.sale_order.copy()
with self.assertRaises(AccessError):
so_copy.with_user(self.company_data['default_user_employee']).unlink()
self.assertTrue(so_copy.unlink(), 'Sale: deleting a quotation should be possible')
# SO in state 'cancel' can be deleted
so_copy = self.sale_order.copy()
so_copy.action_confirm()
self.assertTrue(so_copy.state == 'sale', 'Sale: SO should be in state "sale"')
so_copy.action_cancel()
self.assertTrue(so_copy.state == 'cancel', 'Sale: SO should be in state "cancel"')
with self.assertRaises(AccessError):
so_copy.with_user(self.company_data['default_user_employee']).unlink()
self.assertTrue(so_copy.unlink(), 'Sale: deleting a cancelled SO should be possible')
# SO in state 'sale' or 'done' cannot be deleted
self.sale_order.action_confirm()
self.assertTrue(self.sale_order.state == 'sale', 'Sale: SO should be in state "sale"')
with self.assertRaises(UserError):
self.sale_order.unlink()
self.sale_order.action_done()
self.assertTrue(self.sale_order.state == 'done', 'Sale: SO should be in state "done"')
with self.assertRaises(UserError):
self.sale_order.unlink()
def test_cost_invoicing(self):
""" Test confirming a vendor invoice to reinvoice cost on the so """
serv_cost = self.env['product.product'].create({
'name': "Ordered at cost",
'standard_price': 160,
'list_price': 180,
'type': 'consu',
'invoice_policy': 'order',
'expense_policy': 'cost',
'default_code': 'PROD_COST',
'service_type': 'manual',
})
prod_gap = self.company_data['product_service_order']
so = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'order_line': [(0, 0, {'name': prod_gap.name, 'product_id': prod_gap.id, 'product_uom_qty': 2, 'product_uom': prod_gap.uom_id.id, 'price_unit': prod_gap.list_price})],
'pricelist_id': self.company_data['default_pricelist'].id,
})
so.action_confirm()
so._create_analytic_account()
inv = self.env['account.move'].with_context(default_move_type='in_invoice').create({
'partner_id': self.partner_a.id,
'invoice_date': so.date_order,
'invoice_line_ids': [
(0, 0, {
'name': serv_cost.name,
'product_id': serv_cost.id,
'product_uom_id': serv_cost.uom_id.id,
'quantity': 2,
'price_unit': serv_cost.standard_price,
'analytic_account_id': so.analytic_account_id.id,
}),
],
})
inv.action_post()
sol = so.order_line.filtered(lambda l: l.product_id == serv_cost)
self.assertTrue(sol, 'Sale: cost invoicing does not add lines when confirming vendor invoice')
self.assertEqual((sol.price_unit, sol.qty_delivered, sol.product_uom_qty, sol.qty_invoiced), (160, 2, 0, 0), 'Sale: line is wrong after confirming vendor invoice')
def test_sale_with_taxes(self):
""" Test SO with taxes applied on its lines and check subtotal applied on its lines and total applied on the SO """
# Create a tax with price included
tax_include = self.env['account.tax'].create({
'name': 'Tax with price include',
'amount': 10,
'price_include': True
})
# Create a tax with price not included
tax_exclude = self.env['account.tax'].create({
'name': 'Tax with no price include',
'amount': 10,
})
# Apply taxes on the sale order lines
self.sol_product_order.write({'tax_id': [(4, tax_include.id)]})
self.sol_serv_deliver.write({'tax_id': [(4, tax_include.id)]})
self.sol_serv_order.write({'tax_id': [(4, tax_exclude.id)]})
self.sol_product_deliver.write({'tax_id': [(4, tax_exclude.id)]})
# Trigger onchange to reset discount, unit price, subtotal, ...
for line in self.sale_order.order_line:
line.product_id_change()
line._onchange_discount()
for line in self.sale_order.order_line:
if line.tax_id.price_include:
price = line.price_unit * line.product_uom_qty - line.price_tax
else:
price = line.price_unit * line.product_uom_qty
self.assertEqual(float_compare(line.price_subtotal, price, precision_digits=2), 0)
self.assertEqual(self.sale_order.amount_total,
self.sale_order.amount_untaxed + self.sale_order.amount_tax,
'Taxes should be applied')
def test_so_create_multicompany(self):
"""Check that only taxes of the right company are applied on the lines."""
# Preparing test Data
product_shared = self.env['product.template'].create({
'name': 'shared product',
'invoice_policy': 'order',
'taxes_id': [(6, False, (self.company_data['default_tax_sale'] + self.company_data_2['default_tax_sale']).ids)],
'property_account_income_id': self.company_data['default_account_revenue'].id,
})
so_1 = self.env['sale.order'].with_user(self.company_data['default_user_salesman']).create({
'partner_id': self.env['res.partner'].create({'name': 'A partner'}).id,
'company_id': self.company_data['company'].id,
})
so_1.write({
'order_line': [(0, False, {'product_id': product_shared.product_variant_id.id, 'order_id': so_1.id})],
})
self.assertEqual(so_1.order_line.tax_id, self.company_data['default_tax_sale'],
'Only taxes from the right company are put by default')
so_1.action_confirm()
# i'm not interested in groups/acls, but in the multi-company flow only
# the sudo is there for that and does not impact the invoice that gets created
# the goal here is to invoice in company 1 (because the order is in company 1) while being
# 'mainly' in company 2 (through the context), the invoice should be in company 1
inv=so_1.sudo()\
.with_context(allowed_company_ids=(self.company_data['company'] + self.company_data_2['company']).ids)\
._create_invoices()
self.assertEqual(inv.company_id, self.company_data['company'], 'invoices should be created in the company of the SO, not the main company of the context')
def test_group_invoice(self):
""" Test that invoicing multiple sales order for the same customer works. """
# Create 3 SOs for the same partner, one of which that uses another currency
eur_pricelist = self.env['product.pricelist'].create({'name': 'EUR', 'currency_id': self.env.ref('base.EUR').id})
so1 = self.sale_order.with_context(mail_notrack=True).copy()
so1.pricelist_id = eur_pricelist
so2 = so1.copy()
usd_pricelist = self.env['product.pricelist'].create({'name': 'USD', 'currency_id': self.env.ref('base.USD').id})
so3 = so1.copy()
so1.pricelist_id = usd_pricelist
orders = so1 | so2 | so3
orders.action_confirm()
# Create the invoicing wizard and invoice all of them at once
wiz = self.env['sale.advance.payment.inv'].with_context(active_ids=orders.ids, open_invoices=True).create({})
res = wiz.create_invoices()
# Check that exactly 2 invoices are generated
self.assertEqual(len(res['domain'][0][2]),2, "Grouping invoicing 3 orders for the same partner with 2 currencies should create exactly 2 invoices")
def test_so_note_to_invoice(self):
"""Test that notes from SO are pushed into invoices"""
sol_note = self.env['sale.order.line'].create({
'name': 'This is a note',
'display_type': 'line_note',
'product_id': False,
'product_uom_qty': 0,
'product_uom': False,
'price_unit': 0,
'order_id': self.sale_order.id,
'tax_id': False,
})
# confirm quotation
self.sale_order.action_confirm()
# create invoice
invoice = self.sale_order._create_invoices()
# check note from SO has been pushed in invoice
self.assertEqual(len(invoice.invoice_line_ids.filtered(lambda line: line.display_type == 'line_note')), 1, 'Note SO line should have been pushed to the invoice')
def test_multi_currency_discount(self):
"""Verify the currency used for pricelist price & discount computation."""
products = self.env["product.product"].search([], limit=2)
product_1 = products[0]
product_2 = products[1]
# Make sure the company is in USD
main_company = self.env.ref('base.main_company')
main_curr = main_company.currency_id
current_curr = self.env.company.currency_id
other_curr = self.currency_data['currency']
# main_company.currency_id = other_curr # product.currency_id when no company_id set
other_company = self.env["res.company"].create({
"name": "Test",
"currency_id": other_curr.id
})
user_in_other_company = self.env["res.users"].create({
"company_id": other_company.id,
"company_ids": [(6, 0, [other_company.id])],
"name": "E.T",
"login": "hohoho",
})
user_in_other_company.groups_id |= self.env.ref('product.group_discount_per_so_line')
self.env['res.currency.rate'].search([]).unlink()
self.env['res.currency.rate'].create({
'name': '2010-01-01',
'rate': 2.0,
'currency_id': main_curr.id,
"company_id": False,
})
product_1.company_id = False
product_2.company_id = False
self.assertEqual(product_1.currency_id, main_curr)
self.assertEqual(product_2.currency_id, main_curr)
self.assertEqual(product_1.cost_currency_id, current_curr)
self.assertEqual(product_2.cost_currency_id, current_curr)
product_1_ctxt = product_1.with_user(user_in_other_company)
product_2_ctxt = product_2.with_user(user_in_other_company)
self.assertEqual(product_1_ctxt.currency_id, main_curr)
self.assertEqual(product_2_ctxt.currency_id, main_curr)
self.assertEqual(product_1_ctxt.cost_currency_id, other_curr)
self.assertEqual(product_2_ctxt.cost_currency_id, other_curr)
product_1.lst_price = 100.0
product_2_ctxt.standard_price = 10.0 # cost is company_dependent
pricelist = self.env["product.pricelist"].create({
"name": "Test multi-currency",
"discount_policy": "without_discount",
"currency_id": other_curr.id,
"item_ids": [
(0, 0, {
"base": "list_price",
"product_id": product_1.id,
"compute_price": "percentage",
"percent_price": 20,
}),
(0, 0, {
"base": "standard_price",
"product_id": product_2.id,
"compute_price": "percentage",
"percent_price": 10,
})
]
})
# Create a SO in the other company
##################################
# product_currency = main_company.currency_id when no company_id on the product
# CASE 1:
# company currency = so currency
# product_1.currency != so currency
# product_2.cost_currency_id = so currency
sales_order = product_1_ctxt.with_context(mail_notrack=True, mail_create_nolog=True).env["sale.order"].create({
"partner_id": self.env.user.partner_id.id,
"pricelist_id": pricelist.id,
"order_line": [
(0, 0, {
"product_id": product_1.id,
"product_uom_qty": 1.0
}),
(0, 0, {
"product_id": product_2.id,
"product_uom_qty": 1.0
})
]
})
for line in sales_order.order_line:
# Create values autofill does not compute discount.
line._onchange_discount()
so_line_1 = sales_order.order_line[0]
so_line_2 = sales_order.order_line[1]
self.assertEqual(so_line_1.discount, 20)
self.assertEqual(so_line_1.price_unit, 50.0)
self.assertEqual(so_line_2.discount, 10)
self.assertEqual(so_line_2.price_unit, 10)
# CASE 2
# company currency != so currency
# product_1.currency == so currency
# product_2.cost_currency_id != so currency
pricelist.currency_id = main_curr
sales_order = product_1_ctxt.with_context(mail_notrack=True, mail_create_nolog=True).env["sale.order"].create({
"partner_id": self.env.user.partner_id.id,
"pricelist_id": pricelist.id,
"order_line": [
# Verify discount is considered in create hack
(0, 0, {
"product_id": product_1.id,
"product_uom_qty": 1.0
}),
(0, 0, {
"product_id": product_2.id,
"product_uom_qty": 1.0
})
]
})
for line in sales_order.order_line:
line._onchange_discount()
so_line_1 = sales_order.order_line[0]
so_line_2 = sales_order.order_line[1]
self.assertEqual(so_line_1.discount, 20)
self.assertEqual(so_line_1.price_unit, 100.0)
self.assertEqual(so_line_2.discount, 10)
self.assertEqual(so_line_2.price_unit, 20)
def test_assign_sales_team_from_partner_user(self):
"""Use the team from the customer's sales person, if it is set"""
partner = self.env['res.partner'].create({
'name': 'Customer of User In Team',
'user_id': self.user_in_team.id,
'team_id': self.crm_team1.id,
})
sale_order = self.env['sale.order'].create({
'partner_id': partner.id,
})
sale_order.onchange_partner_id()
self.assertEqual(sale_order.team_id.id, self.crm_team0.id, 'Should assign to team of sales person')
def test_assign_sales_team_from_partner_team(self):
"""If no team set on the customer's sales person, fall back to the customer's team"""
partner = self.env['res.partner'].create({
'name': 'Customer of User Not In Team',
'user_id': self.user_not_in_team.id,
'team_id': self.crm_team1.id,
})
sale_order = self.env['sale.order'].create({
'partner_id': partner.id,
})
sale_order.onchange_partner_id()
self.assertEqual(sale_order.team_id.id, self.crm_team1.id, 'Should assign to team of partner')
def test_assign_sales_team_when_changing_user(self):
"""When we assign a sales person, change the team on the sales order to their team"""
sale_order = self.env['sale.order'].create({
'user_id': self.user_not_in_team.id,
'partner_id': self.partner_a.id,
'team_id': self.crm_team1.id
})
sale_order.user_id = self.user_in_team
sale_order.onchange_user_id()
self.assertEqual(sale_order.team_id.id, self.crm_team0.id, 'Should assign to team of sales person')
def test_keep_sales_team_when_changing_user_with_no_team(self):
"""When we assign a sales person that has no team, do not reset the team to default"""
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'team_id': self.crm_team1.id
})
sale_order.user_id = self.user_not_in_team
sale_order.onchange_user_id()
self.assertEqual(sale_order.team_id.id, self.crm_team1.id, 'Should not reset the team to default')
def test_onchange_packaging_00(self):
"""Create a SO and use packaging. Check we suggested suitable packaging
according to the product_qty. Also check product_qty or product_packaging
are correctly calculated when one of them changed.
"""
partner = self.env['res.partner'].create({'name': "I'm a partner"})
product_tmpl = self.env['product.template'].create({'name': "I'm a product"})
product = product_tmpl.product_variant_id
packaging_single = self.env['product.packaging'].create({
'name': "I'm a packaging",
'product_id': product.id,
'qty': 1.0,
})
packaging_dozen = self.env['product.packaging'].create({
'name': "I'm also a packaging",
'product_id': product.id,
'qty': 12.0,
})
so = self.env['sale.order'].create({
'partner_id': partner.id,
})
so_form = Form(so)
with so_form.order_line.new() as line:
line.product_id = product
line.product_uom_qty = 1.0
so_form.save()
self.assertEqual(so.order_line.product_packaging_id, packaging_single)
self.assertEqual(so.order_line.product_packaging_qty, 1.0)
with so_form.order_line.edit(0) as line:
line.product_packaging_qty = 2.0
so_form.save()
self.assertEqual(so.order_line.product_uom_qty, 2.0)
with so_form.order_line.edit(0) as line:
line.product_uom_qty = 24.0
so_form.save()
self.assertEqual(so.order_line.product_packaging_id, packaging_dozen)
self.assertEqual(so.order_line.product_packaging_qty, 2.0)
with so_form.order_line.edit(0) as line:
line.product_packaging_qty = 1.0
so_form.save()
self.assertEqual(so.order_line.product_uom_qty, 12)
def _create_sale_order(self):
"""Create dummy sale order (without lines)"""
return self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
})
def test_invoicing_terms(self):
# Enable invoicing terms
self.env['ir.config_parameter'].sudo().set_param('account.use_invoice_terms', True)
# Plain invoice terms
self.env.company.terms_type = 'plain'
self.env.company.invoice_terms = "Coin coin"
sale_order = self._create_sale_order()
self.assertEqual(sale_order.note, "<p>Coin coin</p>")
# Html invoice terms (/terms page)
self.env.company.terms_type = 'html'
sale_order = self._create_sale_order()
self.assertTrue(sale_order.note.startswith("<p>Terms & Conditions: "))
def test_validity_days(self):
self.env['ir.config_parameter'].sudo().set_param('sale.use_quotation_validity_days', True)
self.env.company.quotation_validity_days = 5
with freeze_time("2020-05-02"):
sale_order = self._create_sale_order()
self.assertEqual(sale_order.validity_date, fields.Date.today() + timedelta(days=5))
self.env.company.quotation_validity_days = 0
sale_order = self._create_sale_order()
self.assertFalse(
sale_order.validity_date,
"No validity date must be specified if the company validity duration is 0")
def test_update_prices(self):
"""Test prices recomputation on SO's.
`update_prices` is shown as a button to update
prices when the pricelist was changed.
"""
self.env.user.write({'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)]})
sale_order = self.sale_order
so_amount = sale_order.amount_total
sale_order.update_prices()
self.assertEqual(
sale_order.amount_total, so_amount,
"Updating the prices of an unmodified SO shouldn't modify the amounts")
pricelist = sale_order.pricelist_id
pricelist.item_ids = [
fields.Command.create({
'percent_price': 5.0,
'compute_price': 'percentage'
})
]
pricelist.discount_policy = "without_discount"
self.env['product.product'].invalidate_cache(['price'])
sale_order.update_prices()
self.assertTrue(all(line.discount == 5 for line in sale_order.order_line))
self.assertEqual(sale_order.amount_undiscounted, so_amount)
self.assertEqual(sale_order.amount_total, 0.95*so_amount)
pricelist.discount_policy = "with_discount"
self.env['product.product'].invalidate_cache(['price'])
sale_order.update_prices()
self.assertTrue(all(line.discount == 0 for line in sale_order.order_line))
self.assertEqual(sale_order.amount_undiscounted, so_amount)
self.assertEqual(sale_order.amount_total, 0.95*so_amount)
def test_so_names(self):
"""Test custom context key for name_get & name_search.
Note: this key is used in sale_expense & sale_timesheet modules.
"""
SaleOrder = self.env['sale.order'].with_context(sale_show_partner_name=True)
res = SaleOrder.name_search(name=self.sale_order.partner_id.name)
self.assertEqual(res[0][0], self.sale_order.id)
self.assertNotIn(self.sale_order.partner_id.name, self.sale_order.display_name)
self.assertIn(
self.sale_order.partner_id.name,
self.sale_order.with_context(sale_show_partner_name=True).name_get()[0][1])
def test_state_changes(self):
"""Test some untested state changes methods & logic."""
self.sale_order.action_quotation_sent()
self.assertEqual(self.sale_order.state, 'sent')
self.assertIn(self.sale_order.partner_id, self.sale_order.message_follower_ids.partner_id)
self.env.user.groups_id += self.env.ref('sale.group_auto_done_setting')
self.sale_order.action_confirm()
self.assertEqual(self.sale_order.state, 'done', "The order wasn't automatically locked at confirmation.")
with self.assertRaises(UserError):
self.sale_order.action_confirm()
self.sale_order.action_unlock()
self.assertEqual(self.sale_order.state, 'sale')
def test_discount_and_untaxed_subtotal(self):
"""When adding a discount on a SO line, this test ensures that the untaxed amount to invoice is
equal to the untaxed subtotal"""
self.product_a.invoice_policy = 'delivery'
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [(0, 0, {
'product_id': self.product_a.id,
'product_uom_qty': 38,
'price_unit': 541.26,
'discount': 2.00,
})]
})
sale_order.action_confirm()
line = sale_order.order_line
self.assertEqual(line.untaxed_amount_to_invoice, 0)
line.qty_delivered = 38
# (541.26 - 0.02 * 541.26) * 38 = 20156.5224 ~= 20156.52
self.assertEqual(line.price_subtotal, 20156.52)
self.assertEqual(line.untaxed_amount_to_invoice, line.price_subtotal)
# Same with an included-in-price tax
sale_order = sale_order.copy()
line = sale_order.order_line
line.tax_id = [(0, 0, {
'name': 'Super Tax',
'amount_type': 'percent',
'amount': 15.0,
'price_include': True,
})]
sale_order.action_confirm()
self.assertEqual(line.untaxed_amount_to_invoice, 0)
line.qty_delivered = 38
# (541,26 / 1,15) * ,98 * 38 = 17527,410782609 ~= 17527.41
self.assertEqual(line.price_subtotal, 17527.41)
self.assertEqual(line.untaxed_amount_to_invoice, line.price_subtotal)
def test_discount_and_amount_undiscounted(self):
"""When adding a discount on a SO line, this test ensures that amount undiscounted is
consistent with the used tax"""
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [(0, 0, {
'product_id': self.product_a.id,
'product_uom_qty': 1,
'price_unit': 100.0,
'discount': 1.00,
})]
})
sale_order.action_confirm()
line = sale_order.order_line
# test discount and qty 1
self.assertEqual(sale_order.amount_undiscounted, 100.0)
self.assertEqual(line.price_subtotal, 99.0)
# more quantity 1 -> 3
sale_form = Form(sale_order)
with sale_form.order_line.edit(0) as line_form:
line_form.product_uom_qty = 3.0
line_form.price_unit = 100.0
sale_order = sale_form.save()
self.assertEqual(sale_order.amount_undiscounted, 300.0)
self.assertEqual(line.price_subtotal, 297.0)
# undiscounted
with sale_form.order_line.edit(0) as line_form:
line_form.discount = 0.0
sale_order = sale_form.save()
self.assertEqual(line.price_subtotal, 300.0)
self.assertEqual(sale_order.amount_undiscounted, 300.0)
# Same with an included-in-price tax
sale_order = sale_order.copy()
line = sale_order.order_line
line.tax_id = [(0, 0, {
'name': 'Super Tax',
'amount_type': 'percent',
'amount': 10.0,
'price_include': True,
})]
line.discount = 50.0
sale_order.action_confirm()
# 300 with 10% incl tax -> 272.72 total tax excluded without discount
# 136.36 price tax excluded with discount applied
self.assertEqual(sale_order.amount_undiscounted, 272.72)
self.assertEqual(line.price_subtotal, 136.36)
def test_free_product_and_price_include_fixed_tax(self):
""" Check that fixed tax include are correctly computed while the price_unit is 0
"""
# please ensure this test remains consistent with
# test_out_invoice_line_onchange_2_taxes_fixed_price_include_free_product in account module
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [(0, 0, {
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': 1,
'price_unit': 0.0,
})]
})
sale_order.action_confirm()
line = sale_order.order_line
line.tax_id = [
(0, 0, {
'name': 'BEBAT 0.05',
'type_tax_use': 'sale',
'amount_type': 'fixed',
'amount': 0.05,
'price_include': True,
'include_base_amount': True,
}),
(0, 0, {
'name': 'Recupel 0.25',
'type_tax_use': 'sale',
'amount_type': 'fixed',
'amount': 0.25,
'price_include': True,
'include_base_amount': True,
}),
]
sale_order.action_confirm()
self.assertRecordValues(sale_order, [{
'amount_untaxed': -0.30,
'amount_tax': 0.30,
'amount_total': 0.0,
}])
def test_sol_name_search(self):
# Shouldn't raise
self.env['sale.order']._search([('order_line', 'ilike', 'acoustic')])
name_search_data = self.env['sale.order.line'].name_search(name=self.sale_order.name)
sol_ids_found = dict(name_search_data).keys()
self.assertEqual(list(sol_ids_found), self.sale_order.order_line.ids)
def test_sale_order_analytic_tag_change(self):
self.env.user.groups_id += self.env.ref('analytic.group_analytic_accounting')
self.env.user.groups_id += self.env.ref('analytic.group_analytic_tags')
analytic_account_super = self.env['account.analytic.account'].create({'name': 'Super Account'})
analytic_account_great = self.env['account.analytic.account'].create({'name': 'Great Account'})
analytic_tag_super = self.env['account.analytic.tag'].create({'name': 'Super Tag'})
analytic_tag_great = self.env['account.analytic.tag'].create({'name': 'Great Tag'})
super_product = self.env['product.product'].create({'name': 'Super Product'})
great_product = self.env['product.product'].create({'name': 'Great Product'})
product_no_account = self.env['product.product'].create({'name': 'Product No Account'})
self.env['account.analytic.default'].create([
{
'analytic_id': analytic_account_super.id,
'product_id': super_product.id,
'analytic_tag_ids': [analytic_tag_super.id],
},
{
'analytic_id': analytic_account_great.id,
'product_id': great_product.id,
'analytic_tag_ids': [analytic_tag_great.id],
},
])
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
})
sol = self.env['sale.order.line'].create({
'name': super_product.name,
'product_id': super_product.id,
'order_id': sale_order.id,
})
self.assertEqual(sol.analytic_tag_ids.id, analytic_tag_super.id, "The analytic tag should be set to 'Super Tag'")
sol.write({'product_id': great_product.id})
self.assertEqual(sol.analytic_tag_ids.id, analytic_tag_great.id, "The analytic tag should be set to 'Great Tag'")
sol.write({'product_id': product_no_account.id})
self.assertFalse(sol.analytic_tag_ids.id, "The analytic account should not be set")
so_no_analytic_account = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
})
sol_no_analytic_account = self.env['sale.order.line'].create({
'name': super_product.name,
'product_id': super_product.id,
'order_id': so_no_analytic_account.id,
'analytic_tag_ids': False,
})
so_no_analytic_account.action_confirm()
self.assertFalse(sol_no_analytic_account.analytic_tag_ids.id, "The compute should not overwrite what the user has set.")
def test_cannot_assign_tax_of_mismatch_company(self):
""" Test that sol cannot have assigned tax belonging to a different company from that of the sale order. """
company_a = self.env['res.company'].create({'name': 'A'})
company_b = self.env['res.company'].create({'name': 'B'})
tax_a = self.env['account.tax'].create({
'name': 'A',
'amount': 10,
'company_id': company_a.id,
})
tax_b = self.env['account.tax'].create({
'name': 'B',
'amount': 10,
'company_id': company_b.id,
})
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'company_id': company_a.id
})
product = self.env['product.product'].create({'name': 'Product'})
# In sudo to simulate an user that have access to both companies.
sol = self.env['sale.order.line'].sudo().create({
'name': product.name,
'product_id': product.id,
'order_id': sale_order.id,
'tax_id': tax_a,
})
with self.assertRaises(UserError):
sol.tax_id = tax_b
| 46.720682 | 43,824 |
21,047 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields
from odoo.addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueCommon
from odoo.tests import tagged
class TestSaleProductAttributeValueCommon(TestProductAttributeValueCommon):
@classmethod
def _setup_currency(cls, currency_ratio=2):
"""Get or create a currency. This makes the test non-reliant on demo.
With an easy currency rate, for a simple 2 ratio in the following tests.
"""
from_currency = cls.computer.currency_id
cls._set_or_create_rate_today(from_currency, rate=1)
to_currency = cls._get_or_create_currency("my currency", "C")
cls._set_or_create_rate_today(to_currency, currency_ratio)
return to_currency
@classmethod
def _set_or_create_rate_today(cls, currency, rate):
"""Get or create a currency rate for today. This makes the test
non-reliant on demo data."""
name = fields.Date.today()
currency_id = currency.id
company_id = cls.env.company.id
CurrencyRate = cls.env['res.currency.rate']
currency_rate = CurrencyRate.search([
('company_id', '=', company_id),
('currency_id', '=', currency_id),
('name', '=', name),
])
if currency_rate:
currency_rate.rate = rate
else:
CurrencyRate.create({
'company_id': company_id,
'currency_id': currency_id,
'name': name,
'rate': rate,
})
@classmethod
def _get_or_create_currency(cls, name, symbol):
"""Get or create a currency based on name. This makes the test
non-reliant on demo data."""
currency = cls.env['res.currency'].search([('name', '=', name)])
return currency or currency.create({
'name': name,
'symbol': symbol,
})
@tagged('post_install', '-at_install')
class TestSaleProductAttributeValueConfig(TestSaleProductAttributeValueCommon):
def _setup_pricelist(self, currency_ratio=2):
to_currency = self._setup_currency(currency_ratio)
discount = 10
pricelist = self.env['product.pricelist'].create({
'name': 'test pl',
'currency_id': to_currency.id,
'company_id': self.computer.company_id.id,
})
pricelist_item = self.env['product.pricelist.item'].create({
'min_quantity': 2,
'compute_price': 'percentage',
'percent_price': discount,
'pricelist_id': pricelist.id,
})
return (pricelist, pricelist_item, currency_ratio, 1 - discount / 100)
def test_01_is_combination_possible_archived(self):
"""The goal is to test the possibility of archived combinations.
This test could not be put into product module because there was no
model which had product_id as required and without cascade on delete.
Here we have the sales order line in this situation.
This is a necessary condition for `_create_variant_ids` to archive
instead of delete the variants.
"""
def do_test(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant2 = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_2)
self.assertTrue(variant)
self.assertTrue(variant2)
# Create a dummy SO to prevent the variant from being deleted by
# _create_variant_ids() because the variant is a related field that
# is required on the SO line
so = self.env['sale.order'].create({'partner_id': 1})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant.id
})
# additional variant to test correct ignoring when mismatch values
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant2.id
})
variant2.active = False
# CASE: 1 not archived, 2 archived
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
# CASE: both archived combination (without no_variant)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: OK after attribute line removed
self.computer_hdd_attribute_lines.write({'active': False})
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8))
# CASE: not archived (with no_variant)
self.hdd_attribute.create_variant = 'no_variant'
self._add_hdd_attribute_line()
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: archived combination found (with no_variant)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: archived combination has different attributes (including no_variant)
self.computer_ssd_attribute_lines.write({'active': False})
variant4 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant4.id
})
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
# CASE: archived combination has different attributes (without no_variant)
self.computer_hdd_attribute_lines.write({'active': False})
self.hdd_attribute.create_variant = 'always'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant5 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant5.id
})
self.assertTrue(variant4 != variant5)
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
computer_ssd_256_before = self._get_product_template_attribute_value(self.ssd_256)
do_test(self)
# CASE: add back the removed attribute and try everything again
self.computer_ssd_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.ssd_attribute.id,
'value_ids': [(6, 0, [self.ssd_256.id, self.ssd_512.id])],
})
computer_ssd_256_after = self._get_product_template_attribute_value(self.ssd_256)
self.assertEqual(computer_ssd_256_after, computer_ssd_256_before)
self.assertEqual(computer_ssd_256_after.attribute_line_id, computer_ssd_256_before.attribute_line_id)
do_test(self)
def test_02_get_combination_info(self):
# If using multi-company, company_id will be False, and this code should
# still work.
# The case with a company_id will be implicitly tested on website_sale.
self.computer.company_id = False
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
# CASE: no pricelist, no currency, with existing combination, with price_extra on attributes
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant = self.computer._get_variant_for_combination(combination)
res = self.computer._get_combination_info(combination)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
# CASE: no combination, product given
res = self.computer._get_combination_info(self.env['product.template.attribute.value'], computer_variant.id)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
# CASE: using pricelist, quantity rule
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: no_variant combination, it's another variant now
self.computer_ssd_attribute_lines.write({'active': False})
self.ssd_attribute.create_variant = 'no_variant'
self._add_ssd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._get_variant_for_combination(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, but the variant already exists
self.computer_hdd_attribute_lines.write({'active': False})
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._create_product_variant(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, no variant existing
# Test invalidate_cache on product.template _create_variant_ids
self._add_keyboard_attribute()
combination += self._get_product_template_attribute_value(self.keyboard_excluded)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], (2222 - 5) * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
# CASE: pricelist set value to 0, no variant
# Test invalidate_cache on product.pricelist write
pricelist_item.percent_price = 100
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], 0)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
def test_03_get_combination_info_discount_policy(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
pricelist.discount_policy = 'with_discount'
# CASE: no discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: no discount, setting without_discount
pricelist.discount_policy = 'without_discount'
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting without_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], True)
def test_04_create_product_variant_non_dynamic(self):
"""The goal of this test is to make sure the create_product_variant does
not create variant if the type is not dynamic. It can however return a
variant if it already exists."""
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant is already created, it should return it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant1 = self.computer._get_variant_for_combination(combination)
self.assertEqual(self.computer._create_product_variant(combination), variant1)
# CASE: variant does not exist, but template is non-dynamic, so it
# should not create it
Product = self.env['product.product']
variant1.unlink()
self.assertEqual(self.computer._create_product_variant(combination), Product)
def test_05_create_product_variant_dynamic(self):
"""The goal of this test is to make sure the create_product_variant does
work with dynamic. If the combination is possible, it should create it.
If it's not possible, it should not create it."""
self.computer_hdd_attribute_lines.write({'active': False})
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant does not exist, but combination is not possible
# so it should not create it
impossible_combination = computer_ssd_256 + computer_ram_16 + computer_hdd_1
Product = self.env['product.product']
self.assertEqual(self.computer._create_product_variant(impossible_combination), Product)
# CASE: the variant does not exist, and the combination is possible, so
# it should create it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant = self.computer._create_product_variant(combination)
self.assertTrue(variant)
# CASE: the variant already exists, so it should return it
self.assertEqual(variant, self.computer._create_product_variant(combination))
def _add_keyboard_attribute(self):
self.keyboard_attribute = self.env['product.attribute'].create({
'name': 'Keyboard',
'sequence': 6,
'create_variant': 'dynamic',
})
self.keyboard_included = self.env['product.attribute.value'].create({
'name': 'Included',
'attribute_id': self.keyboard_attribute.id,
'sequence': 1,
})
self.keyboard_excluded = self.env['product.attribute.value'].create({
'name': 'Excluded',
'attribute_id': self.keyboard_attribute.id,
'sequence': 2,
})
self.computer_keyboard_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.keyboard_attribute.id,
'value_ids': [(6, 0, [self.keyboard_included.id, self.keyboard_excluded.id])],
})
self.computer_keyboard_attribute_lines.product_template_value_ids[0].price_extra = 5
self.computer_keyboard_attribute_lines.product_template_value_ids[1].price_extra = -5
| 51.209246 | 21,047 |
34,551 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tools import float_is_zero
from .common import TestSaleCommon
from odoo.tests import Form, tagged
from odoo import Command, fields
@tagged('-at_install', 'post_install')
class TestSaleToInvoice(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# Create the SO with four order lines
cls.sale_order = cls.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
SaleOrderLine = cls.env['sale.order.line'].with_context(tracking_disable=True)
cls.sol_prod_order = SaleOrderLine.create({
'name': cls.company_data['product_order_no'].name,
'product_id': cls.company_data['product_order_no'].id,
'product_uom_qty': 5,
'product_uom': cls.company_data['product_order_no'].uom_id.id,
'price_unit': cls.company_data['product_order_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_deliver = SaleOrderLine.create({
'name': cls.company_data['product_service_delivery'].name,
'product_id': cls.company_data['product_service_delivery'].id,
'product_uom_qty': 4,
'product_uom': cls.company_data['product_service_delivery'].uom_id.id,
'price_unit': cls.company_data['product_service_delivery'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_serv_order = SaleOrderLine.create({
'name': cls.company_data['product_service_order'].name,
'product_id': cls.company_data['product_service_order'].id,
'product_uom_qty': 3,
'product_uom': cls.company_data['product_service_order'].uom_id.id,
'price_unit': cls.company_data['product_service_order'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
cls.sol_prod_deliver = SaleOrderLine.create({
'name': cls.company_data['product_delivery_no'].name,
'product_id': cls.company_data['product_delivery_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_delivery_no'].uom_id.id,
'price_unit': cls.company_data['product_delivery_no'].list_price,
'order_id': cls.sale_order.id,
'tax_id': False,
})
# Context
cls.context = {
'active_model': 'sale.order',
'active_ids': [cls.sale_order.id],
'active_id': cls.sale_order.id,
'default_journal_id': cls.company_data['default_journal_sale'].id,
}
def _check_order_search(self, orders, domain, expected_result):
domain += [('id', 'in', orders.ids)]
result = self.env['sale.order'].search(domain)
self.assertEqual(result, expected_result, "Unexpected result on search orders")
def test_search_invoice_ids(self):
"""Test searching on computed fields invoice_ids"""
# Make qty zero to have a line without invoices
self.sol_prod_order.product_uom_qty = 0
self.sale_order.action_confirm()
# Tests before creating an invoice
self._check_order_search(self.sale_order, [('invoice_ids', '=', False)], self.sale_order)
self._check_order_search(self.sale_order, [('invoice_ids', '!=', False)], self.env['sale.order'])
# Create invoice
moves = self.sale_order._create_invoices()
# Tests after creating the invoice
self._check_order_search(self.sale_order, [('invoice_ids', 'in', moves.ids)], self.sale_order)
self._check_order_search(self.sale_order, [('invoice_ids', '=', False)], self.env['sale.order'])
self._check_order_search(self.sale_order, [('invoice_ids', '!=', False)], self.sale_order)
def test_downpayment(self):
""" Test invoice with a way of downpayment and check downpayment's SO line is created
and also check a total amount of invoice is equal to a respective sale order's total amount
"""
# Confirm the SO
self.sale_order.action_confirm()
self._check_order_search(self.sale_order, [('invoice_ids', '=', False)], self.sale_order)
# Let's do an invoice for a deposit of 100
downpayment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'fixed',
'fixed_amount': 50,
'deposit_account_id': self.company_data['default_account_revenue'].id
})
downpayment.create_invoices()
downpayment2 = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'fixed',
'fixed_amount': 50,
'deposit_account_id': self.company_data['default_account_revenue'].id
})
downpayment2.create_invoices()
self._check_order_search(self.sale_order, [('invoice_ids', '=', False)], self.env['sale.order'])
self.assertEqual(len(self.sale_order.invoice_ids), 2, 'Invoice should be created for the SO')
downpayment_line = self.sale_order.order_line.filtered(lambda l: l.is_downpayment)
self.assertEqual(len(downpayment_line), 2, 'SO line downpayment should be created on SO')
# Update delivered quantity of SO lines
self.sol_serv_deliver.write({'qty_delivered': 4.0})
self.sol_prod_deliver.write({'qty_delivered': 2.0})
# Let's do an invoice with refunds
payment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'deposit_account_id': self.company_data['default_account_revenue'].id
})
payment.create_invoices()
self.assertEqual(len(self.sale_order.invoice_ids), 3, 'Invoice should be created for the SO')
invoice = max(self.sale_order.invoice_ids)
self.assertEqual(len(invoice.invoice_line_ids.filtered(lambda l: not (l.display_type == 'line_section' and l.name == "Down Payments"))), len(self.sale_order.order_line), 'All lines should be invoiced')
self.assertEqual(len(invoice.invoice_line_ids.filtered(lambda l: l.display_type == 'line_section' and l.name == "Down Payments")), 1, 'A single section for downpayments should be present')
self.assertEqual(invoice.amount_total, self.sale_order.amount_total - sum(downpayment_line.mapped('price_unit')), 'Downpayment should be applied')
def test_downpayment_line_remains_on_SO(self):
""" Test downpayment's SO line is created and remains unchanged even if everything is invoiced
"""
# Create the SO with one line
sale_order = self.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
})
sale_order_line = self.env['sale.order.line'].with_context(tracking_disable=True).create({
'name': self.company_data['product_order_no'].name,
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': 5,
'product_uom': self.company_data['product_order_no'].uom_id.id,
'price_unit': self.company_data['product_order_no'].list_price,
'order_id': sale_order.id,
'tax_id': False,
})
# Confirm the SO
sale_order.action_confirm()
# Update delivered quantity of SO line
sale_order_line.write({'qty_delivered': 5.0})
context = {
'active_model': 'sale.order',
'active_ids': [sale_order.id],
'active_id': sale_order.id,
'default_journal_id': self.company_data['default_journal_sale'].id,
}
# Let's do an invoice for a down payment of 50
downpayment = self.env['sale.advance.payment.inv'].with_context(context).create({
'advance_payment_method': 'fixed',
'fixed_amount': 50,
'deposit_account_id': self.company_data['default_account_revenue'].id
})
downpayment.create_invoices()
# Let's do the invoice
payment = self.env['sale.advance.payment.inv'].with_context(context).create({
'deposit_account_id': self.company_data['default_account_revenue'].id
})
payment.create_invoices()
# Confirm all invoices
for invoice in sale_order.invoice_ids:
invoice.action_post()
downpayment_line = sale_order.order_line.filtered(lambda l: l.is_downpayment)
self.assertEqual(downpayment_line[0].price_unit, 50, 'The down payment unit price should not change on SO')
def test_downpayment_percentage_tax_icl(self):
""" Test invoice with a percentage downpayment and an included tax
Check the total amount of invoice is correct and equal to a respective sale order's total amount
"""
# Confirm the SO
self.sale_order.action_confirm()
tax_downpayment = self.company_data['default_tax_sale'].copy({'price_include': True})
# Let's do an invoice for a deposit of 100
product_id = self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')
product_id = self.env['product.product'].browse(int(product_id)).exists()
product_id.taxes_id = tax_downpayment.ids
payment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'percentage',
'amount': 50,
'deposit_account_id': self.company_data['default_account_revenue'].id,
})
payment.create_invoices()
self.assertEqual(len(self.sale_order.invoice_ids), 1, 'Invoice should be created for the SO')
downpayment_line = self.sale_order.order_line.filtered(lambda l: l.is_downpayment)
self.assertEqual(len(downpayment_line), 1, 'SO line downpayment should be created on SO')
self.assertEqual(downpayment_line.price_unit, self.sale_order.amount_total/2, 'downpayment should have the correct amount')
invoice = self.sale_order.invoice_ids[0]
downpayment_aml = invoice.line_ids.filtered(lambda l: not (l.display_type == 'line_section' and l.name == "Down Payments"))[0]
self.assertEqual(downpayment_aml.price_total, self.sale_order.amount_total/2, 'downpayment should have the correct amount')
self.assertEqual(downpayment_aml.price_unit, self.sale_order.amount_total/2, 'downpayment should have the correct amount')
invoice.action_post()
self.assertEqual(downpayment_line.price_unit, self.sale_order.amount_total/2, 'downpayment should have the correct amount')
def test_invoice_with_discount(self):
""" Test invoice with a discount and check discount applied on both SO lines and an invoice lines """
# Update discount and delivered quantity on SO lines
self.sol_prod_order.write({'discount': 20.0})
self.sol_serv_deliver.write({'discount': 20.0, 'qty_delivered': 4.0})
self.sol_serv_order.write({'discount': -10.0})
self.sol_prod_deliver.write({'qty_delivered': 2.0})
for line in self.sale_order.order_line.filtered(lambda l: l.discount):
product_price = line.price_unit * line.product_uom_qty
self.assertEqual(line.discount, (product_price - line.price_subtotal) / product_price * 100, 'Discount should be applied on order line')
# lines are in draft
for line in self.sale_order.order_line:
self.assertTrue(float_is_zero(line.untaxed_amount_to_invoice, precision_digits=2), "The amount to invoice should be zero, as the line is in draf state")
self.assertTrue(float_is_zero(line.untaxed_amount_invoiced, precision_digits=2), "The invoiced amount should be zero, as the line is in draft state")
self.sale_order.action_confirm()
for line in self.sale_order.order_line:
self.assertTrue(float_is_zero(line.untaxed_amount_invoiced, precision_digits=2), "The invoiced amount should be zero, as the line is in draft state")
self.assertEqual(self.sol_serv_order.untaxed_amount_to_invoice, 297, "The untaxed amount to invoice is wrong")
self.assertEqual(self.sol_serv_deliver.untaxed_amount_to_invoice, self.sol_serv_deliver.qty_delivered * self.sol_serv_deliver.price_reduce, "The untaxed amount to invoice should be qty deli * price reduce, so 4 * (180 - 36)")
# 'untaxed_amount_to_invoice' is invalid when 'sale_stock' is installed.
# self.assertEqual(self.sol_prod_deliver.untaxed_amount_to_invoice, 140, "The untaxed amount to invoice should be qty deli * price reduce, so 4 * (180 - 36)")
# Let's do an invoice with invoiceable lines
payment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'delivered'
})
self._check_order_search(self.sale_order, [('invoice_ids', '=', False)], self.sale_order)
payment.create_invoices()
self._check_order_search(self.sale_order, [('invoice_ids', '=', False)], self.env['sale.order'])
invoice = self.sale_order.invoice_ids[0]
invoice.action_post()
# Check discount appeared on both SO lines and invoice lines
for line, inv_line in zip(self.sale_order.order_line, invoice.invoice_line_ids):
self.assertEqual(line.discount, inv_line.discount, 'Discount on lines of order and invoice should be same')
def test_invoice(self):
""" Test create and invoice from the SO, and check qty invoice/to invoice, and the related amounts """
# lines are in draft
for line in self.sale_order.order_line:
self.assertTrue(float_is_zero(line.untaxed_amount_to_invoice, precision_digits=2), "The amount to invoice should be zero, as the line is in draf state")
self.assertTrue(float_is_zero(line.untaxed_amount_invoiced, precision_digits=2), "The invoiced amount should be zero, as the line is in draft state")
# Confirm the SO
self.sale_order.action_confirm()
# Check ordered quantity, quantity to invoice and invoiced quantity of SO lines
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, 'Quantity to invoice should be same as ordered quantity')
self.assertEqual(line.qty_invoiced, 0.0, 'Invoiced quantity should be zero as no any invoice created for SO')
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
else:
self.assertEqual(line.qty_to_invoice, line.product_uom_qty, 'Quantity to invoice should be same as ordered quantity')
self.assertEqual(line.qty_invoiced, 0.0, 'Invoiced quantity should be zero as no any invoice created for SO')
self.assertEqual(line.untaxed_amount_to_invoice, line.product_uom_qty * line.price_unit, "The amount to invoice should the total of the line, as the line is confirmed")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line is confirmed")
# Let's do an invoice with invoiceable lines
payment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'delivered'
})
payment.create_invoices()
invoice = self.sale_order.invoice_ids[0]
# Update quantity of an invoice lines
move_form = Form(invoice)
with move_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = 3.0
with move_form.invoice_line_ids.edit(1) as line_form:
line_form.quantity = 2.0
invoice = move_form.save()
# amount to invoice / invoiced should not have changed (amounts take only confirmed invoice into account)
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be zero")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as delivered lines are not delivered yet")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity (no confirmed invoice)")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as no invoice are validated for now")
else:
if line == self.sol_prod_order:
self.assertEqual(self.sol_prod_order.qty_to_invoice, 2.0, "Changing the quantity on draft invoice update the qty to invoice on SO lines")
self.assertEqual(self.sol_prod_order.qty_invoiced, 3.0, "Changing the quantity on draft invoice update the invoiced qty on SO lines")
else:
self.assertEqual(self.sol_serv_order.qty_to_invoice, 1.0, "Changing the quantity on draft invoice update the qty to invoice on SO lines")
self.assertEqual(self.sol_serv_order.qty_invoiced, 2.0, "Changing the quantity on draft invoice update the invoiced qty on SO lines")
self.assertEqual(line.untaxed_amount_to_invoice, line.product_uom_qty * line.price_unit, "The amount to invoice should the total of the line, as the line is confirmed (no confirmed invoice)")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as no invoice are validated for now")
invoice.action_post()
# Check quantity to invoice on SO lines
for line in self.sale_order.order_line:
if line.product_id.invoice_policy == 'delivery':
self.assertEqual(line.qty_to_invoice, 0.0, "Quantity to invoice should be same as ordered quantity")
self.assertEqual(line.qty_invoiced, 0.0, "Invoiced quantity should be zero as no any invoice created for SO")
self.assertEqual(line.untaxed_amount_to_invoice, 0.0, "The amount to invoice should be zero, as the line based on delivered quantity")
self.assertEqual(line.untaxed_amount_invoiced, 0.0, "The invoiced amount should be zero, as the line based on delivered quantity")
else:
if line == self.sol_prod_order:
self.assertEqual(line.qty_to_invoice, 2.0, "The ordered sale line are totally invoiced (qty to invoice is zero)")
self.assertEqual(line.qty_invoiced, 3.0, "The ordered (prod) sale line are totally invoiced (qty invoiced come from the invoice lines)")
else:
self.assertEqual(line.qty_to_invoice, 1.0, "The ordered sale line are totally invoiced (qty to invoice is zero)")
self.assertEqual(line.qty_invoiced, 2.0, "The ordered (serv) sale line are totally invoiced (qty invoiced = the invoice lines)")
self.assertEqual(line.untaxed_amount_to_invoice, line.price_unit * line.qty_to_invoice, "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products")
self.assertEqual(line.untaxed_amount_invoiced, line.price_unit * line.qty_invoiced, "Amount invoiced is now set as qty invoiced * unit price since no price change on invoice, for ordered products")
def test_multiple_sale_orders_on_same_invoice(self):
""" The model allows the association of multiple SO lines linked to the same invoice line.
Check that the operations behave well, if a custom module creates such a situation.
"""
self.sale_order.action_confirm()
payment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'delivered'
})
payment.create_invoices()
# create a second SO whose lines are linked to the same invoice lines
# this is a way to create a situation where sale_line_ids has multiple items
sale_order_data = self.sale_order.copy_data()[0]
sale_order_data['order_line'] = [
(0, 0, line.copy_data({
'invoice_lines': [(6, 0, line.invoice_lines.ids)],
})[0])
for line in self.sale_order.order_line
]
self.sale_order.create(sale_order_data)
# we should now have at least one move line linked to several order lines
invoice = self.sale_order.invoice_ids[0]
self.assertTrue(any(len(move_line.sale_line_ids) > 1
for move_line in invoice.line_ids))
# however these actions should not raise
invoice.action_post()
invoice.button_draft()
invoice.button_cancel()
def test_invoice_with_sections(self):
""" Test create and invoice with sections from the SO, and check qty invoice/to invoice, and the related amounts """
sale_order = self.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
})
SaleOrderLine = self.env['sale.order.line'].with_context(tracking_disable=True)
SaleOrderLine.create({
'name': 'Section',
'display_type': 'line_section',
'order_id': sale_order.id,
})
sol_prod_deliver = SaleOrderLine.create({
'name': self.company_data['product_order_no'].name,
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': 5,
'product_uom': self.company_data['product_order_no'].uom_id.id,
'price_unit': self.company_data['product_order_no'].list_price,
'order_id': sale_order.id,
'tax_id': False,
})
# Confirm the SO
sale_order.action_confirm()
sol_prod_deliver.write({'qty_delivered': 5.0})
# Context
self.context = {
'active_model': 'sale.order',
'active_ids': [sale_order.id],
'active_id': sale_order.id,
'default_journal_id': self.company_data['default_journal_sale'].id,
}
# Let's do an invoice with invoiceable lines
payment = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'delivered'
})
payment.create_invoices()
invoice = sale_order.invoice_ids[0]
self.assertEqual(invoice.line_ids[0].display_type, 'line_section')
def test_qty_invoiced(self):
"""Verify uom rounding is correctly considered during qty_invoiced compute"""
sale_order = self.env['sale.order'].with_context(tracking_disable=True).create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'pricelist_id': self.company_data['default_pricelist'].id,
})
SaleOrderLine = self.env['sale.order.line'].with_context(tracking_disable=True)
sol_prod_deliver = SaleOrderLine.create({
'name': self.company_data['product_order_no'].name,
'product_id': self.company_data['product_order_no'].id,
'product_uom_qty': 5,
'product_uom': self.company_data['product_order_no'].uom_id.id,
'price_unit': self.company_data['product_order_no'].list_price,
'order_id': sale_order.id,
'tax_id': False,
})
# Confirm the SO
sale_order.action_confirm()
sol_prod_deliver.write({'qty_delivered': 5.0})
# Context
self.context = {
'active_model': 'sale.order',
'active_ids': [sale_order.id],
'active_id': sale_order.id,
'default_journal_id': self.company_data['default_journal_sale'].id,
}
# Let's do an invoice with invoiceable lines
invoicing_wizard = self.env['sale.advance.payment.inv'].with_context(self.context).create({
'advance_payment_method': 'delivered'
})
invoicing_wizard.create_invoices()
self.assertEqual(sol_prod_deliver.qty_invoiced, 5.0)
# We would have to change the digits of the field to
# test a greater decimal precision.
quantity = 5.13
move_form = Form(sale_order.invoice_ids)
with move_form.invoice_line_ids.edit(0) as line_form:
line_form.quantity = quantity
move_form.save()
# Default uom rounding to 0.01
qty_invoiced_field = sol_prod_deliver._fields.get('qty_invoiced')
sol_prod_deliver.env.add_to_compute(qty_invoiced_field, sol_prod_deliver)
self.assertEqual(sol_prod_deliver.qty_invoiced, quantity)
# Rounding to 0.1, should be rounded with UP (ceil) rounding_method
# Not floor or half up rounding.
sol_prod_deliver.product_uom.rounding *= 10
sol_prod_deliver.product_uom.flush(['rounding'])
expected_qty = 5.2
qty_invoiced_field = sol_prod_deliver._fields.get('qty_invoiced')
sol_prod_deliver.env.add_to_compute(qty_invoiced_field, sol_prod_deliver)
self.assertEqual(sol_prod_deliver.qty_invoiced, expected_qty)
def test_invoice_analytic_account_default(self):
""" Tests whether, when an analytic account rule is set and the so has no analytic account,
the default analytic acount is correctly computed in the invoice.
"""
analytic_account_default = self.env['account.analytic.account'].create({'name': 'default'})
self.env['account.analytic.default'].create({
'analytic_id': analytic_account_default.id,
'product_id': self.product_a.id,
})
so_form = Form(self.env['sale.order'])
so_form.partner_id = self.partner_a
with so_form.order_line.new() as sol:
sol.product_id = self.product_a
sol.product_uom_qty = 1
so = so_form.save()
so.action_confirm()
so._force_lines_to_invoice_policy_order()
so_context = {
'active_model': 'sale.order',
'active_ids': [so.id],
'active_id': so.id,
'default_journal_id': self.company_data['default_journal_sale'].id,
}
down_payment = self.env['sale.advance.payment.inv'].with_context(so_context).create({})
down_payment.create_invoices()
aml = self.env['account.move.line'].search([('move_id', 'in', so.invoice_ids.ids)])[0]
self.assertRecordValues(aml, [{'analytic_account_id': analytic_account_default.id}])
def test_invoice_analytic_account_so_not_default(self):
""" Tests whether, when an analytic account rule is set and the so has an analytic account,
the default analytic acount doesn't replace the one from the so in the invoice.
"""
analytic_account_default = self.env['account.analytic.account'].create({'name': 'default'})
analytic_account_so = self.env['account.analytic.account'].create({'name': 'so'})
self.env['account.analytic.default'].create({
'analytic_id': analytic_account_default.id,
'product_id': self.product_a.id,
})
so_form = Form(self.env['sale.order'])
so_form.partner_id = self.partner_a
so_form.analytic_account_id = analytic_account_so
with so_form.order_line.new() as sol:
sol.product_id = self.product_a
sol.product_uom_qty = 1
so = so_form.save()
so.action_confirm()
so._force_lines_to_invoice_policy_order()
so_context = {
'active_model': 'sale.order',
'active_ids': [so.id],
'active_id': so.id,
'default_journal_id': self.company_data['default_journal_sale'].id,
}
down_payment = self.env['sale.advance.payment.inv'].with_context(so_context).create({})
down_payment.create_invoices()
aml = self.env['account.move.line'].search([('move_id', 'in', so.invoice_ids.ids)])[0]
self.assertRecordValues(aml, [{'analytic_account_id': analytic_account_so.id}])
def test_invoice_analytic_tag_so_not_default(self):
"""
Tests whether, when an analytic tag rule is set and
the so has an analytic tag different from default,
the default analytic tag doesn't get overriden in invoice.
"""
self.env.user.groups_id += self.env.ref('analytic.group_analytic_accounting')
self.env.user.groups_id += self.env.ref('analytic.group_analytic_tags')
analytic_account_default = self.env['account.analytic.account'].create({'name': 'default'})
analytic_tag_default = self.env['account.analytic.tag'].create({'name': 'default'})
analytic_tag_super = self.env['account.analytic.tag'].create({'name': 'Super Tag'})
self.env['account.analytic.default'].create({
'analytic_id': analytic_account_default.id,
'analytic_tag_ids': [(6, 0, analytic_tag_default.ids)],
'product_id': self.product_a.id,
})
so = self.env['sale.order'].create({'partner_id': self.partner_a.id})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': self.product_a.id
})
so.order_line.analytic_tag_ids = [(6, 0, analytic_tag_super.ids)]
so.action_confirm()
so.order_line.qty_delivered = 1
aml = so._create_invoices().invoice_line_ids
self.assertRecordValues(aml, [{'analytic_tag_ids': analytic_tag_super.ids}])
def test_invoice_analytic_tag_set_manually(self):
"""
Tests whether, when there is no analytic tag rule set,
the manually set analytic tag is passed from the so to the invoice.
"""
self.env.user.groups_id += self.env.ref('analytic.group_analytic_accounting')
self.env.user.groups_id += self.env.ref('analytic.group_analytic_tags')
analytic_tag_super = self.env['account.analytic.tag'].create({'name': 'Super Tag'})
so = self.env['sale.order'].create({'partner_id': self.partner_a.id})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': self.product_a.id
})
so.order_line.analytic_tag_ids = [(6, 0, analytic_tag_super.ids)]
so.action_confirm()
so.order_line.qty_delivered = 1
aml = so._create_invoices().invoice_line_ids
self.assertRecordValues(aml, [{'analytic_tag_ids': analytic_tag_super.ids}])
def test_invoice_analytic_tag_default_account_id(self):
"""
Test whether, when an analytic tag rule with the condition `account_id` set,
the default tag is correctly set during the conversion from so to invoice
"""
self.env.user.groups_id += self.env.ref('analytic.group_analytic_accounting')
self.env.user.groups_id += self.env.ref('analytic.group_analytic_tags')
analytic_account_default = self.env['account.analytic.account'].create({'name': 'default'})
analytic_tag_default = self.env['account.analytic.tag'].create({'name': 'Super Tag'})
self.env['account.analytic.default'].create({
'analytic_id': analytic_account_default.id,
'analytic_tag_ids': [(6, 0, analytic_tag_default.ids)],
'product_id': self.product_a.id,
'account_id': self.company_data['default_account_revenue'].id,
})
so = self.env['sale.order'].create({'partner_id': self.partner_a.id})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': self.product_a.id
})
self.assertFalse(so.order_line.analytic_tag_ids, "There should be no tag set.")
so.action_confirm()
so.order_line.qty_delivered = 1
aml = so._create_invoices().invoice_line_ids
self.assertRecordValues(aml, [{'analytic_tag_ids': analytic_tag_default.ids}])
def test_partial_invoicing_interaction_with_invoicing_switch_threshold(self):
""" Let's say you partially invoice a SO, let's call the resuling invoice 'A'. Now if you change the
'Invoicing Switch Threshold' such that the invoice date of 'A' is before the new threshold,
the SO should still take invoice 'A' into account.
"""
if not self.env['ir.module.module'].search([('name', '=', 'account_accountant'), ('state', '=', 'installed')]):
self.skipTest("This test requires the installation of the account_account module")
sale_order = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [
Command.create({
'product_id': self.company_data['product_delivery_no'].id,
'product_uom_qty': 20,
}),
],
})
line = sale_order.order_line[0]
sale_order.action_confirm()
line.qty_delivered = 10
invoice = sale_order._create_invoices()
invoice.action_post()
self.assertEqual(line.qty_invoiced, 10)
self.env['res.config.settings'].create({
'invoicing_switch_threshold': fields.Date.add(invoice.invoice_date, days=30),
}).execute()
invoice.invalidate_cache(fnames=['payment_state'])
self.assertEqual(line.qty_invoiced, 10)
line.qty_delivered = 15
self.assertEqual(line.qty_invoiced, 10)
| 52.669207 | 34,551 |
3,062 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug import urls
from odoo import api, models
class PaymentLinkWizard(models.TransientModel):
_inherit = 'payment.link.wizard'
_description = 'Generate Sales Payment Link'
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if res['res_id'] and res['res_model'] == 'sale.order':
record = self.env[res['res_model']].browse(res['res_id'])
res.update({
'description': record.name,
'amount': record.amount_total - sum(record.invoice_ids.filtered(lambda x: x.state != 'cancel').mapped('amount_total')),
'currency_id': record.currency_id.id,
'partner_id': record.partner_invoice_id.id,
'amount_max': record.amount_total
})
return res
def _get_payment_acquirer_available(self, company_id=None, partner_id=None, currency_id=None, sale_order_id=None):
""" Select and return the acquirers matching the criteria.
:param int company_id: The company to which acquirers must belong, as a `res.company` id
:param int partner_id: The partner making the payment, as a `res.partner` id
:param int currency_id: The payment currency if known beforehand, as a `res.currency` id
:param int sale_order_id: The sale order currency if known beforehand, as a `sale.order` id
:return: The compatible acquirers
:rtype: recordset of `payment.acquirer`
"""
return self.env['payment.acquirer'].sudo()._get_compatible_acquirers(
company_id=company_id or self.company_id.id,
partner_id=partner_id or self.partner_id.id,
currency_id=currency_id or self.currency_id.id,
sale_order_id=sale_order_id or self.res_id,
)
def _generate_link(self):
""" Override of payment to add the sale_order_id in the link. """
for payment_link in self:
# The sale_order_id field only makes sense if the document is a sales order
if payment_link.res_model == 'sale.order':
related_document = self.env[payment_link.res_model].browse(payment_link.res_id)
base_url = related_document.get_base_url()
payment_link.link = f'{base_url}/payment/pay' \
f'?reference={urls.url_quote(payment_link.description)}' \
f'&amount={payment_link.amount}' \
f'&sale_order_id={payment_link.res_id}' \
f'{"&acquirer_id=" + str(payment_link.payment_acquirer_selection) if payment_link.payment_acquirer_selection != "all" else "" }' \
f'&access_token={payment_link.access_token}'
# Order-related fields are retrieved in the controller
else:
super(PaymentLinkWizard, payment_link)._generate_link()
| 51.898305 | 3,062 |
9,810 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class SaleAdvancePaymentInv(models.TransientModel):
_name = "sale.advance.payment.inv"
_description = "Sales Advance Payment Invoice"
@api.model
def _count(self):
return len(self._context.get('active_ids', []))
@api.model
def _default_product_id(self):
product_id = self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')
return self.env['product.product'].browse(int(product_id)).exists()
@api.model
def _default_deposit_account_id(self):
return self._default_product_id()._get_product_accounts()['income']
@api.model
def _default_deposit_taxes_id(self):
return self._default_product_id().taxes_id
@api.model
def _default_has_down_payment(self):
if self._context.get('active_model') == 'sale.order' and self._context.get('active_id', False):
sale_order = self.env['sale.order'].browse(self._context.get('active_id'))
return sale_order.order_line.filtered(
lambda sale_order_line: sale_order_line.is_downpayment
)
return False
@api.model
def _default_currency_id(self):
if self._context.get('active_model') == 'sale.order' and self._context.get('active_id', False):
sale_order = self.env['sale.order'].browse(self._context.get('active_id'))
return sale_order.currency_id
advance_payment_method = fields.Selection([
('delivered', 'Regular invoice'),
('percentage', 'Down payment (percentage)'),
('fixed', 'Down payment (fixed amount)')
], string='Create Invoice', default='delivered', required=True,
help="A standard invoice is issued with all the order lines ready for invoicing, \
according to their invoicing policy (based on ordered or delivered quantity).")
deduct_down_payments = fields.Boolean('Deduct down payments', default=True)
has_down_payments = fields.Boolean('Has down payments', default=_default_has_down_payment, readonly=True)
product_id = fields.Many2one('product.product', string='Down Payment Product', domain=[('type', '=', 'service')],
default=_default_product_id)
count = fields.Integer(default=_count, string='Order Count')
amount = fields.Float('Down Payment Amount', digits='Account', help="The percentage of amount to be invoiced in advance, taxes excluded.")
currency_id = fields.Many2one('res.currency', string='Currency', default=_default_currency_id)
fixed_amount = fields.Monetary('Down Payment Amount (Fixed)', help="The fixed amount to be invoiced in advance, taxes excluded.")
deposit_account_id = fields.Many2one("account.account", string="Income Account", domain=[('deprecated', '=', False)],
help="Account used for deposits", default=_default_deposit_account_id)
deposit_taxes_id = fields.Many2many("account.tax", string="Customer Taxes", help="Taxes used for deposits", default=_default_deposit_taxes_id)
@api.onchange('advance_payment_method')
def onchange_advance_payment_method(self):
if self.advance_payment_method == 'percentage':
amount = self.default_get(['amount']).get('amount')
return {'value': {'amount': amount}}
return {}
def _prepare_invoice_values(self, order, name, amount, so_line):
invoice_vals = {
'ref': order.client_order_ref,
'move_type': 'out_invoice',
'invoice_origin': order.name,
'invoice_user_id': order.user_id.id,
'narration': order.note,
'partner_id': order.partner_invoice_id.id,
'fiscal_position_id': (order.fiscal_position_id or order.fiscal_position_id.get_fiscal_position(order.partner_id.id)).id,
'partner_shipping_id': order.partner_shipping_id.id,
'currency_id': order.pricelist_id.currency_id.id,
'payment_reference': order.reference,
'invoice_payment_term_id': order.payment_term_id.id,
'partner_bank_id': order.company_id.partner_id.bank_ids[:1].id,
'team_id': order.team_id.id,
'campaign_id': order.campaign_id.id,
'medium_id': order.medium_id.id,
'source_id': order.source_id.id,
'invoice_line_ids': [(0, 0, {
'name': name,
'price_unit': amount,
'quantity': 1.0,
'product_id': self.product_id.id,
'product_uom_id': so_line.product_uom.id,
'tax_ids': [(6, 0, so_line.tax_id.ids)],
'sale_line_ids': [(6, 0, [so_line.id])],
'analytic_tag_ids': [(6, 0, so_line.analytic_tag_ids.ids)],
'analytic_account_id': order.analytic_account_id.id if not so_line.display_type and order.analytic_account_id.id else False,
})],
}
return invoice_vals
def _get_advance_details(self, order):
context = {'lang': order.partner_id.lang}
if self.advance_payment_method == 'percentage':
advance_product_taxes = self.product_id.taxes_id.filtered(lambda tax: tax.company_id == order.company_id)
if all(order.fiscal_position_id.map_tax(advance_product_taxes).mapped('price_include')):
amount = order.amount_total * self.amount / 100
else:
amount = order.amount_untaxed * self.amount / 100
name = _("Down payment of %s%%") % (self.amount)
else:
amount = self.fixed_amount
name = _('Down Payment')
del context
return amount, name
def _create_invoice(self, order, so_line, amount):
if (self.advance_payment_method == 'percentage' and self.amount <= 0.00) or (self.advance_payment_method == 'fixed' and self.fixed_amount <= 0.00):
raise UserError(_('The value of the down payment amount must be positive.'))
amount, name = self._get_advance_details(order)
invoice_vals = self._prepare_invoice_values(order, name, amount, so_line)
if order.fiscal_position_id:
invoice_vals['fiscal_position_id'] = order.fiscal_position_id.id
invoice = self.env['account.move'].with_company(order.company_id)\
.sudo().create(invoice_vals).with_user(self.env.uid)
invoice.message_post_with_view('mail.message_origin_link',
values={'self': invoice, 'origin': order},
subtype_id=self.env.ref('mail.mt_note').id)
return invoice
def _prepare_so_line(self, order, analytic_tag_ids, tax_ids, amount):
context = {'lang': order.partner_id.lang}
so_values = {
'name': _('Down Payment: %s') % (time.strftime('%m %Y'),),
'price_unit': amount,
'product_uom_qty': 0.0,
'order_id': order.id,
'discount': 0.0,
'product_uom': self.product_id.uom_id.id,
'product_id': self.product_id.id,
'analytic_tag_ids': analytic_tag_ids,
'tax_id': [(6, 0, tax_ids)],
'is_downpayment': True,
'sequence': order.order_line and order.order_line[-1].sequence + 1 or 10,
}
del context
return so_values
def create_invoices(self):
sale_orders = self.env['sale.order'].browse(self._context.get('active_ids', []))
if self.advance_payment_method == 'delivered':
sale_orders._create_invoices(final=self.deduct_down_payments)
else:
# Create deposit product if necessary
if not self.product_id:
vals = self._prepare_deposit_product()
self.product_id = self.env['product.product'].create(vals)
self.env['ir.config_parameter'].sudo().set_param('sale.default_deposit_product_id', self.product_id.id)
sale_line_obj = self.env['sale.order.line']
for order in sale_orders:
amount, name = self._get_advance_details(order)
if self.product_id.invoice_policy != 'order':
raise UserError(_('The product used to invoice a down payment should have an invoice policy set to "Ordered quantities". Please update your deposit product to be able to create a deposit invoice.'))
if self.product_id.type != 'service':
raise UserError(_("The product used to invoice a down payment should be of type 'Service'. Please use another product or update this product."))
taxes = self.product_id.taxes_id.filtered(lambda r: not order.company_id or r.company_id == order.company_id)
tax_ids = order.fiscal_position_id.map_tax(taxes).ids
analytic_tag_ids = []
for line in order.order_line:
analytic_tag_ids = [(4, analytic_tag.id, None) for analytic_tag in line.analytic_tag_ids]
so_line_values = self._prepare_so_line(order, analytic_tag_ids, tax_ids, amount)
so_line = sale_line_obj.create(so_line_values)
self._create_invoice(order, so_line, amount)
if self._context.get('open_invoices', False):
return sale_orders.action_view_invoice()
return {'type': 'ir.actions.act_window_close'}
def _prepare_deposit_product(self):
return {
'name': _('Down payment'),
'type': 'service',
'invoice_policy': 'order',
'property_account_income_id': self.deposit_account_id.id,
'taxes_id': [(6, 0, self.deposit_taxes_id.ids)],
'company_id': False,
}
| 49.05 | 9,810 |
623 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailComposeMessage(models.TransientModel):
_inherit = 'mail.compose.message'
def _action_send_mail(self, auto_commit=False):
if self.model == 'sale.order':
self = self.with_context(mailing_document_based=True)
if self.env.context.get('mark_so_as_sent'):
self = self.with_context(mail_notify_author=self.env.user.partner_id in self.partner_ids)
return super(MailComposeMessage, self)._action_send_mail(auto_commit=auto_commit)
| 41.533333 | 623 |
545 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class AccountPaymentRegister(models.TransientModel):
_inherit = 'account.payment.register'
def _create_payment_vals_from_wizard(self):
vals = super()._create_payment_vals_from_wizard()
# Make sure the account move linked to generated payment
# belongs to the expected sales team
# team_id field on account.payment comes from the `_inherits` on account.move model
vals.update({'team_id': self.line_ids.move_id[0].team_id.id})
return vals
| 36.333333 | 545 |
807 |
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 SaleOrderCancel(models.TransientModel):
_name = 'sale.order.cancel'
_description = "Sales Order Cancel"
order_id = fields.Many2one('sale.order', string='Sale Order', required=True, ondelete='cascade')
display_invoice_alert = fields.Boolean('Invoice Alert', compute='_compute_display_invoice_alert')
@api.depends('order_id')
def _compute_display_invoice_alert(self):
for wizard in self:
wizard.display_invoice_alert = bool(wizard.order_id.invoice_ids.filtered(lambda inv: inv.state == 'draft'))
def action_cancel(self):
return self.order_id.with_context({'disable_cancel_warning': True}).action_cancel()
| 40.35 | 807 |
1,798 |
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 PaymentWizard(models.TransientModel):
""" Override for the sale quotation onboarding panel. """
_inherit = 'payment.acquirer.onboarding.wizard'
_name = 'sale.payment.acquirer.onboarding.wizard'
_description = 'Sale Payment acquire onboarding wizard'
def _get_default_payment_method(self):
return self.env.company.sale_onboarding_payment_method or 'digital_signature'
payment_method = fields.Selection(selection_add=[
('digital_signature', "Electronic signature"),
('stripe', "Credit & Debit card (via Stripe)"),
('paypal', "PayPal"),
('other', "Other payment acquirer"),
('manual', "Custom payment instructions"),
], default=_get_default_payment_method)
#
def _set_payment_acquirer_onboarding_step_done(self):
""" Override. """
self.env.company.sudo().set_onboarding_step_done('sale_onboarding_order_confirmation_state')
def add_payment_methods(self, *args, **kwargs):
self.env.company.sale_onboarding_payment_method = self.payment_method
if self.payment_method == 'digital_signature':
self.env.company.portal_confirmation_sign = True
if self.payment_method in ('paypal', 'stripe', 'other', 'manual'):
self.env.company.portal_confirmation_pay = True
return super(PaymentWizard, self).add_payment_methods(*args, **kwargs)
def _start_stripe_onboarding(self):
""" Override of payment to set the sale menu as start menu of the payment onboarding. """
menu_id = self.env.ref('sale.sale_menu_root').id
return self.env.company._run_payment_onboarding_step(menu_id)
| 42.809524 | 1,798 |
6,702 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class CrmTeam(models.Model):
_inherit = 'crm.team'
use_quotations = fields.Boolean(string='Quotations', help="Check this box if you send quotations to your customers rather than confirming orders straight away.")
invoiced = fields.Float(
compute='_compute_invoiced',
string='Invoiced This Month', readonly=True,
help="Invoice revenue for the current month. This is the amount the sales "
"channel has invoiced this month. It is used to compute the progression ratio "
"of the current and target revenue on the kanban view.")
invoiced_target = fields.Float(
string='Invoicing Target',
help="Revenue target for the current month (untaxed total of confirmed invoices).")
quotations_count = fields.Integer(
compute='_compute_quotations_to_invoice',
string='Number of quotations to invoice', readonly=True)
quotations_amount = fields.Float(
compute='_compute_quotations_to_invoice',
string='Amount of quotations to invoice', readonly=True)
sales_to_invoice_count = fields.Integer(
compute='_compute_sales_to_invoice',
string='Number of sales to invoice', readonly=True)
sale_order_count = fields.Integer(compute='_compute_sale_order_count', string='# Sale Orders')
def _compute_quotations_to_invoice(self):
query = self.env['sale.order']._where_calc([
('team_id', 'in', self.ids),
('state', 'in', ['draft', 'sent']),
])
self.env['sale.order']._apply_ir_rules(query, 'read')
_, where_clause, where_clause_args = query.get_sql()
select_query = """
SELECT team_id, count(*), sum(amount_total /
CASE COALESCE(currency_rate, 0)
WHEN 0 THEN 1.0
ELSE currency_rate
END
) as amount_total
FROM sale_order
WHERE %s
GROUP BY team_id
""" % where_clause
self.env.cr.execute(select_query, where_clause_args)
quotation_data = self.env.cr.dictfetchall()
teams = self.browse()
for datum in quotation_data:
team = self.browse(datum['team_id'])
team.quotations_amount = datum['amount_total']
team.quotations_count = datum['count']
teams |= team
remaining = (self - teams)
remaining.quotations_amount = 0
remaining.quotations_count = 0
def _compute_sales_to_invoice(self):
sale_order_data = self.env['sale.order'].read_group([
('team_id', 'in', self.ids),
('invoice_status','=','to invoice'),
], ['team_id'], ['team_id'])
data_map = {datum['team_id'][0]: datum['team_id_count'] for datum in sale_order_data}
for team in self:
team.sales_to_invoice_count = data_map.get(team.id,0.0)
def _compute_invoiced(self):
if not self:
return
query = '''
SELECT
move.team_id AS team_id,
SUM(move.amount_untaxed_signed) AS amount_untaxed_signed
FROM account_move move
WHERE move.move_type IN ('out_invoice', 'out_refund', 'out_receipt')
AND move.payment_state IN ('in_payment', 'paid', 'reversed')
AND move.state = 'posted'
AND move.team_id IN %s
AND move.date BETWEEN %s AND %s
GROUP BY move.team_id
'''
today = fields.Date.today()
params = [tuple(self.ids), fields.Date.to_string(today.replace(day=1)), fields.Date.to_string(today)]
self._cr.execute(query, params)
data_map = dict((v[0], v[1]) for v in self._cr.fetchall())
for team in self:
team.invoiced = data_map.get(team.id, 0.0)
def _compute_sale_order_count(self):
data_map = {}
if self.ids:
sale_order_data = self.env['sale.order'].read_group([
('team_id', 'in', self.ids),
('state', '!=', 'cancel'),
], ['team_id'], ['team_id'])
data_map = {datum['team_id'][0]: datum['team_id_count'] for datum in sale_order_data}
for team in self:
team.sale_order_count = data_map.get(team.id, 0)
def _graph_get_model(self):
if self._context.get('in_sales_app'):
return 'sale.report'
return super(CrmTeam,self)._graph_get_model()
def _graph_date_column(self):
if self._context.get('in_sales_app'):
return 'date'
return super(CrmTeam,self)._graph_date_column()
def _graph_y_query(self):
if self._context.get('in_sales_app'):
return 'SUM(price_subtotal)'
return super(CrmTeam,self)._graph_y_query()
def _extra_sql_conditions(self):
if self._context.get('in_sales_app'):
return "AND state in ('sale', 'done', 'pos_done')"
return super(CrmTeam,self)._extra_sql_conditions()
def _graph_title_and_key(self):
if self._context.get('in_sales_app'):
return ['', _('Sales: Untaxed Total')] # no more title
return super(CrmTeam, self)._graph_title_and_key()
def _compute_dashboard_button_name(self):
super(CrmTeam,self)._compute_dashboard_button_name()
if self._context.get('in_sales_app'):
self.update({'dashboard_button_name': _("Sales Analysis")})
def action_primary_channel_button(self):
if self._context.get('in_sales_app'):
return self.env["ir.actions.actions"]._for_xml_id("sale.action_order_report_so_salesteam")
return super(CrmTeam, self).action_primary_channel_button()
def update_invoiced_target(self, value):
return self.write({'invoiced_target': round(float(value or 0))})
@api.ondelete(at_uninstall=False)
def _unlink_except_used_for_sales(self):
""" If more than 5 active SOs, we consider this team to be actively used.
5 is some random guess based on "user testing", aka more than testing
CRM feature and less than use it in real life use cases. """
SO_COUNT_TRIGGER = 5
for team in self:
if team.sale_order_count >= SO_COUNT_TRIGGER:
raise UserError(
_('Team %(team_name)s has %(sale_order_count)s active sale orders. Consider canceling them or archiving the team instead.',
team_name=team.name,
sale_order_count=team.sale_order_count
))
| 42.961538 | 6,702 |
5,784 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class AccountMove(models.Model):
_name = 'account.move'
_inherit = ['account.move', 'utm.mixin']
@api.model
def _get_invoice_default_sale_team(self):
return self.env['crm.team']._get_default_team_id()
team_id = fields.Many2one(
'crm.team', string='Sales Team', default=_get_invoice_default_sale_team,
ondelete="set null", tracking=True,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
partner_shipping_id = fields.Many2one(
'res.partner',
string='Delivery Address',
readonly=True,
states={'draft': [('readonly', False)]},
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
help="Delivery address for current invoice.")
@api.onchange('partner_shipping_id', 'company_id')
def _onchange_partner_shipping_id(self):
"""
Trigger the change of fiscal position when the shipping address is modified.
"""
delivery_partner_id = self._get_invoice_delivery_partner_id()
fiscal_position = self.env['account.fiscal.position'].with_company(self.company_id).get_fiscal_position(
self.partner_id.id, delivery_id=delivery_partner_id)
if fiscal_position:
self.fiscal_position_id = fiscal_position
def unlink(self):
downpayment_lines = self.mapped('line_ids.sale_line_ids').filtered(lambda line: line.is_downpayment and line.invoice_lines <= self.mapped('line_ids'))
res = super(AccountMove, self).unlink()
if downpayment_lines:
downpayment_lines.unlink()
return res
@api.onchange('partner_id')
def _onchange_partner_id(self):
# OVERRIDE
# Recompute 'partner_shipping_id' based on 'partner_id'.
addr = self.partner_id.address_get(['delivery'])
self.partner_shipping_id = addr and addr.get('delivery')
res = super(AccountMove, self)._onchange_partner_id()
return res
@api.onchange('invoice_user_id')
def onchange_user_id(self):
if self.invoice_user_id and self.invoice_user_id.sale_team_id:
self.team_id = self.env['crm.team']._get_default_team_id(user_id=self.invoice_user_id.id, domain=[('company_id', '=', self.company_id.id)])
def _reverse_moves(self, default_values_list=None, cancel=False):
# OVERRIDE
if not default_values_list:
default_values_list = [{} for move in self]
for move, default_values in zip(self, default_values_list):
default_values.update({
'campaign_id': move.campaign_id.id,
'medium_id': move.medium_id.id,
'source_id': move.source_id.id,
})
return super()._reverse_moves(default_values_list=default_values_list, cancel=cancel)
def action_post(self):
#inherit of the function from account.move to validate a new tax and the priceunit of a downpayment
res = super(AccountMove, self).action_post()
line_ids = self.mapped('line_ids').filtered(lambda line: any(line.sale_line_ids.mapped('is_downpayment')))
for line in line_ids:
try:
line.sale_line_ids.tax_id = line.tax_ids
line.sale_line_ids.price_unit = line.price_unit
except UserError:
# a UserError here means the SO was locked, which prevents changing the taxes
# just ignore the error - this is a nice to have feature and should not be blocking
pass
return res
def _post(self, soft=True):
# OVERRIDE
# Auto-reconcile the invoice with payments coming from transactions.
# It's useful when you have a "paid" sale order (using a payment transaction) and you invoice it later.
posted = super()._post(soft)
for invoice in posted.filtered(lambda move: move.is_invoice()):
payments = invoice.mapped('transaction_ids.payment_id').filtered(lambda x: x.state == 'posted')
move_lines = payments.line_ids.filtered(lambda line: line.account_internal_type in ('receivable', 'payable') and not line.reconciled)
for line in move_lines:
invoice.js_assign_outstanding_line(line.id)
return posted
def action_invoice_paid(self):
# OVERRIDE
res = super(AccountMove, self).action_invoice_paid()
todo = set()
for invoice in self.filtered(lambda move: move.is_invoice()):
for line in invoice.invoice_line_ids:
for sale_line in line.sale_line_ids:
todo.add((sale_line.order_id, invoice.name))
for (order, name) in todo:
order.message_post(body=_("Invoice %s paid", name))
return res
def _get_invoice_delivery_partner_id(self):
# OVERRIDE
self.ensure_one()
return self.partner_shipping_id.id or super(AccountMove, self)._get_invoice_delivery_partner_id()
def _action_invoice_ready_to_be_sent(self):
# OVERRIDE
# Make sure the send invoice CRON is called when an invoice becomes ready to be sent by mail.
res = super()._action_invoice_ready_to_be_sent()
send_invoice_cron = self.env.ref('sale.send_invoice_cron', raise_if_not_found=False)
if send_invoice_cron:
send_invoice_cron._trigger()
return res
def _is_downpayment(self):
# OVERRIDE
self.ensure_one()
return self.line_ids.sale_line_ids and all(sale_line.is_downpayment for sale_line in self.line_ids.sale_line_ids) or False
| 43.818182 | 5,784 |
9,867 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import datetime
from dateutil import relativedelta
from odoo import api, fields, models, _, SUPERUSER_ID
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
sale_order_ids = fields.Many2many('sale.order', 'sale_order_transaction_rel', 'transaction_id', 'sale_order_id',
string='Sales Orders', copy=False, readonly=True)
sale_order_ids_nbr = fields.Integer(compute='_compute_sale_order_ids_nbr', string='# of Sales Orders')
def _compute_sale_order_reference(self, order):
self.ensure_one()
if self.acquirer_id.so_reference_type == 'so_name':
return order.name
else:
# self.acquirer_id.so_reference_type == 'partner'
identification_number = order.partner_id.id
return '%s/%s' % ('CUST', str(identification_number % 97).rjust(2, '0'))
@api.depends('sale_order_ids')
def _compute_sale_order_ids_nbr(self):
for trans in self:
trans.sale_order_ids_nbr = len(trans.sale_order_ids)
def _set_pending(self, state_message=None):
""" Override of payment to send the quotations automatically. """
super(PaymentTransaction, self)._set_pending(state_message=state_message)
for record in self:
sales_orders = record.sale_order_ids.filtered(lambda so: so.state in ['draft', 'sent'])
sales_orders.filtered(lambda so: so.state == 'draft').with_context(tracking_disable=True).write({'state': 'sent'})
if record.acquirer_id.provider == 'transfer':
for so in record.sale_order_ids:
so.reference = record._compute_sale_order_reference(so)
# send order confirmation mail
sales_orders._send_order_confirmation_mail()
def _check_amount_and_confirm_order(self):
self.ensure_one()
for order in self.sale_order_ids.filtered(lambda so: so.state in ('draft', 'sent')):
if order.currency_id.compare_amounts(self.amount, order.amount_total) == 0:
order.with_context(send_email=True).action_confirm()
else:
_logger.warning(
'<%s> transaction AMOUNT MISMATCH for order %s (ID %s): expected %r, got %r',
self.acquirer_id.provider,order.name, order.id,
order.amount_total, self.amount,
)
order.message_post(
subject=_("Amount Mismatch (%s)", self.acquirer_id.provider),
body=_("The order was not confirmed despite response from the acquirer (%s): order total is %r but acquirer replied with %r.") % (
self.acquirer_id.provider,
order.amount_total,
self.amount,
)
)
def _set_authorized(self, state_message=None):
""" Override of payment to confirm the quotations automatically. """
super()._set_authorized(state_message=state_message)
sales_orders = self.mapped('sale_order_ids').filtered(lambda so: so.state in ('draft', 'sent'))
for tx in self:
tx._check_amount_and_confirm_order()
# send order confirmation mail
sales_orders._send_order_confirmation_mail()
def _log_message_on_linked_documents(self, message):
""" Override of payment to log a message on the sales orders linked to the transaction.
Note: self.ensure_one()
:param str message: The message to be logged
:return: None
"""
super()._log_message_on_linked_documents(message)
for order in self.sale_order_ids:
order.message_post(body=message)
def _reconcile_after_done(self):
""" Override of payment to automatically confirm quotations and generate invoices. """
draft_orders = self.sale_order_ids.filtered(lambda so: so.state in ('draft', 'sent'))
for tx in self:
tx._check_amount_and_confirm_order()
confirmed_sales_orders = draft_orders.filtered(lambda so: so.state in ('sale', 'done'))
# send order confirmation mail
confirmed_sales_orders._send_order_confirmation_mail()
# invoice the sale orders if needed
self._invoice_sale_orders()
res = super()._reconcile_after_done()
if self.env['ir.config_parameter'].sudo().get_param('sale.automatic_invoice') and any(so.state in ('sale', 'done') for so in self.sale_order_ids):
self.filtered(lambda t: t.sale_order_ids.filtered(lambda so: so.state in ('sale', 'done')))._send_invoice()
return res
def _send_invoice(self):
default_template = self.env['ir.config_parameter'].sudo().get_param('sale.default_invoice_email_template')
if not default_template:
return
template_id = int(default_template)
template = self.env['mail.template'].browse(template_id)
for trans in self:
trans = trans.with_company(trans.acquirer_id.company_id).with_context(
company_id=trans.acquirer_id.company_id.id,
)
invoice_to_send = trans.invoice_ids.filtered(
lambda i: not i.is_move_sent and i.state == 'posted' and i._is_ready_to_be_sent()
)
invoice_to_send.is_move_sent = True # Mark invoice as sent
for invoice in invoice_to_send:
lang = template._render_lang(invoice.ids)[invoice.id]
model_desc = invoice.with_context(lang=lang).type_name
invoice.with_context(model_description=model_desc).with_user(
SUPERUSER_ID
).message_post_with_template(
template_id=template_id, email_layout_xmlid='mail.mail_notification_paynow')
def _cron_send_invoice(self):
"""
Cron to send invoice that where not ready to be send directly after posting
"""
if not self.env['ir.config_parameter'].sudo().get_param('sale.automatic_invoice'):
return
# No need to retrieve old transactions
retry_limit_date = datetime.now() - relativedelta.relativedelta(days=2)
# Retrieve all transactions matching the criteria for post-processing
self.search([
('state', '=', 'done'),
('is_post_processed', '=', True),
('invoice_ids', 'in', self.env['account.move']._search([
('is_move_sent', '=', False),
('state', '=', 'posted'),
])),
('sale_order_ids.state', 'in', ('sale', 'done')),
('last_state_change', '>=', retry_limit_date),
])._send_invoice()
def _invoice_sale_orders(self):
if self.env['ir.config_parameter'].sudo().get_param('sale.automatic_invoice'):
for trans in self.filtered(lambda t: t.sale_order_ids):
trans = trans.with_company(trans.acquirer_id.company_id)\
.with_context(company_id=trans.acquirer_id.company_id.id)
confirmed_orders = trans.sale_order_ids.filtered(lambda so: so.state in ('sale', 'done'))
if confirmed_orders:
confirmed_orders._force_lines_to_invoice_policy_order()
invoices = confirmed_orders._create_invoices()
# Setup access token in advance to avoid serialization failure between
# edi postprocessing of invoice and displaying the sale order on the portal
for invoice in invoices:
invoice._portal_ensure_token()
trans.invoice_ids = [(6, 0, invoices.ids)]
@api.model
def _compute_reference_prefix(self, provider, separator, **values):
""" Override of payment to compute the reference prefix based on Sales-specific values.
If the `values` parameter has an entry with 'sale_order_ids' as key and a list of (4, id, O)
or (6, 0, ids) X2M command as value, the prefix is computed based on the sales order name(s)
Otherwise, the computation is delegated to the super method.
:param str provider: The provider of the acquirer handling the transaction
:param str separator: The custom separator used to separate data references
:param dict values: The transaction values used to compute the reference prefix. It should
have the structure {'sale_order_ids': [(X2M command), ...], ...}.
:return: The computed reference prefix if order ids are found, the one of `super` otherwise
:rtype: str
"""
command_list = values.get('sale_order_ids')
if command_list:
# Extract sales order id(s) from the X2M commands
order_ids = self._fields['sale_order_ids'].convert_to_cache(command_list, self)
orders = self.env['sale.order'].browse(order_ids).exists()
if len(orders) == len(order_ids): # All ids are valid
return separator.join(orders.mapped('name'))
return super()._compute_reference_prefix(provider, separator, **values)
def action_view_sales_orders(self):
action = {
'name': _('Sales Order(s)'),
'type': 'ir.actions.act_window',
'res_model': 'sale.order',
'target': 'current',
}
sale_order_ids = self.sale_order_ids.ids
if len(sale_order_ids) == 1:
action['res_id'] = sale_order_ids[0]
action['view_mode'] = 'form'
else:
action['view_mode'] = 'tree,form'
action['domain'] = [('id', 'in', sale_order_ids)]
return action
| 48.605911 | 9,867 |
56,078 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from itertools import groupby
import json
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.osv import expression
from odoo.tools import float_is_zero, html_keep_url, is_html_empty
from odoo.addons.payment import utils as payment_utils
class SaleOrder(models.Model):
_name = "sale.order"
_inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin']
_description = "Sales Order"
_order = 'date_order desc, id desc'
_check_company_auto = True
def _default_validity_date(self):
if self.env['ir.config_parameter'].sudo().get_param('sale.use_quotation_validity_days'):
days = self.env.company.quotation_validity_days
if days > 0:
return fields.Date.to_string(datetime.now() + timedelta(days))
return False
def _get_default_require_signature(self):
return self.env.company.portal_confirmation_sign
def _get_default_require_payment(self):
return self.env.company.portal_confirmation_pay
def _compute_amount_total_without_delivery(self):
self.ensure_one()
return self.amount_total
@api.depends('order_line.price_total')
def _amount_all(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
amount_untaxed = amount_tax = 0.0
for line in order.order_line:
amount_untaxed += line.price_subtotal
amount_tax += line.price_tax
order.update({
'amount_untaxed': amount_untaxed,
'amount_tax': amount_tax,
'amount_total': amount_untaxed + amount_tax,
})
@api.depends('order_line.invoice_lines')
def _get_invoiced(self):
# The invoice_ids are obtained thanks to the invoice lines of the SO
# lines, and we also search for possible refunds created directly from
# existing invoices. This is necessary since such a refund is not
# directly linked to the SO.
for order in self:
invoices = order.order_line.invoice_lines.move_id.filtered(lambda r: r.move_type in ('out_invoice', 'out_refund'))
order.invoice_ids = invoices
order.invoice_count = len(invoices)
@api.depends('state', 'order_line.invoice_status')
def _get_invoice_status(self):
"""
Compute the invoice status of a SO. Possible statuses:
- no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to
invoice. This is also the default value if the conditions of no other status is met.
- to invoice: if any SO line is 'to invoice', the whole SO is 'to invoice'
- invoiced: if all SO lines are invoiced, the SO is invoiced.
- upselling: if all SO lines are invoiced or upselling, the status is upselling.
"""
unconfirmed_orders = self.filtered(lambda so: so.state not in ['sale', 'done'])
unconfirmed_orders.invoice_status = 'no'
confirmed_orders = self - unconfirmed_orders
if not confirmed_orders:
return
line_invoice_status_all = [
(d['order_id'][0], d['invoice_status'])
for d in self.env['sale.order.line'].read_group([
('order_id', 'in', confirmed_orders.ids),
('is_downpayment', '=', False),
('display_type', '=', False),
],
['order_id', 'invoice_status'],
['order_id', 'invoice_status'], lazy=False)]
for order in confirmed_orders:
line_invoice_status = [d[1] for d in line_invoice_status_all if d[0] == order.id]
if order.state not in ('sale', 'done'):
order.invoice_status = 'no'
elif any(invoice_status == 'to invoice' for invoice_status in line_invoice_status):
order.invoice_status = 'to invoice'
elif line_invoice_status and all(invoice_status == 'invoiced' for invoice_status in line_invoice_status):
order.invoice_status = 'invoiced'
elif line_invoice_status and all(invoice_status in ('invoiced', 'upselling') for invoice_status in line_invoice_status):
order.invoice_status = 'upselling'
else:
order.invoice_status = 'no'
@api.model
def get_empty_list_help(self, help):
self = self.with_context(
empty_list_help_document_name=_("sale order"),
)
return super(SaleOrder, self).get_empty_list_help(help)
@api.model
def _default_note_url(self):
return self.env.company.get_base_url()
@api.model
def _default_note(self):
use_invoice_terms = self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms')
if use_invoice_terms and self.env.company.terms_type == "html":
baseurl = html_keep_url(self._default_note_url() + '/terms')
context = {'lang': self.partner_id.lang or self.env.user.lang}
note = _('Terms & Conditions: %s', baseurl)
del context
return note
return use_invoice_terms and self.env.company.invoice_terms or ''
@api.model
def _get_default_team(self):
return self.env['crm.team']._get_default_team_id()
@api.onchange('fiscal_position_id', 'company_id')
def _compute_tax_id(self):
"""
Trigger the recompute of the taxes if the fiscal position is changed on the SO.
"""
for order in self:
order.order_line._compute_tax_id()
def _search_invoice_ids(self, operator, value):
if operator == 'in' and value:
self.env.cr.execute("""
SELECT array_agg(so.id)
FROM sale_order so
JOIN sale_order_line sol ON sol.order_id = so.id
JOIN sale_order_line_invoice_rel soli_rel ON soli_rel.order_line_id = sol.id
JOIN account_move_line aml ON aml.id = soli_rel.invoice_line_id
JOIN account_move am ON am.id = aml.move_id
WHERE
am.move_type in ('out_invoice', 'out_refund') AND
am.id = ANY(%s)
""", (list(value),))
so_ids = self.env.cr.fetchone()[0] or []
return [('id', 'in', so_ids)]
elif operator == '=' and not value:
# special case for [('invoice_ids', '=', False)], i.e. "Invoices is not set"
#
# We cannot just search [('order_line.invoice_lines', '=', False)]
# because it returns orders with uninvoiced lines, which is not
# same "Invoices is not set" (some lines may have invoices and some
# doesn't)
#
# A solution is making inverted search first ("orders with invoiced
# lines") and then invert results ("get all other orders")
#
# Domain below returns subset of ('order_line.invoice_lines', '!=', False)
order_ids = self._search([
('order_line.invoice_lines.move_id.move_type', 'in', ('out_invoice', 'out_refund'))
])
return [('id', 'not in', order_ids)]
return ['&', ('order_line.invoice_lines.move_id.move_type', 'in', ('out_invoice', 'out_refund')), ('order_line.invoice_lines.move_id', operator, value)]
name = fields.Char(string='Order Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)]}, index=True, default=lambda self: _('New'))
origin = fields.Char(string='Source Document', help="Reference of the document that generated this sales order request.")
client_order_ref = fields.Char(string='Customer Reference', copy=False)
reference = fields.Char(string='Payment Ref.', copy=False,
help='The payment communication of this sale order.')
state = fields.Selection([
('draft', 'Quotation'),
('sent', 'Quotation Sent'),
('sale', 'Sales Order'),
('done', 'Locked'),
('cancel', 'Cancelled'),
], string='Status', readonly=True, copy=False, index=True, tracking=3, default='draft')
date_order = fields.Datetime(string='Order Date', required=True, readonly=True, index=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=False, default=fields.Datetime.now, help="Creation date of draft/sent orders,\nConfirmation date of confirmed orders.")
validity_date = fields.Date(string='Expiration', readonly=True, copy=False, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
default=_default_validity_date)
is_expired = fields.Boolean(compute='_compute_is_expired', string="Is expired")
require_signature = fields.Boolean('Online Signature', default=_get_default_require_signature, readonly=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
help='Request a online signature to the customer in order to confirm orders automatically.')
require_payment = fields.Boolean('Online Payment', default=_get_default_require_payment, readonly=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
help='Request an online payment to the customer in order to confirm orders automatically.')
create_date = fields.Datetime(string='Creation Date', readonly=True, index=True, help="Date on which sales order is created.")
user_id = fields.Many2one(
'res.users', string='Salesperson', index=True, tracking=2, default=lambda self: self.env.user,
domain=lambda self: "[('groups_id', '=', {}), ('share', '=', False), ('company_ids', '=', company_id)]".format(
self.env.ref("sales_team.group_sale_salesman").id
),)
partner_id = fields.Many2one(
'res.partner', string='Customer', readonly=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
required=True, change_default=True, index=True, tracking=1,
domain="[('type', '!=', 'private'), ('company_id', 'in', (False, company_id))]",)
partner_invoice_id = fields.Many2one(
'res.partner', string='Invoice Address',
readonly=True, required=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'sale': [('readonly', False)]},
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",)
partner_shipping_id = fields.Many2one(
'res.partner', string='Delivery Address', readonly=True, required=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'sale': [('readonly', False)]},
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",)
pricelist_id = fields.Many2one(
'product.pricelist', string='Pricelist', check_company=True, # Unrequired company
required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", tracking=1,
help="If you change the pricelist, only newly added lines will be affected.")
currency_id = fields.Many2one(related='pricelist_id.currency_id', depends=["pricelist_id"], store=True, ondelete="restrict")
analytic_account_id = fields.Many2one(
'account.analytic.account', 'Analytic Account',
compute='_compute_analytic_account_id', store=True,
readonly=False, copy=False, check_company=True, # Unrequired company
states={'sale': [('readonly', True)], 'done': [('readonly', True)], 'cancel': [('readonly', True)]},
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
help="The analytic account related to a sales order.")
order_line = fields.One2many('sale.order.line', 'order_id', string='Order Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True, auto_join=True)
invoice_count = fields.Integer(string='Invoice Count', compute='_get_invoiced')
invoice_ids = fields.Many2many("account.move", string='Invoices', compute="_get_invoiced", copy=False, search="_search_invoice_ids")
invoice_status = fields.Selection([
('upselling', 'Upselling Opportunity'),
('invoiced', 'Fully Invoiced'),
('to invoice', 'To Invoice'),
('no', 'Nothing to Invoice')
], string='Invoice Status', compute='_get_invoice_status', store=True)
note = fields.Html('Terms and conditions', default=_default_note)
terms_type = fields.Selection(related='company_id.terms_type')
amount_untaxed = fields.Monetary(string='Untaxed Amount', store=True, compute='_amount_all', tracking=5)
tax_totals_json = fields.Char(compute='_compute_tax_totals_json')
amount_tax = fields.Monetary(string='Taxes', store=True, compute='_amount_all')
amount_total = fields.Monetary(string='Total', store=True, compute='_amount_all', tracking=4)
currency_rate = fields.Float("Currency Rate", compute='_compute_currency_rate', store=True, digits=(12, 6), help='The rate of the currency to the currency of rate 1 applicable at the date of the order')
payment_term_id = fields.Many2one(
'account.payment.term', string='Payment Terms', check_company=True, # Unrequired company
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",)
fiscal_position_id = fields.Many2one(
'account.fiscal.position', string='Fiscal Position',
domain="[('company_id', '=', company_id)]", check_company=True,
help="Fiscal positions are used to adapt taxes and accounts for particular customers or sales orders/invoices."
"The default value comes from the customer.")
tax_country_id = fields.Many2one(
comodel_name='res.country',
compute='_compute_tax_country_id',
# Avoid access error on fiscal position when reading a sale order with company != user.company_ids
compute_sudo=True,
help="Technical field to filter the available taxes depending on the fiscal country and fiscal position.")
company_id = fields.Many2one('res.company', 'Company', required=True, index=True, default=lambda self: self.env.company)
team_id = fields.Many2one(
'crm.team', 'Sales Team',
ondelete="set null", tracking=True,
change_default=True, default=_get_default_team, check_company=True, # Unrequired company
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
signature = fields.Image('Signature', help='Signature received through the portal.', copy=False, attachment=True, max_width=1024, max_height=1024)
signed_by = fields.Char('Signed By', help='Name of the person that signed the SO.', copy=False)
signed_on = fields.Datetime('Signed On', help='Date of the signature.', copy=False)
commitment_date = fields.Datetime('Delivery Date', copy=False,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="This is the delivery date promised to the customer. "
"If set, the delivery order will be scheduled based on "
"this date rather than product lead times.")
expected_date = fields.Datetime("Expected Date", compute='_compute_expected_date', store=False, # Note: can not be stored since depends on today()
help="Delivery date you can promise to the customer, computed from the minimum lead time of the order lines.")
amount_undiscounted = fields.Float('Amount Before Discount', compute='_compute_amount_undiscounted', digits=0)
type_name = fields.Char('Type Name', compute='_compute_type_name')
transaction_ids = fields.Many2many('payment.transaction', 'sale_order_transaction_rel', 'sale_order_id', 'transaction_id',
string='Transactions', copy=False, readonly=True)
authorized_transaction_ids = fields.Many2many('payment.transaction', compute='_compute_authorized_transaction_ids',
string='Authorized Transactions', copy=False)
show_update_pricelist = fields.Boolean(string='Has Pricelist Changed',
help="Technical Field, True if the pricelist was changed;\n"
" this will then display a recomputation button")
tag_ids = fields.Many2many('crm.tag', 'sale_order_tag_rel', 'order_id', 'tag_id', string='Tags')
_sql_constraints = [
('date_order_conditional_required', "CHECK( (state IN ('sale', 'done') AND date_order IS NOT NULL) OR state NOT IN ('sale', 'done') )", "A confirmed sales order requires a confirmation date."),
]
@api.constrains('company_id', 'order_line')
def _check_order_line_company_id(self):
for order in self:
companies = order.order_line.product_id.company_id
if companies and companies != order.company_id:
bad_products = order.order_line.product_id.filtered(lambda p: p.company_id and p.company_id != order.company_id)
raise ValidationError(_(
"Your quotation contains products from company %(product_company)s whereas your quotation belongs to company %(quote_company)s. \n Please change the company of your quotation or remove the products from other companies (%(bad_products)s).",
product_company=', '.join(companies.mapped('display_name')),
quote_company=order.company_id.display_name,
bad_products=', '.join(bad_products.mapped('display_name')),
))
@api.depends('pricelist_id', 'date_order', 'company_id')
def _compute_currency_rate(self):
for order in self:
if not order.company_id:
order.currency_rate = order.currency_id.with_context(date=order.date_order).rate or 1.0
continue
elif order.company_id.currency_id and order.currency_id: # the following crashes if any one is undefined
order.currency_rate = self.env['res.currency']._get_conversion_rate(order.company_id.currency_id, order.currency_id, order.company_id, order.date_order)
else:
order.currency_rate = 1.0
def _compute_access_url(self):
super(SaleOrder, self)._compute_access_url()
for order in self:
order.access_url = '/my/orders/%s' % (order.id)
def _compute_is_expired(self):
today = fields.Date.today()
for order in self:
order.is_expired = order.state == 'sent' and order.validity_date and order.validity_date < today
@api.depends('order_line.customer_lead', 'date_order', 'order_line.state')
def _compute_expected_date(self):
""" For service and consumable, we only take the min dates. This method is extended in sale_stock to
take the picking_policy of SO into account.
"""
self.mapped("order_line") # Prefetch indication
for order in self:
dates_list = []
for line in order.order_line.filtered(lambda x: x.state != 'cancel' and not x._is_delivery() and not x.display_type):
dt = line._expected_date()
dates_list.append(dt)
if dates_list:
order.expected_date = fields.Datetime.to_string(min(dates_list))
else:
order.expected_date = False
@api.depends('order_line.tax_id', 'order_line.price_unit', 'amount_total', 'amount_untaxed')
def _compute_tax_totals_json(self):
def compute_taxes(order_line):
price = order_line.price_unit * (1 - (order_line.discount or 0.0) / 100.0)
order = order_line.order_id
return order_line.tax_id._origin.compute_all(price, order.currency_id, order_line.product_uom_qty, product=order_line.product_id, partner=order.partner_shipping_id)
account_move = self.env['account.move']
for order in self:
tax_lines_data = account_move._prepare_tax_lines_data_for_totals_from_object(order.order_line, compute_taxes)
tax_totals = account_move._get_tax_totals(order.partner_id, tax_lines_data, order.amount_total, order.amount_untaxed, order.currency_id)
order.tax_totals_json = json.dumps(tax_totals)
@api.depends('transaction_ids')
def _compute_authorized_transaction_ids(self):
for trans in self:
trans.authorized_transaction_ids = trans.transaction_ids.filtered(lambda t: t.state == 'authorized')
def _compute_amount_undiscounted(self):
for order in self:
total = 0.0
for line in order.order_line:
total += (line.price_subtotal * 100)/(100-line.discount) if line.discount != 100 else (line.price_unit * line.product_uom_qty)
order.amount_undiscounted = total
@api.depends('state')
def _compute_type_name(self):
for record in self:
record.type_name = _('Quotation') if record.state in ('draft', 'sent', 'cancel') else _('Sales Order')
@api.depends('company_id.account_fiscal_country_id', 'fiscal_position_id.country_id', 'fiscal_position_id.foreign_vat')
def _compute_tax_country_id(self):
for record in self:
if record.fiscal_position_id.foreign_vat:
record.tax_country_id = record.fiscal_position_id.country_id
else:
record.tax_country_id = record.company_id.account_fiscal_country_id
@api.depends('partner_id', 'date_order')
def _compute_analytic_account_id(self):
for order in self:
if not order.analytic_account_id:
default_analytic_account = order.env['account.analytic.default'].sudo().account_get(
partner_id=order.partner_id.id,
user_id=order.env.uid,
date=order.date_order,
company_id=order.company_id.id,
)
order.analytic_account_id = default_analytic_account.analytic_id
@api.ondelete(at_uninstall=False)
def _unlink_except_draft_or_cancel(self):
for order in self:
if order.state not in ('draft', 'cancel'):
raise UserError(_('You can not delete a sent quotation or a confirmed sales order. You must first cancel it.'))
def validate_taxes_on_sales_order(self):
# Override for correct taxcloud computation
# when using coupon and delivery
return True
def _track_subtype(self, init_values):
self.ensure_one()
if 'state' in init_values and self.state == 'sale':
return self.env.ref('sale.mt_order_confirmed')
elif 'state' in init_values and self.state == 'sent':
return self.env.ref('sale.mt_order_sent')
return super(SaleOrder, self)._track_subtype(init_values)
@api.onchange('partner_shipping_id', 'partner_id', 'company_id')
def onchange_partner_shipping_id(self):
"""
Trigger the change of fiscal position when the shipping address is modified.
"""
self.fiscal_position_id = self.env['account.fiscal.position'].with_company(self.company_id).get_fiscal_position(self.partner_id.id, self.partner_shipping_id.id)
return {}
@api.onchange('partner_id')
def onchange_partner_id(self):
"""
Update the following fields when the partner is changed:
- Pricelist
- Payment terms
- Invoice address
- Delivery address
- Sales Team
"""
if not self.partner_id:
self.update({
'partner_invoice_id': False,
'partner_shipping_id': False,
'fiscal_position_id': False,
})
return
self = self.with_company(self.company_id)
addr = self.partner_id.address_get(['delivery', 'invoice'])
partner_user = self.partner_id.user_id or self.partner_id.commercial_partner_id.user_id
values = {
'pricelist_id': self.partner_id.property_product_pricelist and self.partner_id.property_product_pricelist.id or False,
'payment_term_id': self.partner_id.property_payment_term_id and self.partner_id.property_payment_term_id.id or False,
'partner_invoice_id': addr['invoice'],
'partner_shipping_id': addr['delivery'],
}
user_id = partner_user.id
if not self.env.context.get('not_self_saleperson'):
user_id = user_id or self.env.context.get('default_user_id', self.env.uid)
if user_id and self.user_id.id != user_id:
values['user_id'] = user_id
if self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms'):
if self.terms_type == 'html' and self.env.company.invoice_terms_html:
baseurl = html_keep_url(self.get_base_url() + '/terms')
context = {'lang': self.partner_id.lang or self.env.user.lang}
values['note'] = _('Terms & Conditions: %s', baseurl)
del context
elif not is_html_empty(self.env.company.invoice_terms):
values['note'] = self.with_context(lang=self.partner_id.lang).env.company.invoice_terms
if not self.env.context.get('not_self_saleperson') or not self.team_id:
default_team = self.env.context.get('default_team_id', False) or self.partner_id.team_id.id
values['team_id'] = self.env['crm.team'].with_context(
default_team_id=default_team
)._get_default_team_id(domain=['|', ('company_id', '=', self.company_id.id), ('company_id', '=', False)], user_id=user_id)
self.update(values)
@api.onchange('user_id')
def onchange_user_id(self):
if self.user_id:
default_team = self.env.context.get('default_team_id', False) or self.team_id.id
self.team_id = self.env['crm.team'].with_context(
default_team_id=default_team
)._get_default_team_id(user_id=self.user_id.id, domain=None)
@api.onchange('partner_id')
def _onchange_partner_id_warning(self):
if not self.partner_id:
return
partner = self.partner_id
# If partner has no warning, check its company
if partner.sale_warn == 'no-message' and partner.parent_id:
partner = partner.parent_id
if partner.sale_warn and partner.sale_warn != 'no-message':
# Block if partner only has warning but parent company is blocked
if partner.sale_warn != 'block' and partner.parent_id and partner.parent_id.sale_warn == 'block':
partner = partner.parent_id
if partner.sale_warn == 'block':
self.update({'partner_id': False, 'partner_invoice_id': False, 'partner_shipping_id': False, 'pricelist_id': False})
return {
'warning': {
'title': _("Warning for %s", partner.name),
'message': partner.sale_warn_msg,
}
}
@api.onchange('commitment_date', 'expected_date')
def _onchange_commitment_date(self):
""" Warn if the commitment dates is sooner than the expected date """
if (self.commitment_date and self.expected_date and self.commitment_date < self.expected_date):
return {
'warning': {
'title': _('Requested date is too soon.'),
'message': _("The delivery date is sooner than the expected date."
"You may be unable to honor the delivery date.")
}
}
@api.onchange('pricelist_id', 'order_line')
def _onchange_pricelist_id(self):
if self.order_line and self.pricelist_id and self._origin.pricelist_id != self.pricelist_id:
self.show_update_pricelist = True
else:
self.show_update_pricelist = False
def _get_update_prices_lines(self):
""" Hook to exclude specific lines which should not be updated based on price list recomputation """
return self.order_line.filtered(lambda line: not line.display_type)
def update_prices(self):
self.ensure_one()
for line in self._get_update_prices_lines():
line.product_uom_change()
line.discount = 0 # Force 0 as discount for the cases when _onchange_discount directly returns
line._onchange_discount()
self.show_update_pricelist = False
self.message_post(body=_("Product prices have been recomputed according to pricelist <b>%s<b> ", self.pricelist_id.display_name))
@api.model
def create(self, vals):
if 'company_id' in vals:
self = self.with_company(vals['company_id'])
if vals.get('name', _('New')) == _('New'):
seq_date = None
if 'date_order' in vals:
seq_date = fields.Datetime.context_timestamp(self, fields.Datetime.to_datetime(vals['date_order']))
vals['name'] = self.env['ir.sequence'].next_by_code('sale.order', sequence_date=seq_date) or _('New')
# Makes sure partner_invoice_id', 'partner_shipping_id' and 'pricelist_id' are defined
if any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id']):
partner = self.env['res.partner'].browse(vals.get('partner_id'))
addr = partner.address_get(['delivery', 'invoice'])
vals['partner_invoice_id'] = vals.setdefault('partner_invoice_id', addr['invoice'])
vals['partner_shipping_id'] = vals.setdefault('partner_shipping_id', addr['delivery'])
vals['pricelist_id'] = vals.setdefault('pricelist_id', partner.property_product_pricelist.id)
result = super(SaleOrder, self).create(vals)
return result
def _compute_field_value(self, field):
if field.name == 'invoice_status' and not self.env.context.get('mail_activity_automation_skip'):
filtered_self = self.filtered(lambda so: (so.user_id or so.partner_id.user_id) and so._origin.invoice_status != 'upselling')
super()._compute_field_value(field)
if field.name != 'invoice_status' or self.env.context.get('mail_activity_automation_skip'):
return
upselling_orders = filtered_self.filtered(lambda so: so.invoice_status == 'upselling')
if not upselling_orders:
return
upselling_orders._create_upsell_activity()
def copy_data(self, default=None):
if default is None:
default = {}
if 'order_line' not in default:
default['order_line'] = [(0, 0, line.copy_data()[0]) for line in self.order_line.filtered(lambda l: not l.is_downpayment)]
return super(SaleOrder, self).copy_data(default)
def name_get(self):
if self._context.get('sale_show_partner_name'):
res = []
for order in self:
name = order.name
if order.partner_id.name:
name = '%s - %s' % (name, order.partner_id.name)
res.append((order.id, name))
return res
return super(SaleOrder, self).name_get()
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if self._context.get('sale_show_partner_name'):
if operator == 'ilike' and not (name or '').strip():
domain = []
elif operator in ('ilike', 'like', '=', '=like', '=ilike'):
domain = expression.AND([
args or [],
['|', ('name', operator, name), ('partner_id.name', operator, name)]
])
return self._search(domain, limit=limit, access_rights_uid=name_get_uid)
return super(SaleOrder, self)._name_search(name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
def _create_upsell_activity(self):
self and self.activity_unlink(['sale.mail_act_sale_upsell'])
for order in self:
ref = "<a href='#' data-oe-model='%s' data-oe-id='%d'>%s</a>"
order_ref = ref % (order._name, order.id or order._origin.id, order.name)
customer_ref = ref % (order.partner_id._name, order.partner_id.id, order.partner_id.display_name)
order.activity_schedule(
'sale.mail_act_sale_upsell',
user_id=order.user_id.id or order.partner_id.user_id.id,
note=_("Upsell %(order)s for customer %(customer)s", order=order_ref, customer=customer_ref))
def _prepare_invoice(self):
"""
Prepare the dict of values to create the new invoice for a sales order. This method may be
overridden to implement custom invoice generation (making sure to call super() to establish
a clean extension chain).
"""
self.ensure_one()
journal = self.env['account.move'].with_context(default_move_type='out_invoice')._get_default_journal()
if not journal:
raise UserError(_('Please define an accounting sales journal for the company %s (%s).', self.company_id.name, self.company_id.id))
invoice_vals = {
'ref': self.client_order_ref or '',
'move_type': 'out_invoice',
'narration': self.note,
'currency_id': self.pricelist_id.currency_id.id,
'campaign_id': self.campaign_id.id,
'medium_id': self.medium_id.id,
'source_id': self.source_id.id,
'user_id': self.user_id.id,
'invoice_user_id': self.user_id.id,
'team_id': self.team_id.id,
'partner_id': self.partner_invoice_id.id,
'partner_shipping_id': self.partner_shipping_id.id,
'fiscal_position_id': (self.fiscal_position_id or self.fiscal_position_id.get_fiscal_position(self.partner_invoice_id.id)).id,
'partner_bank_id': self.company_id.partner_id.bank_ids.filtered(lambda bank: bank.company_id.id in (self.company_id.id, False))[:1].id,
'journal_id': journal.id, # company comes from the journal
'invoice_origin': self.name,
'invoice_payment_term_id': self.payment_term_id.id,
'payment_reference': self.reference,
'transaction_ids': [(6, 0, self.transaction_ids.ids)],
'invoice_line_ids': [],
'company_id': self.company_id.id,
}
return invoice_vals
def action_quotation_sent(self):
if self.filtered(lambda so: so.state != 'draft'):
raise UserError(_('Only draft orders can be marked as sent directly.'))
for order in self:
order.message_subscribe(partner_ids=order.partner_id.ids)
self.write({'state': 'sent'})
def action_view_invoice(self):
invoices = self.mapped('invoice_ids')
action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_out_invoice_type")
if len(invoices) > 1:
action['domain'] = [('id', 'in', invoices.ids)]
elif len(invoices) == 1:
form_view = [(self.env.ref('account.view_move_form').id, 'form')]
if 'views' in action:
action['views'] = form_view + [(state,view) for state,view in action['views'] if view != 'form']
else:
action['views'] = form_view
action['res_id'] = invoices.id
else:
action = {'type': 'ir.actions.act_window_close'}
context = {
'default_move_type': 'out_invoice',
}
if len(self) == 1:
context.update({
'default_partner_id': self.partner_id.id,
'default_partner_shipping_id': self.partner_shipping_id.id,
'default_invoice_payment_term_id': self.payment_term_id.id or self.partner_id.property_payment_term_id.id or self.env['account.move'].default_get(['invoice_payment_term_id']).get('invoice_payment_term_id'),
'default_invoice_origin': self.name,
})
action['context'] = context
return action
def _get_invoice_grouping_keys(self):
return ['company_id', 'partner_id', 'currency_id']
@api.model
def _nothing_to_invoice_error(self):
return UserError(_(
"There is nothing to invoice!\n\n"
"Reason(s) of this behavior could be:\n"
"- You should deliver your products before invoicing them.\n"
"- You should modify the invoicing policy of your product: Open the product, go to the "
"\"Sales\" tab and modify invoicing policy from \"delivered quantities\" to \"ordered "
"quantities\". For Services, you should modify the Service Invoicing Policy to "
"'Prepaid'."
))
def _get_invoiceable_lines(self, final=False):
"""Return the invoiceable lines for order `self`."""
down_payment_line_ids = []
invoiceable_line_ids = []
pending_section = None
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for line in self.order_line:
if line.display_type == 'line_section':
# Only invoice the section if one of its lines is invoiceable
pending_section = line
continue
if line.display_type != 'line_note' and float_is_zero(line.qty_to_invoice, precision_digits=precision):
continue
if line.qty_to_invoice > 0 or (line.qty_to_invoice < 0 and final) or line.display_type == 'line_note':
if line.is_downpayment:
# Keep down payment lines separately, to put them together
# at the end of the invoice, in a specific dedicated section.
down_payment_line_ids.append(line.id)
continue
if pending_section:
invoiceable_line_ids.append(pending_section.id)
pending_section = None
invoiceable_line_ids.append(line.id)
return self.env['sale.order.line'].browse(invoiceable_line_ids + down_payment_line_ids)
def _create_invoices(self, grouped=False, final=False, date=None):
"""
Create the invoice associated to the SO.
:param grouped: if True, invoices are grouped by SO id. If False, invoices are grouped by
(partner_invoice_id, currency)
:param final: if True, refunds will be generated if necessary
:returns: list of created invoices
"""
if not self.env['account.move'].check_access_rights('create', False):
try:
self.check_access_rights('write')
self.check_access_rule('write')
except AccessError:
return self.env['account.move']
# 1) Create invoices.
invoice_vals_list = []
invoice_item_sequence = 0 # Incremental sequencing to keep the lines order on the invoice.
for order in self:
order = order.with_company(order.company_id)
current_section_vals = None
down_payments = order.env['sale.order.line']
invoice_vals = order._prepare_invoice()
invoiceable_lines = order._get_invoiceable_lines(final)
if not any(not line.display_type for line in invoiceable_lines):
continue
invoice_line_vals = []
down_payment_section_added = False
for line in invoiceable_lines:
if not down_payment_section_added and line.is_downpayment:
# Create a dedicated section for the down payments
# (put at the end of the invoiceable_lines)
invoice_line_vals.append(
(0, 0, order._prepare_down_payment_section_line(
sequence=invoice_item_sequence,
)),
)
down_payment_section_added = True
invoice_item_sequence += 1
invoice_line_vals.append(
(0, 0, line._prepare_invoice_line(
sequence=invoice_item_sequence,
)),
)
invoice_item_sequence += 1
invoice_vals['invoice_line_ids'] += invoice_line_vals
invoice_vals_list.append(invoice_vals)
if not invoice_vals_list:
raise self._nothing_to_invoice_error()
# 2) Manage 'grouped' parameter: group by (partner_id, currency_id).
if not grouped:
new_invoice_vals_list = []
invoice_grouping_keys = self._get_invoice_grouping_keys()
invoice_vals_list = sorted(
invoice_vals_list,
key=lambda x: [
x.get(grouping_key) for grouping_key in invoice_grouping_keys
]
)
for grouping_keys, invoices in groupby(invoice_vals_list, key=lambda x: [x.get(grouping_key) for grouping_key in invoice_grouping_keys]):
origins = set()
payment_refs = set()
refs = set()
ref_invoice_vals = None
for invoice_vals in invoices:
if not ref_invoice_vals:
ref_invoice_vals = invoice_vals
else:
ref_invoice_vals['invoice_line_ids'] += invoice_vals['invoice_line_ids']
origins.add(invoice_vals['invoice_origin'])
payment_refs.add(invoice_vals['payment_reference'])
refs.add(invoice_vals['ref'])
ref_invoice_vals.update({
'ref': ', '.join(refs)[:2000],
'invoice_origin': ', '.join(origins),
'payment_reference': len(payment_refs) == 1 and payment_refs.pop() or False,
})
new_invoice_vals_list.append(ref_invoice_vals)
invoice_vals_list = new_invoice_vals_list
# 3) Create invoices.
# As part of the invoice creation, we make sure the sequence of multiple SO do not interfere
# in a single invoice. Example:
# SO 1:
# - Section A (sequence: 10)
# - Product A (sequence: 11)
# SO 2:
# - Section B (sequence: 10)
# - Product B (sequence: 11)
#
# If SO 1 & 2 are grouped in the same invoice, the result will be:
# - Section A (sequence: 10)
# - Section B (sequence: 10)
# - Product A (sequence: 11)
# - Product B (sequence: 11)
#
# Resequencing should be safe, however we resequence only if there are less invoices than
# orders, meaning a grouping might have been done. This could also mean that only a part
# of the selected SO are invoiceable, but resequencing in this case shouldn't be an issue.
if len(invoice_vals_list) < len(self):
SaleOrderLine = self.env['sale.order.line']
for invoice in invoice_vals_list:
sequence = 1
for line in invoice['invoice_line_ids']:
line[2]['sequence'] = SaleOrderLine._get_invoice_line_sequence(new=sequence, old=line[2]['sequence'])
sequence += 1
# Manage the creation of invoices in sudo because a salesperson must be able to generate an invoice from a
# sale order without "billing" access rights. However, he should not be able to create an invoice from scratch.
moves = self.env['account.move'].sudo().with_context(default_move_type='out_invoice').create(invoice_vals_list)
# 4) Some moves might actually be refunds: convert them if the total amount is negative
# We do this after the moves have been created since we need taxes, etc. to know if the total
# is actually negative or not
if final:
moves.sudo().filtered(lambda m: m.amount_total < 0).action_switch_invoice_into_refund_credit_note()
for move in moves:
move.message_post_with_view('mail.message_origin_link',
values={'self': move, 'origin': move.line_ids.mapped('sale_line_ids.order_id')},
subtype_id=self.env.ref('mail.mt_note').id
)
return moves
def action_draft(self):
orders = self.filtered(lambda s: s.state in ['cancel', 'sent'])
return orders.write({
'state': 'draft',
'signature': False,
'signed_by': False,
'signed_on': False,
})
def action_cancel(self):
cancel_warning = self._show_cancel_wizard()
if cancel_warning:
return {
'name': _('Cancel Sales Order'),
'view_mode': 'form',
'res_model': 'sale.order.cancel',
'view_id': self.env.ref('sale.sale_order_cancel_view_form').id,
'type': 'ir.actions.act_window',
'context': {'default_order_id': self.id},
'target': 'new'
}
return self._action_cancel()
def _action_cancel(self):
inv = self.invoice_ids.filtered(lambda inv: inv.state == 'draft')
inv.button_cancel()
return self.write({'state': 'cancel', 'show_update_pricelist': False})
def _show_cancel_wizard(self):
for order in self:
if order.invoice_ids.filtered(lambda inv: inv.state == 'draft') and not order._context.get('disable_cancel_warning'):
return True
return False
def _find_mail_template(self, force_confirmation_template=False):
self.ensure_one()
template_id = False
if force_confirmation_template or (self.state == 'sale' and not self.env.context.get('proforma', False)):
template_id = int(self.env['ir.config_parameter'].sudo().get_param('sale.default_confirmation_template'))
template_id = self.env['mail.template'].search([('id', '=', template_id)]).id
if not template_id:
template_id = self.env['ir.model.data']._xmlid_to_res_id('sale.mail_template_sale_confirmation', raise_if_not_found=False)
if not template_id:
template_id = self.env['ir.model.data']._xmlid_to_res_id('sale.email_template_edi_sale', raise_if_not_found=False)
return template_id
def action_quotation_send(self):
''' Opens a wizard to compose an email, with relevant mail template loaded by default '''
self.ensure_one()
template_id = self._find_mail_template()
lang = self.env.context.get('lang')
template = self.env['mail.template'].browse(template_id)
if template.lang:
lang = template._render_lang(self.ids)[self.id]
ctx = {
'default_model': 'sale.order',
'default_res_id': self.ids[0],
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_composition_mode': 'comment',
'mark_so_as_sent': True,
'custom_layout': "mail.mail_notification_paynow",
'proforma': self.env.context.get('proforma', False),
'force_email': True,
'model_description': self.with_context(lang=lang).type_name,
}
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(False, 'form')],
'view_id': False,
'target': 'new',
'context': ctx,
}
@api.returns('mail.message', lambda value: value.id)
def message_post(self, **kwargs):
if self.env.context.get('mark_so_as_sent'):
self.filtered(lambda o: o.state == 'draft').with_context(tracking_disable=True).write({'state': 'sent'})
return super(SaleOrder, self.with_context(mail_post_autofollow=self.env.context.get('mail_post_autofollow', True))).message_post(**kwargs)
def _sms_get_number_fields(self):
""" No phone or mobile field is available on sale model. Instead SMS will
fallback on partner-based computation using ``_sms_get_partner_fields``. """
return []
def _sms_get_partner_fields(self):
return ['partner_id']
def _send_order_confirmation_mail(self):
if self.env.su:
# sending mail in sudo was meant for it being sent from superuser
self = self.with_user(SUPERUSER_ID)
for order in self:
template_id = order._find_mail_template(force_confirmation_template=True)
if template_id:
order.with_context(force_send=True).message_post_with_template(template_id, composition_mode='comment', email_layout_xmlid="mail.mail_notification_paynow")
def action_done(self):
for order in self:
tx = order.sudo().transaction_ids._get_last()
if tx and tx.state == 'pending' and tx.acquirer_id.provider == 'transfer':
tx._set_done()
tx.write({'is_post_processed': True})
return self.write({'state': 'done'})
def action_unlock(self):
self.write({'state': 'sale'})
def _action_confirm(self):
""" Implementation of additionnal mecanism of Sales Order confirmation.
This method should be extended when the confirmation should generated
other documents. In this method, the SO are in 'sale' state (not yet 'done').
"""
# create an analytic account if at least an expense product
for order in self:
if any(expense_policy not in [False, 'no'] for expense_policy in order.order_line.mapped('product_id.expense_policy')):
if not order.analytic_account_id:
order._create_analytic_account()
return True
def _prepare_confirmation_values(self):
return {
'state': 'sale',
'date_order': fields.Datetime.now()
}
def action_confirm(self):
if self._get_forbidden_state_confirm() & set(self.mapped('state')):
raise UserError(_(
'It is not allowed to confirm an order in the following states: %s'
) % (', '.join(self._get_forbidden_state_confirm())))
for order in self.filtered(lambda order: order.partner_id not in order.message_partner_ids):
order.message_subscribe([order.partner_id.id])
self.write(self._prepare_confirmation_values())
# Context key 'default_name' is sometimes propagated up to here.
# We don't need it and it creates issues in the creation of linked records.
context = self._context.copy()
context.pop('default_name', None)
self.with_context(context)._action_confirm()
if self.env.user.has_group('sale.group_auto_done_setting'):
self.action_done()
return True
def _get_forbidden_state_confirm(self):
return {'done', 'cancel'}
def _prepare_analytic_account_data(self, prefix=None):
"""
Prepare method for analytic account data
:param prefix: The prefix of the to-be-created analytic account name
:type prefix: string
:return: dictionary of value for new analytic account creation
"""
name = self.name
if prefix:
name = prefix + ": " + self.name
return {
'name': name,
'code': self.client_order_ref,
'company_id': self.company_id.id,
'partner_id': self.partner_id.id
}
def _create_analytic_account(self, prefix=None):
for order in self:
analytic = self.env['account.analytic.account'].create(order._prepare_analytic_account_data(prefix))
order.analytic_account_id = analytic
def has_to_be_signed(self, include_draft=False):
return (self.state == 'sent' or (self.state == 'draft' and include_draft)) and not self.is_expired and self.require_signature and not self.signature
def has_to_be_paid(self, include_draft=False):
transaction = self.get_portal_last_transaction()
return (self.state == 'sent' or (self.state == 'draft' and include_draft)) and not self.is_expired and self.require_payment and transaction.state != 'done' and self.amount_total
def _notify_get_groups(self, msg_vals=None):
""" Give access button to users and portal customer as portal is integrated
in sale. Customer and portal group have probably no right to see
the document so they don't have the access button. """
groups = super(SaleOrder, self)._notify_get_groups(msg_vals=msg_vals)
self.ensure_one()
if self.state not in ('draft', 'cancel'):
for group_name, group_method, group_data in groups:
if group_name not in ('customer', 'portal'):
group_data['has_button_access'] = True
return groups
def preview_sale_order(self):
self.ensure_one()
return {
'type': 'ir.actions.act_url',
'target': 'self',
'url': self.get_portal_url(),
}
def _force_lines_to_invoice_policy_order(self):
for line in self.order_line:
if self.state in ['sale', 'done']:
line.qty_to_invoice = line.product_uom_qty - line.qty_invoiced
else:
line.qty_to_invoice = 0
def payment_action_capture(self):
""" Capture all transactions linked to this sale order. """
payment_utils.check_rights_on_recordset(self)
# In sudo mode because we need to be able to read on acquirer fields.
self.authorized_transaction_ids.sudo().action_capture()
def payment_action_void(self):
""" Void all transactions linked to this sale order. """
payment_utils.check_rights_on_recordset(self)
# In sudo mode because we need to be able to read on acquirer fields.
self.authorized_transaction_ids.sudo().action_void()
def get_portal_last_transaction(self):
self.ensure_one()
return self.transaction_ids._get_last()
@api.model
def _get_customer_lead(self, product_tmpl_id):
return False
def _get_report_base_filename(self):
self.ensure_one()
return '%s %s' % (self.type_name, self.name)
def _get_portal_return_action(self):
""" Return the action used to display orders when returning from customer portal. """
self.ensure_one()
return self.env.ref('sale.action_quotations_with_onboarding')
@api.model
def _prepare_down_payment_section_line(self, **optional_values):
"""
Prepare the dict of values to create a new down payment section for a sales order line.
:param optional_values: any parameter that should be added to the returned down payment section
"""
context = {'lang': self.partner_id.lang}
down_payments_section_line = {
'display_type': 'line_section',
'name': _('Down Payments'),
'product_id': False,
'product_uom_id': False,
'quantity': 0,
'discount': 0,
'price_unit': 0,
'account_id': False
}
del context
if optional_values:
down_payments_section_line.update(optional_values)
return down_payments_section_line
def add_option_to_order_with_taxcloud(self):
self.ensure_one()
| 49.980392 | 56,078 |
11,779 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_is_zero
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
sale_line_ids = fields.Many2many(
'sale.order.line',
'sale_order_line_invoice_rel',
'invoice_line_id', 'order_line_id',
string='Sales Order Lines', readonly=True, copy=False)
def _copy_data_extend_business_fields(self, values):
# OVERRIDE to copy the 'sale_line_ids' field as well.
super(AccountMoveLine, self)._copy_data_extend_business_fields(values)
values['sale_line_ids'] = [(6, None, self.sale_line_ids.ids)]
def _prepare_analytic_line(self):
""" Note: This method is called only on the move.line that having an analytic account, and
so that should create analytic entries.
"""
values_list = super(AccountMoveLine, self)._prepare_analytic_line()
# filter the move lines that can be reinvoiced: a cost (negative amount) analytic line without SO line but with a product can be reinvoiced
move_to_reinvoice = self.env['account.move.line']
for index, move_line in enumerate(self):
values = values_list[index]
if 'so_line' not in values:
if move_line._sale_can_be_reinvoice():
move_to_reinvoice |= move_line
# insert the sale line in the create values of the analytic entries
if move_to_reinvoice:
map_sale_line_per_move = move_to_reinvoice._sale_create_reinvoice_sale_line()
for values in values_list:
sale_line = map_sale_line_per_move.get(values.get('move_id'))
if sale_line:
values['so_line'] = sale_line.id
return values_list
def _sale_can_be_reinvoice(self):
""" determine if the generated analytic line should be reinvoiced or not.
For Vendor Bill flow, if the product has a 'erinvoice policy' and is a cost, then we will find the SO on which reinvoice the AAL
"""
self.ensure_one()
if self.sale_line_ids:
return False
uom_precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
return float_compare(self.credit or 0.0, self.debit or 0.0, precision_digits=uom_precision_digits) != 1 and self.product_id.expense_policy not in [False, 'no']
def _sale_create_reinvoice_sale_line(self):
sale_order_map = self._sale_determine_order()
sale_line_values_to_create = [] # the list of creation values of sale line to create.
existing_sale_line_cache = {} # in the sales_price-delivery case, we can reuse the same sale line. This cache will avoid doing a search each time the case happen
# `map_move_sale_line` is map where
# - key is the move line identifier
# - value is either a sale.order.line record (existing case), or an integer representing the index of the sale line to create in
# the `sale_line_values_to_create` (not existing case, which will happen more often than the first one).
map_move_sale_line = {}
for move_line in self:
sale_order = sale_order_map.get(move_line.id)
# no reinvoice as no sales order was found
if not sale_order:
continue
# raise if the sale order is not currenlty open
if sale_order.state != 'sale':
message_unconfirmed = _('The Sales Order %s linked to the Analytic Account %s must be validated before registering expenses.')
messages = {
'draft': message_unconfirmed,
'sent': message_unconfirmed,
'done': _('The Sales Order %s linked to the Analytic Account %s is currently locked. You cannot register an expense on a locked Sales Order. Please create a new SO linked to this Analytic Account.'),
'cancel': _('The Sales Order %s linked to the Analytic Account %s is cancelled. You cannot register an expense on a cancelled Sales Order.'),
}
raise UserError(messages[sale_order.state] % (sale_order.name, sale_order.analytic_account_id.name))
price = move_line._sale_get_invoice_price(sale_order)
# find the existing sale.line or keep its creation values to process this in batch
sale_line = None
if move_line.product_id.expense_policy == 'sales_price' and move_line.product_id.invoice_policy == 'delivery': # for those case only, we can try to reuse one
map_entry_key = (sale_order.id, move_line.product_id.id, price) # cache entry to limit the call to search
sale_line = existing_sale_line_cache.get(map_entry_key)
if sale_line: # already search, so reuse it. sale_line can be sale.order.line record or index of a "to create values" in `sale_line_values_to_create`
map_move_sale_line[move_line.id] = sale_line
existing_sale_line_cache[map_entry_key] = sale_line
else: # search for existing sale line
sale_line = self.env['sale.order.line'].search([
('order_id', '=', sale_order.id),
('price_unit', '=', price),
('product_id', '=', move_line.product_id.id),
('is_expense', '=', True),
], limit=1)
if sale_line: # found existing one, so keep the browse record
map_move_sale_line[move_line.id] = existing_sale_line_cache[map_entry_key] = sale_line
else: # should be create, so use the index of creation values instead of browse record
# save value to create it
sale_line_values_to_create.append(move_line._sale_prepare_sale_line_values(sale_order, price))
# store it in the cache of existing ones
existing_sale_line_cache[map_entry_key] = len(sale_line_values_to_create) - 1 # save the index of the value to create sale line
# store it in the map_move_sale_line map
map_move_sale_line[move_line.id] = len(sale_line_values_to_create) - 1 # save the index of the value to create sale line
else: # save its value to create it anyway
sale_line_values_to_create.append(move_line._sale_prepare_sale_line_values(sale_order, price))
map_move_sale_line[move_line.id] = len(sale_line_values_to_create) - 1 # save the index of the value to create sale line
# create the sale lines in batch
new_sale_lines = self.env['sale.order.line'].create(sale_line_values_to_create)
for sol in new_sale_lines:
sol._onchange_discount()
# build result map by replacing index with newly created record of sale.order.line
result = {}
for move_line_id, unknown_sale_line in map_move_sale_line.items():
if isinstance(unknown_sale_line, int): # index of newly created sale line
result[move_line_id] = new_sale_lines[unknown_sale_line]
elif isinstance(unknown_sale_line, models.BaseModel): # already record of sale.order.line
result[move_line_id] = unknown_sale_line
return result
def _sale_determine_order(self):
""" Get the mapping of move.line with the sale.order record on which its analytic entries should be reinvoiced
:return a dict where key is the move line id, and value is sale.order record (or None).
"""
analytic_accounts = self.mapped('analytic_account_id')
# link the analytic account with its open SO by creating a map: {AA.id: sale.order}, if we find some analytic accounts
mapping = {}
if analytic_accounts: # first, search for the open sales order
sale_orders = self.env['sale.order'].search([('analytic_account_id', 'in', analytic_accounts.ids), ('state', '=', 'sale')], order='create_date DESC')
for sale_order in sale_orders:
mapping[sale_order.analytic_account_id.id] = sale_order
analytic_accounts_without_open_order = analytic_accounts.filtered(lambda account: not mapping.get(account.id))
if analytic_accounts_without_open_order: # then, fill the blank with not open sales orders
sale_orders = self.env['sale.order'].search([('analytic_account_id', 'in', analytic_accounts_without_open_order.ids)], order='create_date DESC')
for sale_order in sale_orders:
mapping[sale_order.analytic_account_id.id] = sale_order
# map of AAL index with the SO on which it needs to be reinvoiced. Maybe be None if no SO found
return {move_line.id: mapping.get(move_line.analytic_account_id.id) for move_line in self}
def _sale_prepare_sale_line_values(self, order, price):
""" Generate the sale.line creation value from the current move line """
self.ensure_one()
last_so_line = self.env['sale.order.line'].search([('order_id', '=', order.id)], order='sequence desc', limit=1)
last_sequence = last_so_line.sequence + 1 if last_so_line else 100
fpos = order.fiscal_position_id or order.fiscal_position_id.get_fiscal_position(order.partner_id.id)
product_taxes = self.product_id.taxes_id.filtered(lambda tax: tax.company_id == order.company_id)
taxes = fpos.map_tax(product_taxes)
return {
'order_id': order.id,
'name': self.name,
'sequence': last_sequence,
'price_unit': price,
'tax_id': [x.id for x in taxes],
'discount': 0.0,
'product_id': self.product_id.id,
'product_uom': self.product_uom_id.id,
'product_uom_qty': 0.0,
'is_expense': True,
}
def _sale_get_invoice_price(self, order):
""" Based on the current move line, compute the price to reinvoice the analytic line that is going to be created (so the
price of the sale line).
"""
self.ensure_one()
unit_amount = self.quantity
amount = (self.credit or 0.0) - (self.debit or 0.0)
if self.product_id.expense_policy == 'sales_price':
return self.product_id.with_context(
partner=order.partner_id,
date_order=order.date_order,
pricelist=order.pricelist_id.id,
uom=self.product_uom_id.id
).price
uom_precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
if float_is_zero(unit_amount, precision_digits=uom_precision_digits):
return 0.0
# Prevent unnecessary currency conversion that could be impacted by exchange rate
# fluctuations
if self.company_id.currency_id and amount and self.company_id.currency_id == order.currency_id:
return abs(amount / unit_amount)
price_unit = abs(amount / unit_amount)
currency_id = self.company_id.currency_id
if currency_id and currency_id != order.currency_id:
price_unit = currency_id._convert(price_unit, order.currency_id, order.company_id, order.date_order or fields.Date.today())
return price_unit
def _get_downpayment_lines(self):
# OVERRIDE
return self.sale_line_ids.filtered('is_downpayment').invoice_lines.filtered(lambda line: line.move_id._is_downpayment())
| 55.561321 | 11,779 |
48,436 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools.misc import get_lang
from odoo.osv import expression
from odoo.tools import float_is_zero, float_compare, float_round
class SaleOrderLine(models.Model):
_name = 'sale.order.line'
_description = 'Sales Order Line'
_order = 'order_id, sequence, id'
_check_company_auto = True
@api.depends('state', 'product_uom_qty', 'qty_delivered', 'qty_to_invoice', 'qty_invoiced')
def _compute_invoice_status(self):
"""
Compute the invoice status of a SO line. Possible statuses:
- no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to
invoice. This is also hte default value if the conditions of no other status is met.
- to invoice: we refer to the quantity to invoice of the line. Refer to method
`_get_to_invoice_qty()` for more information on how this quantity is calculated.
- upselling: this is possible only for a product invoiced on ordered quantities for which
we delivered more than expected. The could arise if, for example, a project took more
time than expected but we decided not to invoice the extra cost to the client. This
occurs onyl in state 'sale', so that when a SO is set to done, the upselling opportunity
is removed from the list.
- invoiced: the quantity invoiced is larger or equal to the quantity ordered.
"""
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for line in self:
if line.state not in ('sale', 'done'):
line.invoice_status = 'no'
elif line.is_downpayment and line.untaxed_amount_to_invoice == 0:
line.invoice_status = 'invoiced'
elif not float_is_zero(line.qty_to_invoice, precision_digits=precision):
line.invoice_status = 'to invoice'
elif line.state == 'sale' and line.product_id.invoice_policy == 'order' and\
line.product_uom_qty >= 0.0 and\
float_compare(line.qty_delivered, line.product_uom_qty, precision_digits=precision) == 1:
line.invoice_status = 'upselling'
elif float_compare(line.qty_invoiced, line.product_uom_qty, precision_digits=precision) >= 0:
line.invoice_status = 'invoiced'
else:
line.invoice_status = 'no'
def _expected_date(self):
self.ensure_one()
order_date = fields.Datetime.from_string(self.order_id.date_order if self.order_id.date_order and self.order_id.state in ['sale', 'done'] else fields.Datetime.now())
return order_date + timedelta(days=self.customer_lead or 0.0)
@api.depends('product_uom_qty', 'discount', 'price_unit', 'tax_id')
def _compute_amount(self):
"""
Compute the amounts of the SO line.
"""
for line in self:
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_id, partner=line.order_id.partner_shipping_id)
line.update({
'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])),
'price_total': taxes['total_included'],
'price_subtotal': taxes['total_excluded'],
})
@api.depends('product_id', 'order_id.state', 'qty_invoiced', 'qty_delivered')
def _compute_product_updatable(self):
for line in self:
if line.state in ['done', 'cancel'] or (line.state == 'sale' and (line.qty_invoiced > 0 or line.qty_delivered > 0)):
line.product_updatable = False
else:
line.product_updatable = True
# no trigger product_id.invoice_policy to avoid retroactively changing SO
@api.depends('qty_invoiced', 'qty_delivered', 'product_uom_qty', 'order_id.state')
def _get_to_invoice_qty(self):
"""
Compute the quantity to invoice. If the invoice policy is order, the quantity to invoice is
calculated from the ordered quantity. Otherwise, the quantity delivered is used.
"""
for line in self:
if line.order_id.state in ['sale', 'done']:
if line.product_id.invoice_policy == 'order':
line.qty_to_invoice = line.product_uom_qty - line.qty_invoiced
else:
line.qty_to_invoice = line.qty_delivered - line.qty_invoiced
else:
line.qty_to_invoice = 0
@api.depends('invoice_lines.move_id.state', 'invoice_lines.quantity', 'untaxed_amount_to_invoice')
def _compute_qty_invoiced(self):
"""
Compute the quantity invoiced. If case of a refund, the quantity invoiced is decreased. Note
that this is the case only if the refund is generated from the SO and that is intentional: if
a refund made would automatically decrease the invoiced quantity, then there is a risk of reinvoicing
it automatically, which may not be wanted at all. That's why the refund has to be created from the SO
"""
for line in self:
qty_invoiced = 0.0
for invoice_line in line._get_invoice_lines():
if invoice_line.move_id.state != 'cancel' or invoice_line.move_id.payment_state == 'invoicing_legacy':
if invoice_line.move_id.move_type == 'out_invoice':
qty_invoiced += invoice_line.product_uom_id._compute_quantity(invoice_line.quantity, line.product_uom)
elif invoice_line.move_id.move_type == 'out_refund':
qty_invoiced -= invoice_line.product_uom_id._compute_quantity(invoice_line.quantity, line.product_uom)
line.qty_invoiced = qty_invoiced
def _get_invoice_lines(self):
self.ensure_one()
if self._context.get('accrual_entry_date'):
return self.invoice_lines.filtered(
lambda l: l.move_id.invoice_date and l.move_id.invoice_date <= self._context['accrual_entry_date']
)
else:
return self.invoice_lines
@api.depends('price_unit', 'discount')
def _compute_price_reduce(self):
for line in self:
line.price_reduce = line.price_unit * (1.0 - line.discount / 100.0)
@api.depends('price_total', 'product_uom_qty')
def _compute_price_reduce_taxinc(self):
for line in self:
line.price_reduce_taxinc = line.price_total / line.product_uom_qty if line.product_uom_qty else 0.0
@api.depends('price_subtotal', 'product_uom_qty')
def _compute_price_reduce_taxexcl(self):
for line in self:
line.price_reduce_taxexcl = line.price_subtotal / line.product_uom_qty if line.product_uom_qty else 0.0
def _compute_tax_id(self):
for line in self:
line = line.with_company(line.company_id)
fpos = line.order_id.fiscal_position_id or line.order_id.fiscal_position_id.get_fiscal_position(line.order_partner_id.id)
# If company_id is set, always filter taxes by the company
taxes = line.product_id.taxes_id.filtered(lambda t: t.company_id == line.env.company)
line.tax_id = fpos.map_tax(taxes)
@api.model
def _prepare_add_missing_fields(self, values):
""" Deduce missing required fields from the onchange """
res = {}
onchange_fields = ['name', 'price_unit', 'product_uom', 'tax_id']
if values.get('order_id') and values.get('product_id') and any(f not in values for f in onchange_fields):
line = self.new(values)
line.product_id_change()
for field in onchange_fields:
if field not in values:
res[field] = line._fields[field].convert_to_write(line[field], line)
return res
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if values.get('display_type', self.default_get(['display_type'])['display_type']):
values.update(product_id=False, price_unit=0, product_uom_qty=0, product_uom=False, customer_lead=0)
values.update(self._prepare_add_missing_fields(values))
lines = super().create(vals_list)
for line in lines:
if line.product_id and line.order_id.state == 'sale':
msg = _("Extra line with %s", line.product_id.display_name)
line.order_id.message_post(body=msg)
# create an analytic account if at least an expense product
if line.product_id.expense_policy not in [False, 'no'] and not line.order_id.analytic_account_id:
line.order_id._create_analytic_account()
return lines
_sql_constraints = [
('accountable_required_fields',
"CHECK(display_type IS NOT NULL OR (product_id IS NOT NULL AND product_uom IS NOT NULL))",
"Missing required fields on accountable sale order line."),
('non_accountable_null_fields',
"CHECK(display_type IS NULL OR (product_id IS NULL AND price_unit = 0 AND product_uom_qty = 0 AND product_uom IS NULL AND customer_lead = 0))",
"Forbidden values on non-accountable sale order line"),
]
def _update_line_quantity(self, values):
orders = self.mapped('order_id')
for order in orders:
order_lines = self.filtered(lambda x: x.order_id == order)
msg = "<b>" + _("The ordered quantity has been updated.") + "</b><ul>"
for line in order_lines:
msg += "<li> %s: <br/>" % line.product_id.display_name
msg += _(
"Ordered Quantity: %(old_qty)s -> %(new_qty)s",
old_qty=line.product_uom_qty,
new_qty=values["product_uom_qty"]
) + "<br/>"
if line.product_id.type in ('consu', 'product'):
msg += _("Delivered Quantity: %s", line.qty_delivered) + "<br/>"
msg += _("Invoiced Quantity: %s", line.qty_invoiced) + "<br/>"
msg += "</ul>"
order.message_post(body=msg)
def write(self, values):
if 'display_type' in values and self.filtered(lambda line: line.display_type != values.get('display_type')):
raise UserError(_("You cannot change the type of a sale order line. Instead you should delete the current line and create a new line of the proper type."))
if 'product_uom_qty' in values:
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
self.filtered(
lambda r: r.state == 'sale' and float_compare(r.product_uom_qty, values['product_uom_qty'], precision_digits=precision) != 0)._update_line_quantity(values)
# Prevent writing on a locked SO.
protected_fields = self._get_protected_fields()
if 'done' in self.mapped('order_id.state') and any(f in values.keys() for f in protected_fields):
protected_fields_modified = list(set(protected_fields) & set(values.keys()))
fields = self.env['ir.model.fields'].search([
('name', 'in', protected_fields_modified), ('model', '=', self._name)
])
raise UserError(
_('It is forbidden to modify the following fields in a locked order:\n%s')
% '\n'.join(fields.mapped('field_description'))
)
result = super(SaleOrderLine, self).write(values)
return result
order_id = fields.Many2one('sale.order', string='Order Reference', required=True, ondelete='cascade', index=True, copy=False)
name = fields.Text(string='Description', required=True)
sequence = fields.Integer(string='Sequence', default=10)
invoice_lines = fields.Many2many('account.move.line', 'sale_order_line_invoice_rel', 'order_line_id', 'invoice_line_id', string='Invoice Lines', copy=False)
invoice_status = fields.Selection([
('upselling', 'Upselling Opportunity'),
('invoiced', 'Fully Invoiced'),
('to invoice', 'To Invoice'),
('no', 'Nothing to Invoice')
], string='Invoice Status', compute='_compute_invoice_status', store=True, default='no')
price_unit = fields.Float('Unit Price', required=True, digits='Product Price', default=0.0)
price_subtotal = fields.Monetary(compute='_compute_amount', string='Subtotal', store=True)
price_tax = fields.Float(compute='_compute_amount', string='Total Tax', store=True)
price_total = fields.Monetary(compute='_compute_amount', string='Total', store=True)
price_reduce = fields.Float(compute='_compute_price_reduce', string='Price Reduce', digits='Product Price', store=True)
tax_id = fields.Many2many('account.tax', string='Taxes', context={'active_test': False}, check_company=True)
price_reduce_taxinc = fields.Monetary(compute='_compute_price_reduce_taxinc', string='Price Reduce Tax inc', store=True)
price_reduce_taxexcl = fields.Monetary(compute='_compute_price_reduce_taxexcl', string='Price Reduce Tax excl', store=True)
discount = fields.Float(string='Discount (%)', digits='Discount', default=0.0)
product_id = fields.Many2one(
'product.product', string='Product', domain="[('sale_ok', '=', True), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
change_default=True, ondelete='restrict', check_company=True) # Unrequired company
product_template_id = fields.Many2one(
'product.template', string='Product Template',
related="product_id.product_tmpl_id", domain=[('sale_ok', '=', True)])
product_updatable = fields.Boolean(compute='_compute_product_updatable', string='Can Edit Product', default=True)
product_uom_qty = fields.Float(string='Quantity', digits='Product Unit of Measure', required=True, default=1.0)
product_uom = fields.Many2one('uom.uom', string='Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]", ondelete="restrict")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
product_uom_readonly = fields.Boolean(compute='_compute_product_uom_readonly')
product_custom_attribute_value_ids = fields.One2many('product.attribute.custom.value', 'sale_order_line_id', string="Custom Values", copy=True)
# M2M holding the values of product.attribute with create_variant field set to 'no_variant'
# It allows keeping track of the extra_price associated to those attribute values and add them to the SO line description
product_no_variant_attribute_value_ids = fields.Many2many('product.template.attribute.value', string="Extra Values", ondelete='restrict')
qty_delivered_method = fields.Selection([
('manual', 'Manual'),
('analytic', 'Analytic From Expenses')
], string="Method to update delivered qty", compute='_compute_qty_delivered_method', store=True,
help="According to product configuration, the delivered quantity can be automatically computed by mechanism :\n"
" - Manual: the quantity is set manually on the line\n"
" - Analytic From expenses: the quantity is the quantity sum from posted expenses\n"
" - Timesheet: the quantity is the sum of hours recorded on tasks linked to this sale line\n"
" - Stock Moves: the quantity comes from confirmed pickings\n")
qty_delivered = fields.Float('Delivered Quantity', copy=False, compute='_compute_qty_delivered', inverse='_inverse_qty_delivered', store=True, digits='Product Unit of Measure', default=0.0)
qty_delivered_manual = fields.Float('Delivered Manually', copy=False, digits='Product Unit of Measure', default=0.0)
qty_to_invoice = fields.Float(
compute='_get_to_invoice_qty', string='To Invoice Quantity', store=True,
digits='Product Unit of Measure')
qty_invoiced = fields.Float(
compute='_compute_qty_invoiced', string='Invoiced Quantity', store=True,
digits='Product Unit of Measure')
untaxed_amount_invoiced = fields.Monetary("Untaxed Invoiced Amount", compute='_compute_untaxed_amount_invoiced', store=True)
untaxed_amount_to_invoice = fields.Monetary("Untaxed Amount To Invoice", compute='_compute_untaxed_amount_to_invoice', store=True)
salesman_id = fields.Many2one(related='order_id.user_id', store=True, string='Salesperson')
currency_id = fields.Many2one(related='order_id.currency_id', depends=['order_id.currency_id'], store=True, string='Currency')
company_id = fields.Many2one(related='order_id.company_id', string='Company', store=True, index=True)
order_partner_id = fields.Many2one(related='order_id.partner_id', store=True, string='Customer', index=True)
analytic_tag_ids = fields.Many2many(
'account.analytic.tag', string='Analytic Tags',
compute='_compute_analytic_tag_ids', store=True, readonly=False,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
analytic_line_ids = fields.One2many('account.analytic.line', 'so_line', string="Analytic lines")
is_expense = fields.Boolean('Is expense', help="Is true if the sales order line comes from an expense or a vendor bills")
is_downpayment = fields.Boolean(
string="Is a down payment", help="Down payments are made when creating invoices from a sales order."
" They are not copied when duplicating a sales order.")
state = fields.Selection(
related='order_id.state', string='Order Status', copy=False, store=True)
customer_lead = fields.Float(
'Lead Time', required=True, default=0.0,
help="Number of days between the order confirmation and the shipping of the products to the customer")
display_type = fields.Selection([
('line_section', "Section"),
('line_note', "Note")], default=False, help="Technical field for UX purpose.")
product_packaging_id = fields.Many2one('product.packaging', string='Packaging', default=False, domain="[('sales', '=', True), ('product_id','=',product_id)]", check_company=True)
product_packaging_qty = fields.Float('Packaging Quantity')
@api.depends('state')
def _compute_product_uom_readonly(self):
for line in self:
line.product_uom_readonly = line.ids and line.state in ['sale', 'done', 'cancel']
@api.depends('is_expense')
def _compute_qty_delivered_method(self):
""" Sale module compute delivered qty for product [('type', 'in', ['consu']), ('service_type', '=', 'manual')]
- consu + expense_policy : analytic (sum of analytic unit_amount)
- consu + no expense_policy : manual (set manually on SOL)
- service (+ service_type='manual', the only available option) : manual
This is true when only sale is installed: sale_stock redifine the behavior for 'consu' type,
and sale_timesheet implements the behavior of 'service' + service_type=timesheet.
"""
for line in self:
if line.is_expense:
line.qty_delivered_method = 'analytic'
else: # service and consu
line.qty_delivered_method = 'manual'
@api.depends('qty_delivered_method', 'qty_delivered_manual', 'analytic_line_ids.so_line', 'analytic_line_ids.unit_amount', 'analytic_line_ids.product_uom_id')
def _compute_qty_delivered(self):
""" This method compute the delivered quantity of the SO lines: it covers the case provide by sale module, aka
expense/vendor bills (sum of unit_amount of AAL), and manual case.
This method should be overridden to provide other way to automatically compute delivered qty. Overrides should
take their concerned so lines, compute and set the `qty_delivered` field, and call super with the remaining
records.
"""
# compute for analytic lines
lines_by_analytic = self.filtered(lambda sol: sol.qty_delivered_method == 'analytic')
mapping = lines_by_analytic._get_delivered_quantity_by_analytic([('amount', '<=', 0.0)])
for so_line in lines_by_analytic:
so_line.qty_delivered = mapping.get(so_line.id or so_line._origin.id, 0.0)
# compute for manual lines
for line in self:
if line.qty_delivered_method == 'manual':
line.qty_delivered = line.qty_delivered_manual or 0.0
def _get_delivered_quantity_by_analytic(self, additional_domain):
""" Compute and write the delivered quantity of current SO lines, based on their related
analytic lines.
:param additional_domain: domain to restrict AAL to include in computation (required since timesheet is an AAL with a project ...)
"""
result = {}
# avoid recomputation if no SO lines concerned
if not self:
return result
# group analytic lines by product uom and so line
domain = expression.AND([[('so_line', 'in', self.ids)], additional_domain])
data = self.env['account.analytic.line'].read_group(
domain,
['so_line', 'unit_amount', 'product_uom_id'], ['product_uom_id', 'so_line'], lazy=False
)
# convert uom and sum all unit_amount of analytic lines to get the delivered qty of SO lines
# browse so lines and product uoms here to make them share the same prefetch
lines = self.browse([item['so_line'][0] for item in data])
lines_map = {line.id: line for line in lines}
product_uom_ids = [item['product_uom_id'][0] for item in data if item['product_uom_id']]
product_uom_map = {uom.id: uom for uom in self.env['uom.uom'].browse(product_uom_ids)}
for item in data:
if not item['product_uom_id']:
continue
so_line_id = item['so_line'][0]
so_line = lines_map[so_line_id]
result.setdefault(so_line_id, 0.0)
uom = product_uom_map.get(item['product_uom_id'][0])
if so_line.product_uom.category_id == uom.category_id:
qty = uom._compute_quantity(item['unit_amount'], so_line.product_uom, rounding_method='HALF-UP')
else:
qty = item['unit_amount']
result[so_line_id] += qty
return result
@api.onchange('qty_delivered')
def _inverse_qty_delivered(self):
""" When writing on qty_delivered, if the value should be modify manually (`qty_delivered_method` = 'manual' only),
then we put the value in `qty_delivered_manual`. Otherwise, `qty_delivered_manual` should be False since the
delivered qty is automatically compute by other mecanisms.
"""
for line in self:
if line.qty_delivered_method == 'manual':
line.qty_delivered_manual = line.qty_delivered
else:
line.qty_delivered_manual = 0.0
@api.onchange('product_id', 'product_uom_qty', 'product_uom')
def _onchange_suggest_packaging(self):
# remove packaging if not match the product
if self.product_packaging_id.product_id != self.product_id:
self.product_packaging_id = False
# suggest biggest suitable packaging
if self.product_id and self.product_uom_qty and self.product_uom:
self.product_packaging_id = self.product_id.packaging_ids.filtered('sales')._find_suitable_product_packaging(self.product_uom_qty, self.product_uom) or self.product_packaging_id
@api.onchange('product_packaging_id')
def _onchange_product_packaging_id(self):
if self.product_packaging_id and self.product_uom_qty:
newqty = self.product_packaging_id._check_qty(self.product_uom_qty, self.product_uom, "UP")
if float_compare(newqty, self.product_uom_qty, precision_rounding=self.product_uom.rounding) != 0:
return {
'warning': {
'title': _('Warning'),
'message': _(
"This product is packaged by %(pack_size).2f %(pack_name)s. You should sell %(quantity).2f %(unit)s.",
pack_size=self.product_packaging_id.qty,
pack_name=self.product_id.uom_id.name,
quantity=newqty,
unit=self.product_uom.name
),
},
}
@api.onchange('product_packaging_id', 'product_uom', 'product_uom_qty')
def _onchange_update_product_packaging_qty(self):
if not self.product_packaging_id:
self.product_packaging_qty = False
else:
packaging_uom = self.product_packaging_id.product_uom_id
packaging_uom_qty = self.product_uom._compute_quantity(self.product_uom_qty, packaging_uom)
self.product_packaging_qty = float_round(packaging_uom_qty / self.product_packaging_id.qty, precision_rounding=packaging_uom.rounding)
@api.onchange('product_packaging_qty')
def _onchange_product_packaging_qty(self):
if self.product_packaging_id:
packaging_uom = self.product_packaging_id.product_uom_id
qty_per_packaging = self.product_packaging_id.qty
product_uom_qty = packaging_uom._compute_quantity(self.product_packaging_qty * qty_per_packaging, self.product_uom)
if float_compare(product_uom_qty, self.product_uom_qty, precision_rounding=self.product_uom.rounding) != 0:
self.product_uom_qty = product_uom_qty
@api.depends('invoice_lines', 'invoice_lines.price_total', 'invoice_lines.move_id.state', 'invoice_lines.move_id.move_type')
def _compute_untaxed_amount_invoiced(self):
""" Compute the untaxed amount already invoiced from the sale order line, taking the refund attached
the so line into account. This amount is computed as
SUM(inv_line.price_subtotal) - SUM(ref_line.price_subtotal)
where
`inv_line` is a customer invoice line linked to the SO line
`ref_line` is a customer credit note (refund) line linked to the SO line
"""
for line in self:
amount_invoiced = 0.0
for invoice_line in line._get_invoice_lines():
if invoice_line.move_id.state == 'posted':
invoice_date = invoice_line.move_id.invoice_date or fields.Date.today()
if invoice_line.move_id.move_type == 'out_invoice':
amount_invoiced += invoice_line.currency_id._convert(invoice_line.price_subtotal, line.currency_id, line.company_id, invoice_date)
elif invoice_line.move_id.move_type == 'out_refund':
amount_invoiced -= invoice_line.currency_id._convert(invoice_line.price_subtotal, line.currency_id, line.company_id, invoice_date)
line.untaxed_amount_invoiced = amount_invoiced
@api.depends('state', 'price_reduce', 'product_id', 'untaxed_amount_invoiced', 'qty_delivered', 'product_uom_qty')
def _compute_untaxed_amount_to_invoice(self):
""" Total of remaining amount to invoice on the sale order line (taxes excl.) as
total_sol - amount already invoiced
where Total_sol depends on the invoice policy of the product.
Note: Draft invoice are ignored on purpose, the 'to invoice' amount should
come only from the SO lines.
"""
for line in self:
amount_to_invoice = 0.0
if line.state in ['sale', 'done']:
# Note: do not use price_subtotal field as it returns zero when the ordered quantity is
# zero. It causes problem for expense line (e.i.: ordered qty = 0, deli qty = 4,
# price_unit = 20 ; subtotal is zero), but when you can invoice the line, you see an
# amount and not zero. Since we compute untaxed amount, we can use directly the price
# reduce (to include discount) without using `compute_all()` method on taxes.
price_subtotal = 0.0
uom_qty_to_consider = line.qty_delivered if line.product_id.invoice_policy == 'delivery' else line.product_uom_qty
price_reduce = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
price_subtotal = price_reduce * uom_qty_to_consider
if len(line.tax_id.filtered(lambda tax: tax.price_include)) > 0:
# As included taxes are not excluded from the computed subtotal, `compute_all()` method
# has to be called to retrieve the subtotal without them.
# `price_reduce_taxexcl` cannot be used as it is computed from `price_subtotal` field. (see upper Note)
price_subtotal = line.tax_id.compute_all(
price_reduce,
currency=line.order_id.currency_id,
quantity=uom_qty_to_consider,
product=line.product_id,
partner=line.order_id.partner_shipping_id)['total_excluded']
inv_lines = line._get_invoice_lines()
if any(inv_lines.mapped(lambda l: l.discount != line.discount)):
# In case of re-invoicing with different discount we try to calculate manually the
# remaining amount to invoice
amount = 0
for l in inv_lines:
if len(l.tax_ids.filtered(lambda tax: tax.price_include)) > 0:
amount += l.tax_ids.compute_all(l.currency_id._convert(l.price_unit, line.currency_id, line.company_id, l.date or fields.Date.today(), round=False) * l.quantity)['total_excluded']
else:
amount += l.currency_id._convert(l.price_unit, line.currency_id, line.company_id, l.date or fields.Date.today(), round=False) * l.quantity
amount_to_invoice = max(price_subtotal - amount, 0)
else:
amount_to_invoice = price_subtotal - line.untaxed_amount_invoiced
line.untaxed_amount_to_invoice = amount_to_invoice
@api.depends('product_id', 'order_id.date_order', 'order_id.partner_id')
def _compute_analytic_tag_ids(self):
for line in self:
if not line.display_type and line.state == 'draft':
default_analytic_account = line.env['account.analytic.default'].sudo().account_get(
product_id=line.product_id.id,
partner_id=line.order_id.partner_id.id,
user_id=self.env.uid,
date=line.order_id.date_order,
company_id=line.company_id.id,
)
line.analytic_tag_ids = default_analytic_account.analytic_tag_ids
def compute_uom_qty(self, new_qty, stock_move, rounding=True):
return self.product_uom._compute_quantity(new_qty, stock_move.product_uom, rounding)
def _get_invoice_line_sequence(self, new=0, old=0):
"""
Method intended to be overridden in third-party module if we want to prevent the resequencing
of invoice lines.
:param int new: the new line sequence
:param int old: the old line sequence
:return: the sequence of the SO line, by default the new one.
"""
return new or old
def _prepare_invoice_line(self, **optional_values):
"""
Prepare the dict of values to create the new invoice line for a sales order line.
:param qty: float quantity to invoice
:param optional_values: any parameter that should be added to the returned invoice line
"""
self.ensure_one()
res = {
'display_type': self.display_type,
'sequence': self.sequence,
'name': self.name,
'product_id': self.product_id.id,
'product_uom_id': self.product_uom.id,
'quantity': self.qty_to_invoice,
'discount': self.discount,
'price_unit': self.price_unit,
'tax_ids': [(6, 0, self.tax_id.ids)],
'sale_line_ids': [(4, self.id)],
}
if self.order_id.analytic_account_id and not self.display_type:
res['analytic_account_id'] = self.order_id.analytic_account_id.id
if self.analytic_tag_ids and not self.display_type:
res['analytic_tag_ids'] = [(6, 0, self.analytic_tag_ids.ids)]
if optional_values:
res.update(optional_values)
if self.display_type:
res['account_id'] = False
return res
def _prepare_procurement_values(self, group_id=False):
""" Prepare specific key for moves or other components that will be created from a stock rule
comming from a sale order line. This method could be override in order to add other custom key that could
be used in move/po creation.
"""
return {}
def _get_display_price(self, product):
# TO DO: move me in master/saas-16 on sale.order
# awa: don't know if it's still the case since we need the "product_no_variant_attribute_value_ids" field now
# to be able to compute the full price
# it is possible that a no_variant attribute is still in a variant if
# the type of the attribute has been changed after creation.
no_variant_attributes_price_extra = [
ptav.price_extra for ptav in self.product_no_variant_attribute_value_ids.filtered(
lambda ptav:
ptav.price_extra and
ptav not in product.product_template_attribute_value_ids
)
]
if no_variant_attributes_price_extra:
product = product.with_context(
no_variant_attributes_price_extra=tuple(no_variant_attributes_price_extra)
)
if self.order_id.pricelist_id.discount_policy == 'with_discount':
return product.with_context(pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id).price
product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id)
final_price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(product or self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
base_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
if currency != self.order_id.pricelist_id.currency_id:
base_price = currency._convert(
base_price, self.order_id.pricelist_id.currency_id,
self.order_id.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
# negative discounts (= surcharge) are included in the display price
return max(base_price, final_price)
@api.onchange('product_id')
def product_id_change(self):
if not self.product_id:
return
if not self.product_uom or (self.product_id.uom_id.id != self.product_uom.id):
self.update({
'product_uom': self.product_id.uom_id,
'product_uom_qty': self.product_uom_qty or 1.0
})
self._update_description()
self._update_taxes()
product = self.product_id
if product and product.sale_line_warn != 'no-message':
if product.sale_line_warn == 'block':
self.product_id = False
return {
'warning': {
'title': _("Warning for %s", product.name),
'message': product.sale_line_warn_msg,
}
}
def _update_description(self):
if not self.product_id:
return
valid_values = self.product_id.product_tmpl_id.valid_product_template_attribute_line_ids.product_template_value_ids
# remove the is_custom values that don't belong to this template
for pacv in self.product_custom_attribute_value_ids:
if pacv.custom_product_template_attribute_value_id not in valid_values:
self.product_custom_attribute_value_ids -= pacv
# remove the no_variant attributes that don't belong to this template
for ptav in self.product_no_variant_attribute_value_ids:
if ptav._origin not in valid_values:
self.product_no_variant_attribute_value_ids -= ptav
lang = get_lang(self.env, self.order_id.partner_id.lang).code
product = self.product_id.with_context(
lang=lang,
)
self.update({
'name': self.with_context(lang=lang).get_sale_order_line_multiline_description_sale(product)
})
def _update_taxes(self):
if not self.product_id:
return
self._compute_tax_id()
if self.order_id.pricelist_id and self.order_id.partner_id:
product = self.product_id.with_context(
partner=self.order_id.partner_id,
quantity=self.product_uom_qty,
date=self.order_id.date_order,
pricelist=self.order_id.pricelist_id.id,
uom=self.product_uom.id
)
self.update({
'price_unit': product._get_tax_included_unit_price(
self.company_id,
self.order_id.currency_id,
self.order_id.date_order,
'sale',
fiscal_position=self.order_id.fiscal_position_id,
product_price_unit=self._get_display_price(product),
product_currency=self.order_id.currency_id
)
})
@api.onchange('product_uom', 'product_uom_qty')
def product_uom_change(self):
if not self.product_uom or not self.product_id:
self.price_unit = 0.0
return
if self.order_id.pricelist_id and self.order_id.partner_id:
product = self.product_id.with_context(
lang=self.order_id.partner_id.lang,
partner=self.order_id.partner_id,
quantity=self.product_uom_qty,
date=self.order_id.date_order,
pricelist=self.order_id.pricelist_id.id,
uom=self.product_uom.id,
fiscal_position=self.env.context.get('fiscal_position')
)
self.price_unit = product._get_tax_included_unit_price(
self.company_id or self.order_id.company_id,
self.order_id.currency_id,
self.order_id.date_order,
'sale',
fiscal_position=self.order_id.fiscal_position_id,
product_price_unit=self._get_display_price(product),
product_currency=self.order_id.currency_id
)
def name_get(self):
result = []
for so_line in self.sudo():
name = '%s - %s' % (so_line.order_id.name, so_line.name and so_line.name.split('\n')[0] or so_line.product_id.name)
if so_line.order_partner_id.ref:
name = '%s (%s)' % (name, so_line.order_partner_id.ref)
result.append((so_line.id, name))
return result
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if operator in ('ilike', 'like', '=', '=like', '=ilike'):
args = expression.AND([
args or [],
['|', ('order_id.name', operator, name), ('name', operator, name)]
])
return self._search(args, limit=limit, access_rights_uid=name_get_uid)
return super(SaleOrderLine, self)._name_search(name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
def _check_line_unlink(self):
"""
Check wether a line can be deleted or not.
Lines cannot be deleted if the order is confirmed; downpayment
lines who have not yet been invoiced bypass that exception.
Also, allow deleting UX lines (notes/sections).
:rtype: recordset sale.order.line
:returns: set of lines that cannot be deleted
"""
return self.filtered(lambda line: line.state in ('sale', 'done') and (line.invoice_lines or not line.is_downpayment) and not line.display_type)
@api.ondelete(at_uninstall=False)
def _unlink_except_confirmed(self):
if self._check_line_unlink():
raise UserError(_('You can not remove an order line once the sales order is confirmed.\nYou should rather set the quantity to 0.'))
def _get_real_price_currency(self, product, rule_id, qty, uom, pricelist_id):
"""Retrieve the price before applying the pricelist
:param obj product: object of current product record
:parem float qty: total quentity of product
:param tuple price_and_rule: tuple(price, suitable_rule) coming from pricelist computation
:param obj uom: unit of measure of current order line
:param integer pricelist_id: pricelist id of sales order"""
PricelistItem = self.env['product.pricelist.item']
field_name = 'lst_price'
currency_id = None
product_currency = product.currency_id
if rule_id:
pricelist_item = PricelistItem.browse(rule_id)
if pricelist_item.pricelist_id.discount_policy == 'without_discount':
while pricelist_item.base == 'pricelist' and pricelist_item.base_pricelist_id and pricelist_item.base_pricelist_id.discount_policy == 'without_discount':
_price, rule_id = pricelist_item.base_pricelist_id.with_context(uom=uom.id).get_product_price_rule(product, qty, self.order_id.partner_id)
pricelist_item = PricelistItem.browse(rule_id)
if pricelist_item.base == 'standard_price':
field_name = 'standard_price'
product_currency = product.cost_currency_id
elif pricelist_item.base == 'pricelist' and pricelist_item.base_pricelist_id:
field_name = 'price'
product = product.with_context(pricelist=pricelist_item.base_pricelist_id.id)
product_currency = pricelist_item.base_pricelist_id.currency_id
currency_id = pricelist_item.pricelist_id.currency_id
if not currency_id:
currency_id = product_currency
cur_factor = 1.0
else:
if currency_id.id == product_currency.id:
cur_factor = 1.0
else:
cur_factor = currency_id._get_conversion_rate(product_currency, currency_id, self.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
product_uom = self.env.context.get('uom') or product.uom_id.id
if uom and uom.id != product_uom:
# the unit price is in a different uom
uom_factor = uom._compute_price(1.0, product.uom_id)
else:
uom_factor = 1.0
return product[field_name] * uom_factor * cur_factor, currency_id
def _get_protected_fields(self):
return [
'product_id', 'name', 'price_unit', 'product_uom', 'product_uom_qty',
'tax_id', 'analytic_tag_ids'
]
def _onchange_product_id_set_customer_lead(self):
pass
@api.onchange('product_id', 'price_unit', 'product_uom', 'product_uom_qty', 'tax_id')
def _onchange_discount(self):
if not (self.product_id and self.product_uom and
self.order_id.partner_id and self.order_id.pricelist_id and
self.order_id.pricelist_id.discount_policy == 'without_discount' and
self.env.user.has_group('product.group_discount_per_so_line')):
return
self.discount = 0.0
product = self.product_id.with_context(
lang=self.order_id.partner_id.lang,
partner=self.order_id.partner_id,
quantity=self.product_uom_qty,
date=self.order_id.date_order,
pricelist=self.order_id.pricelist_id.id,
uom=self.product_uom.id,
fiscal_position=self.env.context.get('fiscal_position')
)
product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id)
price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
new_list_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
if new_list_price != 0:
if self.order_id.pricelist_id.currency_id != currency:
# we need new_list_price in the same currency as price, which is in the SO's pricelist's currency
new_list_price = currency._convert(
new_list_price, self.order_id.pricelist_id.currency_id,
self.order_id.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
discount = (new_list_price - price) / new_list_price * 100
if (discount > 0 and new_list_price > 0) or (discount < 0 and new_list_price < 0):
self.discount = discount
def _is_delivery(self):
self.ensure_one()
return False
def get_sale_order_line_multiline_description_sale(self, product):
""" Compute a default multiline description for this sales order line.
In most cases the product description is enough but sometimes we need to append information that only
exists on the sale order line itself.
e.g:
- custom attributes and attributes that don't create variants, both introduced by the "product configurator"
- in event_sale we need to know specifically the sales order line as well as the product to generate the name:
the product is not sufficient because we also need to know the event_id and the event_ticket_id (both which belong to the sale order line).
"""
return product.get_product_multiline_description_sale() + self._get_sale_order_line_multiline_description_variants()
def _get_sale_order_line_multiline_description_variants(self):
"""When using no_variant attributes or is_custom values, the product
itself is not sufficient to create the description: we need to add
information about those special attributes and values.
:return: the description related to special variant attributes/values
:rtype: string
"""
if not self.product_custom_attribute_value_ids and not self.product_no_variant_attribute_value_ids:
return ""
name = "\n"
custom_ptavs = self.product_custom_attribute_value_ids.custom_product_template_attribute_value_id
no_variant_ptavs = self.product_no_variant_attribute_value_ids._origin
# display the no_variant attributes, except those that are also
# displayed by a custom (avoid duplicate description)
for ptav in (no_variant_ptavs - custom_ptavs):
name += "\n" + ptav.display_name
# Sort the values according to _order settings, because it doesn't work for virtual records in onchange
custom_values = sorted(self.product_custom_attribute_value_ids, key=lambda r: (r.custom_product_template_attribute_value_id.id, r.id))
# display the is_custom values
for pacv in custom_values:
name += "\n" + pacv.display_name
return name
def _is_not_sellable_line(self):
# True if the line is a computed line (reward, delivery, ...) that user cannot add manually
return False
| 54.668172 | 48,436 |
15,426 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
from odoo import api, fields, models, _
from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_round
_logger = logging.getLogger(__name__)
class ProductTemplate(models.Model):
_inherit = 'product.template'
service_type = fields.Selection([('manual', 'Manually set quantities on order')], string='Track Service',
help="Manually set quantities on order: Invoice based on the manually entered quantity, without creating an analytic account.\n"
"Timesheets on contract: Invoice based on the tracked hours on the related timesheet.\n"
"Create a task and track hours: Create a task on the sales order validation and track the work hours.",
default='manual')
sale_line_warn = fields.Selection(WARNING_MESSAGE, 'Sales Order Line', help=WARNING_HELP, required=True, default="no-message")
sale_line_warn_msg = fields.Text('Message for Sales Order Line')
expense_policy = fields.Selection(
[('no', 'No'), ('cost', 'At cost'), ('sales_price', 'Sales price')],
string='Re-Invoice Expenses',
default='no',
help="Expenses and vendor bills can be re-invoiced to a customer."
"With this option, a validated expense can be re-invoice to a customer at its cost or sales price.")
visible_expense_policy = fields.Boolean("Re-Invoice Policy visible", compute='_compute_visible_expense_policy')
sales_count = fields.Float(compute='_compute_sales_count', string='Sold')
visible_qty_configurator = fields.Boolean("Quantity visible in configurator", compute='_compute_visible_qty_configurator')
invoice_policy = fields.Selection([
('order', 'Ordered quantities'),
('delivery', 'Delivered quantities')], string='Invoicing Policy',
help='Ordered Quantity: Invoice quantities ordered by the customer.\n'
'Delivered Quantity: Invoice quantities delivered to the customer.',
default='order')
def _compute_visible_qty_configurator(self):
for product_template in self:
product_template.visible_qty_configurator = True
@api.depends('name')
def _compute_visible_expense_policy(self):
visibility = self.user_has_groups('analytic.group_analytic_accounting')
for product_template in self:
product_template.visible_expense_policy = visibility
@api.onchange('sale_ok')
def _change_sale_ok(self):
if not self.sale_ok:
self.expense_policy = 'no'
@api.depends('product_variant_ids.sales_count')
def _compute_sales_count(self):
for product in self:
product.sales_count = float_round(sum([p.sales_count for p in product.with_context(active_test=False).product_variant_ids]), precision_rounding=product.uom_id.rounding)
@api.constrains('company_id')
def _check_sale_product_company(self):
"""Ensure the product is not being restricted to a single company while
having been sold in another one in the past, as this could cause issues."""
target_company = self.company_id
if target_company: # don't prevent writing `False`, should always work
product_data = self.env['product.product'].sudo().with_context(active_test=False).search_read([('product_tmpl_id', 'in', self.ids)], fields=['id'])
product_ids = list(map(lambda p: p['id'], product_data))
so_lines = self.env['sale.order.line'].sudo().search_read([('product_id', 'in', product_ids), ('company_id', '!=', target_company.id)], fields=['id', 'product_id'])
used_products = list(map(lambda sol: sol['product_id'][1], so_lines))
if so_lines:
raise ValidationError(_('The following products cannot be restricted to the company'
' %s because they have already been used in quotations or '
'sales orders in another company:\n%s\n'
'You can archive these products and recreate them '
'with your company restriction instead, or leave them as '
'shared product.') % (target_company.name, ', '.join(used_products)))
def action_view_sales(self):
action = self.env["ir.actions.actions"]._for_xml_id("sale.report_all_channels_sales_action")
action['domain'] = [('product_tmpl_id', 'in', self.ids)]
action['context'] = {
'pivot_measures': ['product_uom_qty'],
'active_id': self._context.get('active_id'),
'active_model': 'sale.report',
'search_default_Sales': 1,
'search_default_filter_order_date': 1,
}
return action
def create_product_variant(self, product_template_attribute_value_ids):
""" Create if necessary and possible and return the id of the product
variant matching the given combination for this template.
Note AWA: Known "exploit" issues with this method:
- This method could be used by an unauthenticated user to generate a
lot of useless variants. Unfortunately, after discussing the
matter with ODO, there's no easy and user-friendly way to block
that behavior.
We would have to use captcha/server actions to clean/... that
are all not user-friendly/overkill mechanisms.
- This method could be used to try to guess what product variant ids
are created in the system and what product template ids are
configured as "dynamic", but that does not seem like a big deal.
The error messages are identical on purpose to avoid giving too much
information to a potential attacker:
- returning 0 when failing
- returning the variant id whether it already existed or not
:param product_template_attribute_value_ids: the combination for which
to get or create variant
:type product_template_attribute_value_ids: json encoded list of id
of `product.template.attribute.value`
:return: id of the product variant matching the combination or 0
:rtype: int
"""
combination = self.env['product.template.attribute.value'] \
.browse(json.loads(product_template_attribute_value_ids))
return self._create_product_variant(combination, log_warning=True).id or 0
@api.onchange('type')
def _onchange_type(self):
""" Force values to stay consistent with integrity constraints """
res = super(ProductTemplate, self)._onchange_type()
if self.type == 'consu':
if not self.invoice_policy:
self.invoice_policy = 'order'
self.service_type = 'manual'
if self._origin and self.sales_count > 0:
res['warning'] = {
'title': _("Warning"),
'message': _("You cannot change the product's type because it is already used in sales orders.")
}
return res
@api.model
def get_import_templates(self):
res = super(ProductTemplate, self).get_import_templates()
if self.env.context.get('sale_multi_pricelist_product_template'):
if self.user_has_groups('product.group_sale_pricelist'):
return [{
'label': _('Import Template for Products'),
'template': '/product/static/xls/product_template.xls'
}]
return res
def _get_combination_info(self, combination=False, product_id=False, add_qty=1, pricelist=False, parent_combination=False, only_template=False):
""" Return info about a given combination.
Note: this method does not take into account whether the combination is
actually possible.
:param combination: recordset of `product.template.attribute.value`
:param product_id: id of a `product.product`. If no `combination`
is set, the method will try to load the variant `product_id` if
it exists instead of finding a variant based on the combination.
If there is no combination, that means we definitely want a
variant and not something that will have no_variant set.
:param add_qty: float with the quantity for which to get the info,
indeed some pricelist rules might depend on it.
:param pricelist: `product.pricelist` the pricelist to use
(can be none, eg. from SO if no partner and no pricelist selected)
:param parent_combination: if no combination and no product_id are
given, it will try to find the first possible combination, taking
into account parent_combination (if set) for the exclusion rules.
:param only_template: boolean, if set to True, get the info for the
template only: ignore combination and don't try to find variant
:return: dict with product/combination info:
- product_id: the variant id matching the combination (if it exists)
- product_template_id: the current template id
- display_name: the name of the combination
- price: the computed price of the combination, take the catalog
price if no pricelist is given
- list_price: the catalog price of the combination, but this is
not the "real" list_price, it has price_extra included (so
it's actually more closely related to `lst_price`), and it
is converted to the pricelist currency (if given)
- has_discounted_price: True if the pricelist discount policy says
the price does not include the discount and there is actually a
discount applied (price < list_price), else False
"""
self.ensure_one()
# get the name before the change of context to benefit from prefetch
display_name = self.display_name
display_image = True
quantity = self.env.context.get('quantity', add_qty)
context = dict(self.env.context, quantity=quantity, pricelist=pricelist.id if pricelist else False)
product_template = self.with_context(context)
combination = combination or product_template.env['product.template.attribute.value']
if not product_id and not combination and not only_template:
combination = product_template._get_first_possible_combination(parent_combination)
if only_template:
product = product_template.env['product.product']
elif product_id and not combination:
product = product_template.env['product.product'].browse(product_id)
else:
product = product_template._get_variant_for_combination(combination)
if product:
# We need to add the price_extra for the attributes that are not
# in the variant, typically those of type no_variant, but it is
# possible that a no_variant attribute is still in a variant if
# the type of the attribute has been changed after creation.
no_variant_attributes_price_extra = [
ptav.price_extra for ptav in combination.filtered(
lambda ptav:
ptav.price_extra and
ptav not in product.product_template_attribute_value_ids
)
]
if no_variant_attributes_price_extra:
product = product.with_context(
no_variant_attributes_price_extra=tuple(no_variant_attributes_price_extra)
)
list_price = product.price_compute('list_price')[product.id]
price = product.price if pricelist else list_price
display_image = bool(product.image_128)
display_name = product.display_name
price_extra = (product.price_extra or 0.0 ) + (sum(no_variant_attributes_price_extra) or 0.0)
else:
current_attributes_price_extra = [v.price_extra or 0.0 for v in combination]
product_template = product_template.with_context(current_attributes_price_extra=current_attributes_price_extra)
price_extra = sum(current_attributes_price_extra)
list_price = product_template.price_compute('list_price')[product_template.id]
price = product_template.price if pricelist else list_price
display_image = bool(product_template.image_128)
combination_name = combination._get_combination_name()
if combination_name:
display_name = "%s (%s)" % (display_name, combination_name)
if pricelist and pricelist.currency_id != product_template.currency_id:
list_price = product_template.currency_id._convert(
list_price, pricelist.currency_id, product_template._get_current_company(pricelist=pricelist),
fields.Date.today()
)
price_extra = product_template.currency_id._convert(
price_extra, pricelist.currency_id, product_template._get_current_company(pricelist=pricelist),
fields.Date.today()
)
price_without_discount = list_price if pricelist and pricelist.discount_policy == 'without_discount' else price
has_discounted_price = (pricelist or product_template).currency_id.compare_amounts(price_without_discount, price) == 1
return {
'product_id': product.id,
'product_template_id': product_template.id,
'display_name': display_name,
'display_image': display_image,
'price': price,
'list_price': list_price,
'price_extra': price_extra,
'has_discounted_price': has_discounted_price,
}
def _can_be_added_to_cart(self):
"""
Pre-check to `_is_add_to_cart_possible` to know if product can be sold.
"""
return self.sale_ok
def _is_add_to_cart_possible(self, parent_combination=None):
"""
It's possible to add to cart (potentially after configuration) if
there is at least one possible combination.
:param parent_combination: the combination from which `self` is an
optional or accessory product.
:type parent_combination: recordset `product.template.attribute.value`
:return: True if it's possible to add to cart, else False
:rtype: bool
"""
self.ensure_one()
if not self.active or not self._can_be_added_to_cart():
# for performance: avoid calling `_get_possible_combinations`
return False
return next(self._get_possible_combinations(parent_combination), False) is not False
def _get_current_company_fallback(self, **kwargs):
"""Override: if a pricelist is given, fallback to the company of the
pricelist if it is set, otherwise use the one from parent method."""
res = super(ProductTemplate, self)._get_current_company_fallback(**kwargs)
pricelist = kwargs.get('pricelist')
return pricelist and pricelist.company_id or res
| 49.76129 | 15,426 |
3,659 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta, time
from odoo import fields, models, _, api
from odoo.tools.float_utils import float_round
class ProductProduct(models.Model):
_inherit = 'product.product'
sales_count = fields.Float(compute='_compute_sales_count', string='Sold')
def _compute_sales_count(self):
r = {}
self.sales_count = 0
if not self.user_has_groups('sales_team.group_sale_salesman'):
return r
date_from = fields.Datetime.to_string(fields.datetime.combine(fields.datetime.now() - timedelta(days=365),
time.min))
done_states = self.env['sale.report']._get_done_states()
domain = [
('state', 'in', done_states),
('product_id', 'in', self.ids),
('date', '>=', date_from),
]
for group in self.env['sale.report'].read_group(domain, ['product_id', 'product_uom_qty'], ['product_id']):
r[group['product_id'][0]] = group['product_uom_qty']
for product in self:
if not product.id:
product.sales_count = 0.0
continue
product.sales_count = float_round(r.get(product.id, 0), precision_rounding=product.uom_id.rounding)
return r
@api.onchange('type')
def _onchange_type(self):
if self._origin and self.sales_count > 0:
return {'warning': {
'title': _("Warning"),
'message': _("You cannot change the product's type because it is already used in sales orders.")
}}
def action_view_sales(self):
action = self.env["ir.actions.actions"]._for_xml_id("sale.report_all_channels_sales_action")
action['domain'] = [('product_id', 'in', self.ids)]
action['context'] = {
'pivot_measures': ['product_uom_qty'],
'active_id': self._context.get('active_id'),
'search_default_Sales': 1,
'active_model': 'sale.report',
'search_default_filter_order_date': 1,
}
return action
def _get_invoice_policy(self):
return self.invoice_policy
def _get_combination_info_variant(self, add_qty=1, pricelist=False, parent_combination=False):
"""Return the variant info based on its combination.
See `_get_combination_info` for more information.
"""
self.ensure_one()
return self.product_tmpl_id._get_combination_info(self.product_template_attribute_value_ids, self.id, add_qty, pricelist, parent_combination)
def _filter_to_unlink(self):
domain = [('product_id', 'in', self.ids)]
lines = self.env['sale.order.line'].read_group(domain, ['product_id'], ['product_id'])
linked_product_ids = [group['product_id'][0] for group in lines]
return super(ProductProduct, self - self.browse(linked_product_ids))._filter_to_unlink()
class ProductAttributeCustomValue(models.Model):
_inherit = "product.attribute.custom.value"
sale_order_line_id = fields.Many2one('sale.order.line', string="Sales Order Line", required=True, ondelete='cascade')
_sql_constraints = [
('sol_custom_value_unique', 'unique(custom_product_template_attribute_value_id, sale_order_line_id)', "Only one Custom Value is allowed per Attribute Value per Sales Order Line.")
]
class ProductPackaging(models.Model):
_inherit = 'product.packaging'
sales = fields.Boolean("Sales", default=True, help="If true, the packaging can be used for sales orders")
| 42.546512 | 3,659 |
606 |
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 PaymentAcquirer(models.Model):
_inherit = 'payment.acquirer'
so_reference_type = fields.Selection(string='Communication',
selection=[
('so_name', 'Based on Document Reference'),
('partner', 'Based on Customer ID')], default='so_name',
help='You can set here the communication type that will appear on sales orders.'
'The communication will be given to the customer when they choose the payment method.')
| 40.4 | 606 |
6,588 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo import api, fields, models, _
from odoo.modules.module import get_module_resource
class ResCompany(models.Model):
_inherit = "res.company"
portal_confirmation_sign = fields.Boolean(string='Online Signature', default=True)
portal_confirmation_pay = fields.Boolean(string='Online Payment')
quotation_validity_days = fields.Integer(default=30, string="Default Quotation Validity (Days)")
# sale quotation onboarding
sale_quotation_onboarding_state = fields.Selection([('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done"), ('closed', "Closed")], string="State of the sale onboarding panel", default='not_done')
sale_onboarding_order_confirmation_state = fields.Selection([('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done")], string="State of the onboarding confirmation order step", default='not_done')
sale_onboarding_sample_quotation_state = fields.Selection([('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done")], string="State of the onboarding sample quotation step", default='not_done')
sale_onboarding_payment_method = fields.Selection([
('digital_signature', 'Sign online'),
('paypal', 'PayPal'),
('stripe', 'Stripe'),
('other', 'Pay with another payment acquirer'),
('manual', 'Manual Payment'),
], string="Sale onboarding selected payment method")
@api.model
def action_close_sale_quotation_onboarding(self):
""" Mark the onboarding panel as closed. """
self.env.company.sale_quotation_onboarding_state = 'closed'
@api.model
def action_open_sale_onboarding_payment_acquirer(self):
""" Called by onboarding panel above the quotation list."""
self.env.company.get_chart_of_accounts_or_fail()
action = self.env["ir.actions.actions"]._for_xml_id("sale.action_open_sale_onboarding_payment_acquirer_wizard")
return action
def _mark_payment_onboarding_step_as_done(self):
""" Override of payment to mark the sale onboarding step as done.
The payment onboarding step of Sales is only marked as done if it was started from Sales.
This prevents incorrectly marking the step as done if another module's payment onboarding
step was marked as done.
:return: None
"""
super()._mark_payment_onboarding_step_as_done()
if self.sale_onboarding_payment_method: # The onboarding step was started from Sales
self.set_onboarding_step_done('sale_onboarding_order_confirmation_state')
def _get_sample_sales_order(self):
""" Get a sample quotation or create one if it does not exist. """
# use current user as partner
partner = self.env.user.partner_id
company_id = self.env.company.id
# is there already one?
sample_sales_order = self.env['sale.order'].search(
[('company_id', '=', company_id), ('partner_id', '=', partner.id),
('state', '=', 'draft')], limit=1)
if len(sample_sales_order) == 0:
sample_sales_order = self.env['sale.order'].create({
'partner_id': partner.id
})
# take any existing product or create one
product = self.env['product.product'].search([], limit=1)
if len(product) == 0:
default_image_path = get_module_resource('product', 'static/img', 'product_product_13-image.png')
product = self.env['product.product'].create({
'name': _('Sample Product'),
'active': False,
'image_1920': base64.b64encode(open(default_image_path, 'rb').read())
})
product.product_tmpl_id.write({'active': False})
self.env['sale.order.line'].create({
'name': _('Sample Order Line'),
'product_id': product.id,
'product_uom_qty': 10,
'price_unit': 123,
'order_id': sample_sales_order.id,
'company_id': sample_sales_order.company_id.id,
})
return sample_sales_order
@api.model
def action_open_sale_onboarding_sample_quotation(self):
""" Onboarding step for sending a sample quotation. Open a window to compose an email,
with the edi_invoice_template message loaded by default. """
sample_sales_order = self._get_sample_sales_order()
template = self.env.ref('sale.email_template_edi_sale', False)
message_composer = self.env['mail.compose.message'].with_context(
default_use_template=bool(template),
mark_so_as_sent=True,
custom_layout='mail.mail_notification_paynow',
proforma=self.env.context.get('proforma', False),
force_email=True, mail_notify_author=True
).create({
'res_id': sample_sales_order.id,
'template_id': template and template.id or False,
'model': 'sale.order',
'composition_mode': 'comment'})
# Simulate the onchange (like trigger in form the view)
update_values = message_composer._onchange_template_id(template.id, 'comment', 'sale.order', sample_sales_order.id)['value']
message_composer.write(update_values)
message_composer._action_send_mail()
self.set_onboarding_step_done('sale_onboarding_sample_quotation_state')
self.action_close_sale_quotation_onboarding()
action = self.env["ir.actions.actions"]._for_xml_id("sale.action_orders")
action.update({
'views': [[self.env.ref('sale.view_order_form').id, 'form']],
'view_mode': 'form',
'target': 'main',
})
return action
def get_and_update_sale_quotation_onboarding_state(self):
""" This method is called on the controller rendering method and ensures that the animations
are displayed only one time. """
steps = [
'base_onboarding_company_state',
'account_onboarding_invoice_layout_state',
'sale_onboarding_order_confirmation_state',
'sale_onboarding_sample_quotation_state',
]
return self.get_and_update_onbarding_state('sale_quotation_onboarding_state', steps)
_sql_constraints = [('check_quotation_validity_days', 'CHECK(quotation_validity_days > 0)', 'Quotation Validity is required and must be greater than 0.')]
| 48.8 | 6,588 |
5,039 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
group_auto_done_setting = fields.Boolean("Lock Confirmed Sales", implied_group='sale.group_auto_done_setting')
module_sale_margin = fields.Boolean("Margins")
quotation_validity_days = fields.Integer(related='company_id.quotation_validity_days', string="Default Quotation Validity (Days)", readonly=False)
use_quotation_validity_days = fields.Boolean("Default Quotation Validity", config_parameter='sale.use_quotation_validity_days')
group_warning_sale = fields.Boolean("Sale Order Warnings", implied_group='sale.group_warning_sale')
portal_confirmation_sign = fields.Boolean(related='company_id.portal_confirmation_sign', string='Online Signature', readonly=False)
portal_confirmation_pay = fields.Boolean(related='company_id.portal_confirmation_pay', string='Online Payment', readonly=False)
group_sale_delivery_address = fields.Boolean("Customer Addresses", implied_group='sale.group_delivery_invoice_address')
group_proforma_sales = fields.Boolean(string="Pro-Forma Invoice", implied_group='sale.group_proforma_sales',
help="Allows you to send pro-forma invoice.")
default_invoice_policy = fields.Selection([
('order', 'Invoice what is ordered'),
('delivery', 'Invoice what is delivered')
], 'Invoicing Policy',
default='order',
default_model='product.template')
deposit_default_product_id = fields.Many2one(
'product.product',
'Deposit Product',
domain="[('type', '=', 'service')]",
config_parameter='sale.default_deposit_product_id',
help='Default product used for payment advances')
auth_signup_uninvited = fields.Selection([
('b2b', 'On invitation'),
('b2c', 'Free sign up'),
], string='Customer Account', default='b2b', config_parameter='auth_signup.invitation_scope')
module_delivery = fields.Boolean("Delivery Methods")
module_delivery_dhl = fields.Boolean("DHL Express Connector")
module_delivery_fedex = fields.Boolean("FedEx Connector")
module_delivery_ups = fields.Boolean("UPS Connector")
module_delivery_usps = fields.Boolean("USPS Connector")
module_delivery_bpost = fields.Boolean("bpost Connector")
module_delivery_easypost = fields.Boolean("Easypost Connector")
module_product_email_template = fields.Boolean("Specific Email")
module_sale_coupon = fields.Boolean("Coupons & Promotions")
module_sale_amazon = fields.Boolean("Amazon Sync")
automatic_invoice = fields.Boolean(
string="Automatic Invoice",
help="The invoice is generated automatically and available in the customer portal when the "
"transaction is confirmed by the payment acquirer.\nThe invoice is marked as paid and "
"the payment is registered in the payment journal defined in the configuration of the "
"payment acquirer.\nThis mode is advised if you issue the final invoice at the order "
"and not after the delivery.",
config_parameter='sale.automatic_invoice',
)
invoice_mail_template_id = fields.Many2one(
comodel_name='mail.template',
string='Invoice Email Template',
domain="[('model', '=', 'account.move')]",
config_parameter='sale.default_invoice_email_template',
default=lambda self: self.env.ref('account.email_template_edi_invoice', False)
)
confirmation_mail_template_id = fields.Many2one(
comodel_name='mail.template',
string='Confirmation Email Template',
domain="[('model', '=', 'sale.order')]",
config_parameter='sale.default_confirmation_template',
help="Email sent to the customer once the order is paid."
)
def set_values(self):
super(ResConfigSettings, self).set_values()
if self.default_invoice_policy != 'order':
self.env['ir.config_parameter'].set_param('sale.automatic_invoice', False)
send_invoice_cron = self.env.ref('sale.send_invoice_cron', raise_if_not_found=False)
if send_invoice_cron:
send_invoice_cron.active = self.automatic_invoice
@api.onchange('use_quotation_validity_days')
def _onchange_use_quotation_validity_days(self):
if self.quotation_validity_days <= 0:
self.quotation_validity_days = self.env['res.company'].default_get(['quotation_validity_days'])['quotation_validity_days']
@api.onchange('quotation_validity_days')
def _onchange_quotation_validity_days(self):
if self.quotation_validity_days <= 0:
self.quotation_validity_days = self.env['res.company'].default_get(['quotation_validity_days'])['quotation_validity_days']
return {
'warning': {'title': "Warning", 'message': "Quotation Validity is required and must be greater than 0."},
}
| 53.606383 | 5,039 |
3,385 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class UtmCampaign(models.Model):
_inherit = 'utm.campaign'
_description = 'UTM Campaign'
quotation_count = fields.Integer('Quotation Count', groups='sales_team.group_sale_salesman', compute="_compute_quotation_count")
invoiced_amount = fields.Integer(default=0, compute="_compute_sale_invoiced_amount", string="Revenues generated by the campaign")
company_id = fields.Many2one('res.company', string='Company', readonly=True, states={'draft': [('readonly', False)], 'refused': [('readonly', False)]}, default=lambda self: self.env.company)
currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string='Currency')
def _compute_quotation_count(self):
quotation_data = self.env['sale.order'].read_group([
('campaign_id', 'in', self.ids)],
['campaign_id'], ['campaign_id'])
data_map = {datum['campaign_id'][0]: datum['campaign_id_count'] for datum in quotation_data}
for campaign in self:
campaign.quotation_count = data_map.get(campaign.id, 0)
def _compute_sale_invoiced_amount(self):
self.env['account.move.line'].flush(['balance', 'move_id', 'account_id', 'exclude_from_invoice_tab'])
self.env['account.move'].flush(['state', 'campaign_id', 'move_type'])
query = """SELECT move.campaign_id, -SUM(line.balance) as price_subtotal
FROM account_move_line line
INNER JOIN account_move move ON line.move_id = move.id
WHERE move.state not in ('draft', 'cancel')
AND move.campaign_id IN %s
AND move.move_type IN ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt')
AND line.account_id IS NOT NULL
AND NOT line.exclude_from_invoice_tab
GROUP BY move.campaign_id
"""
self._cr.execute(query, [tuple(self.ids)])
query_res = self._cr.dictfetchall()
campaigns = self.browse()
for datum in query_res:
campaign = self.browse(datum['campaign_id'])
campaign.invoiced_amount = datum['price_subtotal']
campaigns |= campaign
for campaign in (self - campaigns):
campaign.invoiced_amount = 0
def action_redirect_to_quotations(self):
action = self.env["ir.actions.actions"]._for_xml_id("sale.action_quotations_with_onboarding")
action['domain'] = [('campaign_id', '=', self.id)]
action['context'] = {'default_campaign_id': self.id}
return action
def action_redirect_to_invoiced(self):
action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_journal_line")
invoices = self.env['account.move'].search([('campaign_id', '=', self.id)])
action['context'] = {
'create': False,
'edit': False,
'view_no_maturity': True
}
action['domain'] = [
('id', 'in', invoices.ids),
('move_type', 'in', ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt')),
('state', 'not in', ['draft', 'cancel'])
]
return action
| 50.522388 | 3,385 |
647 |
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 AccountAnalyticLine(models.Model):
_inherit = "account.analytic.line"
def _default_sale_line_domain(self):
""" This is only used for delivered quantity of SO line based on analytic line, and timesheet
(see sale_timesheet). This can be override to allow further customization.
"""
return [('qty_delivered_method', '=', 'analytic')]
so_line = fields.Many2one('sale.order.line', string='Sales Order Item', domain=lambda self: self._default_sale_line_domain())
| 40.4375 | 647 |
2,287 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP
class ResPartner(models.Model):
_inherit = 'res.partner'
sale_order_count = fields.Integer(compute='_compute_sale_order_count', string='Sale Order Count')
sale_order_ids = fields.One2many('sale.order', 'partner_id', 'Sales Order')
sale_warn = fields.Selection(WARNING_MESSAGE, 'Sales Warnings', default='no-message', help=WARNING_HELP)
sale_warn_msg = fields.Text('Message for Sales Order')
def _compute_sale_order_count(self):
# retrieve all children partners and prefetch 'parent_id' on them
all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
all_partners.read(['parent_id'])
sale_order_groups = self.env['sale.order'].read_group(
domain=[('partner_id', 'in', all_partners.ids)],
fields=['partner_id'], groupby=['partner_id']
)
partners = self.browse()
for group in sale_order_groups:
partner = self.browse(group['partner_id'][0])
while partner:
if partner in self:
partner.sale_order_count += group['partner_id_count']
partners |= partner
partner = partner.parent_id
(self - partners).sale_order_count = 0
def can_edit_vat(self):
''' Can't edit `vat` if there is (non draft) issued SO. '''
can_edit_vat = super(ResPartner, self).can_edit_vat()
if not can_edit_vat:
return can_edit_vat
SaleOrder = self.env['sale.order']
has_so = SaleOrder.search([
('partner_id', 'child_of', self.commercial_partner_id.id),
('state', 'in', ['sent', 'sale', 'done'])
], limit=1)
return can_edit_vat and not bool(has_so)
def action_view_sale_order(self):
action = self.env['ir.actions.act_window']._for_xml_id('sale.act_res_partner_2_sale_order')
all_child = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
action["domain"] = [("partner_id", "in", all_child.ids)]
return action
| 44.843137 | 2,287 |
393 |
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 AccountInvoiceReport(models.Model):
_inherit = 'account.invoice.report'
team_id = fields.Many2one('crm.team', string='Sales Team')
def _select(self):
return super(AccountInvoiceReport, self)._select() + ", move.team_id as team_id"
| 30.230769 | 393 |
3,997 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools
class PosSaleReport(models.Model):
_name = "report.all.channels.sales"
_description = "Sales by Channel (All in One)"
_auto = False
name = fields.Char('Order Reference', readonly=True)
partner_id = fields.Many2one('res.partner', 'Partner', readonly=True)
product_id = fields.Many2one('product.product', string='Product', readonly=True)
product_tmpl_id = fields.Many2one('product.template', 'Product Template', readonly=True)
date_order = fields.Datetime(string='Date Order', readonly=True)
user_id = fields.Many2one('res.users', 'Salesperson', readonly=True)
categ_id = fields.Many2one('product.category', 'Product Category', readonly=True)
company_id = fields.Many2one('res.company', 'Company', readonly=True)
price_total = fields.Float('Total', readonly=True)
pricelist_id = fields.Many2one('product.pricelist', 'Pricelist', readonly=True)
country_id = fields.Many2one('res.country', 'Partner Country', readonly=True)
price_subtotal = fields.Float(string='Price Subtotal', readonly=True)
product_qty = fields.Float('Product Quantity', readonly=True)
analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account', readonly=True)
team_id = fields.Many2one('crm.team', 'Sales Team', readonly=True)
def _so(self):
so_str = """
SELECT sol.id AS id,
so.name AS name,
so.partner_id AS partner_id,
sol.product_id AS product_id,
pro.product_tmpl_id AS product_tmpl_id,
so.date_order AS date_order,
so.user_id AS user_id,
pt.categ_id AS categ_id,
so.company_id AS company_id,
sol.price_total / CASE COALESCE(so.currency_rate, 0) WHEN 0 THEN 1.0 ELSE so.currency_rate END AS price_total,
so.pricelist_id AS pricelist_id,
rp.country_id AS country_id,
sol.price_subtotal / CASE COALESCE(so.currency_rate, 0) WHEN 0 THEN 1.0 ELSE so.currency_rate END AS price_subtotal,
(sol.product_uom_qty / u.factor * u2.factor) as product_qty,
so.analytic_account_id AS analytic_account_id,
so.team_id AS team_id
FROM sale_order_line sol
JOIN sale_order so ON (sol.order_id = so.id)
LEFT JOIN product_product pro ON (sol.product_id = pro.id)
JOIN res_partner rp ON (so.partner_id = rp.id)
LEFT JOIN product_template pt ON (pro.product_tmpl_id = pt.id)
LEFT JOIN product_pricelist pp ON (so.pricelist_id = pp.id)
LEFT JOIN uom_uom u on (u.id=sol.product_uom)
LEFT JOIN uom_uom u2 on (u2.id=pt.uom_id)
WHERE so.state in ('sale','done')
"""
return so_str
def _from(self):
return """(%s)""" % (self._so())
def _get_main_request(self):
request = """
CREATE or REPLACE VIEW %s AS
SELECT id AS id,
name,
partner_id,
product_id,
product_tmpl_id,
date_order,
user_id,
categ_id,
company_id,
price_total,
pricelist_id,
analytic_account_id,
country_id,
team_id,
price_subtotal,
product_qty
FROM %s
AS foo""" % (self._table, self._from())
return request
def init(self):
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute(self._get_main_request())
| 45.942529 | 3,997 |
9,040 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import tools
from odoo import api, fields, models
class SaleReport(models.Model):
_name = "sale.report"
_description = "Sales Analysis Report"
_auto = False
_rec_name = 'date'
_order = 'date desc'
@api.model
def _get_done_states(self):
return ['sale', 'done', 'paid']
name = fields.Char('Order Reference', readonly=True)
date = fields.Datetime('Order Date', readonly=True)
product_id = fields.Many2one('product.product', 'Product Variant', readonly=True)
product_uom = fields.Many2one('uom.uom', 'Unit of Measure', readonly=True)
product_uom_qty = fields.Float('Qty Ordered', readonly=True)
qty_to_deliver = fields.Float('Qty To Deliver', readonly=True)
qty_delivered = fields.Float('Qty Delivered', readonly=True)
qty_to_invoice = fields.Float('Qty To Invoice', readonly=True)
qty_invoiced = fields.Float('Qty Invoiced', readonly=True)
partner_id = fields.Many2one('res.partner', 'Customer', readonly=True)
company_id = fields.Many2one('res.company', 'Company', readonly=True)
user_id = fields.Many2one('res.users', 'Salesperson', readonly=True)
price_total = fields.Float('Total', readonly=True)
price_subtotal = fields.Float('Untaxed Total', readonly=True)
untaxed_amount_to_invoice = fields.Float('Untaxed Amount To Invoice', readonly=True)
untaxed_amount_invoiced = fields.Float('Untaxed Amount Invoiced', readonly=True)
product_tmpl_id = fields.Many2one('product.template', 'Product', readonly=True)
categ_id = fields.Many2one('product.category', 'Product Category', readonly=True)
nbr = fields.Integer('# of Lines', readonly=True)
pricelist_id = fields.Many2one('product.pricelist', 'Pricelist', readonly=True)
analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account', readonly=True)
team_id = fields.Many2one('crm.team', 'Sales Team', readonly=True)
country_id = fields.Many2one('res.country', 'Customer Country', readonly=True)
industry_id = fields.Many2one('res.partner.industry', 'Customer Industry', readonly=True)
commercial_partner_id = fields.Many2one('res.partner', 'Customer Entity', readonly=True)
state = fields.Selection([
('draft', 'Draft Quotation'),
('sent', 'Quotation Sent'),
('sale', 'Sales Order'),
('done', 'Sales Done'),
('cancel', 'Cancelled'),
], string='Status', readonly=True)
weight = fields.Float('Gross Weight', readonly=True)
volume = fields.Float('Volume', readonly=True)
discount = fields.Float('Discount %', readonly=True)
discount_amount = fields.Float('Discount Amount', readonly=True)
campaign_id = fields.Many2one('utm.campaign', 'Campaign')
medium_id = fields.Many2one('utm.medium', 'Medium')
source_id = fields.Many2one('utm.source', 'Source')
order_id = fields.Many2one('sale.order', 'Order #', readonly=True)
def _select_sale(self, fields=None):
if not fields:
fields = {}
select_ = """
min(l.id) as id,
l.product_id as product_id,
t.uom_id as product_uom,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.product_uom_qty / u.factor * u2.factor) ELSE 0 END as product_uom_qty,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.qty_delivered / u.factor * u2.factor) ELSE 0 END as qty_delivered,
CASE WHEN l.product_id IS NOT NULL THEN SUM((l.product_uom_qty - l.qty_delivered) / u.factor * u2.factor) ELSE 0 END as qty_to_deliver,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.qty_invoiced / u.factor * u2.factor) ELSE 0 END as qty_invoiced,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.qty_to_invoice / u.factor * u2.factor) ELSE 0 END as qty_to_invoice,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.price_total / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) ELSE 0 END as price_total,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.price_subtotal / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) ELSE 0 END as price_subtotal,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.untaxed_amount_to_invoice / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) ELSE 0 END as untaxed_amount_to_invoice,
CASE WHEN l.product_id IS NOT NULL THEN sum(l.untaxed_amount_invoiced / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) ELSE 0 END as untaxed_amount_invoiced,
count(*) as nbr,
s.name as name,
s.date_order as date,
s.state as state,
s.partner_id as partner_id,
s.user_id as user_id,
s.company_id as company_id,
s.campaign_id as campaign_id,
s.medium_id as medium_id,
s.source_id as source_id,
extract(epoch from avg(date_trunc('day',s.date_order)-date_trunc('day',s.create_date)))/(24*60*60)::decimal(16,2) as delay,
t.categ_id as categ_id,
s.pricelist_id as pricelist_id,
s.analytic_account_id as analytic_account_id,
s.team_id as team_id,
p.product_tmpl_id,
partner.country_id as country_id,
partner.industry_id as industry_id,
partner.commercial_partner_id as commercial_partner_id,
CASE WHEN l.product_id IS NOT NULL THEN sum(p.weight * l.product_uom_qty / u.factor * u2.factor) ELSE 0 END as weight,
CASE WHEN l.product_id IS NOT NULL THEN sum(p.volume * l.product_uom_qty / u.factor * u2.factor) ELSE 0 END as volume,
l.discount as discount,
CASE WHEN l.product_id IS NOT NULL THEN sum((l.price_unit * l.product_uom_qty * l.discount / 100.0 / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END))ELSE 0 END as discount_amount,
s.id as order_id
"""
for field in fields.values():
select_ += field
return select_
def _from_sale(self, from_clause=''):
from_ = """
sale_order_line l
left join sale_order s on (s.id=l.order_id)
join res_partner partner on s.partner_id = partner.id
left join product_product p on (l.product_id=p.id)
left join product_template t on (p.product_tmpl_id=t.id)
left join uom_uom u on (u.id=l.product_uom)
left join uom_uom u2 on (u2.id=t.uom_id)
left join product_pricelist pp on (s.pricelist_id = pp.id)
%s
""" % from_clause
return from_
def _group_by_sale(self, groupby=''):
groupby_ = """
l.product_id,
l.order_id,
t.uom_id,
t.categ_id,
s.name,
s.date_order,
s.partner_id,
s.user_id,
s.state,
s.company_id,
s.campaign_id,
s.medium_id,
s.source_id,
s.pricelist_id,
s.analytic_account_id,
s.team_id,
p.product_tmpl_id,
partner.country_id,
partner.industry_id,
partner.commercial_partner_id,
l.discount,
s.id %s
""" % (groupby)
return groupby_
def _select_additional_fields(self, fields):
"""Hook to return additional fields SQL specification for select part of the table query.
:param dict fields: additional fields info provided by _query overrides (old API), prefer overriding
_select_additional_fields instead.
:returns: mapping field -> SQL computation of the field
:rtype: dict
"""
return fields
def _query(self, with_clause='', fields=None, groupby='', from_clause=''):
if not fields:
fields = {}
sale_report_fields = self._select_additional_fields(fields)
with_ = ("WITH %s" % with_clause) if with_clause else ""
return '%s (SELECT %s FROM %s WHERE l.display_type IS NULL GROUP BY %s)' % \
(with_, self._select_sale(sale_report_fields), self._from_sale(from_clause), self._group_by_sale(groupby))
def init(self):
# self._table = sale_report
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute("""CREATE or REPLACE VIEW %s as (%s)""" % (self._table, self._query()))
class SaleOrderReportProforma(models.AbstractModel):
_name = 'report.sale.report_saleproforma'
_description = 'Proforma Report'
@api.model
def _get_report_values(self, docids, data=None):
docs = self.env['sale.order'].browse(docids)
return {
'doc_ids': docs.ids,
'doc_model': 'sale.order',
'docs': docs,
'proforma': True
}
| 49.130435 | 9,040 |
18,372 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import binascii
from odoo import fields, http, SUPERUSER_ID, _
from odoo.exceptions import AccessError, MissingError, ValidationError
from odoo.fields import Command
from odoo.http import request
from odoo.addons.payment.controllers import portal as payment_portal
from odoo.addons.payment import utils as payment_utils
from odoo.addons.portal.controllers.mail import _message_post_helper
from odoo.addons.portal.controllers import portal
from odoo.addons.portal.controllers.portal import pager as portal_pager, get_records_pager
class CustomerPortal(portal.CustomerPortal):
def _prepare_home_portal_values(self, counters):
values = super()._prepare_home_portal_values(counters)
partner = request.env.user.partner_id
SaleOrder = request.env['sale.order']
if 'quotation_count' in counters:
values['quotation_count'] = SaleOrder.search_count(self._prepare_quotations_domain(partner)) \
if SaleOrder.check_access_rights('read', raise_exception=False) else 0
if 'order_count' in counters:
values['order_count'] = SaleOrder.search_count(self._prepare_orders_domain(partner)) \
if SaleOrder.check_access_rights('read', raise_exception=False) else 0
return values
def _prepare_quotations_domain(self, partner):
return [
('message_partner_ids', 'child_of', [partner.commercial_partner_id.id]),
('state', 'in', ['sent', 'cancel'])
]
def _prepare_orders_domain(self, partner):
return [
('message_partner_ids', 'child_of', [partner.commercial_partner_id.id]),
('state', 'in', ['sale', 'done'])
]
#
# Quotations and Sales Orders
#
def _get_sale_searchbar_sortings(self):
return {
'date': {'label': _('Order Date'), 'order': 'date_order desc'},
'name': {'label': _('Reference'), 'order': 'name'},
'stage': {'label': _('Stage'), 'order': 'state'},
}
@http.route(['/my/quotes', '/my/quotes/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_quotes(self, page=1, date_begin=None, date_end=None, sortby=None, **kw):
values = self._prepare_portal_layout_values()
partner = request.env.user.partner_id
SaleOrder = request.env['sale.order']
domain = self._prepare_quotations_domain(partner)
searchbar_sortings = self._get_sale_searchbar_sortings()
# default sortby order
if not sortby:
sortby = 'date'
sort_order = searchbar_sortings[sortby]['order']
if date_begin and date_end:
domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
# count for pager
quotation_count = SaleOrder.search_count(domain)
# make pager
pager = portal_pager(
url="/my/quotes",
url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby},
total=quotation_count,
page=page,
step=self._items_per_page
)
# search the count to display, according to the pager data
quotations = SaleOrder.search(domain, order=sort_order, limit=self._items_per_page, offset=pager['offset'])
request.session['my_quotations_history'] = quotations.ids[:100]
values.update({
'date': date_begin,
'quotations': quotations.sudo(),
'page_name': 'quote',
'pager': pager,
'default_url': '/my/quotes',
'searchbar_sortings': searchbar_sortings,
'sortby': sortby,
})
return request.render("sale.portal_my_quotations", values)
@http.route(['/my/orders', '/my/orders/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_orders(self, page=1, date_begin=None, date_end=None, sortby=None, **kw):
values = self._prepare_portal_layout_values()
partner = request.env.user.partner_id
SaleOrder = request.env['sale.order']
domain = self._prepare_orders_domain(partner)
searchbar_sortings = self._get_sale_searchbar_sortings()
# default sortby order
if not sortby:
sortby = 'date'
sort_order = searchbar_sortings[sortby]['order']
if date_begin and date_end:
domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
# count for pager
order_count = SaleOrder.search_count(domain)
# pager
pager = portal_pager(
url="/my/orders",
url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby},
total=order_count,
page=page,
step=self._items_per_page
)
# content according to pager
orders = SaleOrder.search(domain, order=sort_order, limit=self._items_per_page, offset=pager['offset'])
request.session['my_orders_history'] = orders.ids[:100]
values.update({
'date': date_begin,
'orders': orders.sudo(),
'page_name': 'order',
'pager': pager,
'default_url': '/my/orders',
'searchbar_sortings': searchbar_sortings,
'sortby': sortby,
})
return request.render("sale.portal_my_orders", values)
@http.route(['/my/orders/<int:order_id>'], type='http', auth="public", website=True)
def portal_order_page(self, order_id, report_type=None, access_token=None, message=False, download=False, **kw):
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return request.redirect('/my')
if report_type in ('html', 'pdf', 'text'):
return self._show_report(model=order_sudo, report_type=report_type, report_ref='sale.action_report_saleorder', download=download)
# use sudo to allow accessing/viewing orders for public user
# only if he knows the private token
# Log only once a day
if order_sudo:
# store the date as a string in the session to allow serialization
now = fields.Date.today().isoformat()
session_obj_date = request.session.get('view_quote_%s' % order_sudo.id)
if session_obj_date != now and request.env.user.share and access_token:
request.session['view_quote_%s' % order_sudo.id] = now
body = _('Quotation viewed by customer %s', order_sudo.partner_id.name if request.env.user._is_public() else request.env.user.partner_id.name)
_message_post_helper(
"sale.order",
order_sudo.id,
body,
token=order_sudo.access_token,
message_type="notification",
subtype_xmlid="mail.mt_note",
partner_ids=order_sudo.user_id.sudo().partner_id.ids,
)
values = {
'sale_order': order_sudo,
'message': message,
'token': access_token,
'landing_route': '/shop/payment/validate',
'bootstrap_formatting': True,
'partner_id': order_sudo.partner_id.id,
'report_type': 'html',
'action': order_sudo._get_portal_return_action(),
}
if order_sudo.company_id:
values['res_company'] = order_sudo.company_id
# Payment values
if order_sudo.has_to_be_paid():
logged_in = not request.env.user._is_public()
acquirers_sudo = request.env['payment.acquirer'].sudo()._get_compatible_acquirers(
order_sudo.company_id.id,
order_sudo.partner_id.id,
currency_id=order_sudo.currency_id.id,
sale_order_id=order_sudo.id,
) # In sudo mode to read the fields of acquirers and partner (if not logged in)
tokens = request.env['payment.token'].search([
('acquirer_id', 'in', acquirers_sudo.ids),
('partner_id', '=', order_sudo.partner_id.id)
]) if logged_in else request.env['payment.token']
# Make sure that the partner's company matches the order's company.
if not payment_portal.PaymentPortal._can_partner_pay_in_company(
order_sudo.partner_id, order_sudo.company_id
):
acquirers_sudo = request.env['payment.acquirer'].sudo()
tokens = request.env['payment.token']
fees_by_acquirer = {
acquirer: acquirer._compute_fees(
order_sudo.amount_total,
order_sudo.currency_id,
order_sudo.partner_id.country_id,
) for acquirer in acquirers_sudo.filtered('fees_active')
}
# Prevent public partner from saving payment methods but force it for logged in partners
# buying subscription products
show_tokenize_input = logged_in \
and not request.env['payment.acquirer'].sudo()._is_tokenization_required(
sale_order_id=order_sudo.id
)
values.update({
'acquirers': acquirers_sudo,
'tokens': tokens,
'fees_by_acquirer': fees_by_acquirer,
'show_tokenize_input': show_tokenize_input,
'amount': order_sudo.amount_total,
'currency': order_sudo.pricelist_id.currency_id,
'partner_id': order_sudo.partner_id.id,
'access_token': order_sudo.access_token,
'transaction_route': order_sudo.get_portal_url(suffix='/transaction'),
'landing_route': order_sudo.get_portal_url(),
})
if order_sudo.state in ('draft', 'sent', 'cancel'):
history = request.session.get('my_quotations_history', [])
else:
history = request.session.get('my_orders_history', [])
values.update(get_records_pager(history, order_sudo))
return request.render('sale.sale_order_portal_template', values)
@http.route(['/my/orders/<int:order_id>/accept'], type='json', auth="public", website=True)
def portal_quote_accept(self, order_id, access_token=None, name=None, signature=None):
# get from query string if not on json param
access_token = access_token or request.httprequest.args.get('access_token')
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return {'error': _('Invalid order.')}
if not order_sudo.has_to_be_signed():
return {'error': _('The order is not in a state requiring customer signature.')}
if not signature:
return {'error': _('Signature is missing.')}
try:
order_sudo.write({
'signed_by': name,
'signed_on': fields.Datetime.now(),
'signature': signature,
})
request.env.cr.commit()
except (TypeError, binascii.Error) as e:
return {'error': _('Invalid signature data.')}
if not order_sudo.has_to_be_paid():
order_sudo.action_confirm()
order_sudo._send_order_confirmation_mail()
pdf = request.env.ref('sale.action_report_saleorder').with_user(SUPERUSER_ID)._render_qweb_pdf([order_sudo.id])[0]
_message_post_helper(
'sale.order', order_sudo.id, _('Order signed by %s') % (name,),
attachments=[('%s.pdf' % order_sudo.name, pdf)],
**({'token': access_token} if access_token else {}))
query_string = '&message=sign_ok'
if order_sudo.has_to_be_paid(True):
query_string += '#allow_payment=yes'
return {
'force_refresh': True,
'redirect_url': order_sudo.get_portal_url(query_string=query_string),
}
@http.route(['/my/orders/<int:order_id>/decline'], type='http', auth="public", methods=['POST'], website=True)
def decline(self, order_id, access_token=None, **post):
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return request.redirect('/my')
message = post.get('decline_message')
query_string = False
if order_sudo.has_to_be_signed() and message:
order_sudo.action_cancel()
_message_post_helper('sale.order', order_id, message, **{'token': access_token} if access_token else {})
else:
query_string = "&message=cant_reject"
return request.redirect(order_sudo.get_portal_url(query_string=query_string))
class PaymentPortal(payment_portal.PaymentPortal):
@http.route('/my/orders/<int:order_id>/transaction', type='json', auth='public')
def portal_order_transaction(self, order_id, access_token, **kwargs):
""" Create a draft transaction and return its processing values.
:param int order_id: The sales order to pay, as a `sale.order` id
:param str access_token: The access token used to authenticate the request
:param dict kwargs: Locally unused data passed to `_create_transaction`
:return: The mandatory values for the processing of the transaction
:rtype: dict
:raise: ValidationError if the invoice id or the access token is invalid
"""
# Check the order id and the access token
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token)
except MissingError as error:
raise error
except AccessError:
raise ValidationError("The access token is invalid.")
kwargs.update({
'reference_prefix': None, # Allow the reference to be computed based on the order
'partner_id': order_sudo.partner_invoice_id.id,
'sale_order_id': order_id, # Include the SO to allow Subscriptions tokenizing the tx
})
kwargs.pop('custom_create_values', None) # Don't allow passing arbitrary create values
tx_sudo = self._create_transaction(
custom_create_values={'sale_order_ids': [Command.set([order_id])]}, **kwargs,
)
return tx_sudo._get_processing_values()
# Payment overrides
@http.route()
def payment_pay(self, *args, amount=None, sale_order_id=None, access_token=None, **kwargs):
""" Override of payment to replace the missing transaction values by that of the sale order.
This is necessary for the reconciliation as all transaction values, excepted the amount,
need to match exactly that of the sale order.
:param str amount: The (possibly partial) amount to pay used to check the access token
:param str sale_order_id: The sale order for which a payment id made, as a `sale.order` id
:param str access_token: The access token used to authenticate the partner
:return: The result of the parent method
:rtype: str
:raise: ValidationError if the order id is invalid
"""
# Cast numeric parameters as int or float and void them if their str value is malformed
amount = self._cast_as_float(amount)
sale_order_id = self._cast_as_int(sale_order_id)
if sale_order_id:
order_sudo = request.env['sale.order'].sudo().browse(sale_order_id).exists()
if not order_sudo:
raise ValidationError(_("The provided parameters are invalid."))
# Check the access token against the order values. Done after fetching the order as we
# need the order fields to check the access token.
if not payment_utils.check_access_token(
access_token, order_sudo.partner_invoice_id.id, amount, order_sudo.currency_id.id
):
raise ValidationError(_("The provided parameters are invalid."))
kwargs.update({
'currency_id': order_sudo.currency_id.id,
'partner_id': order_sudo.partner_invoice_id.id,
'company_id': order_sudo.company_id.id,
'sale_order_id': sale_order_id,
})
return super().payment_pay(*args, amount=amount, access_token=access_token, **kwargs)
def _get_custom_rendering_context_values(self, sale_order_id=None, **kwargs):
""" Override of payment to add the sale order id in the custom rendering context values.
:param int sale_order_id: The sale order for which a payment id made, as a `sale.order` id
:return: The extended rendering context values
:rtype: dict
"""
rendering_context_values = super()._get_custom_rendering_context_values(**kwargs)
if sale_order_id:
rendering_context_values['sale_order_id'] = sale_order_id
return rendering_context_values
def _create_transaction(self, *args, sale_order_id=None, custom_create_values=None, **kwargs):
""" Override of payment to add the sale order id in the custom create values.
:param int sale_order_id: The sale order for which a payment id made, as a `sale.order` id
:param dict custom_create_values: Additional create values overwriting the default ones
:return: The result of the parent method
:rtype: recordset of `payment.transaction`
"""
if sale_order_id:
if custom_create_values is None:
custom_create_values = {}
# As this override is also called if the flow is initiated from sale or website_sale, we
# need not to override whatever value these modules could have already set
if 'sale_order_ids' not in custom_create_values: # We are in the payment module's flow
custom_create_values['sale_order_ids'] = [Command.set([int(sale_order_id)])]
return super()._create_transaction(
*args, sale_order_id=sale_order_id, custom_create_values=custom_create_values, **kwargs
)
| 45.251232 | 18,372 |
922 |
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 OnboardingController(http.Controller):
@http.route('/sales/sale_quotation_onboarding_panel', auth='user', type='json')
def sale_quotation_onboarding(self):
""" Returns the `banner` for the sale onboarding panel.
It can be empty if the user has closed it or if he doesn't have
the permission to see it. """
company = request.env.company
if not request.env.is_admin() or \
company.sale_quotation_onboarding_state == 'closed':
return {}
return {
'html': request.env.ref('sale.sale_quotation_onboarding_panel')._render({
'company': company,
'state': company.get_and_update_sale_quotation_onboarding_state()
})
}
| 35.461538 | 922 |
2,141 |
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 VariantController(http.Controller):
@http.route(['/sale/get_combination_info'], type='json', auth="user", methods=['POST'])
def get_combination_info(self, product_template_id, product_id, combination, add_qty, pricelist_id, **kw):
combination = request.env['product.template.attribute.value'].browse(combination)
pricelist = self._get_pricelist(pricelist_id)
ProductTemplate = request.env['product.template']
if 'context' in kw:
ProductTemplate = ProductTemplate.with_context(**kw.get('context'))
product_template = ProductTemplate.browse(int(product_template_id))
res = product_template._get_combination_info(combination, int(product_id or 0), int(add_qty or 1), pricelist)
if 'parent_combination' in kw:
parent_combination = request.env['product.template.attribute.value'].browse(kw.get('parent_combination'))
if not combination.exists() and product_id:
product = request.env['product.product'].browse(int(product_id))
if product.exists():
combination = product.product_template_attribute_value_ids
res.update({
'is_combination_possible': product_template._is_combination_possible(combination=combination, parent_combination=parent_combination),
'parent_exclusions': product_template._get_parent_attribute_exclusions(parent_combination=parent_combination)
})
return res
@http.route(['/sale/create_product_variant'], type='json', auth="user", methods=['POST'])
def create_product_variant(self, product_template_id, product_template_attribute_value_ids, **kwargs):
return request.env['product.template'].browse(int(product_template_id)).create_product_variant(product_template_attribute_value_ids)
def _get_pricelist(self, pricelist_id, pricelist_fallback=False):
return request.env['product.pricelist'].browse(int(pricelist_id or 0))
| 61.171429 | 2,141 |
1,275 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2009-2016 Salvatore Josué Trimarchi Pinto <[email protected]>
# This module provides a minimal Honduran chart of accounts that can be use
# to build upon a more complex one. It also includes a chart of taxes and
# the Lempira currency.
{
'name': 'Honduras - Accounting',
'version': '0.2',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the base module to manage the accounting chart for Honduras.
====================================================================
Agrega una nomenclatura contable para Honduras. También incluye impuestos y la
moneda Lempira. -- Adds accounting chart for Honduras. It also includes taxes
and the Lempira currency.""",
'author': 'Salvatore Josue Trimarchi Pinto',
'website': 'http://bacgroup.net',
'depends': ['base', 'account'],
'data': [
'data/l10n_hn_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_hn_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 36.371429 | 1,273 |
974 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Germany - Accounting',
'author': 'openbig.org',
'version': '1.1',
'website': 'http://www.openbig.org',
'category': 'Accounting/Localizations',
'description': """
Dieses Modul beinhaltet einen deutschen Kontenrahmen basierend auf dem SKR03.
==============================================================================
German accounting chart and localization.
""",
'depends': [
'account',
'base_iban',
'base_vat',
],
'data': [
'data/account_account_tags_data.xml',
'data/menuitem_data.xml',
'views/account_view.xml',
'views/res_company_views.xml',
'report/din5008_report.xml',
'data/report_layout.xml',
],
'assets': {
'web.report_assets_common': [
'l10n_de/static/src/**/*',
],
},
'license': 'LGPL-3',
}
| 27.828571 | 974 |
2,026 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details
from odoo import api, SUPERUSER_ID
def migrate(cr, version):
# The tax report line 68 has been removed as it does not appear in tax report anymore.
# But, it was referenced in the account.sales.report
# So, we update amls of this line only, to make this report consistent.
env = api.Environment(cr, SUPERUSER_ID, {})
country = env['res.country'].search([('code', '=', 'DE')], limit=1)
tags_68 = env['account.account.tag']._get_tax_tags('68', country.id)
tags_60 = env.ref('l10n_de.tax_report_de_tag_60').tag_ids
if tags_68.filtered(lambda tag: tag.tax_negate):
cr.execute(
"""
UPDATE account_account_tag_account_move_line_rel
SET account_account_tag_id = %s
WHERE account_account_tag_id IN %s;
""",
[
tags_60.filtered(lambda tag: tag.tax_negate)[0].id,
tuple(tags_68.filtered(lambda tag: tag.tax_negate).ids)
]
)
if tags_68.filtered(lambda tag: not tag.tax_negate):
cr.execute(
"""
UPDATE account_account_tag_account_move_line_rel
SET account_account_tag_id = %s
WHERE account_account_tag_id IN %s;
""",
[
tags_60.filtered(lambda tag: not tag.tax_negate)[0].id,
tuple(tags_68.filtered(lambda tag: not tag.tax_negate).ids)
]
)
cr.execute(
r"""
UPDATE account_move_line
SET tax_audit = REGEXP_REPLACE(tax_audit, '(?<=(^|\s))68:', '60:')
FROM (
SELECT aml.id as aml_id
FROM account_move_line aml
JOIN account_account_tag_account_move_line_rel aml_tag_rel ON aml_tag_rel.account_move_line_id = aml.id
WHERE aml_tag_rel.account_account_tag_id IN %s
) aml
WHERE id = aml.aml_id
""", [tuple(tags_60.ids)]
)
| 38.226415 | 2,026 |
2,667 |
py
|
PYTHON
|
15.0
|
from odoo import models, fields, _
from odoo.tools import format_date
class AccountMove(models.Model):
_inherit = 'account.move'
l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data')
l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title')
l10n_de_addresses = fields.Binary(compute='_compute_l10n_de_addresses')
def _compute_l10n_de_template_data(self):
for record in self:
record.l10n_de_template_data = data = []
if record.name:
data.append((_("Invoice No."), record.name))
if record.invoice_date:
data.append((_("Invoice Date"), format_date(self.env, record.invoice_date)))
if record.invoice_date_due:
data.append((_("Due Date"), format_date(self.env, record.invoice_date_due)))
if record.invoice_origin:
data.append((_("Source"), record.invoice_origin))
if record.ref:
data.append((_("Reference"), record.ref))
def _compute_l10n_de_document_title(self):
for record in self:
record.l10n_de_document_title = ''
if record.move_type == 'out_invoice':
if record.state == 'posted':
record.l10n_de_document_title = _('Invoice')
elif record.state == 'draft':
record.l10n_de_document_title = _('Draft Invoice')
elif record.state == 'cancel':
record.l10n_de_document_title = _('Cancelled Invoice')
elif record.move_type == 'out_refund':
record.l10n_de_document_title = _('Credit Note')
elif record.move_type == 'in_refund':
record.l10n_de_document_title = _('Vendor Credit Note')
elif record.move_type == 'in_invoice':
record.l10n_de_document_title = _('Vendor Bill')
def _compute_l10n_de_addresses(self):
for record in self:
record.l10n_de_addresses = data = []
if 'partner_shipping_id' not in record._fields:
data.append((_("Invoicing Address:"), record.partner_id))
elif record.partner_shipping_id == record.partner_id:
data.append((_("Invoicing and Shipping Address:"), record.partner_shipping_id))
elif record.move_type in ("in_invoice", "in_refund"):
data.append((_("Invoicing and Shipping Address:"), record.partner_id))
else:
data.append((_("Shipping Address:"), record.partner_shipping_id))
data.append((_("Invoicing Address:"), record.partner_id))
| 49.388889 | 2,667 |
535 |
py
|
PYTHON
|
15.0
|
from odoo import models, fields, api, _
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data')
l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title')
def _compute_l10n_de_template_data(self):
for record in self:
record.l10n_de_template_data = []
def _compute_l10n_de_document_title(self):
for record in self:
record.l10n_de_document_title = ''
| 33.4375 | 535 |
306 |
py
|
PYTHON
|
15.0
|
from odoo import models
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'
def _get_rendering_context(self, docids, data):
data = super()._get_rendering_context(docids, data)
data['din_header_spacing'] = self.get_paperformat().header_spacing
return data
| 30.6 | 306 |
1,351 |
py
|
PYTHON
|
15.0
|
from odoo import models, fields, _
from odoo.tools import format_date
class BaseDocumentLayout(models.TransientModel):
_inherit = 'base.document.layout'
street = fields.Char(related='company_id.street', readonly=True)
street2 = fields.Char(related='company_id.street2', readonly=True)
zip = fields.Char(related='company_id.zip', readonly=True)
city = fields.Char(related='company_id.city', readonly=True)
company_registry = fields.Char(related='company_id.company_registry', readonly=True)
bank_ids = fields.One2many(related='company_id.partner_id.bank_ids', readonly=True)
account_fiscal_country_id = fields.Many2one(related='company_id.account_fiscal_country_id', readonly=True)
l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data')
l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title')
def _compute_l10n_de_template_data(self):
self.l10n_de_template_data = [
(_("Invoice No."), 'INV/2021/12345'),
(_("Invoice Date"), format_date(self.env, fields.Date.today())),
(_("Due Date"), format_date(self.env, fields.Date.add(fields.Date.today(), days=7))),
(_("Reference"), 'SO/2021/45678'),
]
def _compute_l10n_de_document_title(self):
self.l10n_de_document_title = _('Invoice')
| 50.037037 | 1,351 |
446 |
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 ResCompany(models.Model):
_inherit = 'res.company'
l10n_de_stnr = fields.Char(string="St.-Nr.", help="Steuernummer. Scheme: ??FF0BBBUUUUP, e.g.: 2893081508152 https://de.wikipedia.org/wiki/Steuernummer")
l10n_de_widnr = fields.Char(string="W-IdNr.", help="Wirtschafts-Identifikationsnummer.")
| 40.545455 | 446 |
3,023 |
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
from odoo.exceptions import UserError
from odoo.tools.translate import _
class AccountTaxTemplate(models.Model):
_inherit = 'account.tax.template'
l10n_de_datev_code = fields.Char(size=4)
def _get_tax_vals(self, company, tax_template_to_tax):
vals = super(AccountTaxTemplate, self)._get_tax_vals(company, tax_template_to_tax)
vals['l10n_de_datev_code'] = self.l10n_de_datev_code
return vals
class AccountTax(models.Model):
_inherit = "account.tax"
l10n_de_datev_code = fields.Char(size=4, help="4 digits code use by Datev")
class AccountMove(models.Model):
_inherit = 'account.move'
def _post(self, soft=True):
# OVERRIDE to check the invoice lines taxes.
for invoice in self.filtered(lambda move: move.is_invoice()):
for line in invoice.invoice_line_ids:
account_tax = line.account_id.tax_ids.ids
if account_tax and invoice.company_id.account_fiscal_country_id.code == 'DE':
account_name = line.account_id.name
for tax in line.tax_ids:
if tax.id not in account_tax:
raise UserError(_('Account %s does not authorize to have tax %s specified on the line. \
Change the tax used in this invoice or remove all taxes from the account') % (account_name, tax.name))
return super()._post(soft)
class ProductTemplate(models.Model):
_inherit = "product.template"
def _get_product_accounts(self):
""" As taxes with a different rate need a different income/expense account, we add this logic in case people only use
invoicing to not be blocked by the above constraint"""
result = super(ProductTemplate, self)._get_product_accounts()
company = self.env.company
if company.account_fiscal_country_id.code == "DE":
if not self.property_account_income_id:
taxes = self.taxes_id.filtered(lambda t: t.company_id == company)
if not result['income'] or (result['income'].tax_ids and taxes and taxes[0] not in result['income'].tax_ids):
result['income'] = self.env['account.account'].search([('internal_group', '=', 'income'), ('deprecated', '=', False),
('tax_ids', 'in', taxes.ids)], limit=1)
if not self.property_account_expense_id:
supplier_taxes = self.supplier_taxes_id.filtered(lambda t: t.company_id == company)
if not result['expense'] or (result['expense'].tax_ids and supplier_taxes and supplier_taxes[0] not in result['expense'].tax_ids):
result['expense'] = self.env['account.account'].search([('internal_group', '=', 'expense'), ('deprecated', '=', False),
('tax_ids', 'in', supplier_taxes.ids)], limit=1)
return result
| 53.035088 | 3,023 |
1,065 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, models
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
@api.model
def _prepare_transfer_account_for_direct_creation(self, name, company):
res = super(AccountChartTemplate, self)._prepare_transfer_account_for_direct_creation(name, company)
if company.account_fiscal_country_id.code == 'DE':
xml_id = self.env.ref('l10n_de.tag_de_asset_bs_B_III_2').id
res.setdefault('tag_ids', [])
res['tag_ids'].append((4, xml_id))
return res
# Write paperformat and report template used on company
def _load(self, sale_tax_rate, purchase_tax_rate, company):
res = super(AccountChartTemplate, self)._load(sale_tax_rate, purchase_tax_rate, company)
if company.account_fiscal_country_id.code == 'DE':
company.write({'external_report_layout_id': self.env.ref('l10n_de.external_layout_din5008').id,
'paperformat_id': self.env.ref('l10n_de.paperformat_euro_din').id})
return res
| 46.304348 | 1,065 |
1,131 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Warehouse Management: Batch Transfer',
'version': '1.0',
'category': 'Inventory/Inventory',
'description': """
This module adds the batch transfer option in warehouse management
==================================================================
""",
'depends': ['stock'],
'data': [
'security/ir.model.access.csv',
'views/stock_picking_batch_views.xml',
'views/stock_picking_wave_views.xml',
'views/stock_move_line_views.xml',
'data/stock_picking_batch_data.xml',
'wizard/stock_picking_to_batch_views.xml',
'wizard/stock_add_to_wave_views.xml',
'report/stock_picking_batch_report_views.xml',
'report/report_picking_batch.xml',
'security/stock_picking_batch_security.xml',
],
'demo': [
'data/stock_picking_batch_demo.xml',
],
'assets': {
'web.assets_backend': [
'stock_picking_batch/static/src/js/*',
]
},
'installable': True,
'license': 'LGPL-3',
}
| 32.314286 | 1,131 |
25,504 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo.exceptions import UserError
from odoo.tests import Form, tagged
from odoo.tests.common import TransactionCase
class TestBatchPicking(TransactionCase):
def setUp(self):
""" Create a picking batch with two pickings from stock to customer """
super(TestBatchPicking, self).setUp()
self.stock_location = self.env.ref('stock.stock_location_stock')
self.customer_location = self.env.ref('stock.stock_location_customers')
self.picking_type_out = self.env['ir.model.data']._xmlid_to_res_id('stock.picking_type_out')
self.env['stock.picking.type'].browse(self.picking_type_out).reservation_method = 'manual'
self.productA = self.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.productB = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.picking_client_1 = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.picking_type_out,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': self.picking_client_1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
self.picking_client_2 = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.picking_type_out,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': self.picking_client_2.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
self.picking_client_3 = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.picking_type_out,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': self.picking_client_3.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
self.batch = self.env['stock.picking.batch'].create({
'name': 'Batch 1',
'company_id': self.env.company.id,
'picking_ids': [(4, self.picking_client_1.id), (4, self.picking_client_2.id)]
})
def test_batch_scheduled_date(self):
""" Test to make sure the correct scheduled date is set for both a batch and its pickings.
Setting a batch's scheduled date manually has different behavior from when it is automatically
set/updated via compute.
"""
now = datetime.now().replace(microsecond=0)
self.batch.scheduled_date = now
# TODO: this test cannot currently handle the onchange scheduled_date logic because of test form
# view not handling the M2M widget assigned to picking_ids (O2M). Hopefully if this changes then
# commented parts of this test can be used later.
# manually set batch scheduled date => picking's scheduled dates auto update to match (onchange logic test)
# with Form(self.batch) as batch_form:
# batch_form.scheduled_date = now - timedelta(days=1)
# batch_form.save()
# self.assertEqual(self.batch.scheduled_date, self.picking_client_1.scheduled_date)
# self.assertEqual(self.batch.scheduled_date, self.picking_client_2.scheduled_date)
picking1_scheduled_date = now - timedelta(days=2)
picking2_scheduled_date = now - timedelta(days=3)
picking3_scheduled_date = now - timedelta(days=4)
# manually update picking scheduled dates => batch's scheduled date auto update to match lowest value
self.picking_client_1.scheduled_date = picking1_scheduled_date
self.picking_client_2.scheduled_date = picking2_scheduled_date
self.assertEqual(self.batch.scheduled_date, self.picking_client_2.scheduled_date)
# but individual pickings keep original scheduled dates
self.assertEqual(self.picking_client_1.scheduled_date, picking1_scheduled_date)
self.assertEqual(self.picking_client_2.scheduled_date, picking2_scheduled_date)
# add a new picking with an earlier scheduled date => batch's scheduled date should auto-update
self.picking_client_3.scheduled_date = picking3_scheduled_date
self.batch.write({'picking_ids': [(4, self.picking_client_3.id)]})
self.assertEqual(self.batch.scheduled_date, self.picking_client_3.scheduled_date)
# remove that picking and batch scheduled date should auto-update to next min date
self.batch.write({'picking_ids': [(3, self.picking_client_3.id)]})
self.assertEqual(self.batch.scheduled_date, self.picking_client_2.scheduled_date)
# directly add new picking with an earlier scheduled date => batch's scheduled date auto updates to match,
# but existing pickings do not (onchange logic test)
# with Form(self.batch) as batch_form:
# batch_form.picking_ids.add(self.picking_client_3)
# batch_form.save()
# # individual pickings keep original scheduled dates
self.assertEqual(self.picking_client_1.scheduled_date, picking1_scheduled_date)
self.assertEqual(self.picking_client_2.scheduled_date, picking2_scheduled_date)
# self.assertEqual(self.batch.scheduled_date, self.picking_client_3.scheduled_date)
# self.batch.write({'picking_ids': [(3, self.picking_client_3.id)]})
# cancelling batch should auto-remove all pickings => scheduled_date should default to none
self.batch.action_cancel()
self.assertEqual(len(self.batch.picking_ids), 0)
self.assertEqual(self.batch.scheduled_date, False)
def test_simple_batch_with_manual_qty_done(self):
""" Test a simple batch picking with all quantity for picking available.
The user set all the quantity_done on picking manually and no wizard are used.
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 10.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 10.0)
# Confirm batch, pickings should not be automatically assigned.
self.batch.action_confirm()
self.assertEqual(self.picking_client_1.state, 'confirmed', 'Picking 1 should be confirmed')
self.assertEqual(self.picking_client_2.state, 'confirmed', 'Picking 2 should be confirmed')
# Ask to assign, so pickings should be assigned now.
self.batch.action_assign()
self.assertEqual(self.picking_client_1.state, 'assigned', 'Picking 1 should be ready')
self.assertEqual(self.picking_client_2.state, 'assigned', 'Picking 2 should be ready')
self.picking_client_1.move_lines.quantity_done = 10
self.picking_client_2.move_lines.quantity_done = 10
self.batch.action_done()
self.assertEqual(self.picking_client_1.state, 'done', 'Picking 1 should be done')
self.assertEqual(self.picking_client_2.state, 'done', 'Picking 2 should be done')
quant_A = self.env['stock.quant']._gather(self.productA, self.stock_location)
quant_B = self.env['stock.quant']._gather(self.productB, self.stock_location)
# ensure that quantity for picking has been moved
self.assertFalse(sum(quant_A.mapped('quantity')))
self.assertFalse(sum(quant_B.mapped('quantity')))
# ensure that batch cannot be deleted now that it is done
with self.assertRaises(UserError):
self.batch.unlink()
def test_simple_batch_with_wizard(self):
""" Test a simple batch picking with all quantity for picking available.
The user use the wizard in order to complete automatically the quantity_done to
the initial demand (or reserved quantity in this test).
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 10.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 10.0)
# Confirm batch, pickings should not be automatically assigned.
self.batch.action_confirm()
self.assertEqual(self.picking_client_1.state, 'confirmed', 'Picking 1 should be confirmed')
self.assertEqual(self.picking_client_2.state, 'confirmed', 'Picking 2 should be confirmed')
# Ask to assign, so pickings should be assigned now.
self.batch.action_assign()
self.assertEqual(self.picking_client_1.state, 'assigned', 'Picking 1 should be ready')
self.assertEqual(self.picking_client_2.state, 'assigned', 'Picking 2 should be ready')
# There should be a wizard asking to process picking without quantity done
immediate_transfer_wizard_dict = self.batch.action_done()
self.assertTrue(immediate_transfer_wizard_dict)
immediate_transfer_wizard = Form(self.env[(immediate_transfer_wizard_dict.get('res_model'))].with_context(immediate_transfer_wizard_dict['context'])).save()
self.assertEqual(len(immediate_transfer_wizard.pick_ids), 2)
immediate_transfer_wizard.process()
self.assertEqual(self.picking_client_1.state, 'done', 'Picking 1 should be done')
self.assertEqual(self.picking_client_2.state, 'done', 'Picking 2 should be done')
quant_A = self.env['stock.quant']._gather(self.productA, self.stock_location)
quant_B = self.env['stock.quant']._gather(self.productB, self.stock_location)
# ensure that quantity for picking has been moved
self.assertFalse(sum(quant_A.mapped('quantity')))
self.assertFalse(sum(quant_B.mapped('quantity')))
def test_batch_with_backorder_wizard(self):
""" Test a simple batch picking with only one quantity fully available.
The user will set by himself the quantity reserved for each picking and
run the picking batch. There should be a wizard asking for a backorder.
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 5.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 10.0)
# Confirm batch, pickings should not be automatically assigned.
self.batch.action_confirm()
self.assertEqual(self.picking_client_1.state, 'confirmed', 'Picking 1 should be confirmed')
self.assertEqual(self.picking_client_2.state, 'confirmed', 'Picking 2 should be confirmed')
# Ask to assign, so pickings should be assigned now.
self.batch.action_assign()
self.assertEqual(self.picking_client_1.state, 'assigned', 'Picking 1 should be ready')
self.assertEqual(self.picking_client_2.state, 'assigned', 'Picking 2 should be ready')
self.picking_client_1.move_lines.quantity_done = 5
self.picking_client_2.move_lines.quantity_done = 10
# There should be a wizard asking to process picking without quantity done
back_order_wizard_dict = self.batch.action_done()
self.assertTrue(back_order_wizard_dict)
back_order_wizard = Form(self.env[(back_order_wizard_dict.get('res_model'))].with_context(back_order_wizard_dict['context'])).save()
self.assertEqual(len(back_order_wizard.pick_ids), 1)
back_order_wizard.process()
self.assertEqual(self.picking_client_2.state, 'done', 'Picking 2 should be done')
self.assertEqual(self.picking_client_1.state, 'done', 'Picking 1 should be done')
self.assertEqual(self.picking_client_1.move_lines.product_uom_qty, 5, 'initial demand should be 5 after picking split')
self.assertTrue(self.env['stock.picking'].search([('backorder_id', '=', self.picking_client_1.id)]), 'no back order created')
quant_A = self.env['stock.quant']._gather(self.productA, self.stock_location)
quant_B = self.env['stock.quant']._gather(self.productB, self.stock_location)
# ensure that quantity for picking has been moved
self.assertFalse(sum(quant_A.mapped('quantity')))
self.assertFalse(sum(quant_B.mapped('quantity')))
def test_batch_with_immediate_transfer_and_backorder_wizard(self):
""" Test a simple batch picking with only one product fully available.
Everything should be automatically. First one backorder in order to set quantity_done
to reserved quantity. After a second wizard asking for a backorder for the quantity that
has not been fully transfered.
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 5.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 10.0)
# Confirm batch, pickings should not be automatically assigned.
self.batch.action_confirm()
self.assertEqual(self.picking_client_1.state, 'confirmed', 'Picking 1 should be confirmed')
self.assertEqual(self.picking_client_2.state, 'confirmed', 'Picking 2 should be confirmed')
# Ask to assign, so pickings should be assigned now.
self.batch.action_assign()
self.assertEqual(self.picking_client_1.state, 'assigned', 'Picking 1 should be ready')
self.assertEqual(self.picking_client_2.state, 'assigned', 'Picking 2 should be ready')
# There should be a wizard asking to process picking without quantity done
immediate_transfer_wizard_dict = self.batch.action_done()
self.assertTrue(immediate_transfer_wizard_dict)
immediate_transfer_wizard = Form(self.env[(immediate_transfer_wizard_dict.get('res_model'))].with_context(immediate_transfer_wizard_dict['context'])).save()
self.assertEqual(len(immediate_transfer_wizard.pick_ids), 2)
back_order_wizard_dict = immediate_transfer_wizard.process()
self.assertTrue(back_order_wizard_dict)
back_order_wizard = Form(self.env[(back_order_wizard_dict.get('res_model'))].with_context(back_order_wizard_dict['context'])).save()
self.assertEqual(len(back_order_wizard.pick_ids), 1)
back_order_wizard.process()
self.assertEqual(self.picking_client_1.state, 'done', 'Picking 1 should be done')
self.assertEqual(self.picking_client_1.move_lines.product_uom_qty, 5, 'initial demand should be 5 after picking split')
self.assertTrue(self.env['stock.picking'].search([('backorder_id', '=', self.picking_client_1.id)]), 'no back order created')
quant_A = self.env['stock.quant']._gather(self.productA, self.stock_location)
quant_B = self.env['stock.quant']._gather(self.productB, self.stock_location)
# ensure that quantity for picking has been moved
self.assertFalse(sum(quant_A.mapped('quantity')))
self.assertFalse(sum(quant_B.mapped('quantity')))
def test_batch_with_immediate_transfer_and_backorder_wizard_with_manual_operations(self):
""" Test a simple batch picking with only one quantity fully available.
The user set the quantity done only for the partially available picking.
The test should run the immediate transfer for the first picking and then
the backorder wizard for the second picking.
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 5.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 10.0)
# Confirm batch, pickings should not be automatically assigned.
self.batch.action_confirm()
self.assertEqual(self.picking_client_1.state, 'confirmed', 'Picking 1 should be confirmed')
self.assertEqual(self.picking_client_2.state, 'confirmed', 'Picking 2 should be confirmed')
# Ask to assign, so pickings should be assigned now.
self.batch.action_assign()
self.assertEqual(self.picking_client_1.state, 'assigned', 'Picking 1 should be ready')
self.assertEqual(self.picking_client_2.state, 'assigned', 'Picking 2 should be ready')
self.picking_client_1.move_lines.quantity_done = 5
# There should be a wizard asking to make a backorder
back_order_wizard_dict = self.batch.action_done()
self.assertTrue(back_order_wizard_dict)
self.assertEqual(back_order_wizard_dict.get('res_model'), 'stock.backorder.confirmation')
back_order_wizard = Form(self.env[(back_order_wizard_dict.get('res_model'))].with_context(back_order_wizard_dict['context'])).save()
self.assertEqual(len(back_order_wizard.pick_ids), 2)
back_order_wizard.process()
self.assertEqual(self.picking_client_1.state, 'done', 'Picking 1 should be done')
self.assertEqual(self.picking_client_1.move_lines.product_uom_qty, 5, 'initial demand should be 5 after picking split')
self.assertFalse(self.picking_client_2.batch_id)
def test_put_in_pack(self):
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 10.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 10.0)
# Confirm batch, pickings should not be automatically assigned.
self.batch.action_confirm()
self.assertEqual(self.picking_client_1.state, 'confirmed', 'Picking 1 should be confirmed')
self.assertEqual(self.picking_client_2.state, 'confirmed', 'Picking 2 should be confirmed')
# Ask to assign, so pickings should be assigned now.
self.batch.action_assign()
self.assertEqual(self.picking_client_1.state, 'assigned', 'Picking 1 should be ready')
self.assertEqual(self.picking_client_2.state, 'assigned', 'Picking 2 should be ready')
# only do part of pickings + assign different destinations + try to pack (should get wizard to correct destination)
self.batch.move_line_ids.qty_done = 5
self.batch.move_line_ids[0].location_dest_id = self.stock_location.id
wizard_values = self.batch.action_put_in_pack()
wizard = self.env[(wizard_values.get('res_model'))].browse(wizard_values.get('res_id'))
wizard.location_dest_id = self.customer_location.id
package = wizard.action_done()
# a new package is made and done quantities should be in same package
self.assertTrue(package)
done_qty_move_lines = self.batch.move_line_ids.filtered(lambda ml: ml.qty_done == 5)
self.assertEqual(done_qty_move_lines[0].result_package_id.id, package.id)
self.assertEqual(done_qty_move_lines[1].result_package_id.id, package.id)
# not done quantities should be split into separate lines
self.assertEqual(len(self.batch.move_line_ids), 4)
# confirm w/ backorder
back_order_wizard_dict = self.batch.action_done()
self.assertTrue(back_order_wizard_dict)
back_order_wizard = Form(self.env[(back_order_wizard_dict.get('res_model'))].with_context(back_order_wizard_dict['context'])).save()
self.assertEqual(len(back_order_wizard.pick_ids), 2)
back_order_wizard.process()
# final package location should be correctly set based on wizard
self.assertEqual(package.location_id.id, self.customer_location.id)
def test_remove_all_transfers_from_confirmed_batch(self):
"""
Check that the batch is canceled when all transfers are deleted
"""
self.batch.action_confirm()
self.assertEqual(self.batch.state, 'in_progress', 'Batch Transfers should be in progress.')
self.batch.write({'picking_ids': [[5, 0, 0]]})
self.assertEqual(self.batch.state, 'cancel', 'Batch Transfers should be cancelled when there are no transfers.')
@tagged('-at_install', 'post_install')
class TestBatchPicking02(TransactionCase):
def setUp(self):
super().setUp()
self.stock_location = self.env.ref('stock.stock_location_stock')
self.picking_type_internal = self.env.ref('stock.picking_type_internal')
self.productA = self.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.productB = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
def test_same_package_several_pickings(self):
"""
A batch with two transfers, source and destination are the same. The
first picking contains 3 x P, the second one 7 x P. The 10 P are in a
package. It should be possible to transfer the whole package across the
two pickings
"""
package = self.env['stock.quant.package'].create({
'name': 'superpackage',
})
loc1, loc2 = self.stock_location.child_ids
self.env['stock.quant']._update_available_quantity(self.productA, loc1, 10, package_id=package)
pickings = self.env['stock.picking'].create([{
'location_id': loc1.id,
'location_dest_id': loc2.id,
'picking_type_id': self.picking_type_internal.id,
'move_lines': [(0, 0, {
'name': 'test_put_in_pack_from_multiple_pages',
'location_id': loc1.id,
'location_dest_id': loc2.id,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': qty,
})]
} for qty in (3, 7)])
pickings.action_confirm()
pickings.action_assign()
batch_form = Form(self.env['stock.picking.batch'])
batch_form.picking_ids.add(pickings[0])
batch_form.picking_ids.add(pickings[1])
batch = batch_form.save()
batch.action_confirm()
pickings.move_line_ids[0].qty_done = 3
pickings.move_line_ids[1].qty_done = 7
pickings.move_line_ids.result_package_id = package
batch.action_done()
self.assertRecordValues(pickings.move_lines, [
{'state': 'done', 'quantity_done': 3},
{'state': 'done', 'quantity_done': 7},
])
self.assertEqual(pickings.move_line_ids.result_package_id, package)
def test_batch_validation_without_backorder(self):
loc1, loc2 = self.stock_location.child_ids
self.env['stock.quant']._update_available_quantity(self.productA, loc1, 10)
self.env['stock.quant']._update_available_quantity(self.productB, loc1, 10)
picking_1 = self.env['stock.picking'].create({
'location_id': loc1.id,
'location_dest_id': loc2.id,
'picking_type_id': self.picking_type_internal.id,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_1.id,
'location_id': loc1.id,
'location_dest_id': loc2.id,
})
picking_2 = self.env['stock.picking'].create({
'location_id': loc1.id,
'location_dest_id': loc2.id,
'picking_type_id': self.picking_type_internal.id,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 5,
'product_uom': self.productB.uom_id.id,
'picking_id': picking_2.id,
'location_id': loc1.id,
'location_dest_id': loc2.id,
})
(picking_1 | picking_2).action_confirm()
(picking_1 | picking_2).action_assign()
picking_2.move_lines.move_line_ids.write({'qty_done': 1})
batch = self.env['stock.picking.batch'].create({
'name': 'Batch 1',
'company_id': self.env.company.id,
'picking_ids': [(4, picking_1.id), (4, picking_2.id)]
})
batch.action_confirm()
action = batch.action_done()
Form(self.env[action['res_model']].with_context(action['context'])).save().process_cancel_backorder()
self.assertEqual(batch.state, 'done')
| 52.477366 | 25,504 |
21,435 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestBatchPicking(TransactionCase):
@classmethod
def setUpClass(cls):
""" Create 3 standard pickings and reserve them to have some move lines.
The setup data looks like this:
Picking1 Picking2 Picking3
ProductA ProductA ProductB
Lot1: 5 units Lot4: 5 units SN6 : 1 unit
Lot2: 5 units SN7 : 1 unit
Lot3: 5 units SN8 : 1 unit
ProductB SN9 : 1 unit
SN1 : 1 unit SN10: 1 unit
SN2 : 1 unit
SN3 : 1 unit
SN4 : 1 unit
SN5 : 1 unit
"""
super().setUpClass()
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.picking_type_out = cls.env['ir.model.data']._xmlid_to_res_id('stock.picking_type_out')
cls.picking_type_in = cls.env['ir.model.data']._xmlid_to_res_id('stock.picking_type_in')
cls.user_demo = cls.env['res.users'].search([('login', '=', 'demo')])
cls.productA = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'tracking': 'lot',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.lots_p_a = cls.env['stock.production.lot'].create([{
'name': 'lot_product_a_' + str(i + 1),
'product_id': cls.productA.id,
'company_id': cls.env.company.id,
} for i in range(4)])
cls.productB = cls.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'tracking': 'serial',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.lots_p_b = cls.env['stock.production.lot'].create([{
'name': 'lot_product_a_' + str(i + 1),
'product_id': cls.productB.id,
'company_id': cls.env.company.id,
} for i in range(10)])
Quant = cls.env['stock.quant']
for lot in cls.lots_p_a:
Quant._update_available_quantity(cls.productA, cls.stock_location, 5.0, lot_id=lot)
for lot in cls.lots_p_b:
Quant._update_available_quantity(cls.productB, cls.stock_location, 1.0, lot_id=lot)
cls.picking_client_1 = cls.env['stock.picking'].create({
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
'picking_type_id': cls.picking_type_out,
'company_id': cls.env.company.id,
})
cls.env['stock.move'].create({
'name': cls.productA.name,
'product_id': cls.productA.id,
'product_uom_qty': 15,
'product_uom': cls.productA.uom_id.id,
'picking_id': cls.picking_client_1.id,
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
})
cls.env['stock.move'].create({
'name': cls.productB.name,
'product_id': cls.productB.id,
'product_uom_qty': 5,
'product_uom': cls.productB.uom_id.id,
'picking_id': cls.picking_client_1.id,
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
})
cls.picking_client_2 = cls.env['stock.picking'].create({
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
'picking_type_id': cls.picking_type_out,
'company_id': cls.env.company.id,
})
cls.env['stock.move'].create({
'name': cls.productA.name,
'product_id': cls.productA.id,
'product_uom_qty': 5,
'product_uom': cls.productA.uom_id.id,
'picking_id': cls.picking_client_2.id,
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
})
cls.picking_client_3 = cls.env['stock.picking'].create({
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
'picking_type_id': cls.picking_type_out,
'company_id': cls.env.company.id,
})
cls.env['stock.move'].create({
'name': cls.productB.name,
'product_id': cls.productB.id,
'product_uom_qty': 5,
'product_uom': cls.productB.uom_id.id,
'picking_id': cls.picking_client_3.id,
'location_id': cls.stock_location.id,
'location_dest_id': cls.customer_location.id,
})
cls.all_pickings = cls.picking_client_1 | cls.picking_client_2 | cls.picking_client_3
cls.all_pickings.action_confirm()
def test_creation_from_lines(self):
""" Select all the move_lines and create a wave from them """
all_lines = self.all_pickings.move_line_ids
res_dict = all_lines.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': all_lines.ids}
self.assertEqual(res_dict.get('res_model'), 'stock.add.to.wave')
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard_form.user_id = self.user_demo
wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertTrue(wave)
self.assertEqual(wave.picking_ids, self.all_pickings)
self.assertEqual(wave.move_line_ids, all_lines)
self.assertEqual(wave.user_id, self.user_demo)
def test_creation_from_pickings(self):
""" Select all the picking_ids and create a wave from them """
action = self.env['ir.actions.actions']._for_xml_id('stock_picking_batch.stock_add_to_wave_action_stock_picking')
action['context'] = {'active_model': 'stock.picking', 'active_ids': self.all_pickings.ids}
self.assertEqual(action.get('res_model'), 'stock.add.to.wave')
wizard_form = Form(self.env[action['res_model']].with_context(action['context']))
wizard_form.mode = 'new'
wizard = wizard_form.save()
res = wizard.attach_pickings()
self.assertEqual(set(res['context']['picking_to_wave']), set(self.all_pickings.ids))
def test_add_to_existing_wave_from_lines(self):
res_dict = self.picking_client_1.move_line_ids.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': self.picking_client_1.move_line_ids.ids}
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard_form.user_id = self.user_demo
wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
res_dict = self.picking_client_2.move_line_ids.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': self.picking_client_2.move_line_ids.ids}
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'existing'
wizard_form.wave_id = wave
wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertEqual(len(wave), 1)
self.assertEqual(wave.picking_ids, self.picking_client_1 | self.picking_client_2)
def test_add_to_existing_wave_from_pickings(self):
res_dict = self.picking_client_1.move_line_ids.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': self.picking_client_1.move_line_ids.ids}
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard_form.user_id = self.user_demo
action = wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
action = self.env['ir.actions.actions']._for_xml_id('stock_picking_batch.stock_add_to_wave_action_stock_picking')
action['context'] = {'active_model': 'stock.picking', 'active_ids': self.all_pickings.ids}
self.assertEqual(action.get('res_model'), 'stock.add.to.wave')
wizard_form = Form(self.env[action['res_model']].with_context(action['context']))
wizard_form.mode = 'existing'
wizard_form.wave_id = wave
wizard = wizard_form.save()
res = wizard.attach_pickings()
self.assertEqual(set(res['context']['picking_to_wave']), set(self.all_pickings.ids))
self.assertEqual(res['context']['active_wave_id'], wave.id)
def test_wave_split_picking(self):
lines = self.picking_client_1.move_lines.filtered(lambda m: m.product_id == self.productB).move_line_ids
move = lines.move_id
self.assertEqual(len(move), 1)
all_db_pickings = self.env['stock.picking'].search([])
res_dict = lines.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': lines.ids}
self.assertEqual(res_dict.get('res_model'), 'stock.add.to.wave')
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertTrue(wave)
# Original picking lost a stock move
self.assertTrue(move.picking_id)
self.assertFalse(move.picking_id == self.picking_client_1)
self.assertTrue(self.picking_client_1.move_lines)
self.assertTrue(move.picking_id.batch_id == wave)
self.assertTrue(lines.batch_id == wave)
new_all_db_picking = self.env['stock.picking'].search([])
self.assertEqual(len(all_db_pickings) + 1, len(new_all_db_picking))
def test_wave_split_move(self):
lines = self.picking_client_1.move_lines.filtered(lambda m: m.product_id == self.productB).move_line_ids[0:2]
move = lines.move_id
all_db_pickings = self.env['stock.picking'].search([])
res_dict = lines.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': lines.ids}
self.assertEqual(res_dict.get('res_model'), 'stock.add.to.wave')
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertTrue(wave)
# Original picking lost a stock move
self.assertTrue(move.picking_id)
self.assertTrue(move.picking_id == self.picking_client_1)
self.assertFalse(lines.move_id == move)
self.assertFalse(move.picking_id.batch_id)
new_move = lines.move_id
self.assertTrue(new_move.picking_id.batch_id == wave)
self.assertTrue(lines.batch_id == wave)
new_all_db_picking = self.env['stock.picking'].search([])
self.assertEqual(len(all_db_pickings) + 1, len(new_all_db_picking))
def test_wave_split_move_uom(self):
self.uom_dozen = self.env.ref('uom.product_uom_dozen')
sns = self.env['stock.production.lot'].create([{
'name': 'sn-' + str(i),
'product_id': self.productB.id,
'company_id': self.env.company.id
} for i in range(12)])
for i in range(12):
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 1.0, lot_id=sns[i])
dozen_move = self.env['stock.move'].create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 1,
'product_uom': self.uom_dozen.id,
'picking_id': self.picking_client_1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
dozen_move._action_confirm()
dozen_move._action_assign()
self.assertEqual(len(dozen_move.move_line_ids), 12)
self.assertEqual(dozen_move.move_line_ids.product_uom_id, self.env.ref('uom.product_uom_unit'))
lines = dozen_move.move_line_ids[0:5]
res_dict = lines.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': lines.ids}
self.assertEqual(res_dict.get('res_model'), 'stock.add.to.wave')
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard_form.save().attach_pickings()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertFalse(lines.move_id == dozen_move)
self.assertEqual(lines.batch_id, wave)
self.assertEqual(dozen_move.product_uom_qty, 0.58)
def test_wave_mutliple_move_lines(self):
self.productA = self.env['product.product'].create({
'name': 'Product Test A',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.picking_type_out,
'company_id': self.env.company.id,
'immediate_transfer': True,
})
ml1 = self.env['stock.move.line'].create({
'product_id': self.productA.id,
'qty_done': 5,
'product_uom_id': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
self.env['stock.move.line'].create({
'product_id': self.productA.id,
'qty_done': 5,
'product_uom_id': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
ml2 = self.env['stock.move.line'].create({
'product_id': self.productA.id,
'qty_done': 5,
'product_uom_id': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
picking.action_confirm()
ml1._add_to_wave()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertFalse(picking.batch_id)
self.assertEqual(ml1.picking_id.batch_id.id, wave.id)
self.assertEqual(ml1.picking_id.move_lines.product_uom_qty, 5)
self.assertEqual(ml2.picking_id.id, picking.id)
self.assertEqual(ml2.picking_id.move_lines.product_uom_qty, 10)
def test_wave_trigger_errors(self):
with self.assertRaises(UserError):
lines = self.picking_client_1.move_line_ids
res_dict = lines.action_open_add_to_wave()
wizard_form = Form(self.env[res_dict['res_model']])
wizard_form.mode = 'new'
wizard = wizard_form.save()
wizard.attach_pickings()
with self.assertRaises(UserError):
companies = self.env['res.company'].search([])
self.picking_client_1.company_id = companies[0]
self.picking_client_2.company_id = companies[1]
lines = (self.picking_client_1 | self.picking_client_2).move_line_ids
res_dict = lines.action_open_add_to_wave()
res_dict['context'] = {'active_model': 'stock.move.line', 'active_ids': lines.ids}
wizard_form = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
wizard_form.mode = 'new'
wizard = wizard_form.save()
wizard.attach_pickings()
def test_not_assign_to_wave(self):
""" Picking
- Move line A 5 from Container to Cust -> Going to a wave picking
- Move line A 5 from Container to Cust -> Validate
---------------------------------------------
Create
- Move A 5 from Container to Cust
Check it creates a new picking and it's not assign to the wave
"""
location = self.env['stock.location'].create({
'name': 'Container',
'location_id': self.stock_location.id
})
self.env['stock.quant']._update_available_quantity(self.productA, location, 5.0, lot_id=self.lots_p_a[0])
self.env['stock.quant']._update_available_quantity(self.productA, location, 5.0, lot_id=self.lots_p_a[1])
picking_1 = self.env['stock.picking'].create({
'location_id': location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.picking_type_out,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': 'Test Wave',
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_1.id,
'picking_type_id': self.picking_type_out,
'location_id': location.id,
'location_dest_id': self.customer_location.id,
})
picking_1.action_confirm()
picking_1.action_assign()
self.assertEqual(len(picking_1.move_line_ids), 2)
move_line_to_wave = picking_1.move_line_ids[0]
move_line_to_wave._add_to_wave()
picking_1.move_line_ids.qty_done = 5
picking_1._action_done()
new_move = self.env['stock.move'].create({
'name': 'Test Wave',
'product_id': self.productA.id,
'product_uom_qty': 5,
'product_uom': self.productA.uom_id.id,
'picking_type_id': self.picking_type_out,
'location_id': location.id,
'location_dest_id': self.customer_location.id,
})
new_move._action_confirm()
self.assertTrue(new_move.picking_id)
self.assertTrue(new_move.picking_id.id not in [picking_1.id, move_line_to_wave.picking_id.id])
def test_operation_type_in_wave(self):
"""
Check that the operation type of the picking is set correclty in the wave.
"""
warehouse = self.env['stock.warehouse'].search([], limit=1)
warehouse.reception_steps = 'three_steps'
self.productA = self.env['product.product'].create({
'name': 'Product Test A',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.productB = self.env['product.product'].create({
'name': 'Product Test B',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
picking = self.env['stock.picking'].create({
'location_id': self.customer_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': self.picking_type_in,
'company_id': self.env.company.id,
})
self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': self.customer_location.id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
self.env['stock.move'].create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 5,
'product_uom': self.productB.uom_id.id,
'picking_id': picking.id,
'location_id': self.customer_location.id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
picking.action_confirm()
picking.move_lines.move_line_ids.write({'qty_done': 1})
res_dict = picking.button_validate()
self.env[res_dict['res_model']].with_context(res_dict['context']).process()
move_line = self.env["stock.move.line"].search([('product_id', '=', self.productA.id), ('location_id', '=', warehouse.wh_input_stock_loc_id.id)])
move_line._add_to_wave()
wave = self.env['stock.picking.batch'].search([
('is_wave', '=', True)
])
self.assertEqual(wave.picking_type_id, move_line.picking_type_id)
| 45.899358 | 21,435 |
1,336 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import UserError
class StockPickingToBatch(models.TransientModel):
_name = 'stock.picking.to.batch'
_description = 'Batch Transfer Lines'
batch_id = fields.Many2one('stock.picking.batch', string='Batch Transfer', domain="[('state', '=', 'draft')]")
mode = fields.Selection([('existing', 'an existing batch transfer'), ('new', 'a new batch transfer')], default='existing')
user_id = fields.Many2one('res.users', string='Responsible', help='Person responsible for this batch transfer')
def attach_pickings(self):
self.ensure_one()
pickings = self.env['stock.picking'].browse(self.env.context.get('active_ids'))
if self.mode == 'new':
company = pickings.company_id
if len(company) > 1:
raise UserError(_("The selected pickings should belong to an unique company."))
batch = self.env['stock.picking.batch'].create({
'user_id': self.user_id.id,
'company_id': company.id,
'picking_type_id': pickings[0].picking_type_id.id,
})
else:
batch = self.batch_id
pickings.write({'batch_id': batch.id})
| 43.096774 | 1,336 |
727 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class StockBackorderConfirmation(models.TransientModel):
_inherit = 'stock.backorder.confirmation'
def process(self):
res = super().process()
if self.env.context.get('pickings_to_detach'):
self.env['stock.picking'].browse(self.env.context['pickings_to_detach']).batch_id = False
return res
def process_cancel_backorder(self):
res = super().process_cancel_backorder()
if self.env.context.get('pickings_to_detach'):
self.env['stock.picking'].browse(self.env.context['pickings_to_detach']).batch_id = False
return res
| 36.35 | 727 |
1,100 |
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 ChooseDestinationLocation(models.TransientModel):
_inherit = "stock.package.destination"
def _compute_move_line_ids(self):
destination_without_batch = self.env['stock.package.destination']
for destination in self:
if not destination.picking_id.batch_id:
destination_without_batch |= destination
continue
destination.move_line_ids = destination.picking_id.batch_id.move_line_ids.filtered(lambda l: l.qty_done > 0 and not l.result_package_id)
super(ChooseDestinationLocation, destination_without_batch)._compute_move_line_ids()
def action_done(self):
if self.picking_id.batch_id:
# set the same location on each move line and pass again in action_put_in_pack
self.move_line_ids.location_dest_id = self.location_dest_id
return self.picking_id.batch_id.action_put_in_pack()
else:
return super().action_done()
| 44 | 1,100 |
2,965 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
from odoo.exceptions import UserError
class StockPickingToWave(models.TransientModel):
_name = 'stock.add.to.wave'
_description = 'Wave Transfer Lines'
@api.model
def default_get(self, fields_list):
res = super().default_get(fields_list)
if self.env.context.get('active_model') == 'stock.move.line':
lines = self.env['stock.move.line'].browse(self.env.context.get('active_ids'))
res['line_ids'] = self.env.context.get('active_ids')
picking_types = lines.picking_type_id
elif self.env.context.get('active_model') == 'stock.picking':
pickings = self.env['stock.picking'].browse(self.env.context.get('active_ids'))
res['picking_ids'] = self.env.context.get('active_ids')
picking_types = pickings.picking_type_id
else:
return res
if len(picking_types) > 1:
raise UserError(_("The selected transfers should belong to the same operation type"))
return res
wave_id = fields.Many2one('stock.picking.batch', string='Wave Transfer', domain="[('is_wave', '=', True), ('state', '!=', 'done')]")
picking_ids = fields.Many2many('stock.picking')
line_ids = fields.Many2many('stock.move.line')
mode = fields.Selection([('existing', 'an existing wave transfer'), ('new', 'a new wave transfer')], default='existing')
user_id = fields.Many2one('res.users', string='Responsible', help='Person responsible for this wave transfer')
def attach_pickings(self):
self.ensure_one()
self = self.with_context(active_owner_id=self.user_id.id)
if self.line_ids:
company = self.line_ids.company_id
if len(company) > 1:
raise UserError(_("The selected operations should belong to a unique company."))
return self.line_ids._add_to_wave(self.wave_id)
if self.picking_ids:
company = self.picking_ids.company_id
if len(company) > 1:
raise UserError(_("The selected transfers should belong to a unique company."))
else:
raise UserError(_('Cannot create wave transfers'))
view = self.env.ref('stock_picking_batch.view_move_line_tree_detailed_wave')
return {
'name': _('Add Operations'),
'type': 'ir.actions.act_window',
'view_mode': 'list',
'views': [(view.id, 'tree')],
'res_model': 'stock.move.line',
'target': 'new',
'domain': [
('picking_id', 'in', self.picking_ids.ids),
('state', '!=', 'done')
],
'context': dict(
self.env.context,
picking_to_wave=self.picking_ids.ids,
active_wave_id=self.wave_id.id,
)}
| 42.971014 | 2,965 |
14,458 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.osv.expression import AND
from odoo.tools.float_utils import float_compare, float_is_zero, float_round
class StockPickingBatch(models.Model):
_inherit = ['mail.thread', 'mail.activity.mixin']
_name = "stock.picking.batch"
_description = "Batch Transfer"
_order = "name desc"
name = fields.Char(
string='Batch Transfer', default='New',
copy=False, required=True, readonly=True,
help='Name of the batch transfer')
user_id = fields.Many2one(
'res.users', string='Responsible', tracking=True, check_company=True,
readonly=True, states={'draft': [('readonly', False)], 'in_progress': [('readonly', False)]},
help='Person responsible for this batch transfer')
company_id = fields.Many2one(
'res.company', string="Company", required=True, readonly=True,
index=True, default=lambda self: self.env.company)
picking_ids = fields.One2many(
'stock.picking', 'batch_id', string='Transfers', readonly=True,
domain="[('id', 'in', allowed_picking_ids)]", check_company=True,
states={'draft': [('readonly', False)], 'in_progress': [('readonly', False)]},
help='List of transfers associated to this batch')
show_check_availability = fields.Boolean(
compute='_compute_move_ids',
help='Technical field used to compute whether the check availability button should be shown.')
show_validate = fields.Boolean(
compute='_compute_show_validate',
help='Technical field used to decide whether the validate button should be shown.')
show_allocation = fields.Boolean(
compute='_compute_show_allocation',
help='Technical Field used to decide whether the button "Allocation" should be displayed.')
allowed_picking_ids = fields.One2many('stock.picking', compute='_compute_allowed_picking_ids')
move_ids = fields.One2many(
'stock.move', string="Stock moves", compute='_compute_move_ids')
move_line_ids = fields.One2many(
'stock.move.line', string='Stock move lines',
compute='_compute_move_ids', inverse='_set_move_line_ids', readonly=True,
states={'draft': [('readonly', False)], 'in_progress': [('readonly', False)]})
state = fields.Selection([
('draft', 'Draft'),
('in_progress', 'In progress'),
('done', 'Done'),
('cancel', 'Cancelled')], default='draft',
store=True, compute='_compute_state',
copy=False, tracking=True, required=True, readonly=True)
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type', check_company=True, copy=False,
readonly=True, states={'draft': [('readonly', False)]})
picking_type_code = fields.Selection(
related='picking_type_id.code')
scheduled_date = fields.Datetime(
'Scheduled Date', copy=False, store=True, readonly=False, compute="_compute_scheduled_date",
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="""Scheduled date for the transfers to be processed.
- If manually set then scheduled date for all transfers in batch will automatically update to this date.
- If not manually changed and transfers are added/removed/updated then this will be their earliest scheduled date
but this scheduled date will not be set for all transfers in batch.""")
is_wave = fields.Boolean('This batch is a wave')
@api.depends('company_id', 'picking_type_id', 'state')
def _compute_allowed_picking_ids(self):
allowed_picking_states = ['waiting', 'confirmed', 'assigned']
for batch in self:
domain_states = list(allowed_picking_states)
# Allows to add draft pickings only if batch is in draft as well.
if batch.state == 'draft':
domain_states.append('draft')
domain = [
('company_id', '=', batch.company_id.id),
('state', 'in', domain_states),
]
if not batch.is_wave:
domain = AND([domain, [('immediate_transfer', '=', False)]])
if batch.picking_type_id:
domain += [('picking_type_id', '=', batch.picking_type_id.id)]
batch.allowed_picking_ids = self.env['stock.picking'].search(domain)
@api.depends('picking_ids', 'picking_ids.move_line_ids', 'picking_ids.move_lines', 'picking_ids.move_lines.state')
def _compute_move_ids(self):
for batch in self:
batch.move_ids = batch.picking_ids.move_lines
batch.move_line_ids = batch.picking_ids.move_line_ids
batch.show_check_availability = any(m.state not in ['assigned', 'done'] for m in batch.move_ids)
@api.depends('picking_ids', 'picking_ids.show_validate')
def _compute_show_validate(self):
for batch in self:
batch.show_validate = any(picking.show_validate for picking in batch.picking_ids)
@api.depends('state', 'move_ids', 'picking_type_id')
def _compute_show_allocation(self):
self.show_allocation = False
if not self.user_has_groups('stock.group_reception_report'):
return
for batch in self:
batch.show_allocation = batch.picking_ids._get_show_allocation(batch.picking_type_id)
@api.depends('picking_ids', 'picking_ids.state')
def _compute_state(self):
batchs = self.filtered(lambda batch: batch.state not in ['cancel', 'done'])
for batch in batchs:
if not batch.picking_ids:
continue
# Cancels automatically the batch picking if all its transfers are cancelled.
if all(picking.state == 'cancel' for picking in batch.picking_ids):
batch.state = 'cancel'
# Batch picking is marked as done if all its not canceled transfers are done.
elif all(picking.state in ['cancel', 'done'] for picking in batch.picking_ids):
batch.state = 'done'
@api.depends('picking_ids', 'picking_ids.scheduled_date')
def _compute_scheduled_date(self):
for rec in self:
rec.scheduled_date = min(rec.picking_ids.filtered('scheduled_date').mapped('scheduled_date'), default=False)
@api.onchange('scheduled_date')
def onchange_scheduled_date(self):
if self.scheduled_date:
self.picking_ids.scheduled_date = self.scheduled_date
def _set_move_line_ids(self):
new_move_lines = self[0].move_line_ids
for picking in self.picking_ids:
old_move_lines = picking.move_line_ids
picking.move_line_ids = new_move_lines.filtered(lambda ml: ml.picking_id.id == picking.id)
move_lines_to_unlink = old_move_lines - new_move_lines
if move_lines_to_unlink:
move_lines_to_unlink.unlink()
# -------------------------------------------------------------------------
# CRUD
# -------------------------------------------------------------------------
@api.model
def create(self, vals):
if vals.get('name', '/') == '/':
if vals.get('is_wave'):
vals['name'] = self.env['ir.sequence'].next_by_code('picking.wave') or '/'
else:
vals['name'] = self.env['ir.sequence'].next_by_code('picking.batch') or '/'
return super().create(vals)
def write(self, vals):
res = super().write(vals)
if not self.picking_ids:
self.filtered(lambda b: b.state == 'in_progress').action_cancel()
if vals.get('picking_type_id'):
self._sanity_check()
if vals.get('picking_ids'):
batch_without_picking_type = self.filtered(lambda batch: not batch.picking_type_id)
if batch_without_picking_type:
picking = self.picking_ids and self.picking_ids[0]
batch_without_picking_type.picking_type_id = picking.picking_type_id.id
return res
@api.ondelete(at_uninstall=False)
def _unlink_if_not_done(self):
if any(batch.state == 'done' for batch in self):
raise UserError(_("You cannot delete Done batch transfers."))
def onchange(self, values, field_name, field_onchange):
"""Override onchange to NOT to update all scheduled_date on pickings when
scheduled_date on batch is updated by the change of scheduled_date on pickings.
"""
result = super().onchange(values, field_name, field_onchange)
if field_name == 'picking_ids' and 'value' in result:
for line in result['value'].get('picking_ids', []):
if line[0] < 2 and 'scheduled_date' in line[2]:
del line[2]['scheduled_date']
return result
# -------------------------------------------------------------------------
# Action methods
# -------------------------------------------------------------------------
def action_confirm(self):
"""Sanity checks, confirm the pickings and mark the batch as confirmed."""
self.ensure_one()
if not self.picking_ids:
raise UserError(_("You have to set some pickings to batch."))
self.picking_ids.action_confirm()
self._check_company()
self.state = 'in_progress'
return True
def action_cancel(self):
self.state = 'cancel'
self.picking_ids = False
return True
def action_print(self):
self.ensure_one()
return self.env.ref('stock_picking_batch.action_report_picking_batch').report_action(self)
def action_set_quantities_to_reservation(self):
self.ensure_one()
self.picking_ids.filtered("show_validate").action_set_quantities_to_reservation()
def action_done(self):
self.ensure_one()
self._check_company()
pickings = self.mapped('picking_ids').filtered(lambda picking: picking.state not in ('cancel', 'done'))
if any(picking.state not in ('assigned', 'confirmed') for picking in pickings):
raise UserError(_('Some transfers are still waiting for goods. Please check or force their availability before setting this batch to done.'))
empty_pickings = set()
for picking in pickings:
if all(float_is_zero(line.qty_done, precision_rounding=line.product_uom_id.rounding) for line in picking.move_line_ids if line.state not in ('done', 'cancel')):
empty_pickings.add(picking.id)
picking.message_post(
body="<b>%s:</b> %s <a href=#id=%s&view_type=form&model=stock.picking.batch>%s</a>" % (
_("Transferred by"),
_("Batch Transfer"),
picking.batch_id.id,
picking.batch_id.name))
if len(empty_pickings) == len(pickings):
return pickings.button_validate()
else:
res = pickings.with_context(skip_immediate=True).button_validate()
if empty_pickings and res.get('context'):
res['context']['pickings_to_detach'] = list(empty_pickings)
return res
def action_assign(self):
self.ensure_one()
self.picking_ids.action_assign()
def action_put_in_pack(self):
""" Action to put move lines with 'Done' quantities into a new pack
This method follows same logic to stock.picking.
"""
self.ensure_one()
if self.state not in ('done', 'cancel'):
picking_move_lines = self.move_line_ids
move_line_ids = picking_move_lines.filtered(lambda ml:
float_compare(ml.qty_done, 0.0, precision_rounding=ml.product_uom_id.rounding) > 0
and not ml.result_package_id
)
if not move_line_ids:
move_line_ids = picking_move_lines.filtered(lambda ml: float_compare(ml.product_uom_qty, 0.0,
precision_rounding=ml.product_uom_id.rounding) > 0 and float_compare(ml.qty_done, 0.0,
precision_rounding=ml.product_uom_id.rounding) == 0)
if move_line_ids:
res = move_line_ids.picking_id[0]._pre_put_in_pack_hook(move_line_ids)
if not res:
res = move_line_ids.picking_id[0]._put_in_pack(move_line_ids, False)
return res
else:
raise UserError(_("Please add 'Done' quantities to the batch picking to create a new pack."))
def action_view_reception_report(self):
action = self.picking_ids[0].action_view_reception_report()
action['context'] = {'default_picking_ids': self.picking_ids.ids}
return action
def action_open_label_layout(self):
view = self.env.ref('stock.product_label_layout_form_picking')
return {
'name': _('Choose Labels Layout'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'product.label.layout',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'context': {
'default_product_ids': self.move_line_ids.product_id.ids,
'default_move_line_ids': self.move_line_ids.ids,
'default_picking_quantity': 'picking'},
}
# -------------------------------------------------------------------------
# Miscellaneous
# -------------------------------------------------------------------------
def _sanity_check(self):
for batch in self:
if not batch.picking_ids <= batch.allowed_picking_ids:
erroneous_pickings = batch.picking_ids - batch.allowed_picking_ids
raise UserError(_(
"The following transfers cannot be added to batch transfer %s. "
"Please check their states and operation types, if they aren't immediate "
"transfers.\n\n"
"Incompatibilities: %s", batch.name, ', '.join(erroneous_pickings.mapped('name'))))
def _track_subtype(self, init_values):
if 'state' in init_values:
return self.env.ref('stock_picking_batch.mt_batch_state')
return super()._track_subtype(init_values)
| 48.354515 | 14,458 |
4,095 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import _, fields, models
from odoo import Command
from odoo.tools.float_utils import float_compare
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
batch_id = fields.Many2one(related='picking_id.batch_id')
def action_open_add_to_wave(self):
# This action can be called from the move line list view or from the 'Add to wave' wizard
if 'active_wave_id' in self.env.context:
wave = self.env['stock.picking.batch'].browse(self.env.context.get('active_wave_id'))
return self._add_to_wave(wave)
view = self.env.ref('stock_picking_batch.stock_add_to_wave_form')
return {
'name': _('Add to Wave'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'stock.add.to.wave',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
}
def _add_to_wave(self, wave=False):
""" Detach lines (and corresponding stock move from a picking to another). If wave is
passed, attach new picking into it. If not attach line to their original picking.
:param int wave: id of the wave picking on which to put the move lines. """
if not wave:
wave = self.env['stock.picking.batch'].create({
'is_wave': True,
'user_id': self.env.context.get('active_owner_id'),
})
line_by_picking = defaultdict(lambda: self.env['stock.move.line'])
for line in self:
line_by_picking[line.picking_id] |= line
picking_to_wave_vals_list = []
for picking, lines in line_by_picking.items():
# Move the entire picking if all the line are taken
line_by_move = defaultdict(lambda: self.env['stock.move.line'])
qty_by_move = defaultdict(float)
for line in lines:
move = line.move_id
line_by_move[move] |= line
if move.from_immediate_transfer:
qty = line.product_uom_id._compute_quantity(line.qty_done, line.product_id.uom_id, rounding_method='HALF-UP')
else:
qty = line.product_qty
qty_by_move[line.move_id] += qty
if lines == picking.move_line_ids and lines.move_id == picking.move_lines:
move_complete = True
for move, qty in qty_by_move.items():
if float_compare(move.product_qty, qty, precision_rounding=move.product_uom.rounding) != 0:
move_complete = False
break
if move_complete:
wave.picking_ids = [Command.link(picking.id)]
continue
# Split the picking in two part to extract only line that are taken on the wave
picking_to_wave_vals = picking.copy_data({
'move_lines': [],
'move_line_ids': [],
'batch_id': wave.id,
})[0]
for move, move_lines in line_by_move.items():
picking_to_wave_vals['move_line_ids'] += [Command.link(line.id) for line in lines]
# if all the line of a stock move are taken we change the picking on the stock move
if move_lines == move.move_line_ids:
picking_to_wave_vals['move_lines'] += [Command.link(move.id)]
continue
# Split the move
qty = qty_by_move[move]
new_move = move._split(qty)
new_move[0]['move_line_ids'] = [Command.set(move_lines.ids)]
picking_to_wave_vals['move_lines'] += [Command.create(new_move[0])]
picking_to_wave_vals_list.append(picking_to_wave_vals)
if picking_to_wave_vals_list:
self.env['stock.picking'].create(picking_to_wave_vals_list)
wave.action_confirm()
| 44.51087 | 4,095 |
469 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.osv import expression
class StockMove(models.Model):
_inherit = "stock.move"
def _search_picking_for_assignation_domain(self):
domain = super()._search_picking_for_assignation_domain()
domain = expression.AND([domain, ['|', ('batch_id', '=', False), ('batch_id.is_wave', '=', False)]])
return domain
| 33.5 | 469 |
3,317 |
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 StockPickingType(models.Model):
_inherit = "stock.picking.type"
count_picking_batch = fields.Integer(compute='_compute_picking_count')
count_picking_wave = fields.Integer(compute='_compute_picking_count')
def _compute_picking_count(self):
super()._compute_picking_count()
domains = {
'count_picking_batch': [('is_wave', '=', False)],
'count_picking_wave': [('is_wave', '=', True)],
}
for field in domains:
data = self.env['stock.picking.batch'].read_group(domains[field] +
[('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', self.ids)],
['picking_type_id'], ['picking_type_id'])
count = {
x['picking_type_id'][0]: x['picking_type_id_count']
for x in data if x['picking_type_id']
}
for record in self:
record[field] = count.get(record.id, 0)
def get_action_picking_tree_batch(self):
return self._get_action('stock_picking_batch.stock_picking_batch_action')
def get_action_picking_tree_wave(self):
return self._get_action('stock_picking_batch.action_picking_tree_wave')
class StockPicking(models.Model):
_inherit = "stock.picking"
batch_id = fields.Many2one(
'stock.picking.batch', string='Batch Transfer',
check_company=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help='Batch associated to this transfer', copy=False)
@api.model
def create(self, vals):
res = super().create(vals)
if vals.get('batch_id'):
if not res.batch_id.picking_type_id:
res.batch_id.picking_type_id = res.picking_type_id[0]
res.batch_id._sanity_check()
return res
def write(self, vals):
batches = self.batch_id
res = super().write(vals)
if vals.get('batch_id'):
batches.filtered(lambda b: not b.picking_ids).state = 'cancel'
if not self.batch_id.picking_type_id:
self.batch_id.picking_type_id = self.picking_type_id[0]
self.batch_id._sanity_check()
return res
def action_add_operations(self):
view = self.env.ref('stock_picking_batch.view_move_line_tree_detailed_wave')
return {
'name': _('Add Operations'),
'type': 'ir.actions.act_window',
'view_mode': 'list',
'view': view,
'views': [(view.id, 'tree')],
'res_model': 'stock.move.line',
'target': 'new',
'domain': [
('picking_id', 'in', self.ids),
('state', '!=', 'done')
],
'context': dict(
self.env.context,
picking_to_wave=self.ids,
active_wave_id=self.env.context.get('active_wave_id').id,
search_default_by_location=True,
)}
def _should_show_transfers(self):
if len(self.batch_id) == 1 and self == self.batch_id.picking_ids:
return False
return super()._should_show_transfers()
| 37.269663 | 3,317 |
1,762 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Coded by: Alejandro Negrin [email protected],
# Planified by: Alejandro Negrin, Humberto Arocha, Moises Lopez
# Finance by: Vauxoo.
# Audited by: Humberto Arocha ([email protected]) y Moises Lopez ([email protected])
{
"name": "Mexico - Accounting",
"version": "2.0",
"author": "Vauxoo",
'category': 'Accounting/Localizations/Account Charts',
"description": """
Minimal accounting configuration for Mexico.
============================================
This Chart of account is a minimal proposal to be able to use OoB the
accounting feature of Odoo.
This doesn't pretend be all the localization for MX it is just the minimal
data required to start from 0 in mexican localization.
This modules and its content is updated frequently by openerp-mexico team.
With this module you will have:
- Minimal chart of account tested in production environments.
- Minimal chart of taxes, to comply with SAT_ requirements.
.. _SAT: http://www.sat.gob.mx/
""",
"depends": [
"account",
],
"data": [
"data/account.account.tag.csv",
"data/l10n_mx_chart_data.xml",
"data/account.account.template.csv",
"data/l10n_mx_chart_post_data.xml",
"data/account_tax_group_data.xml",
"data/account_tax_data.xml",
"data/fiscal_position_data.xml",
"data/account_chart_template_data.xml",
"data/res_bank_data.xml",
"views/partner_view.xml",
"views/res_bank_view.xml",
"views/res_config_settings_views.xml",
"views/account_views.xml",
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 32.036364 | 1,762 |
1,213 |
py
|
PYTHON
|
15.0
|
# coding: utf-8
from odoo import models, fields
class AccountTaxTemplate(models.Model):
_inherit = 'account.tax.template'
l10n_mx_tax_type = fields.Selection(
selection=[
('Tasa', "Tasa"),
('Cuota', "Cuota"),
('Exento', "Exento"),
],
string="Factor Type",
default='Tasa',
help="The CFDI version 3.3 have the attribute 'TipoFactor' in the tax lines. In it is indicated the factor "
"type that is applied to the base of the tax.")
def _get_tax_vals(self, company, tax_template_to_tax):
# OVERRIDE
res = super()._get_tax_vals(company, tax_template_to_tax)
res['l10n_mx_tax_type'] = self.l10n_mx_tax_type
return res
class AccountTax(models.Model):
_inherit = 'account.tax'
l10n_mx_tax_type = fields.Selection(
selection=[
('Tasa', "Tasa"),
('Cuota', "Cuota"),
('Exento', "Exento"),
],
string="Factor Type",
default='Tasa',
help="The CFDI version 3.3 have the attribute 'TipoFactor' in the tax lines. In it is indicated the factor "
"type that is applied to the base of the tax.")
| 31.921053 | 1,213 |
612 |
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 Bank(models.Model):
_inherit = "res.bank"
l10n_mx_edi_code = fields.Char(
"ABM Code",
help="Three-digit number assigned by the ABM to identify banking "
"institutions (ABM is an acronym for Asociación de Bancos de México)")
class ResPartnerBank(models.Model):
_inherit = "res.partner.bank"
l10n_mx_edi_clabe = fields.Char(
"CLABE", help="Standardized banking cipher for Mexico. More info "
"wikipedia.org/wiki/CLABE")
| 29.047619 | 610 |
217 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
module_l10n_mx_edi = fields.Boolean('Mexican Electronic Invoicing')
| 24.111111 | 217 |
2,056 |
py
|
PYTHON
|
15.0
|
# coding: utf-8
# Copyright 2016 Vauxoo (https://www.vauxoo.com) <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import models, api, _
class AccountChartTemplate(models.Model):
_inherit = "account.chart.template"
@api.model
def generate_journals(self, acc_template_ref, company, journals_dict=None):
"""Set the tax_cash_basis_journal_id on the company"""
res = super(AccountChartTemplate, self).generate_journals(
acc_template_ref, company, journals_dict=journals_dict)
if not self == self.env.ref('l10n_mx.mx_coa'):
return res
journal_basis = self.env['account.journal'].search([
('company_id', '=', company.id),
('type', '=', 'general'),
('code', '=', 'CBMX')], limit=1)
company.write({'tax_cash_basis_journal_id': journal_basis.id})
return res
def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):
"""Create the tax_cash_basis_journal_id"""
res = super(AccountChartTemplate, self)._prepare_all_journals(
acc_template_ref, company, journals_dict=journals_dict)
if not self == self.env.ref('l10n_mx.mx_coa'):
return res
account = acc_template_ref.get(self.env.ref('l10n_mx.cuenta118_01').id)
res.append({
'type': 'general',
'name': _('Effectively Paid'),
'code': 'CBMX',
'company_id': company.id,
'default_account_id': account,
'show_on_dashboard': True,
})
return res
@api.model
def _prepare_transfer_account_for_direct_creation(self, name, company):
res = super(AccountChartTemplate, self)._prepare_transfer_account_for_direct_creation(name, company)
if company.account_fiscal_country_id.code == 'MX':
xml_id = self.env.ref('l10n_mx.account_tag_102_01').id
res.setdefault('tag_ids', [])
res['tag_ids'].append((4, xml_id))
return res
| 41.959184 | 2,056 |
2,101 |
py
|
PYTHON
|
15.0
|
# coding: utf-8
# Copyright 2016 Vauxoo (https://www.vauxoo.com) <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import re
from odoo import models, api, fields, _
class AccountJournal(models.Model):
_inherit = 'account.journal'
def _prepare_liquidity_account_vals(self, company, code, vals):
# OVERRIDE
account_vals = super()._prepare_liquidity_account_vals(company, code, vals)
if company.account_fiscal_country_id.code == 'MX':
# When preparing the values to use when creating the default debit and credit accounts of a
# liquidity journal, set the correct tags for the mexican localization.
account_vals.setdefault('tag_ids', [])
account_vals['tag_ids'] += [(4, tag_id) for tag_id in self.env['account.account'].mx_search_tags(code).ids]
return account_vals
class AccountAccount(models.Model):
_inherit = 'account.account'
@api.model
def mx_search_tags(self, code):
account_tag = self.env['account.account.tag']
#search if the code is compliant with the regexp we have for tags auto-assignation
re_res = re.search(
'^(?P<first>[1-8][0-9][0-9])[,.]'
'(?P<second>[0-9][0-9])[,.]'
'(?P<third>[0-9]{2,3})$', code)
if not re_res:
return account_tag
#get the elements of that code divided with separation declared in the regexp
account = re_res.groups()
return account_tag.search([
('name', '=like', "%s.%s%%" % (account[0], account[1])),
('color', '=', 4)], limit=1)
@api.onchange('code')
def _onchange_code(self):
if self.company_id.country_id.code == "MX" and self.code:
tags = self.mx_search_tags(self.code)
self.tag_ids = tags
class AccountAccountTag(models.Model):
_inherit = 'account.account.tag'
nature = fields.Selection([
('D', 'Debitable Account'), ('A', 'Creditable Account')],
help='Used in Mexican report of electronic accounting (account nature).')
| 36.859649 | 2,101 |
7,664 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Live Chat',
'version': '1.0',
'sequence': 210,
'summary': 'Chat with your website visitors',
'category': 'Website/Live Chat',
'complexity': 'easy',
'website': 'https://www.odoo.com/app/live-chat',
'description':
"""
Live Chat Support
==========================
Allow to drop instant messaging widgets on any web page that will communicate
with the current server and dispatch visitors request amongst several live
chat operators.
Help your customers with this chat, and analyse their feedback.
""",
'data': [
"security/im_livechat_channel_security.xml",
"security/ir.model.access.csv",
"data/mail_shortcode_data.xml",
"data/mail_data.xml",
"data/im_livechat_channel_data.xml",
'data/digest_data.xml',
"views/rating_views.xml",
"views/mail_channel_views.xml",
"views/im_livechat_channel_views.xml",
"views/im_livechat_channel_templates.xml",
"views/res_users_views.xml",
"views/digest_views.xml",
"report/im_livechat_report_channel_views.xml",
"report/im_livechat_report_operator_views.xml"
],
'demo': [
"data/im_livechat_channel_demo.xml",
'data/mail_shortcode_demo.xml',
],
'depends': ["mail", "rating", "digest"],
'installable': True,
'auto_install': False,
'application': True,
'assets': {
'mail.assets_discuss_public': [
'im_livechat/static/src/components/*/*',
'im_livechat/static/src/models/*/*.js',
],
'web.assets_backend': [
'im_livechat/static/src/js/im_livechat_channel_form_view.js',
'im_livechat/static/src/js/im_livechat_channel_form_controller.js',
'im_livechat/static/src/components/*/*.js',
'im_livechat/static/src/models/*/*.js',
'im_livechat/static/src/scss/im_livechat_history.scss',
'im_livechat/static/src/scss/im_livechat_form.scss',
],
'web.qunit_suite_tests': [
'im_livechat/static/src/components/*/tests/*.js',
'im_livechat/static/src/legacy/public_livechat.js',
'im_livechat/static/tests/helpers/mock_models.js',
'im_livechat/static/tests/helpers/mock_server.js',
],
'web.assets_qweb': [
'im_livechat/static/src/components/*/*.xml',
],
# Bundle of External Librairies of the Livechat (Odoo + required modules)
'im_livechat.external_lib': [
# Momentjs
'web/static/lib/moment/moment.js',
'web/static/lib/luxon/luxon.js',
# Odoo minimal lib
'web/static/lib/underscore/underscore.js',
'web/static/lib/underscore.string/lib/underscore.string.js',
# jQuery
'web/static/lib/jquery/jquery.js',
'web/static/lib/jquery.ui/jquery-ui.js',
'web/static/lib/jquery/jquery.browser.js',
'web/static/lib/jquery.ba-bbq/jquery.ba-bbq.js',
# Qweb2 lib
'web/static/lib/qweb/qweb2.js',
# Odoo JS Framework
'web/static/lib/owl/owl.js',
'web/static/src/legacy/js/promise_extension.js',
'web/static/src/boot.js',
'web/static/src/core/assets.js',
'web/static/src/core/browser/browser.js',
'web/static/src/core/browser/feature_detection.js',
'web/static/src/core/dialog/dialog.js',
'web/static/src/core/errors/error_dialogs.js',
'web/static/src/core/effects/**/*.js',
'web/static/src/core/hotkeys/hotkey_service.js',
'web/static/src/core/hotkeys/hotkey_hook.js',
'web/static/src/core/l10n/dates.js',
'web/static/src/core/l10n/localization.js',
'web/static/src/core/l10n/localization_service.js',
'web/static/src/core/l10n/translation.js',
'web/static/src/core/main_components_container.js',
'web/static/src/core/network/rpc_service.js',
'web/static/src/core/notifications/notification.js',
'web/static/src/core/notifications/notification_container.js',
'web/static/src/core/notifications/notification_service.js',
'web/static/src/core/registry.js',
'web/static/src/core/ui/block_ui.js',
'web/static/src/core/ui/ui_service.js',
'web/static/src/core/user_service.js',
'web/static/src/core/utils/components.js',
'web/static/src/core/utils/functions.js',
'web/static/src/core/utils/hooks.js',
'web/static/src/core/utils/strings.js',
'web/static/src/core/utils/timing.js',
'web/static/src/core/utils/ui.js',
'web/static/src/env.js',
'web/static/src/legacy/utils.js',
'web/static/src/legacy/js/owl_compatibility.js',
'web/static/src/legacy/js/libs/download.js',
'web/static/src/legacy/js/libs/content-disposition.js',
'web/static/src/legacy/js/libs/pdfjs.js',
'web/static/src/legacy/js/services/config.js',
'web/static/src/legacy/js/core/abstract_service.js',
'web/static/src/legacy/js/core/class.js',
'web/static/src/legacy/js/core/collections.js',
'web/static/src/legacy/js/core/translation.js',
'web/static/src/legacy/js/core/ajax.js',
'im_livechat/static/src/js/ajax_external.js',
'web/static/src/legacy/js/core/time.js',
'web/static/src/legacy/js/core/mixins.js',
'web/static/src/legacy/js/core/service_mixins.js',
'web/static/src/legacy/js/core/rpc.js',
'web/static/src/legacy/js/core/widget.js',
'web/static/src/legacy/js/core/registry.js',
'web/static/src/session.js',
'web/static/src/legacy/js/core/session.js',
'web/static/src/legacy/js/core/concurrency.js',
'web/static/src/legacy/js/core/cookie_utils.js',
'web/static/src/legacy/js/core/utils.js',
'web/static/src/legacy/js/core/dom.js',
'web/static/src/legacy/js/core/qweb.js',
'web/static/src/legacy/js/core/bus.js',
'web/static/src/legacy/js/services/core.js',
'web/static/src/legacy/js/core/local_storage.js',
'web/static/src/legacy/js/core/ram_storage.js',
'web/static/src/legacy/js/core/abstract_storage_service.js',
'web/static/src/legacy/js/common_env.js',
'web/static/src/legacy/js/public/lazyloader.js',
'web/static/src/legacy/js/public/public_env.js',
'web/static/src/legacy/js/public/public_root.js',
'web/static/src/legacy/js/public/public_root_instance.js',
'web/static/src/legacy/js/public/public_widget.js',
'web/static/src/legacy/js/services/ajax_service.js',
'web/static/src/legacy/js/services/local_storage_service.js',
# Bus, Mail, Livechat
'bus/static/src/js/longpolling_bus.js',
'bus/static/src/js/crosstab_bus.js',
'bus/static/src/js/services/bus_service.js',
'mail/static/src/js/utils.js',
'im_livechat/static/src/legacy/public_livechat.js',
('include', 'web._assets_helpers'),
'web/static/lib/bootstrap/scss/_variables.scss',
'im_livechat/static/src/scss/im_livechat_bootstrap.scss',
'im_livechat/static/src/legacy/public_livechat.scss',
]
},
'license': 'LGPL-3',
}
| 45.892216 | 7,664 |
856 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
from odoo.tests import HttpCase
@odoo.tests.tagged('-at_install', 'post_install')
class TestImLivechatSupportPage(HttpCase):
def test_load_modules(self):
"""Checks that all javascript modules load correctly on the livechat support page"""
check_js_modules = """
const { missing, failed, unloaded } = odoo.__DEBUG__.jsModules;
if ([missing, failed, unloaded].some(arr => arr.length)) {
console.error("Couldn't load all JS modules.", JSON.stringify({ missing, failed, unloaded }));
} else {
console.log("test successful");
}
"""
self.browser_js("/im_livechat/support/1", code=check_js_modules, ready="odoo.__DEBUG__.didLogInfo")
| 45.052632 | 856 |
6,109 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.im_livechat.tests.common import TestImLivechatCommon
class TestGetMailChannel(TestImLivechatCommon):
def test_get_mail_channel(self):
"""For a livechat with 5 available operators, we open 5 channels 5 times (25 channels total).
For every 5 channels opening, we check that all operators were assigned.
"""
for i in range(5):
mail_channels = self._open_livechat_mail_channel()
channel_operators = [channel_info['operator_pid'] for channel_info in mail_channels]
channel_operator_ids = [channel_operator[0] for channel_operator in channel_operators]
self.assertTrue(all(partner_id in channel_operator_ids for partner_id in self.operators.mapped('partner_id').ids))
def test_channel_get_livechat_visitor_info(self):
belgium = self.env.ref('base.be')
public_user = self.env.ref('base.public_user')
test_user = self.env['res.users'].create({'name': 'Roger', 'login': 'roger', 'country_id': belgium.id})
# ensure visitor info are correct with anonymous
operator = self.operators[0]
channel_info = self.livechat_channel.with_user(public_user)._open_livechat_mail_channel(anonymous_name='Visitor 22', previous_operator_id=operator.partner_id.id, country_id=belgium.id)
visitor_info = channel_info['livechat_visitor']
self.assertFalse(visitor_info['id'])
self.assertEqual(visitor_info['name'], "Visitor 22")
self.assertEqual(visitor_info['country'], (20, "Belgium"))
# ensure member info are hidden (in particular email and real name when livechat username is present)
self.assertEqual(sorted(channel_info['members'], key=lambda m: m['id']), sorted([{
'active': True,
'email': False,
'id': operator.partner_id.id,
'im_status': False,
'livechat_username': 'Michel Operator',
'name': 'Michel Operator',
}, {
'active': False,
'email': False,
'id': public_user.partner_id.id,
'im_status': False,
'livechat_username': False,
'name': 'Public user',
}], key=lambda m: m['id']))
# ensure visitor info are correct with real user
channel_info = self.livechat_channel.with_user(test_user)._open_livechat_mail_channel(anonymous_name='whatever', user_id=test_user.id)
visitor_info = channel_info['livechat_visitor']
self.assertEqual(visitor_info['id'], test_user.partner_id.id)
self.assertEqual(visitor_info['name'], "Roger")
self.assertEqual(visitor_info['country'], (20, "Belgium"))
# ensure visitor info are correct when operator is testing himself
operator = self.operators[0]
channel_info = self.livechat_channel.with_user(operator)._open_livechat_mail_channel(anonymous_name='whatever', previous_operator_id=operator.partner_id.id, user_id=operator.id)
self.assertEqual(channel_info['operator_pid'], (operator.partner_id.id, "Michel Operator"))
visitor_info = channel_info['livechat_visitor']
self.assertEqual(visitor_info['id'], operator.partner_id.id)
self.assertEqual(visitor_info['name'], "Michel")
self.assertFalse(visitor_info['country'])
def _open_livechat_mail_channel(self):
mail_channels = []
for i in range(5):
mail_channel = self.livechat_channel._open_livechat_mail_channel('Anonymous')
mail_channels.append(mail_channel)
# send a message to mark this channel as 'active'
self.env['mail.channel'].browse(mail_channel['id']).message_post(body='cc')
return mail_channels
def test_channel_not_pinned_for_operator_before_first_message(self):
public_user = self.env.ref('base.public_user')
channel_info = self.livechat_channel.with_user(public_user)._open_livechat_mail_channel(anonymous_name='whatever')
operator_channel_partner = self.env['mail.channel.partner'].search([('channel_id', '=', channel_info['id']), ('partner_id', 'in', self.operators.partner_id.ids)])
self.assertEqual(len(operator_channel_partner), 1, "operator should be member of channel")
self.assertFalse(operator_channel_partner.is_pinned, "channel should not be pinned for operator initially")
self.env['mail.channel'].browse(channel_info['id']).message_post(body='cc')
self.assertTrue(operator_channel_partner.is_pinned, "channel should be pinned for operator after visitor sent a message")
self.assertIn(channel_info['id'], operator_channel_partner.partner_id._get_channels_as_member().ids, "channel should be fetched by operator on new page")
def test_operator_livechat_username(self):
"""Ensures the operator livechat_username is returned by `_channel_fetch_message`, which is
the method called by the public route displaying chat history."""
public_user = self.env.ref('base.public_user')
operator = self.operators[0]
operator.write({
'email': '[email protected]',
'livechat_username': 'Michel at your service',
})
channel_info = self.livechat_channel.with_user(public_user)._open_livechat_mail_channel(anonymous_name='whatever')
channel = self.env['mail.channel'].browse(channel_info['id'])
channel.with_user(operator).message_post(body='Hello', message_type='comment', subtype_xmlid='mail.mt_comment')
message_formats = channel.with_user(public_user)._channel_fetch_message()
self.assertEqual(len(message_formats), 1)
self.assertEqual(message_formats[0]['author_id'][0], operator.partner_id.id)
self.assertEqual(message_formats[0]['author_id'][1], operator.livechat_username)
self.assertEqual(message_formats[0]['author_id'][2], operator.livechat_username)
self.assertFalse(message_formats[0].get('email_from'), "should not send email_from to livechat user")
| 59.31068 | 6,109 |
1,390 |
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
class TestImLivechatCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.operators = cls.env['res.users'].create([{
'name': 'Michel',
'login': 'michel',
'livechat_username': "Michel Operator",
'email': '[email protected]',
}, {
'name': 'Paul',
'login': 'paul'
}, {
'name': 'Pierre',
'login': 'pierre'
}, {
'name': 'Jean',
'login': 'jean'
}, {
'name': 'Georges',
'login': 'georges'
}])
cls.visitor_user = cls.env['res.users'].create({
'name': 'Rajesh',
'login': 'rajesh',
'country_id': cls.env.ref('base.in').id,
'email': '[email protected]',
})
cls.livechat_channel = cls.env['im_livechat.channel'].create({
'name': 'The channel',
'user_ids': [(6, 0, cls.operators.ids)]
})
def setUp(self):
super().setUp()
def get_available_users(_):
return self.operators
self.patch(type(self.env['im_livechat.channel']), '_get_available_users', get_available_users)
| 28.958333 | 1,390 |
2,720 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.addons.im_livechat.tests.common import TestImLivechatCommon
class TestImLivechatReport(TestImLivechatCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env['mail.channel'].search([('livechat_channel_id', '!=', False)]).unlink()
with patch.object(type(cls.env['im_livechat.channel']), '_get_available_users', lambda _: cls.operators):
channel_id = cls.livechat_channel._open_livechat_mail_channel('Anonymous')['id']
channel = cls.env['mail.channel'].browse(channel_id)
cls.operator = channel.livechat_operator_id
cls._create_message(channel, cls.visitor_user.partner_id, '2023-03-17 06:05:54')
cls._create_message(channel, cls.operator, '2023-03-17 08:15:54')
cls._create_message(channel, cls.operator, '2023-03-17 08:45:54')
# message with the same record id, but with a different model
# should not be taken into account for statistics
partner_message = cls._create_message(channel, cls.operator, '2023-03-17 05:05:54')
partner_message |= cls._create_message(channel, cls.operator, '2023-03-17 09:15:54')
partner_message.model = 'res.partner'
cls.env['mail.message'].flush()
def test_im_livechat_report_channel(self):
report = self.env['im_livechat.report.channel'].search([('livechat_channel_id', '=', self.livechat_channel.id)])
self.assertEqual(len(report), 1, 'Should have one channel report for this live channel')
# We have those messages, ordered by creation;
# 05:05:54: wrong model
# 06:05:54: visitor message
# 08:15:54: operator first answer
# 08:45:54: operator second answer
# 09:15:54: wrong model
# So the duration of the session is: (08:45:54 - 06:05:54) = 2h40 = 9600 seconds
# The time to answer of this session is: (08:15:54 - 06:05:54) = 2h10 = 7800 seconds
self.assertEqual(int(report.time_to_answer), 7800)
self.assertEqual(int(report.duration), 9600)
def test_im_livechat_report_operator(self):
result = self.env['im_livechat.report.operator'].read_group([], ['time_to_answer:avg', 'duration:avg'], [])
self.assertEqual(len(result), 1)
self.assertEqual(int(result[0]['time_to_answer']), 7800)
self.assertEqual(int(result[0]['duration']), 9600)
@classmethod
def _create_message(cls, channel, author, date):
with patch.object(cls.env.cr, 'now', lambda: date):
return channel.message_post(author_id=author.id, body=f'Message {date}')
| 49.454545 | 2,720 |
2,913 |
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 Digest(models.Model):
_inherit = 'digest.digest'
kpi_livechat_rating = fields.Boolean('% of Happiness')
kpi_livechat_rating_value = fields.Float(digits=(16, 2), compute='_compute_kpi_livechat_rating_value')
kpi_livechat_conversations = fields.Boolean('Conversations handled')
kpi_livechat_conversations_value = fields.Integer(compute='_compute_kpi_livechat_conversations_value')
kpi_livechat_response = fields.Boolean('Time to answer(sec)', help="Time to answer the user in second.")
kpi_livechat_response_value = fields.Float(digits=(16, 2), compute='_compute_kpi_livechat_response_value')
def _compute_kpi_livechat_rating_value(self):
channels = self.env['mail.channel'].search([('livechat_operator_id', '=', self.env.user.partner_id.id)])
for record in self:
start, end, company = record._get_kpi_compute_parameters()
domain = [
('create_date', '>=', start), ('create_date', '<', end),
('rated_partner_id', '=', self.env.user.partner_id.id)
]
ratings = channels.rating_get_grades(domain)
record.kpi_livechat_rating_value = ratings['great'] * 100 / sum(ratings.values()) if sum(ratings.values()) else 0
def _compute_kpi_livechat_conversations_value(self):
for record in self:
start, end, company = record._get_kpi_compute_parameters()
record.kpi_livechat_conversations_value = self.env['mail.channel'].search_count([
('channel_type', '=', 'livechat'),
('livechat_operator_id', '=', self.env.user.partner_id.id),
('create_date', '>=', start), ('create_date', '<', end)
])
def _compute_kpi_livechat_response_value(self):
for record in self:
start, end, company = record._get_kpi_compute_parameters()
response_time = self.env['im_livechat.report.operator'].sudo().read_group([
('start_date', '>=', start), ('start_date', '<', end),
('partner_id', '=', self.env.user.partner_id.id)], ['partner_id', 'time_to_answer'], ['partner_id'])
record.kpi_livechat_response_value = sum(
response['time_to_answer']
for response in response_time
if response['time_to_answer'] > 0
)
def _compute_kpis_actions(self, company, user):
res = super(Digest, self)._compute_kpis_actions(company, user)
res['kpi_livechat_rating'] = 'im_livechat.rating_rating_action_livechat_report'
res['kpi_livechat_conversations'] = 'im_livechat.im_livechat_report_operator_action'
res['kpi_livechat_response'] = 'im_livechat.im_livechat_report_channel_time_to_answer_action'
return res
| 53.944444 | 2,913 |
828 |
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 ChannelPartner(models.Model):
_inherit = 'mail.channel.partner'
@api.autovacuum
def _gc_unpin_livechat_sessions(self):
""" Unpin livechat sessions with no activity for at least one day to
clean the operator's interface """
self.env.cr.execute("""
UPDATE mail_channel_partner
SET is_pinned = false
WHERE id in (
SELECT cp.id FROM mail_channel_partner cp
INNER JOIN mail_channel c on c.id = cp.channel_id
WHERE c.channel_type = 'livechat' AND cp.is_pinned is true AND
cp.write_date < current_timestamp - interval '1 day'
)
""")
| 36 | 828 |
1,110 |
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 Rating(models.Model):
_inherit = "rating.rating"
@api.depends('res_model', 'res_id')
def _compute_res_name(self):
for rating in self:
# cannot change the rec_name of session since it is use to create the bus channel
# so, need to override this method to set the same alternative rec_name as in reporting
if rating.res_model == 'mail.channel':
current_object = self.env[rating.res_model].sudo().browse(rating.res_id)
rating.res_name = ('%s / %s') % (current_object.livechat_channel_id.name, current_object.id)
else:
super(Rating, rating)._compute_res_name()
def action_open_rated_object(self):
action = super(Rating, self).action_open_rated_object()
if self.res_model == 'mail.channel':
view_id = self.env.ref('im_livechat.mail_channel_view_form').id
action['views'] = [[view_id, 'form']]
return action
| 41.111111 | 1,110 |
315 |
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 ResUsersSettings(models.Model):
_inherit = 'res.users.settings'
is_discuss_sidebar_category_livechat_open = fields.Boolean("Is category livechat open", default=True)
| 31.5 | 315 |
15,551 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import random
import re
from odoo import api, Command, fields, models, modules, _
class ImLivechatChannel(models.Model):
""" Livechat Channel
Define a communication channel, which can be accessed with 'script_external' (script tag to put on
external website), 'script_internal' (code to be integrated with odoo website) or via 'web_page' link.
It provides rating tools, and access rules for anonymous people.
"""
_name = 'im_livechat.channel'
_inherit = ['rating.parent.mixin']
_description = 'Livechat Channel'
_rating_satisfaction_days = 7 # include only last 7 days to compute satisfaction
def _default_image(self):
image_path = modules.get_module_resource('im_livechat', 'static/src/img', 'default.png')
return base64.b64encode(open(image_path, 'rb').read())
def _default_user_ids(self):
return [(6, 0, [self._uid])]
def _default_button_text(self):
return _('Have a Question? Chat with us.')
def _default_default_message(self):
return _('How may I help you?')
# attribute fields
name = fields.Char('Name', required=True, help="The name of the channel")
button_text = fields.Char('Text of the Button', default=_default_button_text, translate=True,
help="Default text displayed on the Livechat Support Button")
default_message = fields.Char('Welcome Message', default=_default_default_message, translate=True,
help="This is an automated 'welcome' message that your visitor will see when they initiate a new conversation.")
input_placeholder = fields.Char('Chat Input Placeholder', translate=True, help='Text that prompts the user to initiate the chat.')
header_background_color = fields.Char(default="#875A7B", help="Default background color of the channel header once open")
title_color = fields.Char(default="#FFFFFF", help="Default title color of the channel once open")
button_background_color = fields.Char(default="#878787", help="Default background color of the Livechat button")
button_text_color = fields.Char(default="#FFFFFF", help="Default text color of the Livechat button")
# computed fields
web_page = fields.Char('Web Page', compute='_compute_web_page_link', store=False, readonly=True,
help="URL to a static page where you client can discuss with the operator of the channel.")
are_you_inside = fields.Boolean(string='Are you inside the matrix?',
compute='_are_you_inside', store=False, readonly=True)
script_external = fields.Html('Script (external)', compute='_compute_script_external', store=False, readonly=True, sanitize=False)
nbr_channel = fields.Integer('Number of conversation', compute='_compute_nbr_channel', store=False, readonly=True)
image_128 = fields.Image("Image", max_width=128, max_height=128, default=_default_image)
# relationnal fields
user_ids = fields.Many2many('res.users', 'im_livechat_channel_im_user', 'channel_id', 'user_id', string='Operators', default=_default_user_ids)
channel_ids = fields.One2many('mail.channel', 'livechat_channel_id', 'Sessions')
rule_ids = fields.One2many('im_livechat.channel.rule', 'channel_id', 'Rules')
def _are_you_inside(self):
for channel in self:
channel.are_you_inside = bool(self.env.uid in [u.id for u in channel.user_ids])
def _compute_script_external(self):
view = self.env.ref('im_livechat.external_loader')
values = {
"dbname": self._cr.dbname,
}
for record in self:
values["channel_id"] = record.id
values["url"] = record.get_base_url()
record.script_external = view._render(values) if record.id else False
def _compute_web_page_link(self):
for record in self:
record.web_page = "%s/im_livechat/support/%i" % (record.get_base_url(), record.id) if record.id else False
@api.depends('channel_ids')
def _compute_nbr_channel(self):
data = self.env['mail.channel'].read_group([
('livechat_channel_id', 'in', self._ids),
('has_message', '=', True)], ['__count'], ['livechat_channel_id'], lazy=False)
channel_count = {x['livechat_channel_id'][0]: x['__count'] for x in data}
for record in self:
record.nbr_channel = channel_count.get(record.id, 0)
# --------------------------
# Action Methods
# --------------------------
def action_join(self):
self.ensure_one()
return self.write({'user_ids': [(4, self._uid)]})
def action_quit(self):
self.ensure_one()
return self.write({'user_ids': [(3, self._uid)]})
def action_view_rating(self):
""" Action to display the rating relative to the channel, so all rating of the
sessions of the current channel
:returns : the ir.action 'action_view_rating' with the correct context
"""
self.ensure_one()
action = self.env['ir.actions.act_window']._for_xml_id('im_livechat.rating_rating_action_livechat')
action['context'] = {'search_default_parent_res_name': self.name}
return action
# --------------------------
# Channel Methods
# --------------------------
def _get_available_users(self):
""" get available user of a given channel
:retuns : return the res.users having their im_status online
"""
self.ensure_one()
return self.user_ids.filtered(lambda user: user.im_status == 'online')
def _get_livechat_mail_channel_vals(self, anonymous_name, operator, user_id=None, country_id=None):
# partner to add to the mail.channel
operator_partner_id = operator.partner_id.id
channel_partner_to_add = [Command.create({'partner_id': operator_partner_id, 'is_pinned': False})]
visitor_user = False
if user_id:
visitor_user = self.env['res.users'].browse(user_id)
if visitor_user and visitor_user.active and visitor_user != operator: # valid session user (not public)
channel_partner_to_add.append(Command.create({'partner_id': visitor_user.partner_id.id}))
return {
'channel_last_seen_partner_ids': channel_partner_to_add,
'livechat_active': True,
'livechat_operator_id': operator_partner_id,
'livechat_channel_id': self.id,
'anonymous_name': False if user_id else anonymous_name,
'country_id': country_id,
'channel_type': 'livechat',
'name': ' '.join([visitor_user.display_name if visitor_user else anonymous_name, operator.livechat_username if operator.livechat_username else operator.name]),
'public': 'private',
}
def _open_livechat_mail_channel(self, anonymous_name, previous_operator_id=None, user_id=None, country_id=None):
""" Return a mail.channel given a livechat channel. It creates one with a connected operator, or return false otherwise
:param anonymous_name : the name of the anonymous person of the channel
:param previous_operator_id : partner_id.id of the previous operator that this visitor had in the past
:param user_id : the id of the logged in visitor, if any
:param country_code : the country of the anonymous person of the channel
:type anonymous_name : str
:return : channel header
:rtype : dict
If this visitor already had an operator within the last 7 days (information stored with the 'im_livechat_previous_operator_pid' cookie),
the system will first try to assign that operator if he's available (to improve user experience).
"""
self.ensure_one()
operator = False
if previous_operator_id:
available_users = self._get_available_users()
# previous_operator_id is the partner_id of the previous operator, need to convert to user
if previous_operator_id in available_users.mapped('partner_id').ids:
operator = next(available_user for available_user in available_users if available_user.partner_id.id == previous_operator_id)
if not operator:
operator = self._get_random_operator()
if not operator:
# no one available
return False
# create the session, and add the link with the given channel
mail_channel_vals = self._get_livechat_mail_channel_vals(anonymous_name, operator, user_id=user_id, country_id=country_id)
mail_channel = self.env["mail.channel"].with_context(mail_create_nosubscribe=False).sudo().create(mail_channel_vals)
mail_channel._broadcast([operator.partner_id.id])
return mail_channel.sudo().channel_info()[0]
def _get_random_operator(self):
""" Return a random operator from the available users of the channel that have the lowest number of active livechats.
A livechat is considered 'active' if it has at least one message within the 30 minutes.
(Some annoying conversions have to be made on the fly because this model holds 'res.users' as available operators
and the mail_channel model stores the partner_id of the randomly selected operator)
:return : user
:rtype : res.users
"""
operators = self._get_available_users()
if len(operators) == 0:
return False
self.env.cr.execute("""SELECT COUNT(DISTINCT c.id), c.livechat_operator_id
FROM mail_channel c
LEFT OUTER JOIN mail_message m ON c.id = m.res_id AND m.model = 'mail.channel'
WHERE c.channel_type = 'livechat'
AND c.livechat_operator_id in %s
AND m.create_date > ((now() at time zone 'UTC') - interval '30 minutes')
GROUP BY c.livechat_operator_id
ORDER BY COUNT(DISTINCT c.id) asc""", (tuple(operators.mapped('partner_id').ids),))
active_channels = self.env.cr.dictfetchall()
# If inactive operator(s), return one of them
active_channel_operator_ids = [active_channel['livechat_operator_id'] for active_channel in active_channels]
inactive_operators = [operator for operator in operators if operator.partner_id.id not in active_channel_operator_ids]
if inactive_operators:
return random.choice(inactive_operators)
# If no inactive operator, active_channels is not empty as len(operators) > 0 (see above).
# Get the less active operator using the active_channels first element's count (since they are sorted 'ascending')
lowest_number_of_conversations = active_channels[0]['count']
less_active_operator = random.choice([
active_channel['livechat_operator_id'] for active_channel in active_channels
if active_channel['count'] == lowest_number_of_conversations])
# convert the selected 'partner_id' to its corresponding res.users
return next(operator for operator in operators if operator.partner_id.id == less_active_operator)
def _get_channel_infos(self):
self.ensure_one()
return {
'header_background_color': self.header_background_color,
'button_background_color': self.button_background_color,
'title_color': self.title_color,
'button_text_color': self.button_text_color,
'button_text': self.button_text,
'input_placeholder': self.input_placeholder,
'default_message': self.default_message,
"channel_name": self.name,
"channel_id": self.id,
}
def get_livechat_info(self, username=None):
self.ensure_one()
if username is None:
username = _('Visitor')
info = {}
info['available'] = len(self._get_available_users()) > 0
info['server_url'] = self.get_base_url()
if info['available']:
info['options'] = self._get_channel_infos()
info['options']['current_partner_id'] = self.env.user.partner_id.id
info['options']["default_username"] = username
return info
class ImLivechatChannelRule(models.Model):
""" Channel Rules
Rules defining access to the channel (countries, and url matching). It also provide the 'auto pop'
option to open automatically the conversation.
"""
_name = 'im_livechat.channel.rule'
_description = 'Livechat Channel Rules'
_order = 'sequence asc'
regex_url = fields.Char('URL Regex',
help="Regular expression specifying the web pages this rule will be applied on.")
action = fields.Selection([('display_button', 'Display the button'), ('auto_popup', 'Auto popup'), ('hide_button', 'Hide the button')],
string='Action', required=True, default='display_button',
help="* 'Display the button' displays the chat button on the pages.\n"\
"* 'Auto popup' displays the button and automatically open the conversation pane.\n"\
"* 'Hide the button' hides the chat button on the pages.")
auto_popup_timer = fields.Integer('Auto popup timer', default=0,
help="Delay (in seconds) to automatically open the conversation window. Note: the selected action must be 'Auto popup' otherwise this parameter will not be taken into account.")
channel_id = fields.Many2one('im_livechat.channel', 'Channel',
help="The channel of the rule")
country_ids = fields.Many2many('res.country', 'im_livechat_channel_country_rel', 'channel_id', 'country_id', 'Country',
help="The rule will only be applied for these countries. Example: if you select 'Belgium' and 'United States' and that you set the action to 'Hide Button', the chat button will be hidden on the specified URL from the visitors located in these 2 countries. This feature requires GeoIP installed on your server.")
sequence = fields.Integer('Matching order', default=10,
help="Given the order to find a matching rule. If 2 rules are matching for the given url/country, the one with the lowest sequence will be chosen.")
def match_rule(self, channel_id, url, country_id=False):
""" determine if a rule of the given channel matches with the given url
:param channel_id : the identifier of the channel_id
:param url : the url to match with a rule
:param country_id : the identifier of the country
:returns the rule that matches the given condition. False otherwise.
:rtype : im_livechat.channel.rule
"""
def _match(rules):
for rule in rules:
# url might not be set because it comes from referer, in that
# case match the first rule with no regex_url
if re.search(rule.regex_url or '', url or ''):
return rule
return False
# first, search the country specific rules (the first match is returned)
if country_id: # don't include the country in the research if geoIP is not installed
domain = [('country_ids', 'in', [country_id]), ('channel_id', '=', channel_id)]
rule = _match(self.search(domain))
if rule:
return rule
# second, fallback on the rules without country
domain = [('country_ids', '=', False), ('channel_id', '=', channel_id)]
return _match(self.search(domain))
| 53.256849 | 15,551 |
670 |
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 Users(models.Model):
""" Update of res.users class
- add a preference about username for livechat purpose
"""
_inherit = 'res.users'
livechat_username = fields.Char("Livechat Username", help="This username will be used as your name in the livechat channels.")
@property
def SELF_READABLE_FIELDS(self):
return super().SELF_READABLE_FIELDS + ['livechat_username']
@property
def SELF_WRITEABLE_FIELDS(self):
return super().SELF_WRITEABLE_FIELDS + ['livechat_username']
| 31.904762 | 670 |
1,114 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailMessage(models.Model):
_inherit = 'mail.message'
def _message_format(self, fnames, format_reply=True):
"""Override to remove email_from and to return the livechat username if applicable.
A third param is added to the author_id tuple in this case to be able to differentiate it
from the normal name in client code."""
vals_list = super()._message_format(fnames=fnames, format_reply=format_reply)
for vals in vals_list:
message_sudo = self.browse(vals['id']).sudo().with_prefetch(self.ids)
if message_sudo.model == 'mail.channel' and self.env['mail.channel'].browse(message_sudo.res_id).channel_type == 'livechat':
vals.pop('email_from')
if message_sudo.author_id.user_livechat_username:
vals['author_id'] = (message_sudo.author_id.id, message_sudo.author_id.user_livechat_username, message_sudo.author_id.user_livechat_username)
return vals_list
| 53.047619 | 1,114 |
1,034 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class Partners(models.Model):
"""Update of res.partner class to take into account the livechat username."""
_inherit = 'res.partner'
user_livechat_username = fields.Char(compute='_compute_user_livechat_username')
def _get_channels_as_member(self):
channels = super()._get_channels_as_member()
channels |= self.env['mail.channel'].search([
('channel_type', '=', 'livechat'),
('channel_last_seen_partner_ids', 'in', self.env['mail.channel.partner'].sudo()._search([
('partner_id', '=', self.id),
('is_pinned', '=', True),
])),
])
return channels
@api.depends('user_ids.livechat_username')
def _compute_user_livechat_username(self):
for partner in self:
partner.user_livechat_username = next(iter(partner.user_ids.mapped('livechat_username')), False)
| 38.296296 | 1,034 |
10,388 |
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 html_escape
class MailChannel(models.Model):
""" Chat Session
Reprensenting a conversation between users.
It extends the base method for anonymous usage.
"""
_name = 'mail.channel'
_inherit = ['mail.channel', 'rating.mixin']
anonymous_name = fields.Char('Anonymous Name')
channel_type = fields.Selection(selection_add=[('livechat', 'Livechat Conversation')])
livechat_active = fields.Boolean('Is livechat ongoing?', help='Livechat session is active until visitor leave the conversation.')
livechat_channel_id = fields.Many2one('im_livechat.channel', 'Channel')
livechat_operator_id = fields.Many2one('res.partner', string='Operator', help="""Operator for this specific channel""")
country_id = fields.Many2one('res.country', string="Country", help="Country of the visitor of the channel")
_sql_constraints = [('livechat_operator_id', "CHECK((channel_type = 'livechat' and livechat_operator_id is not null) or (channel_type != 'livechat'))",
'Livechat Operator ID is required for a channel of type livechat.')]
def _compute_is_chat(self):
super(MailChannel, self)._compute_is_chat()
for record in self:
if record.channel_type == 'livechat':
record.is_chat = True
def _channel_message_notifications(self, message, message_format=False):
""" When a anonymous user create a mail.channel, the operator is not notify (to avoid massive polling when
clicking on livechat button). So when the anonymous person is sending its FIRST message, the channel header
should be added to the notification, since the user cannot be listining to the channel.
"""
notifications = super()._channel_message_notifications(message=message, message_format=message_format)
for channel in self:
# add uuid for private livechat channels to allow anonymous to listen
if channel.channel_type == 'livechat' and channel.public == 'private':
notifications.append([channel.uuid, 'mail.channel/new_message', notifications[0][2]])
if not message.author_id:
unpinned_channel_partner = self.channel_last_seen_partner_ids.filtered(lambda cp: not cp.is_pinned)
if unpinned_channel_partner:
unpinned_channel_partner.write({'is_pinned': True})
notifications = self._channel_channel_notifications(unpinned_channel_partner.mapped('partner_id').ids) + notifications
return notifications
def channel_info(self):
""" Extends the channel header by adding the livechat operator and the 'anonymous' profile
:rtype : list(dict)
"""
channel_infos = super().channel_info()
channel_infos_dict = dict((c['id'], c) for c in channel_infos)
for channel in self:
# add the last message date
if channel.channel_type == 'livechat':
# add the operator id
if channel.livechat_operator_id:
display_name = channel.livechat_operator_id.user_livechat_username or channel.livechat_operator_id.display_name
channel_infos_dict[channel.id]['operator_pid'] = (channel.livechat_operator_id.id, display_name.replace(',', ''))
# add the anonymous or partner name
channel_infos_dict[channel.id]['livechat_visitor'] = channel._channel_get_livechat_visitor_info()
return list(channel_infos_dict.values())
def _channel_info_format_member(self, partner, partner_info):
"""Override to remove sensitive information in livechat."""
if self.channel_type == 'livechat':
return {
'active': partner.active,
'id': partner.id,
'name': partner.user_livechat_username or partner.name, # for API compatibility in stable
'email': False, # for API compatibility in stable
'im_status': False, # for API compatibility in stable
'livechat_username': partner.user_livechat_username,
}
return super()._channel_info_format_member(partner=partner, partner_info=partner_info)
def _notify_typing_partner_data(self):
"""Override to remove name and return livechat username if applicable."""
data = super()._notify_typing_partner_data()
if self.channel_type == 'livechat' and self.env.user.partner_id.user_livechat_username:
data['partner_name'] = self.env.user.partner_id.user_livechat_username # for API compatibility in stable
data['livechat_username'] = self.env.user.partner_id.user_livechat_username
return data
def _channel_get_livechat_visitor_info(self):
self.ensure_one()
# remove active test to ensure public partner is taken into account
channel_partner_ids = self.with_context(active_test=False).channel_partner_ids
partners = channel_partner_ids - self.livechat_operator_id
if not partners:
# operator probably testing the livechat with his own user
partners = channel_partner_ids
first_partner = partners and partners[0]
if first_partner and (not first_partner.user_ids or not any(user._is_public() for user in first_partner.user_ids)):
# legit non-public partner
return {
'country': first_partner.country_id.name_get()[0] if first_partner.country_id else False,
'id': first_partner.id,
'name': first_partner.name,
}
return {
'country': self.country_id.name_get()[0] if self.country_id else False,
'id': False,
'name': self.anonymous_name or _("Visitor"),
}
def _channel_get_livechat_partner_name(self):
if self.livechat_operator_id in self.channel_partner_ids:
partners = self.channel_partner_ids - self.livechat_operator_id
if partners:
partner_name = False
for partner in partners:
if not partner_name:
partner_name = partner.name
else:
partner_name += ', %s' % partner.name
if partner.country_id:
partner_name += ' (%s)' % partner.country_id.name
return partner_name
if self.anonymous_name:
return self.anonymous_name
return _("Visitor")
@api.autovacuum
def _gc_empty_livechat_sessions(self):
hours = 1 # never remove empty session created within the last hour
self.env.cr.execute("""
SELECT id as id
FROM mail_channel C
WHERE NOT EXISTS (
SELECT *
FROM mail_message M
WHERE M.res_id = C.id AND m.model = 'mail.channel'
) AND C.channel_type = 'livechat' AND livechat_channel_id IS NOT NULL AND
COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp
< ((now() at time zone 'UTC') - interval %s)""", ("%s hours" % hours,))
empty_channel_ids = [item['id'] for item in self.env.cr.dictfetchall()]
self.browse(empty_channel_ids).unlink()
def _execute_command_help_message_extra(self):
msg = super(MailChannel, self)._execute_command_help_message_extra()
return msg + _("Type <b>:shortcut</b> to insert a canned response in your message.<br>")
def execute_command_history(self, **kwargs):
self.env['bus.bus']._sendone(self.uuid, 'im_livechat.history_command', {'id': self.id})
def _send_history_message(self, pid, page_history):
message_body = _('No history found')
if page_history:
html_links = ['<li><a href="%s" target="_blank">%s</a></li>' % (html_escape(page), html_escape(page)) for page in page_history]
message_body = '<ul>%s</ul>' % (''.join(html_links))
self._send_transient_message(self.env['res.partner'].browse(pid), message_body)
def _message_update_content_after_hook(self, message):
self.ensure_one()
if self.channel_type == 'livechat':
self.env['bus.bus']._sendone(self.uuid, 'mail.message/insert', {
'id': message.id,
'body': message.body,
})
super()._message_update_content_after_hook(message=message)
def _get_visitor_leave_message(self, operator=False, cancel=False):
return _('Visitor has left the conversation.')
def _close_livechat_session(self, **kwargs):
""" Set deactivate the livechat channel and notify (the operator) the reason of closing the session."""
self.ensure_one()
if self.livechat_active:
self.livechat_active = False
# avoid useless notification if the channel is empty
if not self.message_ids:
return
# Notify that the visitor has left the conversation
self.message_post(author_id=self.env.ref('base.partner_root').id,
body=self._get_visitor_leave_message(**kwargs), message_type='comment', subtype_xmlid='mail.mt_comment')
# Rating Mixin
def _rating_get_parent_field_name(self):
return 'livechat_channel_id'
def _email_livechat_transcript(self, email):
company = self.env.user.company_id
render_context = {
"company": company,
"channel": self,
}
template = self.env.ref('im_livechat.livechat_email_template')
mail_body = template._render(render_context, engine='ir.qweb', minimal_qcontext=True)
mail_body = self.env['mail.render.mixin']._replace_local_links(mail_body)
mail = self.env['mail.mail'].sudo().create({
'subject': _('Conversation with %s', self.livechat_operator_id.user_livechat_username or self.livechat_operator_id.name),
'email_from': company.catchall_formatted or company.email_formatted,
'author_id': self.env.user.partner_id.id,
'email_to': email,
'body_html': mail_body,
})
mail.send()
| 51.425743 | 10,388 |
6,348 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools
class ImLivechatReportChannel(models.Model):
""" Livechat Support Report on the Channels """
_name = "im_livechat.report.channel"
_description = "Livechat Support Channel Report"
_order = 'start_date, technical_name'
_auto = False
uuid = fields.Char('UUID', readonly=True)
channel_id = fields.Many2one('mail.channel', 'Conversation', readonly=True)
channel_name = fields.Char('Channel Name', readonly=True)
technical_name = fields.Char('Code', readonly=True)
livechat_channel_id = fields.Many2one('im_livechat.channel', 'Channel', readonly=True)
start_date = fields.Datetime('Start Date of session', readonly=True, help="Start date of the conversation")
start_hour = fields.Char('Start Hour of session', readonly=True, help="Start hour of the conversation")
day_number = fields.Char('Day Number', readonly=True, help="Day number of the session (1 is Monday, 7 is Sunday)")
time_to_answer = fields.Float('Time to answer (sec)', digits=(16, 2), readonly=True, group_operator="avg", help="Average time in seconds to give the first answer to the visitor")
start_date_hour = fields.Char('Hour of start Date of session', readonly=True)
duration = fields.Float('Average duration', digits=(16, 2), readonly=True, group_operator="avg", help="Duration of the conversation (in seconds)")
nbr_speaker = fields.Integer('# of speakers', readonly=True, group_operator="avg", help="Number of different speakers")
nbr_message = fields.Integer('Average message', readonly=True, group_operator="avg", help="Number of message in the conversation")
is_without_answer = fields.Integer('Session(s) without answer', readonly=True, group_operator="sum",
help="""A session is without answer if the operator did not answer.
If the visitor is also the operator, the session will always be answered.""")
days_of_activity = fields.Integer('Days of activity', group_operator="max", readonly=True, help="Number of days since the first session of the operator")
is_anonymous = fields.Integer('Is visitor anonymous', readonly=True)
country_id = fields.Many2one('res.country', 'Country of the visitor', readonly=True)
is_happy = fields.Integer('Visitor is Happy', readonly=True)
rating = fields.Integer('Rating', group_operator="avg", readonly=True)
# TODO DBE : Use Selection field - Need : Pie chart must show labels, not keys.
rating_text = fields.Char('Satisfaction Rate', readonly=True)
is_unrated = fields.Integer('Session not rated', readonly=True)
partner_id = fields.Many2one('res.partner', 'Operator', readonly=True)
def init(self):
# Note : start_date_hour must be remove when the read_group will allow grouping on the hour of a datetime. Don't forget to change the view !
tools.drop_view_if_exists(self.env.cr, 'im_livechat_report_channel')
self.env.cr.execute("""
CREATE OR REPLACE VIEW im_livechat_report_channel AS (
SELECT
C.id as id,
C.uuid as uuid,
C.id as channel_id,
C.name as channel_name,
CONCAT(L.name, ' / ', C.id) as technical_name,
C.livechat_channel_id as livechat_channel_id,
C.create_date as start_date,
to_char(date_trunc('hour', C.create_date), 'YYYY-MM-DD HH24:MI:SS') as start_date_hour,
to_char(date_trunc('hour', C.create_date), 'HH24') as start_hour,
extract(dow from C.create_date) as day_number,
EXTRACT('epoch' FROM MAX(M.create_date) - MIN(M.create_date)) AS duration,
EXTRACT('epoch' FROM MIN(MO.create_date) - MIN(M.create_date)) AS time_to_answer,
count(distinct C.livechat_operator_id) as nbr_speaker,
count(distinct M.id) as nbr_message,
CASE
WHEN EXISTS (select distinct M.author_id FROM mail_message M
WHERE M.author_id=C.livechat_operator_id
AND M.res_id = C.id
AND M.model = 'mail.channel'
AND C.livechat_operator_id = M.author_id)
THEN 0
ELSE 1
END as is_without_answer,
(DATE_PART('day', date_trunc('day', now()) - date_trunc('day', C.create_date)) + 1) as days_of_activity,
CASE
WHEN C.anonymous_name IS NULL THEN 0
ELSE 1
END as is_anonymous,
C.country_id,
CASE
WHEN rate.rating = 5 THEN 1
ELSE 0
END as is_happy,
Rate.rating as rating,
CASE
WHEN Rate.rating = 1 THEN 'Unhappy'
WHEN Rate.rating = 5 THEN 'Happy'
WHEN Rate.rating = 3 THEN 'Neutral'
ELSE null
END as rating_text,
CASE
WHEN rate.rating > 0 THEN 0
ELSE 1
END as is_unrated,
C.livechat_operator_id as partner_id
FROM mail_channel C
JOIN mail_message M ON (M.res_id = C.id AND M.model = 'mail.channel')
JOIN im_livechat_channel L ON (L.id = C.livechat_channel_id)
LEFT JOIN mail_message MO ON (MO.res_id = C.id AND MO.model = 'mail.channel' AND MO.author_id = C.livechat_operator_id)
LEFT JOIN rating_rating Rate ON (Rate.res_id = C.id and Rate.res_model = 'mail.channel' and Rate.parent_res_model = 'im_livechat.channel')
WHERE C.livechat_operator_id is not null
GROUP BY C.livechat_operator_id, C.id, C.name, C.livechat_channel_id, L.name, C.create_date, C.uuid, Rate.rating
)
""")
| 63.48 | 6,348 |
2,486 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools
class ImLivechatReportOperator(models.Model):
""" Livechat Support Report on the Operator """
_name = "im_livechat.report.operator"
_description = "Livechat Support Operator Report"
_order = 'livechat_channel_id, partner_id'
_auto = False
partner_id = fields.Many2one('res.partner', 'Operator', readonly=True)
livechat_channel_id = fields.Many2one('im_livechat.channel', 'Channel', readonly=True)
nbr_channel = fields.Integer('# of Sessions', readonly=True, group_operator="sum", help="Number of conversation")
channel_id = fields.Many2one('mail.channel', 'Conversation', readonly=True)
start_date = fields.Datetime('Start Date of session', readonly=True, help="Start date of the conversation")
time_to_answer = fields.Float('Time to answer', digits=(16, 2), readonly=True, group_operator="avg", help="Average time to give the first answer to the visitor")
duration = fields.Float('Average duration', digits=(16, 2), readonly=True, group_operator="avg", help="Duration of the conversation (in seconds)")
def init(self):
# Note : start_date_hour must be remove when the read_group will allow grouping on the hour of a datetime. Don't forget to change the view !
tools.drop_view_if_exists(self.env.cr, 'im_livechat_report_operator')
self.env.cr.execute("""
CREATE OR REPLACE VIEW im_livechat_report_operator AS (
SELECT
row_number() OVER () AS id,
C.livechat_operator_id AS partner_id,
C.livechat_channel_id AS livechat_channel_id,
COUNT(DISTINCT C.id) AS nbr_channel,
C.id AS channel_id,
C.create_date AS start_date,
EXTRACT('epoch' FROM MAX(M.create_date) - MIN(M.create_date)) AS duration,
EXTRACT('epoch' FROM MIN(MO.create_date) - MIN(M.create_date)) AS time_to_answer
FROM mail_channel C
JOIN mail_message M ON M.res_id = C.id AND M.model = 'mail.channel'
LEFT JOIN mail_message MO ON (MO.res_id = C.id AND MO.model = 'mail.channel' AND MO.author_id = C.livechat_operator_id)
WHERE C.livechat_channel_id IS NOT NULL
GROUP BY C.id, C.livechat_operator_id
)
""")
| 57.813953 | 2,486 |
8,468 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo import http,tools, _
from odoo.http import request
from odoo.addons.base.models.assetsbundle import AssetsBundle
class LivechatController(http.Controller):
# Note: the `cors` attribute on many routes is meant to allow the livechat
# to be embedded in an external website.
@http.route('/im_livechat/external_lib.<any(css,js):ext>', type='http', auth='public')
def livechat_lib(self, ext, **kwargs):
# _get_asset return the bundle html code (script and link list) but we want to use the attachment content
bundle = 'im_livechat.external_lib'
files, _ = request.env["ir.qweb"]._get_asset_content(bundle)
asset = AssetsBundle(bundle, files)
mock_attachment = getattr(asset, ext)()
if isinstance(mock_attachment, list): # suppose that CSS asset will not required to be split in pages
mock_attachment = mock_attachment[0]
# can't use /web/content directly because we don't have attachment ids (attachments must be created)
status, headers, content = request.env['ir.http'].binary_content(id=mock_attachment.id, unique=asset.checksum)
content_base64 = base64.b64decode(content) if content else ''
headers.append(('Content-Length', len(content_base64)))
return request.make_response(content_base64, headers)
@http.route('/im_livechat/load_templates', type='json', auth='none', cors="*")
def load_templates(self, **kwargs):
base_url = request.httprequest.base_url
templates = [
'im_livechat/static/src/legacy/public_livechat.xml',
]
return [tools.file_open(tmpl, 'rb').read() for tmpl in templates]
@http.route('/im_livechat/support/<int:channel_id>', type='http', auth='public')
def support_page(self, channel_id, **kwargs):
channel = request.env['im_livechat.channel'].sudo().browse(channel_id)
return request.render('im_livechat.support_page', {'channel': channel})
@http.route('/im_livechat/loader/<int:channel_id>', type='http', auth='public')
def loader(self, channel_id, **kwargs):
username = kwargs.get("username", _("Visitor"))
channel = request.env['im_livechat.channel'].sudo().browse(channel_id)
info = channel.get_livechat_info(username=username)
return request.render('im_livechat.loader', {'info': info, 'web_session_required': True}, headers=[('Content-Type', 'application/javascript')])
@http.route('/im_livechat/init', type='json', auth="public", cors="*")
def livechat_init(self, channel_id):
available = len(request.env['im_livechat.channel'].sudo().browse(channel_id)._get_available_users())
rule = {}
if available:
# find the country from the request
country_id = False
country_code = request.session.geoip.get('country_code') if request.session.geoip else False
if country_code:
country_id = request.env['res.country'].sudo().search([('code', '=', country_code)], limit=1).id
# extract url
url = request.httprequest.headers.get('Referer')
# find the first matching rule for the given country and url
matching_rule = request.env['im_livechat.channel.rule'].sudo().match_rule(channel_id, url, country_id)
if matching_rule:
rule = {
'action': matching_rule.action,
'auto_popup_timer': matching_rule.auto_popup_timer,
'regex_url': matching_rule.regex_url,
}
return {
'available_for_me': available and (not rule or rule['action'] != 'hide_button'),
'rule': rule,
}
@http.route('/im_livechat/get_session', type="json", auth='public', cors="*")
def get_session(self, channel_id, anonymous_name, previous_operator_id=None, **kwargs):
user_id = None
country_id = None
# if the user is identifiy (eg: portal user on the frontend), don't use the anonymous name. The user will be added to session.
if request.session.uid:
user_id = request.env.user.id
country_id = request.env.user.country_id.id
else:
# if geoip, add the country name to the anonymous name
if request.session.geoip:
# get the country of the anonymous person, if any
country_code = request.session.geoip.get('country_code', "")
country = request.env['res.country'].sudo().search([('code', '=', country_code)], limit=1) if country_code else None
if country:
anonymous_name = "%s (%s)" % (anonymous_name, country.name)
country_id = country.id
if previous_operator_id:
previous_operator_id = int(previous_operator_id)
return request.env["im_livechat.channel"].with_context(lang=False).sudo().browse(channel_id)._open_livechat_mail_channel(anonymous_name, previous_operator_id, user_id, country_id)
@http.route('/im_livechat/feedback', type='json', auth='public', cors="*")
def feedback(self, uuid, rate, reason=None, **kwargs):
channel = request.env['mail.channel'].sudo().search([('uuid', '=', uuid)], limit=1)
if channel:
# limit the creation : only ONE rating per session
values = {
'rating': rate,
'consumed': True,
'feedback': reason,
'is_internal': False,
}
if not channel.rating_ids:
values.update({
'res_id': channel.id,
'res_model_id': request.env['ir.model']._get_id('mail.channel'),
})
# find the partner (operator)
if channel.channel_partner_ids:
values['rated_partner_id'] = channel.channel_partner_ids[0].id
# if logged in user, set its partner on rating
values['partner_id'] = request.env.user.partner_id.id if request.session.uid else False
# create the rating
rating = request.env['rating.rating'].sudo().create(values)
else:
rating = channel.rating_ids[0]
rating.write(values)
return rating.id
return False
@http.route('/im_livechat/history', type="json", auth="public", cors="*")
def history_pages(self, pid, channel_uuid, page_history=None):
partner_ids = (pid, request.env.user.partner_id.id)
channel = request.env['mail.channel'].sudo().search([('uuid', '=', channel_uuid), ('channel_partner_ids', 'in', partner_ids)])
if channel:
channel._send_history_message(pid, page_history)
return True
@http.route('/im_livechat/notify_typing', type='json', auth='public', cors="*")
def notify_typing(self, uuid, is_typing):
""" Broadcast the typing notification of the website user to other channel members
:param uuid: (string) the UUID of the livechat channel
:param is_typing: (boolean) tells whether the website user is typing or not.
"""
channel = request.env['mail.channel'].sudo().search([('uuid', '=', uuid)], limit=1)
channel.notify_typing(is_typing=is_typing)
@http.route('/im_livechat/email_livechat_transcript', type='json', auth='public', cors="*")
def email_livechat_transcript(self, uuid, email):
channel = request.env['mail.channel'].sudo().search([
('channel_type', '=', 'livechat'),
('uuid', '=', uuid)], limit=1)
if channel:
channel._email_livechat_transcript(email)
@http.route('/im_livechat/visitor_leave_session', type='json', auth="public")
def visitor_leave_session(self, uuid):
""" Called when the livechat visitor leaves the conversation.
This will clean the chat request and warn the operator that the conversation is over.
This allows also to re-send a new chat request to the visitor, as while the visitor is
in conversation with an operator, it's not possible to send the visitor a chat request."""
mail_channel = request.env['mail.channel'].sudo().search([('uuid', '=', uuid)])
if mail_channel:
mail_channel._close_livechat_session()
| 52.271605 | 8,468 |
1,253 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Saudi Arabia - E-invoicing',
'icon': '/l10n_sa/static/description/icon.png',
'version': '0.1',
'depends': [
'account_edi_ubl_cii',
'account_debit_note',
'l10n_sa_invoice',
'base_vat'
],
'author': 'Odoo',
'summary': """
E-Invoicing, Universal Business Language
""",
'description': """
E-invoice implementation for the Kingdom of Saudi Arabia
""",
'category': 'Accounting/Localizations/EDI',
'license': 'LGPL-3',
'data': [
'security/ir.model.access.csv',
'data/account_edi_format.xml',
'data/ubl_21_zatca.xml',
'data/res_country_data.xml',
'wizard/l10n_sa_edi_otp_wizard.xml',
'views/account_tax_views.xml',
'views/account_journal_views.xml',
'views/res_partner_views.xml',
'views/res_company_views.xml',
'views/res_config_settings_view.xml',
'views/report_invoice.xml',
],
'demo': [
'demo/demo_company.xml',
],
'assets': {
'web.assets_backend': [
'l10n_sa_edi/static/src/scss/form_view.scss',
]
}
}
| 28.477273 | 1,253 |
11,703 |
py
|
PYTHON
|
15.0
|
# coding: utf-8
from datetime import datetime
from odoo import Command
from odoo.tests import tagged
from odoo.addons.account_edi.tests.common import AccountEdiTestCommon
@tagged('post_install_l10n', '-at_install', 'post_install')
class TestSaEdiCommon(AccountEdiTestCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_sa.sa_chart_template_standard', edi_format_ref='l10n_sa_edi.edi_sa_zatca'):
super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref)
# Setup company
cls.company = cls.company_data['company']
cls.company.name = 'SA Company Test'
cls.company.country_id = cls.env.ref('base.sa')
cls.company.email = "[email protected]"
cls.company.phone = '+966 51 234 5678'
cls.customer_invoice_journal = cls.env['account.journal'].search([('company_id', '=', cls.company.id), ('name', '=', 'Customer Invoices')])
cls.company.l10n_sa_edi_building_number = '1234'
cls.company.l10n_sa_edi_plot_identification = '1234'
cls.company.street2 = "Testomania"
cls.company.l10n_sa_additional_identification_number = '2525252525252'
cls.company.l10n_sa_additional_identification_scheme = 'CRN'
cls.company.vat = '311111111111113'
cls.company.l10n_sa_private_key = cls.env['res.company']._l10n_sa_generate_private_key()
cls.company.state_id = cls.env['res.country.state'].create({
'name': 'Riyadh',
'code': 'RYA',
'country_id': cls.company.country_id.id
})
cls.company.street = 'Al Amir Mohammed Bin Abdul Aziz Street'
cls.company.city = 'المدينة المنورة'
cls.company.zip = '42317'
cls.customer_invoice_journal.l10n_sa_serial_number = '123456789'
cls.partner_us = cls.env['res.partner'].create({
'name': 'Chichi Lboukla',
'ref': 'Azure Interior',
'street': '4557 De Silva St',
'l10n_sa_edi_building_number': '12300',
'l10n_sa_edi_plot_identification': '2323',
'l10n_sa_additional_identification_scheme': 'CRN',
'l10n_sa_additional_identification_number': '353535353535353',
'city': 'Fremont',
'zip': '94538',
'street2': 'Neighbor!',
'country_id': cls.env.ref('base.us').id,
'state_id': cls.env['res.country.state'].search([('name', '=', 'California')]).id,
'email': '[email protected]',
'phone': '(870)-931-0505',
'company_type': 'company',
'lang': 'en_US',
})
cls.partner_sa = cls.env['res.partner'].create({
'name': 'Chichi Lboukla',
'ref': 'Azure Interior',
'street': '4557 De Silva St',
'l10n_sa_edi_building_number': '12300',
'l10n_sa_edi_plot_identification': '2323',
'l10n_sa_additional_identification_scheme': 'CRN',
'l10n_sa_additional_identification_number': '353535353535353',
'city': 'Fremont',
'zip': '94538',
'street2': 'Neighbor!',
'country_id': cls.env.ref('base.sa').id,
'state_id': cls.env['res.country.state'].search([('name', '=', 'California')]).id,
'email': '[email protected]',
'phone': '(870)-931-0505',
'company_type': 'company',
'lang': 'en_US',
})
cls.partner_sa_simplified = cls.env['res.partner'].create({
'name': 'Mohammed Ali',
'ref': 'Mohammed Ali',
'country_id': cls.env.ref('base.sa').id,
'l10n_sa_additional_identification_scheme': 'MOM',
'l10n_sa_additional_identification_number': '3123123213131',
'state_id': cls.company.state_id.id,
'company_type': 'person',
'lang': 'en_US',
})
# 15% tax
cls.tax_15 = cls.env['account.tax'].search([('company_id', '=', cls.company.id), ('name', '=', 'Sales Tax 15%')])
# Large cabinet product
cls.product_a = cls.env['product.product'].create({
'name': 'Product A',
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'standard_price': 320.0,
'default_code': 'P0001',
})
cls.product_b = cls.env['product.product'].create({
'name': 'Product B',
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'standard_price': 15.8,
'default_code': 'P0002',
})
cls.product_burger = cls.env['product.product'].create({
'name': 'Burger',
'uom_id': cls.env.ref('uom.product_uom_unit').id,
'standard_price': 265.00,
})
cls.remove_ubl_extensions_xpath = '''<xpath expr="//*[local-name()='UBLExtensions']" position="replace"/>'''
cls.invoice_applied_xpath = '''
<xpath expr="(//*[local-name()='Invoice']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='Invoice']/*[local-name()='UUID'])[1]" position="replace">
<UUID>___ignore___</UUID>
</xpath>
<xpath expr="(//*[local-name()='Contact']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='Contact']/*[local-name()='ID'])[2]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="//*[local-name()='PaymentMeans']/*[local-name()='InstructionID']" position="replace">
<InstructionID>___ignore___</InstructionID>
</xpath>
<xpath expr="(//*[local-name()='PaymentMeans']/*[local-name()='PaymentID'])" position="replace">
<PaymentID>___ignore___</PaymentID>
</xpath>
<xpath expr="//*[local-name()='InvoiceLine']/*[local-name()='ID']" position="replace">
<ID>___ignore___</ID>
</xpath>
'''
cls.credit_note_applied_xpath = '''
<xpath expr="(//*[local-name()='Invoice']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='Invoice']/*[local-name()='UUID'])[1]" position="replace">
<UUID>___ignore___</UUID>
</xpath>
<xpath expr="(//*[local-name()='Contact']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='Contact']/*[local-name()='ID'])[2]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='OrderReference']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='InvoiceDocumentReference']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='PaymentMeans']/*[local-name()='InstructionNote'])" position="replace">
<InstructionNote>___ignore___</InstructionNote>
</xpath>
<xpath expr="(//*[local-name()='PaymentMeans']/*[local-name()='PaymentID'])" position="replace">
<PaymentID>___ignore___</PaymentID>
</xpath>
<xpath expr="//*[local-name()='InvoiceLine']/*[local-name()='ID']" position="replace">
<ID>___ignore___</ID>
</xpath>
'''
cls.debit_note_applied_xpath = '''
<xpath expr="(//*[local-name()='Invoice']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='Invoice']/*[local-name()='UUID'])[1]" position="replace">
<UUID>___ignore___</UUID>
</xpath>
<xpath expr="(//*[local-name()='Contact']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='Contact']/*[local-name()='ID'])[2]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='OrderReference']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="(//*[local-name()='InvoiceDocumentReference']/*[local-name()='ID'])[1]" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="//*[local-name()='InvoiceLine']/*[local-name()='ID']" position="replace">
<ID>___ignore___</ID>
</xpath>
<xpath expr="//*[local-name()='PaymentMeans']/*[local-name()='InstructionID']" position="replace">
<InstructionID>___ignore___</InstructionID>
</xpath>
<xpath expr="(//*[local-name()='PaymentMeans']/*[local-name()='PaymentID'])" position="replace">
<PaymentID>___ignore___</PaymentID>
</xpath>
<xpath expr="(//*[local-name()='PaymentMeans']/*[local-name()='InstructionNote'])" position="replace">
<InstructionNote>___ignore___</InstructionNote>
</xpath>
'''
def _create_invoice(self, **kwargs):
vals = {
'name': kwargs['name'],
'move_type': 'out_invoice',
'company_id': self.company,
'partner_id': kwargs['partner_id'],
'invoice_date': kwargs['date'],
'invoice_date_due': kwargs['date_due'],
'currency_id': self.company.currency_id,
'invoice_line_ids': [Command.create({
'product_id': kwargs['product_id'].id,
'price_unit': kwargs['price'],
'quantity': kwargs.get('quantity', 1.0),
'tax_ids': [Command.set(self.tax_15.ids)],
}),
],
}
move = self.env['account.move'].create(vals)
move.state = 'posted'
move.l10n_sa_confirmation_datetime = datetime.now()
# move.payment_reference = move.name
return move
def _create_debit_note(self, **kwargs):
invoice = self._create_invoice(**kwargs)
debit_note_wizard = self.env['account.debit.note'].with_context(
{'active_ids': [invoice.id], 'active_model': 'account.move', 'default_copy_lines': True}).create({
'reason': 'Totes forgot'})
res = debit_note_wizard.create_debit()
debit_note = self.env['account.move'].browse(res['res_id'])
debit_note.l10n_sa_confirmation_datetime = datetime.now()
debit_note.state = 'posted'
return debit_note
def _create_credit_note(self, **kwargs):
move = self._create_invoice(**kwargs)
move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=move.ids).create({
'reason': 'no reason',
'refund_method': 'refund',
'journal_id': move.journal_id.id,
})
reversal = move_reversal.reverse_moves()
reverse_move = self.env['account.move'].browse(reversal['res_id'])
reverse_move.l10n_sa_confirmation_datetime = datetime.now()
reverse_move.state = 'posted'
return reverse_move
| 47.710204 | 11,689 |
7,568 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from freezegun import freeze_time
import logging
from pytz import timezone
from odoo.tests import tagged
from odoo.tools import misc
from .common import TestSaEdiCommon
_logger = logging.getLogger(__name__)
@tagged('post_install_l10n', '-at_install', 'post_install')
class TestEdiZatca(TestSaEdiCommon):
def testInvoiceStandard(self):
with freeze_time(datetime(year=2022, month=9, day=5, hour=8, minute=20, second=2, tzinfo=timezone('Etc/GMT-3'))):
standard_invoice = misc.file_open('l10n_sa_edi/tests/compliance/standard/invoice.xml', 'rb').read()
expected_tree = self.get_xml_tree_from_string(standard_invoice)
expected_tree = self.with_applied_xpath(expected_tree, self.invoice_applied_xpath)
move = self._create_invoice(name='INV/2022/00014', date='2022-09-05', date_due='2022-09-22', partner_id=self.partner_us,
product_id=self.product_a, price=320.0)
move._l10n_sa_generate_unsigned_data()
generated_file = self.env['account.edi.format']._l10n_sa_generate_zatca_template(move)
current_tree = self.get_xml_tree_from_string(generated_file)
current_tree = self.with_applied_xpath(current_tree, self.remove_ubl_extensions_xpath)
self.assertXmlTreeEqual(current_tree, expected_tree)
def testCreditNoteStandard(self):
with freeze_time(datetime(year=2022, month=9, day=5, hour=9, minute=39, second=15, tzinfo=timezone('Etc/GMT-3'))):
applied_xpath = self.credit_note_applied_xpath + \
'''
<xpath expr="(//*[local-name()='AdditionalDocumentReference']/*[local-name()='UUID'])[1]" position="replace">
<UUID>___ignore___</UUID>
</xpath>
'''
standard_credit_note = misc.file_open('l10n_sa_edi/tests/compliance/standard/credit.xml', 'rb').read()
expected_tree = self.get_xml_tree_from_string(standard_credit_note)
expected_tree = self.with_applied_xpath(expected_tree, applied_xpath)
credit_note = self._create_credit_note(name='INV/2022/00014', date='2022-09-05', date_due='2022-09-22',
partner_id=self.partner_us, product_id=self.product_a, price=320.0)
credit_note._l10n_sa_generate_unsigned_data()
generated_file = self.env['account.edi.format']._l10n_sa_generate_zatca_template(credit_note)
current_tree = self.get_xml_tree_from_string(generated_file)
current_tree = self.with_applied_xpath(current_tree, self.remove_ubl_extensions_xpath)
self.assertXmlTreeEqual(current_tree, expected_tree)
def testDebitNoteStandard(self):
with freeze_time(datetime(year=2022, month=9, day=5, hour=9, minute=45, second=27, tzinfo=timezone('Etc/GMT-3'))):
applied_xpath = self.debit_note_applied_xpath + \
'''
<xpath expr="(//*[local-name()='AdditionalDocumentReference']/*[local-name()='UUID'])[1]" position="replace">
<UUID>___ignore___</UUID>
</xpath>
'''
standard_debit_note = misc.file_open('l10n_sa_edi/tests/compliance/standard/debit.xml', 'rb').read()
expected_tree = self.get_xml_tree_from_string(standard_debit_note)
expected_tree = self.with_applied_xpath(expected_tree, applied_xpath)
debit_note = self._create_debit_note(name='INV/2022/00001', date='2022-09-05', date_due='2022-09-22',
partner_id=self.partner_us, product_id=self.product_b, price=15.80)
debit_note._l10n_sa_generate_unsigned_data()
generated_file = self.env['account.edi.format']._l10n_sa_generate_zatca_template(debit_note)
current_tree = self.get_xml_tree_from_string(generated_file)
current_tree = self.with_applied_xpath(current_tree, self.remove_ubl_extensions_xpath)
self.assertXmlTreeEqual(current_tree, expected_tree)
def testInvoiceSimplified(self):
with freeze_time(datetime(year=2023, month=3, day=10, hour=14, minute=56, second=55, tzinfo=timezone('Etc/GMT-3'))):
simplified_invoice = misc.file_open('l10n_sa_edi/tests/compliance/simplified/invoice.xml', 'rb').read()
expected_tree = self.get_xml_tree_from_string(simplified_invoice)
expected_tree = self.with_applied_xpath(expected_tree, self.invoice_applied_xpath)
move = self._create_invoice(name='INV/2023/00034', date='2023-03-10', date_due='2023-03-10', partner_id=self.partner_sa_simplified,
product_id=self.product_burger, price=265.00, quantity=3.0)
move._l10n_sa_generate_unsigned_data()
generated_file = self.env['account.edi.format']._l10n_sa_generate_zatca_template(move)
current_tree = self.get_xml_tree_from_string(generated_file)
current_tree = self.with_applied_xpath(current_tree, self.remove_ubl_extensions_xpath)
self.assertXmlTreeEqual(current_tree, expected_tree)
def testCreditNoteSimplified(self):
with freeze_time(datetime(year=2023, month=3, day=10, hour=14, minute=59, second=38, tzinfo=timezone('Etc/GMT-3'))):
simplified_credit_note = misc.file_open('l10n_sa_edi/tests/compliance/simplified/credit.xml', 'rb').read()
expected_tree = self.get_xml_tree_from_string(simplified_credit_note)
expected_tree = self.with_applied_xpath(expected_tree, self.credit_note_applied_xpath)
move = self._create_credit_note(name='INV/2023/00034', date='2023-03-10', date_due='2023-03-10',
partner_id=self.partner_sa_simplified, product_id=self.product_burger,
price=265.00, quantity=3.0)
move._l10n_sa_generate_unsigned_data()
generated_file = self.env['account.edi.format']._l10n_sa_generate_zatca_template(move)
current_tree = self.get_xml_tree_from_string(generated_file)
current_tree = self.with_applied_xpath(current_tree, self.remove_ubl_extensions_xpath)
self.assertXmlTreeEqual(current_tree, expected_tree)
def testDebitNoteSimplified(self):
with freeze_time(datetime(year=2023, month=3, day=10, hour=15, minute=1, second=46, tzinfo=timezone('Etc/GMT-3'))):
simplified_credit_note = misc.file_open('l10n_sa_edi/tests/compliance/simplified/debit.xml', 'rb').read()
expected_tree = self.get_xml_tree_from_string(simplified_credit_note)
expected_tree = self.with_applied_xpath(expected_tree, self.debit_note_applied_xpath)
move = self._create_debit_note(name='INV/2023/00034', date='2023-03-10', date_due='2023-03-10',
partner_id=self.partner_sa_simplified, product_id=self.product_burger,
price=265.00, quantity=2.0)
move._l10n_sa_generate_unsigned_data()
generated_file = self.env['account.edi.format']._l10n_sa_generate_zatca_template(move)
current_tree = self.get_xml_tree_from_string(generated_file)
current_tree = self.with_applied_xpath(current_tree, self.remove_ubl_extensions_xpath)
self.assertXmlTreeEqual(current_tree, expected_tree)
| 61.032258 | 7,568 |
1,332 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models, _, api
from odoo.exceptions import UserError
class RequestZATCAOtp(models.TransientModel):
_name = 'l10n_sa_edi.otp.wizard'
_description = 'Request ZATCA OTP'
l10n_sa_renewal = fields.Boolean("PCSID Renewal",
help="Used to decide whether we should call the PCSID renewal API or the CCSID API",
default=False)
l10n_sa_otp = fields.Char("OTP", copy=False, help="OTP required to get a CCSID. Can only be acquired through "
"the Fatoora portal.")
journal_id = fields.Many2one('account.journal', default=lambda self: self.env.context.get('active_id'), required=True)
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if self.env.company.l10n_sa_api_mode == 'sandbox':
res['l10n_sa_otp'] = '123456' if self.l10n_sa_renewal else '123345'
return res
def validate(self):
if not self.l10n_sa_otp:
raise UserError(_("You need to provide an OTP to be able to request a CCSID"))
if self.l10n_sa_renewal:
return self.journal_id._l10n_sa_get_production_CSID(self.l10n_sa_otp)
self.journal_id._l10n_sa_api_onboard_journal(self.l10n_sa_otp)
| 47.571429 | 1,332 |
514 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
from odoo.tools.translate import _
from odoo.exceptions import UserError
class AccountDebitNote(models.TransientModel):
_inherit = 'account.debit.note'
def create_debit(self):
self.ensure_one()
for move in self.move_ids:
if move.journal_id.country_code == 'SA' and not self.reason:
raise UserError(_("For debit notes issued in Saudi Arabia, you need to specify a Reason"))
return super().create_debit()
| 34.266667 | 514 |
529 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
from odoo.tools.translate import _
from odoo.exceptions import UserError
class AccountMoveReversal(models.TransientModel):
_inherit = 'account.move.reversal'
def reverse_moves(self):
self.ensure_one()
for move in self.move_ids:
if move.journal_id.country_code == 'SA' and not self.reason:
raise UserError(_("For Credit/Debit notes issued in Saudi Arabia, you need to specify a Reason"))
return super().reverse_moves()
| 35.266667 | 529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.