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
|
---|---|---|---|---|---|---|
9,540 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from odoo import api, fields, models
from odoo.exceptions import UserError
from odoo.tools.translate import _
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
def _default_website(self):
return self.env['website'].search([('company_id', '=', self.env.company.id)], limit=1)
website_id = fields.Many2one('website', string="website",
default=_default_website, ondelete='cascade')
website_name = fields.Char('Website Name', related='website_id.name', readonly=False)
website_domain = fields.Char('Website Domain', related='website_id.domain', readonly=False)
website_country_group_ids = fields.Many2many(related='website_id.country_group_ids', readonly=False)
website_company_id = fields.Many2one(related='website_id.company_id', string='Website Company', readonly=False)
website_logo = fields.Binary(related='website_id.logo', readonly=False)
language_ids = fields.Many2many(related='website_id.language_ids', relation='res.lang', readonly=False)
website_language_count = fields.Integer(string='Number of languages', compute='_compute_website_language_count', readonly=True)
website_default_lang_id = fields.Many2one(string='Default language', related='website_id.default_lang_id', readonly=False)
website_default_lang_code = fields.Char('Default language code', related='website_id.default_lang_id.code', readonly=False)
specific_user_account = fields.Boolean(related='website_id.specific_user_account', readonly=False,
help='Are newly created user accounts website specific')
website_cookies_bar = fields.Boolean(related='website_id.cookies_bar', readonly=False)
google_analytics_key = fields.Char('Google Analytics Key', related='website_id.google_analytics_key', readonly=False)
google_management_client_id = fields.Char('Google Client ID', related='website_id.google_management_client_id', readonly=False)
google_management_client_secret = fields.Char('Google Client Secret', related='website_id.google_management_client_secret', readonly=False)
google_search_console = fields.Char('Google Search Console', related='website_id.google_search_console', readonly=False)
cdn_activated = fields.Boolean(related='website_id.cdn_activated', readonly=False)
cdn_url = fields.Char(related='website_id.cdn_url', readonly=False)
cdn_filters = fields.Text(related='website_id.cdn_filters', readonly=False)
auth_signup_uninvited = fields.Selection(compute="_compute_auth_signup", inverse="_set_auth_signup")
social_twitter = fields.Char(related='website_id.social_twitter', readonly=False)
social_facebook = fields.Char(related='website_id.social_facebook', readonly=False)
social_github = fields.Char(related='website_id.social_github', readonly=False)
social_linkedin = fields.Char(related='website_id.social_linkedin', readonly=False)
social_youtube = fields.Char(related='website_id.social_youtube', readonly=False)
social_instagram = fields.Char(related='website_id.social_instagram', readonly=False)
@api.depends('website_id', 'social_twitter', 'social_facebook', 'social_github', 'social_linkedin', 'social_youtube', 'social_instagram')
def has_social_network(self):
self.has_social_network = self.social_twitter or self.social_facebook or self.social_github \
or self.social_linkedin or self.social_youtube or self.social_instagram
def inverse_has_social_network(self):
if not self.has_social_network:
self.social_twitter = ''
self.social_facebook = ''
self.social_github = ''
self.social_linkedin = ''
self.social_youtube = ''
self.social_instagram = ''
has_social_network = fields.Boolean("Configure Social Network", compute=has_social_network, inverse=inverse_has_social_network)
favicon = fields.Binary('Favicon', related='website_id.favicon', readonly=False)
social_default_image = fields.Binary('Default Social Share Image', related='website_id.social_default_image', readonly=False)
google_maps_api_key = fields.Char(related='website_id.google_maps_api_key', readonly=False)
group_multi_website = fields.Boolean("Multi-website", implied_group="website.group_multi_website")
@api.onchange('website_id')
@api.depends('website_id.auth_signup_uninvited')
def _compute_auth_signup(self):
self.auth_signup_uninvited = self.website_id.auth_signup_uninvited
def _set_auth_signup(self):
for config in self:
config.website_id.auth_signup_uninvited = config.auth_signup_uninvited
@api.depends('website_id')
def has_google_analytics(self):
self.has_google_analytics = bool(self.google_analytics_key)
@api.depends('website_id')
def has_google_analytics_dashboard(self):
self.has_google_analytics_dashboard = bool(self.google_management_client_id)
@api.depends('website_id')
def has_google_maps(self):
self.has_google_maps = bool(self.google_maps_api_key)
@api.depends('website_id')
def has_default_share_image(self):
self.has_default_share_image = bool(self.social_default_image)
@api.depends('website_id')
def has_google_search_console(self):
self.has_google_search_console = bool(self.google_search_console)
def inverse_has_google_analytics(self):
if not self.has_google_analytics:
self.has_google_analytics_dashboard = False
self.google_analytics_key = False
def inverse_has_google_maps(self):
if not self.has_google_maps:
self.google_maps_api_key = False
def inverse_has_google_analytics_dashboard(self):
if not self.has_google_analytics_dashboard:
self.google_management_client_id = False
self.google_management_client_secret = False
def inverse_has_google_search_console(self):
if not self.has_google_search_console:
self.google_search_console = False
def inverse_has_default_share_image(self):
if not self.has_default_share_image:
self.social_default_image = False
has_google_analytics = fields.Boolean("Google Analytics", compute=has_google_analytics, inverse=inverse_has_google_analytics)
has_google_analytics_dashboard = fields.Boolean("Google Analytics Dashboard", compute=has_google_analytics_dashboard, inverse=inverse_has_google_analytics_dashboard)
has_google_maps = fields.Boolean("Google Maps", compute=has_google_maps, inverse=inverse_has_google_maps)
has_google_search_console = fields.Boolean("Console Google Search", compute=has_google_search_console, inverse=inverse_has_google_search_console)
has_default_share_image = fields.Boolean("Use a image by default for sharing", compute=has_default_share_image, inverse=inverse_has_default_share_image)
@api.onchange('language_ids')
def _onchange_language_ids(self):
# If current default language is removed from language_ids
# update the website_default_lang_id
language_ids = self.language_ids._origin
if not language_ids:
self.website_default_lang_id = False
elif self.website_default_lang_id not in language_ids:
self.website_default_lang_id = language_ids[0]
@api.depends('language_ids')
def _compute_website_language_count(self):
for config in self:
config.website_language_count = len(config.language_ids)
def set_values(self):
super(ResConfigSettings, self).set_values()
def open_template_user(self):
action = self.env["ir.actions.actions"]._for_xml_id("base.action_res_users")
action['res_id'] = literal_eval(self.env['ir.config_parameter'].sudo().get_param('base.template_portal_user_id', 'False'))
action['views'] = [[self.env.ref('base.view_users_form').id, 'form']]
return action
def website_go_to(self):
self.website_id._force()
return {
'type': 'ir.actions.act_url',
'url': '/',
'target': 'self',
}
def action_website_create_new(self):
return {
'view_mode': 'form',
'view_id': self.env.ref('website.view_website_form_view_themes_modal').id,
'res_model': 'website',
'type': 'ir.actions.act_window',
'target': 'new',
'res_id': False,
}
def action_open_robots(self):
self.website_id._force()
return {
'name': _("Robots.txt"),
'view_mode': 'form',
'res_model': 'website.robots',
'type': 'ir.actions.act_window',
"views": [[False, "form"]],
'target': 'new',
}
def action_ping_sitemap(self):
if not self.website_id._get_http_domain():
raise UserError(_("You haven't defined your domain"))
return {
'type': 'ir.actions.act_url',
'url': 'http://www.google.com/ping?sitemap=%s/sitemap.xml' % self.website_id._get_http_domain(),
'target': 'new',
}
def install_theme_on_current_website(self):
self.website_id._force()
action = self.env["ir.actions.actions"]._for_xml_id("website.theme_install_kanban_action")
action['target'] = 'main'
return action
| 48.923077 | 9,540 |
84,978 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import hashlib
import inspect
import json
import logging
import re
import requests
from lxml import etree, html
from psycopg2 import sql
from werkzeug import urls
from werkzeug.datastructures import OrderedMultiDict
from werkzeug.exceptions import NotFound
from odoo import api, fields, models, tools, http, release, registry
from odoo.addons.http_routing.models.ir_http import slugify, _guess_mimetype, url_for
from odoo.addons.website.models.ir_http import sitemap_qs2dom
from odoo.addons.website.tools import get_unaccent_sql_wrapper, similarity_score, text_from_html
from odoo.addons.portal.controllers.portal import pager
from odoo.addons.iap.tools import iap_tools
from odoo.exceptions import UserError, AccessError
from odoo.http import request
from odoo.modules.module import get_resource_path
from odoo.osv.expression import AND, OR, FALSE_DOMAIN
from odoo.tools.translate import _
from odoo.tools import escape_psql, pycompat
logger = logging.getLogger(__name__)
DEFAULT_CDN_FILTERS = [
"^/[^/]+/static/",
"^/web/(css|js)/",
"^/web/image",
"^/web/content",
"^/web/assets",
# retrocompatibility
"^/website/image/",
]
DEFAULT_ENDPOINT = 'https://website.api.odoo.com'
class Website(models.Model):
_name = "website"
_description = "Website"
_order = "sequence, id"
@api.model
def website_domain(self, website_id=False):
return [('website_id', 'in', (False, website_id or self.id))]
def _active_languages(self):
return self.env['res.lang'].search([]).ids
def _default_language(self):
lang_code = self.env['ir.default'].get('res.partner', 'lang')
def_lang_id = self.env['res.lang']._lang_get_id(lang_code)
return def_lang_id or self._active_languages()[0]
name = fields.Char('Website Name', required=True)
sequence = fields.Integer(default=10)
domain = fields.Char('Website Domain', help='E.g. https://www.mydomain.com')
country_group_ids = fields.Many2many('res.country.group', 'website_country_group_rel', 'website_id', 'country_group_id',
string='Country Groups', help='Used when multiple websites have the same domain.')
company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.company, required=True)
language_ids = fields.Many2many('res.lang', 'website_lang_rel', 'website_id', 'lang_id', 'Languages', default=_active_languages)
default_lang_id = fields.Many2one('res.lang', string="Default Language", default=_default_language, required=True)
auto_redirect_lang = fields.Boolean('Autoredirect Language', default=True, help="Should users be redirected to their browser's language")
cookies_bar = fields.Boolean('Cookies Bar', help="Display a customizable cookies bar on your website.")
configurator_done = fields.Boolean(help='True if configurator has been completed or ignored')
def _default_social_facebook(self):
return self.env.ref('base.main_company').social_facebook
def _default_social_github(self):
return self.env.ref('base.main_company').social_github
def _default_social_linkedin(self):
return self.env.ref('base.main_company').social_linkedin
def _default_social_youtube(self):
return self.env.ref('base.main_company').social_youtube
def _default_social_instagram(self):
return self.env.ref('base.main_company').social_instagram
def _default_social_twitter(self):
return self.env.ref('base.main_company').social_twitter
def _default_logo(self):
image_path = get_resource_path('website', 'static/src/img', 'website_logo.svg')
with tools.file_open(image_path, 'rb') as f:
return base64.b64encode(f.read())
logo = fields.Binary('Website Logo', default=_default_logo, help="Display this logo on the website.")
social_twitter = fields.Char('Twitter Account', default=_default_social_twitter)
social_facebook = fields.Char('Facebook Account', default=_default_social_facebook)
social_github = fields.Char('GitHub Account', default=_default_social_github)
social_linkedin = fields.Char('LinkedIn Account', default=_default_social_linkedin)
social_youtube = fields.Char('Youtube Account', default=_default_social_youtube)
social_instagram = fields.Char('Instagram Account', default=_default_social_instagram)
social_default_image = fields.Binary(string="Default Social Share Image", help="If set, replaces the website logo as the default social share image.")
has_social_default_image = fields.Boolean(compute='_compute_has_social_default_image', store=True)
google_analytics_key = fields.Char('Google Analytics Key')
google_management_client_id = fields.Char('Google Client ID')
google_management_client_secret = fields.Char('Google Client Secret')
google_search_console = fields.Char(help='Google key, or Enable to access first reply')
google_maps_api_key = fields.Char('Google Maps API Key')
user_id = fields.Many2one('res.users', string='Public User', required=True)
cdn_activated = fields.Boolean('Content Delivery Network (CDN)')
cdn_url = fields.Char('CDN Base URL', default='')
cdn_filters = fields.Text('CDN Filters', default=lambda s: '\n'.join(DEFAULT_CDN_FILTERS), help="URL matching those filters will be rewritten using the CDN Base URL")
partner_id = fields.Many2one(related='user_id.partner_id', string='Public Partner', readonly=False)
menu_id = fields.Many2one('website.menu', compute='_compute_menu', string='Main Menu')
homepage_id = fields.Many2one('website.page', string='Homepage')
custom_code_head = fields.Html('Custom <head> code', sanitize=False)
custom_code_footer = fields.Html('Custom end of <body> code', sanitize=False)
robots_txt = fields.Html('Robots.txt', translate=False, groups='website.group_website_designer', sanitize=False)
def _default_favicon(self):
img_path = get_resource_path('web', 'static/img/favicon.ico')
with tools.file_open(img_path, 'rb') as f:
return base64.b64encode(f.read())
favicon = fields.Binary(string="Website Favicon", help="This field holds the image used to display a favicon on the website.", default=_default_favicon)
theme_id = fields.Many2one('ir.module.module', help='Installed theme')
specific_user_account = fields.Boolean('Specific User Account', help='If True, new accounts will be associated to the current website')
auth_signup_uninvited = fields.Selection([
('b2b', 'On invitation'),
('b2c', 'Free sign up'),
], string='Customer Account', default='b2b')
@api.onchange('language_ids')
def _onchange_language_ids(self):
language_ids = self.language_ids._origin
if language_ids and self.default_lang_id not in language_ids:
self.default_lang_id = language_ids[0]
@api.depends('social_default_image')
def _compute_has_social_default_image(self):
for website in self:
website.has_social_default_image = bool(website.social_default_image)
def _compute_menu(self):
for website in self:
menus = self.env['website.menu'].browse(website._get_menu_ids())
# use field parent_id (1 query) to determine field child_id (2 queries by level)"
for menu in menus:
menu._cache['child_id'] = ()
for menu in menus:
# don't add child menu if parent is forbidden
if menu.parent_id and menu.parent_id in menus:
menu.parent_id._cache['child_id'] += (menu.id,)
# prefetch every website.page and ir.ui.view at once
menus.mapped('is_visible')
top_menus = menus.filtered(lambda m: not m.parent_id)
website.menu_id = top_menus and top_menus[0].id or False
# self.env.uid for ir.rule groups on menu
@tools.ormcache('self.env.uid', 'self.id')
def _get_menu_ids(self):
return self.env['website.menu'].search([('website_id', '=', self.id)]).ids
# self.env.uid for ir.rule groups on menu
@tools.ormcache('self.env.uid', 'self.id')
def _get_menu_page_ids(self):
return self.env['website.menu'].search([('website_id', '=', self.id)]).page_id.ids
@api.model
def create(self, vals):
self._handle_create_write(vals)
if 'user_id' not in vals:
company = self.env['res.company'].browse(vals.get('company_id'))
vals['user_id'] = company._get_public_user().id if company else self.env.ref('base.public_user').id
res = super(Website, self).create(vals)
res.company_id._compute_website_id()
res._bootstrap_homepage()
if not self.env.user.has_group('website.group_multi_website') and self.search_count([]) > 1:
all_user_groups = 'base.group_portal,base.group_user,base.group_public'
groups = self.env['res.groups'].concat(*(self.env.ref(it) for it in all_user_groups.split(',')))
groups.write({'implied_ids': [(4, self.env.ref('website.group_multi_website').id)]})
return res
def write(self, values):
public_user_to_change_websites = self.env['website']
original_company = self.company_id
self._handle_create_write(values)
self.clear_caches()
if 'company_id' in values and 'user_id' not in values:
public_user_to_change_websites = self.filtered(lambda w: w.sudo().user_id.company_id.id != values['company_id'])
if public_user_to_change_websites:
company = self.env['res.company'].browse(values['company_id'])
super(Website, public_user_to_change_websites).write(dict(values, user_id=company and company._get_public_user().id))
result = super(Website, self - public_user_to_change_websites).write(values)
if 'cdn_activated' in values or 'cdn_url' in values or 'cdn_filters' in values:
# invalidate the caches from static node at compile time
self.env['ir.qweb'].clear_caches()
# invalidate cache for `company.website_id` to be recomputed
if 'sequence' in values or 'company_id' in values:
(original_company | self.company_id)._compute_website_id()
if 'cookies_bar' in values:
existing_policy_page = self.env['website.page'].search([
('website_id', '=', self.id),
('url', '=', '/cookie-policy'),
])
if not values['cookies_bar']:
existing_policy_page.unlink()
elif not existing_policy_page:
cookies_view = self.env.ref('website.cookie_policy', raise_if_not_found=False)
if cookies_view:
cookies_view.with_context(website_id=self.id).write({'website_id': self.id})
specific_cook_view = self.with_context(website_id=self.id).viewref('website.cookie_policy')
self.env['website.page'].create({
'is_published': True,
'website_indexed': False,
'url': '/cookie-policy',
'website_id': self.id,
'view_id': specific_cook_view.id,
})
return result
@api.model
def _handle_create_write(self, vals):
self._handle_favicon(vals)
self._handle_domain(vals)
@api.model
def _handle_favicon(self, vals):
if 'favicon' in vals:
vals['favicon'] = tools.image_process(vals['favicon'], size=(256, 256), crop='center', output_format='ICO')
@api.model
def _handle_domain(self, vals):
if 'domain' in vals and vals['domain']:
if not vals['domain'].startswith('http'):
vals['domain'] = 'https://%s' % vals['domain']
vals['domain'] = vals['domain'].rstrip('/')
# TODO: rename in master
@api.ondelete(at_uninstall=False)
def _unlink_except_last_remaining_website(self):
website = self.search([('id', 'not in', self.ids)], limit=1)
if not website:
raise UserError(_('You must keep at least one website.'))
default_website = self.env.ref('website.default_website', raise_if_not_found=False)
if default_website and default_website in self:
raise UserError(_("You cannot delete default website %s. Try to change its settings instead", default_website.name))
def unlink(self):
self._remove_attachments_on_website_unlink()
companies = self.company_id
res = super().unlink()
companies._compute_website_id()
return res
def _remove_attachments_on_website_unlink(self):
# Do not delete invoices, delete what's strictly necessary
attachments_to_unlink = self.env['ir.attachment'].search([
('website_id', 'in', self.ids),
'|', '|',
('key', '!=', False), # theme attachment
('url', 'ilike', '.custom.'), # customized theme attachment
('url', 'ilike', '.assets\\_'),
])
attachments_to_unlink.unlink()
def create_and_redirect_configurator(self):
self._force()
configurator_action_todo = self.env.ref('website.website_configurator_todo')
return configurator_action_todo.action_launch()
# ----------------------------------------------------------
# Configurator
# ----------------------------------------------------------
def _website_api_rpc(self, route, params):
params['version'] = release.version
IrConfigParameter = self.env['ir.config_parameter'].sudo()
website_api_endpoint = IrConfigParameter.get_param('website.website_api_endpoint', DEFAULT_ENDPOINT)
endpoint = website_api_endpoint + route
return iap_tools.iap_jsonrpc(endpoint, params=params)
def get_cta_data(self, website_purpose, website_type):
return {'cta_btn_text': False, 'cta_btn_href': '/contactus'}
@api.model
def get_theme_snippet_lists(self, theme_name):
default_snippet_lists = http.addons_manifest['theme_default'].get('snippet_lists', {})
theme_snippet_lists = http.addons_manifest[theme_name].get('snippet_lists', {})
snippet_lists = {**default_snippet_lists, **theme_snippet_lists}
return snippet_lists
def configurator_set_menu_links(self, menu_company, module_data):
menus = self.env['website.menu'].search([('url', 'in', list(module_data.keys())), ('website_id', '=', self.id)])
for m in menus:
m.sequence = module_data[m.url]['sequence']
def configurator_get_footer_links(self):
return [
{'text': _("Privacy Policy"), 'href': '/privacy'},
]
@api.model
def configurator_init(self):
r = dict()
company = self.get_current_website().company_id
configurator_features = self.env['website.configurator.feature'].with_context(lang=self.get_current_website().default_lang_id.code).search([])
r['features'] = [{
'id': feature.id,
'name': feature.name,
'description': feature.description,
'type': 'page' if feature.page_view_id else 'app',
'icon': feature.icon,
'website_config_preselection': feature.website_config_preselection,
'module_state': feature.module_id.state,
} for feature in configurator_features]
r['logo'] = False
if company.logo and company.logo != company._get_logo():
r['logo'] = company.logo.decode('utf-8')
try:
result = self._website_api_rpc('/api/website/1/configurator/industries', {'lang': self.get_current_website().default_lang_id.code})
r['industries'] = result['industries']
except AccessError as e:
logger.warning(e.args[0])
return r
@api.model
def configurator_recommended_themes(self, industry_id, palette):
domain = [('name', '=like', 'theme%'), ('name', 'not in', ['theme_default', 'theme_common']), ('state', '!=', 'uninstallable')]
client_themes = request.env['ir.module.module'].search(domain).mapped('name')
client_themes_img = dict([
(t, http.addons_manifest[t].get('images_preview_theme', {}))
for t in client_themes if t in http.addons_manifest
])
themes_suggested = self._website_api_rpc(
'/api/website/2/configurator/recommended_themes/%s' % industry_id,
{'client_themes': client_themes_img}
)
process_svg = self.env['website.configurator.feature']._process_svg
for theme in themes_suggested:
theme['svg'] = process_svg(theme['name'], palette, theme.pop('image_urls'))
return themes_suggested
@api.model
def configurator_skip(self):
website = self.get_current_website()
website.configurator_done = True
@api.model
def configurator_apply(self, **kwargs):
def set_colors(selected_palette):
url = '/website/static/src/scss/options/user_values.scss'
selected_palette_name = selected_palette if isinstance(selected_palette, str) else 'base-1'
values = {'color-palettes-name': "'%s'" % selected_palette_name}
self.env['web_editor.assets'].make_scss_customization(url, values)
if isinstance(selected_palette, list):
url = '/website/static/src/scss/options/colors/user_color_palette.scss'
values = {f'o-color-{i}': color for i, color in enumerate(selected_palette, 1)}
self.env['web_editor.assets'].make_scss_customization(url, values)
def set_features(selected_features):
features = self.env['website.configurator.feature'].browse(selected_features)
menu_company = self.env['website.menu']
if len(features.filtered('menu_sequence')) > 5 and len(features.filtered('menu_company')) > 1:
menu_company = self.env['website.menu'].create({
'name': _('Company'),
'parent_id': website.menu_id.id,
'website_id': website.id,
'sequence': 40,
})
pages_views = {}
modules = self.env['ir.module.module']
module_data = {}
for feature in features:
add_menu = bool(feature.menu_sequence)
if feature.module_id:
if feature.module_id.state != 'installed':
modules += feature.module_id
if add_menu:
if feature.module_id.name != 'website_blog':
module_data[feature.feature_url] = {'sequence': feature.menu_sequence}
else:
blogs = module_data.setdefault('#blog', [])
blogs.append({'name': feature.name, 'sequence': feature.menu_sequence})
elif feature.page_view_id:
result = self.env['website'].new_page(
name=feature.name,
add_menu=add_menu,
page_values=dict(url=feature.feature_url, is_published=True),
menu_values=add_menu and {
'url': feature.feature_url,
'sequence': feature.menu_sequence,
'parent_id': feature.menu_company and menu_company.id or website.menu_id.id,
},
template=feature.page_view_id.key
)
pages_views[feature.iap_page_code] = result['view_id']
if modules:
modules.button_immediate_install()
assert self.env.registry is registry()
self.env['website'].browse(website.id).configurator_set_menu_links(menu_company, module_data)
return pages_views
def configure_page(page_code, snippet_list, pages_views, cta_data):
if page_code == 'homepage':
page_view_id = website.homepage_id.view_id
else:
page_view_id = self.env['ir.ui.view'].browse(pages_views[page_code])
rendered_snippets = []
nb_snippets = len(snippet_list)
for i, snippet in enumerate(snippet_list, start=1):
try:
view_id = self.env['website'].with_context(website_id=website.id, lang=website.default_lang_id.code).viewref('website.' + snippet)
if view_id:
el = html.fromstring(view_id._render(values=cta_data))
# Add the data-snippet attribute to identify the snippet
# for compatibility code
el.attrib['data-snippet'] = snippet
# Tweak the shape of the first snippet to connect it
# properly with the header color in some themes
if i == 1:
shape_el = el.xpath("//*[hasclass('o_we_shape')]")
if shape_el:
shape_el[0].attrib['class'] += ' o_header_extra_shape_mapping'
# Tweak the shape of the last snippet to connect it
# properly with the footer color in some themes
if i == nb_snippets:
shape_el = el.xpath("//*[hasclass('o_we_shape')]")
if shape_el:
shape_el[0].attrib['class'] += ' o_footer_extra_shape_mapping'
rendered_snippet = pycompat.to_text(etree.tostring(el))
rendered_snippets.append(rendered_snippet)
except ValueError as e:
logger.warning(e)
page_view_id.save(value=''.join(rendered_snippets), xpath="(//div[hasclass('oe_structure')])[last()]")
def set_images(images):
for name, url in images.items():
try:
response = requests.get(url, timeout=3)
response.raise_for_status()
except Exception as e:
logger.warning("Failed to download image: %s.\n%s", url, e)
else:
attachment = self.env['ir.attachment'].create({
'name': name,
'website_id': website.id,
'key': name,
'type': 'binary',
'raw': response.content,
'public': True,
})
self.env['ir.model.data'].create({
'name': 'configurator_%s_%s' % (website.id, name.split('.')[1]),
'module': 'website',
'model': 'ir.attachment',
'res_id': attachment.id,
'noupdate': True,
})
website = self.get_current_website()
theme_name = kwargs['theme_name']
theme = self.env['ir.module.module'].search([('name', '=', theme_name)])
url = theme.button_choose_theme()
# Force to refresh env after install of module
assert self.env.registry is registry()
website.configurator_done = True
# Enable tour
tour_asset_id = self.env.ref('website.configurator_tour')
tour_asset_id.copy({'key': tour_asset_id.key, 'website_id': website.id, 'active': True})
# Set logo from generated attachment or from company's logo
logo_attachment_id = kwargs.get('logo_attachment_id')
company = website.company_id
if logo_attachment_id:
attachment = self.env['ir.attachment'].browse(logo_attachment_id)
attachment.write({
'res_model': 'website',
'res_field': 'logo',
'res_id': website.id,
})
elif not logo_attachment_id and company.logo and company.logo != company._get_logo():
website.logo = company.logo.decode('utf-8')
# palette
palette = kwargs.get('selected_palette')
if palette:
set_colors(palette)
# Update CTA
cta_data = website.get_cta_data(kwargs.get('website_purpose'), kwargs.get('website_type'))
if cta_data['cta_btn_text']:
xpath_view = 'website.snippets'
parent_view = self.env['website'].with_context(website_id=website.id).viewref(xpath_view)
self.env['ir.ui.view'].create({
'name': parent_view.key + ' CTA',
'key': parent_view.key + "_cta",
'inherit_id': parent_view.id,
'website_id': website.id,
'type': 'qweb',
'priority': 32,
'arch_db': """
<data>
<xpath expr="//t[@t-set='cta_btn_href']" position="replace">
<t t-set="cta_btn_href">%s</t>
</xpath>
<xpath expr="//t[@t-set='cta_btn_text']" position="replace">
<t t-set="cta_btn_text">%s</t>
</xpath>
</data>
""" % (cta_data['cta_btn_href'], cta_data['cta_btn_text'])
})
try:
view_id = self.env['website'].viewref('website.header_call_to_action')
if view_id:
el = etree.fromstring(view_id.arch_db)
btn_cta_el = el.xpath("//a[hasclass('btn_cta')]")
if btn_cta_el:
btn_cta_el[0].attrib['href'] = cta_data['cta_btn_href']
btn_cta_el[0].text = cta_data['cta_btn_text']
view_id.with_context(website_id=website.id).write({'arch_db': etree.tostring(el)})
except ValueError as e:
logger.warning(e)
# modules
pages_views = set_features(kwargs.get('selected_features'))
# We need to refresh the environment of website because set_features installed some new module
# and we need the overrides of these new menus e.g. for .get_cta_data()
website = self.env['website'].browse(website.id)
# Update footers links, needs to be done after `set_features` to go
# through module overide of `configurator_get_footer_links`
footer_links = website.configurator_get_footer_links()
footer_ids = [
'website.template_footer_contact', 'website.template_footer_headline',
'website.footer_custom', 'website.template_footer_links',
'website.template_footer_minimalist',
]
for footer_id in footer_ids:
try:
view_id = self.env['website'].viewref(footer_id)
if view_id:
# Deliberately hardcode dynamic code inside the view arch,
# it will be transformed into static nodes after a save/edit
# thanks to the t-ignore in parents node.
arch_string = etree.fromstring(view_id.arch_db)
el = arch_string.xpath("//t[@t-set='configurator_footer_links']")[0]
el.attrib['t-value'] = json.dumps(footer_links)
view_id.with_context(website_id=website.id).write({'arch_db': etree.tostring(arch_string)})
except Exception as e:
# The xml view could have been modified in the backend, we don't
# want the xpath error to break the configurator feature
logger.warning(e)
# Load suggestion from iap for selected pages
custom_resources = self._website_api_rpc(
'/api/website/2/configurator/custom_resources/%s' % kwargs['industry_id'],
{'theme': theme_name, }
)
# Update pages
requested_pages = list(pages_views.keys()) + ['homepage']
snippet_lists = website.get_theme_snippet_lists(theme_name)
for page_code in requested_pages:
configure_page(page_code, snippet_lists.get(page_code, []), pages_views, cta_data)
images = custom_resources.get('images', {})
set_images(images)
return url
# ----------------------------------------------------------
# Page Management
# ----------------------------------------------------------
def _bootstrap_homepage(self):
Page = self.env['website.page']
standard_homepage = self.env.ref('website.homepage', raise_if_not_found=False)
if not standard_homepage:
return
# keep strange indentation in python file, to get it correctly in database
new_homepage_view = '''<t name="Homepage" t-name="website.homepage%s">
<t t-call="website.layout">
<t t-set="pageName" t-value="'homepage'"/>
<div id="wrap" class="oe_structure oe_empty"/>
</t>
</t>''' % (self.id)
standard_homepage.with_context(website_id=self.id).arch_db = new_homepage_view
homepage_page = Page.search([
('website_id', '=', self.id),
('key', '=', standard_homepage.key),
], limit=1)
if not homepage_page:
homepage_page = Page.create({
'website_published': True,
'url': '/',
'view_id': self.with_context(website_id=self.id).viewref('website.homepage').id,
})
# prevent /-1 as homepage URL
homepage_page.url = '/'
self.homepage_id = homepage_page
# Bootstrap default menu hierarchy, create a new minimalist one if no default
default_menu = self.env.ref('website.main_menu')
self.copy_menu_hierarchy(default_menu)
home_menu = self.env['website.menu'].search([('website_id', '=', self.id), ('url', '=', '/')])
home_menu.page_id = self.homepage_id
def copy_menu_hierarchy(self, top_menu):
def copy_menu(menu, t_menu):
new_menu = menu.copy({
'parent_id': t_menu.id,
'website_id': self.id,
})
for submenu in menu.child_id:
copy_menu(submenu, new_menu)
for website in self:
new_top_menu = top_menu.copy({
'name': _('Top Menu for Website %s', website.id),
'website_id': website.id,
})
for submenu in top_menu.child_id:
copy_menu(submenu, new_top_menu)
@api.model
def new_page(self, name=False, add_menu=False, template='website.default_page', ispage=True, namespace=None, page_values=None, menu_values=None):
""" Create a new website page, and assign it a xmlid based on the given one
:param name : the name of the page
:param add_menu : if True, add a menu for that page
:param template : potential xml_id of the page to create
:param namespace : module part of the xml_id if none, the template module name is used
:param page_values : default values for the page to be created
:param menu_values : default values for the menu to be created
"""
if namespace:
template_module = namespace
else:
template_module, _ = template.split('.')
page_url = '/' + slugify(name, max_length=1024, path=True)
page_url = self.get_unique_path(page_url)
page_key = slugify(name)
result = {'url': page_url}
if not name:
name = 'Home'
page_key = 'home'
template_record = self.env.ref(template)
website_id = self._context.get('website_id')
key = self.get_unique_key(page_key, template_module)
view = template_record.copy({'website_id': website_id, 'key': key})
view.with_context(lang=None).write({
'arch': template_record.arch.replace(template, key),
'name': name,
})
result['view_id'] = view.id
if view.arch_fs:
view.arch_fs = False
website = self.get_current_website()
if ispage:
default_page_values = {
'url': page_url,
'website_id': website.id, # remove it if only one website or not?
'view_id': view.id,
'track': True,
}
if page_values:
default_page_values.update(page_values)
page = self.env['website.page'].create(default_page_values)
result['page_id'] = page.id
if add_menu:
default_menu_values = {
'name': name,
'url': page_url,
'parent_id': website.menu_id.id,
'page_id': page.id,
'website_id': website.id,
}
if menu_values:
default_menu_values.update(menu_values)
menu = self.env['website.menu'].create(default_menu_values)
result['menu_id'] = menu.id
return result
@api.model
def guess_mimetype(self):
return _guess_mimetype()
def get_unique_path(self, page_url):
""" Given an url, return that url suffixed by counter if it already exists
:param page_url : the url to be checked for uniqueness
"""
inc = 0
# we only want a unique_path for website specific.
# we need to be able to have /url for website=False, and /url for website=1
# in case of duplicate, page manager will allow you to manage this case
domain_static = [('website_id', '=', self.get_current_website().id)] # .website_domain()
page_temp = page_url
while self.env['website.page'].with_context(active_test=False).sudo().search([('url', '=', page_temp)] + domain_static):
inc += 1
page_temp = page_url + (inc and "-%s" % inc or "")
return page_temp
def get_unique_key(self, string, template_module=False):
""" Given a string, return an unique key including module prefix.
It will be suffixed by a counter if it already exists to garantee uniqueness.
:param string : the key to be checked for uniqueness, you can pass it with 'website.' or not
:param template_module : the module to be prefixed on the key, if not set, we will use website
"""
if template_module:
string = template_module + '.' + string
else:
if not string.startswith('website.'):
string = 'website.' + string
# Look for unique key
key_copy = string
inc = 0
domain_static = self.get_current_website().website_domain()
while self.env['ir.ui.view'].with_context(active_test=False).sudo().search([('key', '=', key_copy)] + domain_static):
inc += 1
key_copy = string + (inc and "-%s" % inc or "")
return key_copy
@api.model
def page_search_dependencies(self, page_id=False):
""" Search dependencies just for information. It will not catch 100%
of dependencies and False positive is more than possible
Each module could add dependences in this dict
:returns a dictionnary where key is the 'categorie' of object related to the given
view, and the value is the list of text and link to the resource using given page
"""
dependencies = {}
if not page_id:
return dependencies
page = self.env['website.page'].browse(int(page_id))
website = self.env['website'].browse(self._context.get('website_id'))
url = page.url
# search for website_page with link
website_page_search_dom = [('view_id.arch_db', 'ilike', url)] + website.website_domain()
pages = self.env['website.page'].search(website_page_search_dom)
page_key = _('Page')
if len(pages) > 1:
page_key = _('Pages')
page_view_ids = []
for page in pages:
dependencies.setdefault(page_key, [])
dependencies[page_key].append({
'text': _('Page <b>%s</b> contains a link to this page', page.url),
'item': page.name,
'link': page.url,
})
page_view_ids.append(page.view_id.id)
# search for ir_ui_view (not from a website_page) with link
page_search_dom = [('arch_db', 'ilike', url), ('id', 'not in', page_view_ids)] + website.website_domain()
views = self.env['ir.ui.view'].search(page_search_dom)
view_key = _('Template')
if len(views) > 1:
view_key = _('Templates')
for view in views:
dependencies.setdefault(view_key, [])
dependencies[view_key].append({
'text': _('Template <b>%s (id:%s)</b> contains a link to this page') % (view.key or view.name, view.id),
'link': '/web#id=%s&view_type=form&model=ir.ui.view' % view.id,
'item': _('%s (id:%s)') % (view.key or view.name, view.id),
})
# search for menu with link
menu_search_dom = [('url', 'ilike', '%s' % url)] + website.website_domain()
menus = self.env['website.menu'].search(menu_search_dom)
menu_key = _('Menu')
if len(menus) > 1:
menu_key = _('Menus')
for menu in menus:
dependencies.setdefault(menu_key, []).append({
'text': _('This page is in the menu <b>%s</b>', menu.name),
'link': '/web#id=%s&view_type=form&model=website.menu' % menu.id,
'item': menu.name,
})
return dependencies
@api.model
def page_search_key_dependencies(self, page_id=False):
""" Search dependencies just for information. It will not catch 100%
of dependencies and False positive is more than possible
Each module could add dependences in this dict
:returns a dictionnary where key is the 'categorie' of object related to the given
view, and the value is the list of text and link to the resource using given page
"""
dependencies = {}
if not page_id:
return dependencies
page = self.env['website.page'].browse(int(page_id))
website = self.env['website'].browse(self._context.get('website_id'))
key = page.key
# search for website_page with link
website_page_search_dom = [
('view_id.arch_db', 'ilike', key),
('id', '!=', page.id)
] + website.website_domain()
pages = self.env['website.page'].search(website_page_search_dom)
page_key = _('Page')
if len(pages) > 1:
page_key = _('Pages')
page_view_ids = []
for p in pages:
dependencies.setdefault(page_key, [])
dependencies[page_key].append({
'text': _('Page <b>%s</b> is calling this file', p.url),
'item': p.name,
'link': p.url,
})
page_view_ids.append(p.view_id.id)
# search for ir_ui_view (not from a website_page) with link
page_search_dom = [
('arch_db', 'ilike', key), ('id', 'not in', page_view_ids),
('id', '!=', page.view_id.id),
] + website.website_domain()
views = self.env['ir.ui.view'].search(page_search_dom)
view_key = _('Template')
if len(views) > 1:
view_key = _('Templates')
for view in views:
dependencies.setdefault(view_key, [])
dependencies[view_key].append({
'text': _('Template <b>%s (id:%s)</b> is calling this file') % (view.key or view.name, view.id),
'item': _('%s (id:%s)') % (view.key or view.name, view.id),
'link': '/web#id=%s&view_type=form&model=ir.ui.view' % view.id,
})
return dependencies
# ----------------------------------------------------------
# Languages
# ----------------------------------------------------------
def _get_alternate_languages(self, canonical_params):
self.ensure_one()
if not self._is_canonical_url(canonical_params=canonical_params):
# no hreflang on non-canonical pages
return []
languages = self.language_ids
if len(languages) <= 1:
# no hreflang if no alternate language
return []
langs = []
shorts = []
for lg in languages:
lg_codes = lg.code.split('_')
short = lg_codes[0]
shorts.append(short)
langs.append({
'hreflang': ('-'.join(lg_codes)).lower(),
'short': short,
'href': self._get_canonical_url_localized(lang=lg, canonical_params=canonical_params),
})
# if there is only one region for a language, use only the language code
for lang in langs:
if shorts.count(lang['short']) == 1:
lang['hreflang'] = lang['short']
# add the default
langs.append({
'hreflang': 'x-default',
'href': self._get_canonical_url_localized(lang=self.default_lang_id, canonical_params=canonical_params),
})
return langs
# ----------------------------------------------------------
# Utilities
# ----------------------------------------------------------
@api.model
def get_current_website(self, fallback=True):
if request and request.session.get('force_website_id'):
website_id = self.browse(request.session['force_website_id']).exists()
if not website_id:
# Don't crash is session website got deleted
request.session.pop('force_website_id')
else:
return website_id
website_id = self.env.context.get('website_id')
if website_id:
return self.browse(website_id)
# The format of `httprequest.host` is `domain:port`
domain_name = request and request.httprequest.host or ''
country = request.session.geoip.get('country_code') if request and request.session.geoip else False
country_id = False
if country:
country_id = self.env['res.country'].search([('code', '=', country)], limit=1).id
website_id = self._get_current_website_id(domain_name, country_id, fallback=fallback)
return self.browse(website_id)
@tools.cache('domain_name', 'country_id', 'fallback')
@api.model
def _get_current_website_id(self, domain_name, country_id, fallback=True):
"""Get the current website id.
First find all the websites for which the configured `domain` (after
ignoring a potential scheme) is equal to the given
`domain_name`. If there is only one result, return it immediately.
If there are no website found for the given `domain_name`, either
fallback to the first found website (no matter its `domain`) or return
False depending on the `fallback` parameter.
If there are multiple websites for the same `domain_name`, we need to
filter them out by country. We return the first found website matching
the given `country_id`. If no found website matching `domain_name`
corresponds to the given `country_id`, the first found website for
`domain_name` will be returned (no matter its country).
:param domain_name: the domain for which we want the website.
In regard to the `url_parse` method, only the `netloc` part should
be given here, no `scheme`.
:type domain_name: string
:param country_id: id of the country for which we want the website
:type country_id: int
:param fallback: if True and no website is found for the specificed
`domain_name`, return the first website (without filtering them)
:type fallback: bool
:return: id of the found website, or False if no website is found and
`fallback` is False
:rtype: int or False
:raises: if `fallback` is True but no website at all is found
"""
def _remove_port(domain_name):
return (domain_name or '').split(':')[0]
def _filter_domain(website, domain_name, ignore_port=False):
"""Ignore `scheme` from the `domain`, just match the `netloc` which
is host:port in the version of `url_parse` we use."""
# Here we add http:// to the domain if it's not set because
# `url_parse` expects it to be set to correctly return the `netloc`.
website_domain = urls.url_parse(website._get_http_domain()).netloc
if ignore_port:
website_domain = _remove_port(website_domain)
domain_name = _remove_port(domain_name)
return website_domain.lower() == (domain_name or '').lower()
# Sort on country_group_ids so that we fall back on a generic website:
# websites with empty country_group_ids will be first.
found_websites = self.search([('domain', 'ilike', _remove_port(domain_name))]).sorted('country_group_ids')
# Filter for the exact domain (to filter out potential subdomains) due
# to the use of ilike.
websites = found_websites.filtered(lambda w: _filter_domain(w, domain_name))
# If there is no domain matching for the given port, ignore the port.
websites = websites or found_websites.filtered(lambda w: _filter_domain(w, domain_name, ignore_port=True))
if not websites:
if not fallback:
return False
return self.search([], limit=1).id
elif len(websites) == 1:
return websites.id
else: # > 1 website with the same domain
country_specific_websites = websites.filtered(lambda website: country_id in website.country_group_ids.mapped('country_ids').ids)
return country_specific_websites[0].id if country_specific_websites else websites[0].id
def _force(self):
self._force_website(self.id)
def _force_website(self, website_id):
if request:
request.session['force_website_id'] = website_id and str(website_id).isdigit() and int(website_id)
@api.model
def is_publisher(self):
return self.env['ir.model.access'].check('ir.ui.view', 'write', False)
@api.model
def is_user(self):
return self.env['ir.model.access'].check('ir.ui.menu', 'read', False)
@api.model
def is_public_user(self):
return request.env.user.id == request.website._get_cached('user_id')
@api.model
def viewref(self, view_id, raise_if_not_found=True):
''' Given an xml_id or a view_id, return the corresponding view record.
In case of website context, return the most specific one.
If no website_id is in the context, it will return the generic view,
instead of a random one like `get_view_id`.
Look also for archived views, no matter the context.
:param view_id: either a string xml_id or an integer view_id
:param raise_if_not_found: should the method raise an error if no view found
:return: The view record or empty recordset
'''
View = self.env['ir.ui.view'].sudo()
view = View
if isinstance(view_id, str):
if 'website_id' in self._context:
domain = [('key', '=', view_id)] + self.env['website'].website_domain(self._context.get('website_id'))
order = 'website_id'
else:
domain = [('key', '=', view_id)]
order = View._order
views = View.with_context(active_test=False).search(domain, order=order)
if views:
view = views.filter_duplicate()
else:
# we handle the raise below
view = self.env.ref(view_id, raise_if_not_found=False)
# self.env.ref might return something else than an ir.ui.view (eg: a theme.ir.ui.view)
if not view or view._name != 'ir.ui.view':
# make sure we always return a recordset
view = View
elif isinstance(view_id, int):
view = View.browse(view_id)
else:
raise ValueError('Expecting a string or an integer, not a %s.' % (type(view_id)))
if not view and raise_if_not_found:
raise ValueError('No record found for unique ID %s. It may have been deleted.' % (view_id))
return view
@tools.ormcache_context(keys=('website_id',))
def _cache_customize_show_views(self):
views = self.env['ir.ui.view'].with_context(active_test=False).sudo().search([('customize_show', '=', True)])
views = views.filter_duplicate()
return {v.key: v.active for v in views}
@tools.ormcache_context('key', keys=('website_id',))
def is_view_active(self, key, raise_if_not_found=False):
"""
Return True if active, False if not active, None if not found or not a customize_show view
"""
views = self._cache_customize_show_views()
view = key in views and views[key]
if view is None and raise_if_not_found:
raise ValueError('No view of type customize_show found for key %s' % key)
return view
@api.model
def get_template(self, template):
View = self.env['ir.ui.view']
if isinstance(template, int):
view_id = template
else:
if '.' not in template:
template = 'website.%s' % template
view_id = View.get_view_id(template)
if not view_id:
raise NotFound
return View.sudo().browse(view_id)
@api.model
def pager(self, url, total, page=1, step=30, scope=5, url_args=None):
return pager(url, total, page=page, step=step, scope=scope, url_args=url_args)
def rule_is_enumerable(self, rule):
""" Checks that it is possible to generate sensible GET queries for
a given rule (if the endpoint matches its own requirements)
:type rule: werkzeug.routing.Rule
:rtype: bool
"""
endpoint = rule.endpoint
methods = endpoint.routing.get('methods') or ['GET']
converters = list(rule._converters.values())
if not ('GET' in methods and
endpoint.routing['type'] == 'http' and
endpoint.routing['auth'] in ('none', 'public') and
endpoint.routing.get('website', False) and
all(hasattr(converter, 'generate') for converter in converters)):
return False
# dont't list routes without argument having no default value or converter
sign = inspect.signature(endpoint.method.original_func)
params = list(sign.parameters.values())[1:] # skip self
supported_kinds = (inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD)
has_no_default = lambda p: p.default is inspect.Parameter.empty
# check that all args have a converter
return all(p.name in rule._converters for p in params
if p.kind in supported_kinds and has_no_default(p))
def _enumerate_pages(self, query_string=None, force=False):
""" Available pages in the website/CMS. This is mostly used for links
generation and can be overridden by modules setting up new HTML
controllers for dynamic pages (e.g. blog).
By default, returns template views marked as pages.
:param str query_string: a (user-provided) string, fetches pages
matching the string
:returns: a list of mappings with two keys: ``name`` is the displayable
name of the resource (page), ``url`` is the absolute URL
of the same.
:rtype: list({name: str, url: str})
"""
router = http.root.get_db_router(request.db)
url_set = set()
sitemap_endpoint_done = set()
for rule in router.iter_rules():
if 'sitemap' in rule.endpoint.routing and rule.endpoint.routing['sitemap'] is not True:
if rule.endpoint in sitemap_endpoint_done:
continue
sitemap_endpoint_done.add(rule.endpoint)
func = rule.endpoint.routing['sitemap']
if func is False:
continue
for loc in func(self.env, rule, query_string):
yield loc
continue
if not self.rule_is_enumerable(rule):
continue
if 'sitemap' not in rule.endpoint.routing:
logger.warning('No Sitemap value provided for controller %s (%s)' %
(rule.endpoint.method, ','.join(rule.endpoint.routing['routes'])))
converters = rule._converters or {}
if query_string and not converters and (query_string not in rule.build({}, append_unknown=False)[1]):
continue
values = [{}]
# converters with a domain are processed after the other ones
convitems = sorted(
converters.items(),
key=lambda x: (hasattr(x[1], 'domain') and (x[1].domain != '[]'), rule._trace.index((True, x[0]))))
for (i, (name, converter)) in enumerate(convitems):
if 'website_id' in self.env[converter.model]._fields and (not converter.domain or converter.domain == '[]'):
converter.domain = "[('website_id', 'in', (False, current_website_id))]"
newval = []
for val in values:
query = i == len(convitems) - 1 and query_string
if query:
r = "".join([x[1] for x in rule._trace[1:] if not x[0]]) # remove model converter from route
query = sitemap_qs2dom(query, r, self.env[converter.model]._rec_name)
if query == FALSE_DOMAIN:
continue
for rec in converter.generate(uid=self.env.uid, dom=query, args=val):
newval.append(val.copy())
newval[-1].update({name: rec})
values = newval
for value in values:
domain_part, url = rule.build(value, append_unknown=False)
if not query_string or query_string.lower() in url.lower():
page = {'loc': url}
if url in url_set:
continue
url_set.add(url)
yield page
# '/' already has a http.route & is in the routing_map so it will already have an entry in the xml
domain = [('url', '!=', '/')]
if not force:
domain += [('website_indexed', '=', True), ('visibility', '=', False)]
# is_visible
domain += [
('website_published', '=', True), ('visibility', '=', False),
'|', ('date_publish', '=', False), ('date_publish', '<=', fields.Datetime.now())
]
if query_string:
domain += [('url', 'like', query_string)]
pages = self._get_website_pages(domain)
for page in pages:
record = {'loc': page['url'], 'id': page['id'], 'name': page['name']}
if page.view_id and page.view_id.priority != 16:
record['priority'] = min(round(page.view_id.priority / 32.0, 1), 1)
if page['write_date']:
record['lastmod'] = page['write_date'].date()
yield record
def _get_website_pages(self, domain=None, order='name', limit=None):
if domain is None:
domain = []
domain += self.get_current_website().website_domain()
pages = self.env['website.page'].sudo().search(domain, order=order, limit=limit)
# TODO In 16.0 remove condition on _filter_duplicate_pages.
if self.env.context.get('_filter_duplicate_pages'):
pages = pages._get_most_specific_pages()
return pages
def search_pages(self, needle=None, limit=None):
name = slugify(needle, max_length=50, path=True)
res = []
for page in self._enumerate_pages(query_string=name, force=True):
res.append(page)
if len(res) == limit:
break
return res
def get_suggested_controllers(self):
"""
Returns a tuple (name, url, icon).
Where icon can be a module name, or a path
"""
suggested_controllers = [
(_('Homepage'), url_for('/'), 'website'),
(_('Contact Us'), url_for('/contactus'), 'website_crm'),
]
return suggested_controllers
@api.model
def image_url(self, record, field, size=None):
""" Returns a local url that points to the image field of a given browse record. """
sudo_record = record.sudo()
sha = hashlib.sha512(str(getattr(sudo_record, '__last_update')).encode('utf-8')).hexdigest()[:7]
size = '' if size is None else '/%s' % size
return '/web/image/%s/%s/%s%s?unique=%s' % (record._name, record.id, field, size, sha)
def get_cdn_url(self, uri):
self.ensure_one()
if not uri:
return ''
cdn_url = self.cdn_url
cdn_filters = (self.cdn_filters or '').splitlines()
for flt in cdn_filters:
if flt and re.match(flt, uri):
return urls.url_join(cdn_url, uri)
return uri
@api.model
def action_dashboard_redirect(self):
if self.env.user.has_group('base.group_system') or self.env.user.has_group('website.group_website_designer'):
return self.env["ir.actions.actions"]._for_xml_id("website.backend_dashboard")
return self.env["ir.actions.actions"]._for_xml_id("website.action_website")
def button_go_website(self, path='/', mode_edit=False):
self._force()
if mode_edit:
# If the user gets on a translated page (e.g /fr) the editor will
# never start. Forcing the default language fixes this issue.
path = url_for(path, self.default_lang_id.url_code)
path += '?enable_editor=1'
return {
'type': 'ir.actions.act_url',
'url': path,
'target': 'self',
}
def _get_http_domain(self):
"""Get the domain of the current website, prefixed by http if no
scheme is specified.
Empty string if no domain is specified on the website.
"""
self.ensure_one()
if not self.domain:
return ''
res = urls.url_parse(self.domain)
return 'http://' + self.domain if not res.scheme else self.domain
def _get_canonical_url_localized(self, lang, canonical_params):
"""Returns the canonical URL for the current request with translatable
elements appropriately translated in `lang`.
If `request.endpoint` is not true, returns the current `path` instead.
`url_quote_plus` is applied on the returned path.
"""
self.ensure_one()
if request.endpoint:
router = http.root.get_db_router(request.db).bind('')
arguments = dict(request.endpoint_arguments)
for key, val in list(arguments.items()):
if isinstance(val, models.BaseModel):
if val.env.context.get('lang') != lang.code:
arguments[key] = val.with_context(lang=lang.code)
path = router.build(request.endpoint, arguments)
else:
# The build method returns a quoted URL so convert in this case for consistency.
path = urls.url_quote_plus(request.httprequest.path, safe='/')
lang_path = ('/' + lang.url_code) if lang != self.default_lang_id else ''
canonical_query_string = '?%s' % urls.url_encode(canonical_params) if canonical_params else ''
if lang_path and path == '/':
# We want `/fr_BE` not `/fr_BE/` for correct canonical on homepage
localized_path = lang_path
else:
localized_path = lang_path + path
return self.get_base_url() + localized_path + canonical_query_string
def _get_canonical_url(self, canonical_params):
"""Returns the canonical URL for the current request."""
self.ensure_one()
return self._get_canonical_url_localized(lang=request.lang, canonical_params=canonical_params)
def _is_canonical_url(self, canonical_params):
"""Returns whether the current request URL is canonical."""
self.ensure_one()
# Compare OrderedMultiDict because the order is important, there must be
# only one canonical and not params permutations.
params = request.httprequest.args
canonical_params = canonical_params or OrderedMultiDict()
if params != canonical_params:
return False
# Compare URL at the first rerouting iteration (if available) because
# it's the one with the language in the path.
# It is important to also test the domain of the current URL.
current_url = request.httprequest.url_root[:-1] + (hasattr(request, 'rerouting') and request.rerouting[0] or request.httprequest.path)
canonical_url = self._get_canonical_url_localized(lang=request.lang, canonical_params=None)
# A request path with quotable characters (such as ",") is never
# canonical because request.httprequest.base_url is always unquoted,
# and canonical url is always quoted, so it is never possible to tell
# if the current URL is indeed canonical or not.
return current_url == canonical_url
@tools.ormcache('self.id')
def _get_cached_values(self):
self.ensure_one()
return {
'user_id': self.user_id.id,
'company_id': self.company_id.id,
'default_lang_id': self.default_lang_id.id,
'homepage_id': self.homepage_id.id,
}
def _get_cached(self, field):
return self._get_cached_values()[field]
def _get_html_fields(self):
html_fields = [('ir_ui_view', 'arch_db')]
cr = self.env.cr
cr.execute(r"""
SELECT f.model,
f.name
FROM ir_model_fields f
JOIN ir_model m
ON m.id = f.model_id
WHERE f.ttype = 'html'
AND f.store = true
AND m.transient = false
AND f.model NOT LIKE 'ir.actions%'
AND f.model != 'mail.message'
""")
for model, name in cr.fetchall():
table = self.env[model]._table
if tools.table_exists(cr, table) and tools.column_exists(cr, table, name):
html_fields.append((table, name))
return html_fields
def _get_snippets_assets(self):
"""Returns every parent snippet asset from the database, filtering out
their potential overrides defined in other modules. As they share the same
snippet_id, asset_version and asset_type, it is possible to do that using
Postgres' DISTINCT ON and ordering by asset_id, as overriden assets will be
created later than their parents.
The assets are returned in the form of a list of tuples :
[(snippet_module, snippet_id, asset_version, asset_type, asset_id)]
"""
self.env.cr.execute(r"""
SELECT DISTINCT ON (snippet_id, asset_version, asset_type)
regexp_matches[1] AS snippet_module,
regexp_matches[2] AS snippet_id,
regexp_matches[3] AS asset_version,
CASE
WHEN regexp_matches[4]='scss' THEN 'css'
ELSE regexp_matches[4]
END AS asset_type,
id AS asset_id
FROM (
SELECT REGEXP_MATCHES(PATH, '(\w*)\/.*\/snippets\/(\w*)\/(\d{3})\.(js|scss)'),
id
FROM ir_asset
) AS regexp
ORDER BY snippet_id, asset_version, asset_type, asset_id;
""")
return self.env.cr.fetchall()
def _is_snippet_used(self, snippet_module, snippet_id, asset_version, asset_type, html_fields):
snippet_occurences = []
# Check snippet template definition to avoid disabling its related assets.
# This special case is needed because snippet template definitions do not
# have a `data-snippet` attribute (which is added during drag&drop).
snippet_template = self.env.ref(f'{snippet_module}.{snippet_id}', raise_if_not_found=False)
if snippet_template:
snippet_template_html = snippet_template._render()
match = re.search('<([^>]*class="[^>]*)>', snippet_template_html)
snippet_occurences.append(match.group())
if self._check_snippet_used(snippet_occurences, asset_type, asset_version):
return True
# As well as every snippet dropped in html fields
self.env.cr.execute(sql.SQL(" UNION ").join(
sql.SQL("SELECT regexp_matches({}, {}, 'g') FROM {}").format(
sql.Identifier(column),
sql.Placeholder('snippet_regex'),
sql.Identifier(table)
) for table, column in html_fields
), {'snippet_regex': f'<([^>]*data-snippet="{snippet_id}"[^>]*)>'})
snippet_occurences = [r[0][0] for r in self.env.cr.fetchall()]
return self._check_snippet_used(snippet_occurences, asset_type, asset_version)
def _check_snippet_used(self, snippet_occurences, asset_type, asset_version):
for snippet in snippet_occurences:
if asset_version == '000':
if f'data-v{asset_type}' not in snippet:
return True
else:
if f'data-v{asset_type}="{asset_version}"' in snippet:
return True
return False
def _disable_unused_snippets_assets(self):
snippets_assets = self._get_snippets_assets()
html_fields = self._get_html_fields()
for snippet_module, snippet_id, asset_version, asset_type, _ in snippets_assets:
is_snippet_used = self._is_snippet_used(snippet_module, snippet_id, asset_version, asset_type, html_fields)
# The regex catches XXX.scss, XXX.js and XXX_variables.scss
assets_regex = f'{snippet_id}/{asset_version}.+{asset_type}'
# The query will also set to active or inactive assets overrides, as they
# share the same snippet_id, asset_version and filename_type as their parents
self.env.cr.execute("""
UPDATE ir_asset
SET active = %(active)s
WHERE path ~ %(assets_regex)s
""", {"active": is_snippet_used, "assets_regex": assets_regex})
def _search_build_domain(self, domain, search, fields, extra=None):
"""
Builds a search domain AND-combining a base domain with partial matches of each term in
the search expression in any of the fields.
:param domain: base domain combined in the search expression
:param search: search expression string
:param fields: list of field names to match the terms of the search expression with
:param extra: function that returns an additional subdomain for a search term
:return: domain limited to the matches of the search expression
"""
domains = domain.copy()
if search:
for search_term in search.split(' '):
subdomains = []
for field in fields:
subdomains.append([(field, 'ilike', escape_psql(search_term))])
if extra:
subdomains.append(extra(self.env, search_term))
domains.append(OR(subdomains))
return AND(domains)
def _search_text_from_html(self, html_fragment):
"""
Returns the plain non-tag text from an html
:param html_fragment: document from which text must be extracted
:return text extracted from the html
"""
# lxml requires one single root element
tree = etree.fromstring('<p>%s</p>' % html_fragment, etree.XMLParser(recover=True))
return ' '.join(tree.itertext())
def _search_get_details(self, search_type, order, options):
"""
Returns indications on how to perform the searches
:param search_type: type of search
:param order: order in which the results are to be returned
:param options: search options
:return: list of search details obtained from the `website.searchable.mixin`'s `_search_get_detail()`
"""
result = []
if search_type in ['pages', 'all']:
result.append(self.env['website.page']._search_get_detail(self, order, options))
return result
def _search_with_fuzzy(self, search_type, search, limit, order, options):
"""
Performs a search with a search text or with a resembling word
:param search_type: indicates what to search within, 'all' matches all available types
:param search: text against which to match results
:param limit: maximum number of results per model type involved in the result
:param order: order on which to sort results within a model type
:param options: search options from the submitted form containing:
- allowFuzzy: boolean indicating whether the fuzzy matching must be done
- other options used by `_search_get_details()`
:return: tuple containing:
- count: total number of results across all involved models
- results: list of results per model (see _search_exact)
- fuzzy_term: similar word against which results were obtained, indicates there were
no results for the initially requested search
"""
fuzzy_term = False
search_details = self._search_get_details(search_type, order, options)
if search and options.get('allowFuzzy', True):
fuzzy_term = self._search_find_fuzzy_term(search_details, search)
if fuzzy_term:
count, results = self._search_exact(search_details, fuzzy_term, limit, order)
if fuzzy_term.lower() == search.lower():
fuzzy_term = False
else:
count, results = self._search_exact(search_details, search, limit, order)
else:
count, results = self._search_exact(search_details, search, limit, order)
return count, results, fuzzy_term
def _search_exact(self, search_details, search, limit, order):
"""
Performs a search with a search text
:param search_details: see :meth:`_search_get_details`
:param search: text against which to match results
:param limit: maximum number of results per model type involved in the result
:param order: order on which to sort results within a model type
:return: tuple containing:
- total number of results across all involved models
- list of results per model made of:
- initial search_detail for the model
- count: number of results for the model
- results: model list equivalent to a `model.search()`
"""
all_results = []
total_count = 0
for search_detail in search_details:
model = self.env[search_detail['model']]
results, count = model._search_fetch(search_detail, search, limit, order)
search_detail['results'] = results
total_count += count
search_detail['count'] = count
all_results.append(search_detail)
return total_count, all_results
def _search_render_results(self, search_details, limit):
"""
Prepares data for the autocomplete and hybrid list rendering
:param search_details: obtained from `_search_exact()`
:param limit: maximum number or rows to render
:return: the updated `search_details` containing an additional `results_data` field equivalent
to the result of a `model.read()`
"""
for search_detail in search_details:
fields = search_detail['fetch_fields']
results = search_detail['results']
icon = search_detail['icon']
mapping = search_detail['mapping']
results_data = results._search_render_results(fields, mapping, icon, limit)
search_detail['results_data'] = results_data
return search_details
def _search_find_fuzzy_term(self, search_details, search, limit=1000, word_list=None):
"""
Returns the "closest" match of the search parameter within available words.
:param search_details: obtained from `_search_get_details()`
:param search: search term to which words must be matched against
:param limit: maximum number of records fetched per model to build the word list
:param word_list: if specified, this list of words is used as possible targets instead of
the words contained in the match fields of each involved model
:return: term on which a search can be performed instead of the initial search
"""
# No fuzzy search for less that 4 characters, multi-words nor 80%+ numbers.
if len(search) < 4 or ' ' in search or len(re.findall(r'\d', search)) / len(search) >= 0.8:
return search
search = search.lower()
words = set()
best_score = 0
best_word = None
enumerate_words = self._trigram_enumerate_words if self.env.registry.has_trigram else self._basic_enumerate_words
for word in word_list or enumerate_words(search_details, search, limit):
if search in word:
return search
if word[0] == search[0] and word not in words:
similarity = similarity_score(search, word)
if similarity > best_score:
best_score = similarity
best_word = word
words.add(word)
return best_word
def _trigram_enumerate_words(self, search_details, search, limit):
"""
Browses through all words that need to be compared to the search term.
It extracts all words of every field associated to models in the fields_per_model parameter.
The search is restricted to a records having the non-zero pg_trgm.word_similarity() score.
:param search_details: obtained from `_search_get_details()`
:param search: search term to which words must be matched against
:param limit: maximum number of records fetched per model to build the word list
:return: yields words
"""
match_pattern = r'[\w./-]{%s,}' % min(4, len(search) - 3)
similarity_threshold = 0.3
for search_detail in search_details:
model_name, fields = search_detail['model'], search_detail['search_fields']
model = self.env[model_name]
if search_detail.get('requires_sudo'):
model = model.sudo()
domain = search_detail['base_domain'].copy()
fields = set(fields).intersection(model._fields)
unaccent = get_unaccent_sql_wrapper(self.env.cr)
# Specific handling for fields being actually part of another model
# through the `inherits` mechanism.
# It gets the list of fields requested to search upon and that are
# actually not part of the requested model itself but part of a
# `inherits` model:
# {
# 'name': {
# 'table': 'ir_ui_view',
# 'fname': 'view_id',
# },
# 'url': {
# 'table': 'ir_ui_view',
# 'fname': 'view_id',
# },
# 'another_field': {
# 'table': 'another_table',
# 'fname': 'record_id',
# },
# }
inherits_fields = {
inherits_model_fname: {
'table': self.env[inherits_model_name]._table,
'fname': inherits_field_name,
}
for inherits_model_name, inherits_field_name in model._inherits.items()
for inherits_model_fname in self.env[inherits_model_name]._fields.keys()
if inherits_model_fname in fields
}
similarities = []
for field in fields:
# Field might belong to another model (`inherits` mechanism)
table = inherits_fields[field]['table'] if field in inherits_fields else model._table
similarities.append(
sql.SQL("word_similarity({search}, {field})").format(
search=unaccent(sql.Placeholder('search')),
field=unaccent(sql.SQL("{table}.{field}").format(
table=sql.Identifier(table),
field=sql.Identifier(field)
))
)
)
best_similarity = sql.SQL('GREATEST({similarities})').format(
similarities=sql.SQL(', ').join(similarities)
)
from_clause = sql.SQL("FROM {table}").format(table=sql.Identifier(model._table))
# Specific handling for fields being actually part of another model
# through the `inherits` mechanism.
for table_to_join in {
field['table']: field['fname'] for field in inherits_fields.values()
}.items(): # Removes duplicate inherits model
from_clause = sql.SQL("""
{from_clause}
LEFT JOIN {inherits_table} ON {table}.{inherits_field} = {inherits_table}.id
""").format(
from_clause=from_clause,
table=sql.Identifier(model._table),
inherits_table=sql.Identifier(table_to_join[0]),
inherits_field=sql.Identifier(table_to_join[1]),
)
query = sql.SQL("""
SELECT {table}.id, {best_similarity} AS _best_similarity
{from_clause}
ORDER BY _best_similarity desc
LIMIT 1000
""").format(
table=sql.Identifier(model._table),
best_similarity=best_similarity,
from_clause=from_clause,
)
self.env.cr.execute(query, {'search': search})
ids = {row[0] for row in self.env.cr.fetchall() if row[1] and row[1] >= similarity_threshold}
if self.env.lang:
# Specific handling for website.page that inherits its arch_db and name fields
# TODO make more generic
if 'arch_db' in fields:
# Look for partial translations
similarity = sql.SQL("word_similarity({search}, {field})").format(
search=unaccent(sql.Placeholder('search')),
field=unaccent(sql.SQL('t.value'))
)
names = ['%s,%s' % (self.env['ir.ui.view']._name, field) for field in fields]
query = sql.SQL("""
SELECT {table}.id, {similarity} AS _similarity
FROM {table}
LEFT JOIN ir_ui_view v ON {table}.view_id = v.id
LEFT JOIN ir_translation t ON v.id = t.res_id
WHERE t.lang = {lang}
AND t.name = ANY({names})
AND t.type = 'model_terms'
AND t.value IS NOT NULL
ORDER BY _similarity desc
LIMIT 1000
""").format(
table=sql.Identifier(model._table),
similarity=similarity,
lang=sql.Placeholder('lang'),
names=sql.Placeholder('names'),
)
else:
similarity = sql.SQL("word_similarity({search}, {field})").format(
search=unaccent(sql.Placeholder('search')),
field=unaccent(sql.SQL('value'))
)
names = ['%s,%s' % (model._name, field) for field in fields]
query = sql.SQL("""
SELECT res_id, {similarity} AS _similarity
FROM ir_translation
WHERE lang = {lang}
AND name = ANY({names})
AND type = 'model'
AND value IS NOT NULL
ORDER BY _similarity desc
LIMIT 1000
""").format(
similarity=similarity,
lang=sql.Placeholder('lang'),
names=sql.Placeholder('names'),
)
self.env.cr.execute(query, {'lang': self.env.lang, 'names': names, 'search': search})
ids.update(row[0] for row in self.env.cr.fetchall() if row[1] and row[1] >= similarity_threshold)
domain.append([('id', 'in', list(ids))])
domain = AND(domain)
records = model.search_read(domain, fields, limit=limit)
for record in records:
for field, value in record.items():
if isinstance(value, str):
value = value.lower()
yield from re.findall(match_pattern, value)
def _basic_enumerate_words(self, search_details, search, limit):
"""
Browses through all words that need to be compared to the search term.
It extracts all words of every field associated to models in the fields_per_model parameter.
:param search_details: obtained from `_search_get_details()`
:param search: search term to which words must be matched against
:param limit: maximum number of records fetched per model to build the word list
:return: yields words
"""
match_pattern = r'[\w./-]{%s,}' % min(4, len(search) - 3)
first = escape_psql(search[0])
for search_detail in search_details:
model_name, fields = search_detail['model'], search_detail['search_fields']
model = self.env[model_name]
if search_detail.get('requires_sudo'):
model = model.sudo()
domain = search_detail['base_domain'].copy()
fields_domain = []
fields = set(fields).intersection(model._fields)
for field in fields:
fields_domain.append([(field, '=ilike', '%s%%' % first)])
fields_domain.append([(field, '=ilike', '%% %s%%' % first)])
fields_domain.append([(field, '=ilike', '%%>%s%%' % first)]) # HTML
domain.append(OR(fields_domain))
domain = AND(domain)
perf_limit = 1000
records = model.search_read(domain, fields, limit=perf_limit)
if len(records) == perf_limit:
# Exact match might have been missed because the fetched
# results are limited for performance reasons.
exact_records, _ = model._search_fetch(search_detail, search, 1, None)
if exact_records:
yield search
for record in records:
for field, value in record.items():
if isinstance(value, str):
value = value.lower()
if field == 'arch_db':
value = text_from_html(value)
for word in re.findall(match_pattern, value):
if word[0] == search[0]:
yield word.lower()
| 45.934054 | 84,978 |
2,777 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError
from odoo.modules.module import get_resource_path
class WebsiteConfiguratorFeature(models.Model):
_name = 'website.configurator.feature'
_description = 'Website Configurator Feature'
_order = 'sequence'
sequence = fields.Integer()
name = fields.Char(translate=True)
description = fields.Char(translate=True)
icon = fields.Char()
iap_page_code = fields.Char(help='Page code used to tell IAP website_service for which page a snippet list should be generated')
website_config_preselection = fields.Char(help='Comma-separated list of website type/purpose for which this feature should be pre-selected')
page_view_id = fields.Many2one('ir.ui.view', ondelete='cascade')
module_id = fields.Many2one('ir.module.module', ondelete='cascade')
feature_url = fields.Char()
menu_sequence = fields.Integer(help='If set, a website menu will be created for the feature.')
menu_company = fields.Boolean(help='If set, add the menu as a second level menu, as a child of "Company" menu.')
@api.constrains('module_id', 'page_view_id')
def _check_module_xor_page_view(self):
if bool(self.module_id) == bool(self.page_view_id):
raise ValidationError(_("One and only one of the two fields 'page_view_id' and 'module_id' should be set"))
@staticmethod
def _process_svg(theme, colors, image_mapping):
svg = None
preview_svg = get_resource_path(theme, 'static', 'description', theme + '.svg')
if not preview_svg:
return False
with tools.file_open(preview_svg, 'r') as file:
svg = file.read()
default_colors = {
'color1': '#3AADAA',
'color2': '#7C6576',
'color3': '#F6F6F6',
'color4': '#FFFFFF',
'color5': '#383E45',
'menu': '#MENU_COLOR',
'footer': '#FOOTER_COLOR',
}
color_mapping = {default_colors[color_key]: color_value for color_key, color_value in colors.items() if color_key in default_colors.keys()}
color_regex = '(?i)%s' % '|'.join('(%s)' % color for color in color_mapping.keys())
image_regex = '(?i)%s' % '|'.join('(%s)' % image for image in image_mapping.keys())
def subber_maker(mapping):
def subber(match):
key = match.group()
return mapping[key] if key in mapping else key
return subber
svg = re.sub(color_regex, subber_maker(color_mapping), svg)
svg = re.sub(image_regex, subber_maker(image_mapping), svg)
return svg
| 43.390625 | 2,777 |
1,749 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug.urls
from odoo import models, fields
class Partner(models.Model):
_name = 'res.partner'
_inherit = ['res.partner', 'website.published.multi.mixin']
visitor_ids = fields.One2many('website.visitor', 'partner_id', string='Visitors')
def google_map_img(self, zoom=8, width=298, height=298):
google_maps_api_key = self.env['website'].get_current_website().google_maps_api_key
if not google_maps_api_key:
return False
params = {
'center': '%s, %s %s, %s' % (self.street or '', self.city or '', self.zip or '', self.country_id and self.country_id.display_name or ''),
'size': "%sx%s" % (width, height),
'zoom': zoom,
'sensor': 'false',
'key': google_maps_api_key,
}
return '//maps.googleapis.com/maps/api/staticmap?'+werkzeug.urls.url_encode(params)
def google_map_link(self, zoom=10):
params = {
'q': '%s, %s %s, %s' % (self.street or '', self.city or '', self.zip or '', self.country_id and self.country_id.display_name or ''),
'z': zoom,
}
return 'https://maps.google.com/maps?' + werkzeug.urls.url_encode(params)
def _get_name(self):
name = super(Partner, self)._get_name()
if self._context.get('display_website') and self.env.user.has_group('website.group_multi_website'):
if self.website_id:
name += ' [%s]' % self.website_id.name
return name
def _compute_display_name(self):
self2 = self.with_context(display_website=False)
super(Partner, self2)._compute_display_name()
| 40.674419 | 1,749 |
2,862 |
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, fields, models
from odoo.http import request
from odoo.tools.json import scriptsafe as json_scriptsafe
class ServerAction(models.Model):
""" Add website option in server actions. """
_name = 'ir.actions.server'
_inherit = 'ir.actions.server'
xml_id = fields.Char('External ID', compute='_compute_xml_id', help="ID of the action if defined in a XML file")
website_path = fields.Char('Website Path')
website_url = fields.Char('Website Url', compute='_get_website_url', help='The full URL to access the server action through the website.')
website_published = fields.Boolean('Available on the Website', copy=False,
help='A code server action can be executed from the website, using a dedicated '
'controller. The address is <base>/website/action/<website_path>. '
'Set this field as True to allow users to run this action. If it '
'is set to False the action cannot be run through the website.')
def _compute_xml_id(self):
res = self.get_external_id()
for action in self:
action.xml_id = res.get(action.id)
def _compute_website_url(self, website_path, xml_id):
base_url = self.get_base_url()
link = website_path or xml_id or (self.id and '%d' % self.id) or ''
if base_url and link:
path = '%s/%s' % ('/website/action', link)
return urls.url_join(base_url, path)
return ''
@api.depends('state', 'website_published', 'website_path', 'xml_id')
def _get_website_url(self):
for action in self:
if action.state == 'code' and action.website_published:
action.website_url = action._compute_website_url(action.website_path, action.xml_id)
else:
action.website_url = False
@api.model
def _get_eval_context(self, action):
""" Override to add the request object in eval_context. """
eval_context = super(ServerAction, self)._get_eval_context(action)
if action.state == 'code':
eval_context['request'] = request
eval_context['json'] = json_scriptsafe
return eval_context
@api.model
def _run_action_code_multi(self, eval_context=None):
""" Override to allow returning response the same way action is already
returned by the basic server action behavior. Note that response has
priority over action, avoid using both.
"""
res = super(ServerAction, self)._run_action_code_multi(eval_context)
return eval_context.get('response', res)
| 46.16129 | 2,862 |
16,665 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
import uuid
import pytz
from odoo import fields, models, api, _
from odoo.addons.base.models.res_partner import _tz_get
from odoo.exceptions import UserError
from odoo.tools.misc import _format_time_ago
from odoo.http import request
from odoo.osv import expression
class WebsiteTrack(models.Model):
_name = 'website.track'
_description = 'Visited Pages'
_order = 'visit_datetime DESC'
_log_access = False
visitor_id = fields.Many2one('website.visitor', ondelete="cascade", index=True, required=True, readonly=True)
page_id = fields.Many2one('website.page', index=True, ondelete='cascade', readonly=True)
url = fields.Text('Url', index=True)
visit_datetime = fields.Datetime('Visit Date', default=fields.Datetime.now, required=True, readonly=True)
class WebsiteVisitor(models.Model):
_name = 'website.visitor'
_description = 'Website Visitor'
_order = 'last_connection_datetime DESC'
name = fields.Char('Name')
access_token = fields.Char(required=True, default=lambda x: uuid.uuid4().hex, index=False, copy=False, groups='website.group_website_publisher')
active = fields.Boolean('Active', default=True)
website_id = fields.Many2one('website', "Website", readonly=True)
partner_id = fields.Many2one('res.partner', string="Contact", help="Partner of the last logged in user.")
partner_image = fields.Binary(related='partner_id.image_1920')
# localisation and info
country_id = fields.Many2one('res.country', 'Country', readonly=True)
country_flag = fields.Char(related="country_id.image_url", string="Country Flag")
lang_id = fields.Many2one('res.lang', string='Language', help="Language from the website when visitor has been created")
timezone = fields.Selection(_tz_get, string='Timezone')
email = fields.Char(string='Email', compute='_compute_email_phone')
mobile = fields.Char(string='Mobile', compute='_compute_email_phone')
# Visit fields
visit_count = fields.Integer('# Visits', default=1, readonly=True, help="A new visit is considered if last connection was more than 8 hours ago.")
website_track_ids = fields.One2many('website.track', 'visitor_id', string='Visited Pages History', readonly=True)
visitor_page_count = fields.Integer('Page Views', compute="_compute_page_statistics", help="Total number of visits on tracked pages")
page_ids = fields.Many2many('website.page', string="Visited Pages", compute="_compute_page_statistics", groups="website.group_website_designer", search="_search_page_ids")
page_count = fields.Integer('# Visited Pages', compute="_compute_page_statistics", help="Total number of tracked page visited")
last_visited_page_id = fields.Many2one('website.page', string="Last Visited Page", compute="_compute_last_visited_page_id")
# Time fields
create_date = fields.Datetime('First Connection', readonly=True)
last_connection_datetime = fields.Datetime('Last Connection', default=fields.Datetime.now, help="Last page view date", readonly=True)
time_since_last_action = fields.Char('Last action', compute="_compute_time_statistics", help='Time since last page view. E.g.: 2 minutes ago')
is_connected = fields.Boolean('Is connected ?', compute='_compute_time_statistics', help='A visitor is considered as connected if his last page view was within the last 5 minutes.')
_sql_constraints = [
('access_token_unique', 'unique(access_token)', 'Access token should be unique.'),
('partner_uniq', 'unique(partner_id)', 'A partner is linked to only one visitor.'),
]
@api.depends('name')
def name_get(self):
res = []
for record in self:
res.append((
record.id,
record.name or _('Website Visitor #%s', record.id)
))
return res
@api.depends('partner_id.email_normalized', 'partner_id.mobile', 'partner_id.phone')
def _compute_email_phone(self):
results = self.env['res.partner'].search_read(
[('id', 'in', self.partner_id.ids)],
['id', 'email_normalized', 'mobile', 'phone'],
)
mapped_data = {
result['id']: {
'email_normalized': result['email_normalized'],
'mobile': result['mobile'] if result['mobile'] else result['phone']
} for result in results
}
for visitor in self:
visitor.email = mapped_data.get(visitor.partner_id.id, {}).get('email_normalized')
visitor.mobile = mapped_data.get(visitor.partner_id.id, {}).get('mobile')
@api.depends('website_track_ids')
def _compute_page_statistics(self):
results = self.env['website.track'].read_group(
[('visitor_id', 'in', self.ids), ('url', '!=', False)], ['visitor_id', 'page_id', 'url'], ['visitor_id', 'page_id', 'url'], lazy=False)
mapped_data = {}
for result in results:
visitor_info = mapped_data.get(result['visitor_id'][0], {'page_count': 0, 'visitor_page_count': 0, 'page_ids': set()})
visitor_info['visitor_page_count'] += result['__count']
visitor_info['page_count'] += 1
if result['page_id']:
visitor_info['page_ids'].add(result['page_id'][0])
mapped_data[result['visitor_id'][0]] = visitor_info
for visitor in self:
visitor_info = mapped_data.get(visitor.id, {'page_count': 0, 'visitor_page_count': 0, 'page_ids': set()})
visitor.page_ids = [(6, 0, visitor_info['page_ids'])]
visitor.visitor_page_count = visitor_info['visitor_page_count']
visitor.page_count = visitor_info['page_count']
def _search_page_ids(self, operator, value):
if operator not in ('like', 'ilike', 'not like', 'not ilike', '=like', '=ilike', '=', '!='):
raise ValueError(_('This operator is not supported'))
return [('website_track_ids.page_id.name', operator, value)]
@api.depends('website_track_ids.page_id')
def _compute_last_visited_page_id(self):
results = self.env['website.track'].read_group([('visitor_id', 'in', self.ids)],
['visitor_id', 'page_id', 'visit_datetime:max'],
['visitor_id', 'page_id'], lazy=False)
mapped_data = {result['visitor_id'][0]: result['page_id'][0] for result in results if result['page_id']}
for visitor in self:
visitor.last_visited_page_id = mapped_data.get(visitor.id, False)
@api.depends('last_connection_datetime')
def _compute_time_statistics(self):
for visitor in self:
visitor.time_since_last_action = _format_time_ago(self.env, (datetime.now() - visitor.last_connection_datetime))
visitor.is_connected = (datetime.now() - visitor.last_connection_datetime) < timedelta(minutes=5)
def _check_for_message_composer(self):
""" Purpose of this method is to actualize visitor model prior to contacting
him. Used notably for inheritance purpose, when dealing with leads that
could update the visitor model. """
return bool(self.partner_id and self.partner_id.email)
def _prepare_message_composer_context(self):
return {
'default_model': 'res.partner',
'default_res_id': self.partner_id.id,
'default_partner_ids': [self.partner_id.id],
}
def action_send_mail(self):
self.ensure_one()
if not self._check_for_message_composer():
raise UserError(_("There are no contact and/or no email linked to this visitor."))
visitor_composer_ctx = self._prepare_message_composer_context()
compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)
compose_ctx = dict(
default_use_template=False,
default_composition_mode='comment',
)
compose_ctx.update(**visitor_composer_ctx)
return {
'name': _('Contact Visitor'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form.id, 'form')],
'view_id': compose_form.id,
'target': 'new',
'context': compose_ctx,
}
def _get_visitor_from_request(self, force_create=False):
""" Return the visitor as sudo from the request if there is a visitor_uuid cookie.
It is possible that the partner has changed or has disconnected.
In that case the cookie is still referencing the old visitor and need to be replaced
with the one of the visitor returned !!!. """
# This function can be called in json with mobile app.
# In case of mobile app, no uid is set on the jsonRequest env.
# In case of multi db, _env is None on request, and request.env unbound.
if not request:
return None
Visitor = self.env['website.visitor'].sudo()
visitor = Visitor
access_token = request.httprequest.cookies.get('visitor_uuid')
if access_token:
visitor = Visitor.with_context(active_test=False).search([('access_token', '=', access_token)])
# Prefetch access_token and other fields. Since access_token has a restricted group and we access
# a non restricted field (partner_id) first it is not fetched and will require an additional query to be retrieved.
visitor.access_token
if not self.env.user._is_public():
partner_id = self.env.user.partner_id
if not visitor or visitor.partner_id and visitor.partner_id != partner_id:
# Partner and no cookie or wrong cookie
visitor = Visitor.with_context(active_test=False).search([('partner_id', '=', partner_id.id)])
elif visitor and visitor.partner_id:
# Cookie associated to a Partner
visitor = Visitor
if visitor and not visitor.timezone:
tz = self._get_visitor_timezone()
if tz:
visitor._update_visitor_timezone(tz)
if not visitor and force_create:
visitor = self._create_visitor()
return visitor
def _handle_webpage_dispatch(self, response, website_page):
# get visitor. Done here to avoid having to do it multiple times in case of override.
visitor_sudo = self._get_visitor_from_request(force_create=True)
if request.httprequest.cookies.get('visitor_uuid', '') != visitor_sudo.access_token:
expiration_date = datetime.now() + timedelta(days=365)
response.set_cookie('visitor_uuid', visitor_sudo.access_token, expires=expiration_date)
self._handle_website_page_visit(website_page, visitor_sudo)
def _handle_website_page_visit(self, website_page, visitor_sudo):
""" Called on dispatch. This will create a website.visitor if the http request object
is a tracked website page or a tracked view. Only on tracked elements to avoid having
too much operations done on every page or other http requests.
Note: The side effect is that the last_connection_datetime is updated ONLY on tracked elements."""
url = request.httprequest.url
website_track_values = {
'url': url,
'visit_datetime': datetime.now(),
}
if website_page:
website_track_values['page_id'] = website_page.id
domain = [('page_id', '=', website_page.id)]
else:
domain = [('url', '=', url)]
visitor_sudo._add_tracking(domain, website_track_values)
if visitor_sudo.lang_id.id != request.lang.id:
visitor_sudo.write({'lang_id': request.lang.id})
def _add_tracking(self, domain, website_track_values):
""" Add the track and update the visitor"""
domain = expression.AND([domain, [('visitor_id', '=', self.id)]])
last_view = self.env['website.track'].sudo().search(domain, limit=1)
if not last_view or last_view.visit_datetime < datetime.now() - timedelta(minutes=30):
website_track_values['visitor_id'] = self.id
self.env['website.track'].create(website_track_values)
self._update_visitor_last_visit()
def _create_visitor(self):
""" Create a visitor. Tracking is added after the visitor has been created."""
country_code = request.session.get('geoip', {}).get('country_code', False)
country_id = request.env['res.country'].sudo().search([('code', '=', country_code)], limit=1).id if country_code else False
vals = {
'lang_id': request.lang.id,
'country_id': country_id,
'website_id': request.website.id,
}
tz = self._get_visitor_timezone()
if tz:
vals['timezone'] = tz
if not self.env.user._is_public():
vals['partner_id'] = self.env.user.partner_id.id
vals['name'] = self.env.user.partner_id.name
return self.sudo().create(vals)
def _link_to_partner(self, partner, update_values=None):
""" Link visitors to a partner. This method is meant to be overridden in
order to propagate, if necessary, partner information to sub records.
:param partner: partner used to link sub records;
:param update_values: optional values to update visitors to link;
"""
vals = {'name': partner.name}
if update_values:
vals.update(update_values)
self.write(vals)
def _link_to_visitor(self, target, keep_unique=True):
""" Link visitors to target visitors, because they are linked to the
same identity. Purpose is mainly to propagate partner identity to sub
records to ease database update and decide what to do with "duplicated".
THis method is meant to be overridden in order to implement some specific
behavior linked to sub records of duplicate management.
:param target: main visitor, target of link process;
:param keep_unique: if True, find a way to make target unique;
"""
# Link sub records of self to target partner
if target.partner_id:
self._link_to_partner(target.partner_id)
# Link sub records of self to target visitor
self.website_track_ids.write({'visitor_id': target.id})
if keep_unique:
self.unlink()
return target
def _cron_archive_visitors(self):
delay_days = int(self.env['ir.config_parameter'].sudo().get_param('website.visitor.live.days', 30))
deadline = datetime.now() - timedelta(days=delay_days)
visitors_to_archive = self.env['website.visitor'].sudo().search([('last_connection_datetime', '<', deadline)])
visitors_to_archive.write({'active': False})
def _update_visitor_timezone(self, timezone):
""" We need to do this part here to avoid concurrent updates error. """
query = """
UPDATE website_visitor
SET timezone = %s
WHERE id IN (
SELECT id FROM website_visitor WHERE id = %s
FOR NO KEY UPDATE SKIP LOCKED
)
"""
self.env.cr.execute(query, (timezone, self.id))
def _update_visitor_last_visit(self):
""" We need to do this part here to avoid concurrent updates error. """
try:
with self.env.cr.savepoint():
query_lock = "SELECT * FROM website_visitor where id = %s FOR NO KEY UPDATE NOWAIT"
self.env.cr.execute(query_lock, (self.id,), log_exceptions=False)
date_now = datetime.now()
query = "UPDATE website_visitor SET "
if self.last_connection_datetime < (date_now - timedelta(hours=8)):
query += "visit_count = visit_count + 1,"
query += """
active = True,
last_connection_datetime = %s
WHERE id = %s
"""
self.env.cr.execute(query, (date_now, self.id), log_exceptions=False)
except Exception:
pass
def _get_visitor_timezone(self):
tz = request.httprequest.cookies.get('tz') if request else None
if tz in pytz.all_timezones:
return tz
elif not self.env.user._is_public():
return self.env.user.tz
else:
return None
| 49.159292 | 16,665 |
3,030 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo.tools.translate import _
class WebsiteBackend(http.Controller):
@http.route('/website/fetch_dashboard_data', type="json", auth='user')
def fetch_dashboard_data(self, website_id, date_from, date_to):
Website = request.env['website']
has_group_system = request.env.user.has_group('base.group_system')
has_group_designer = request.env.user.has_group('website.group_website_designer')
dashboard_data = {
'groups': {
'system': has_group_system,
'website_designer': has_group_designer
},
'currency': request.env.company.currency_id.id,
'dashboards': {
'visits': {},
}
}
current_website = website_id and Website.browse(website_id) or Website.get_current_website()
multi_website = request.env.user.has_group('website.group_multi_website')
websites = multi_website and request.env['website'].search([]) or current_website
dashboard_data['websites'] = websites.read(['id', 'name'])
for rec, website in zip(websites, dashboard_data['websites']):
website['domain'] = rec._get_http_domain()
if website['id'] == current_website.id:
website['selected'] = True
if has_group_designer:
if current_website.google_management_client_id and current_website.google_analytics_key:
dashboard_data['dashboards']['visits'] = dict(
ga_client_id=current_website.google_management_client_id or '',
ga_analytics_key=current_website.google_analytics_key or '',
)
return dashboard_data
@http.route('/website/dashboard/set_ga_data', type='json', auth='user')
def website_set_ga_data(self, website_id, ga_client_id, ga_analytics_key):
if not request.env.user.has_group('base.group_system'):
return {
'error': {
'title': _('Access Error'),
'message': _('You do not have sufficient rights to perform that action.'),
}
}
if not ga_analytics_key or not ga_client_id.endswith('.apps.googleusercontent.com'):
return {
'error': {
'title': _('Incorrect Client ID / Key'),
'message': _('The Google Analytics Client ID or Key you entered seems incorrect.'),
}
}
Website = request.env['website']
current_website = website_id and Website.browse(website_id) or Website.get_current_website()
request.env['res.config.settings'].create({
'google_management_client_id': ga_client_id,
'google_analytics_key': ga_analytics_key,
'website_id': current_website.id,
}).execute()
return True
| 44.558824 | 3,030 |
13,360 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import json
from psycopg2 import IntegrityError
from werkzeug.exceptions import BadRequest
from odoo import http, SUPERUSER_ID, _
from odoo.http import request
from odoo.tools import plaintext2html
from odoo.exceptions import ValidationError, UserError
from odoo.addons.base.models.ir_qweb_fields import nl2br
class WebsiteForm(http.Controller):
@http.route('/website/form', type='http', auth="public", methods=['POST'], multilang=False)
def website_form_empty(self, **kwargs):
# This is a workaround to don't add language prefix to <form action="/website/form/" ...>
return ""
# Check and insert values from the form on the model <model>
@http.route('/website/form/<string:model_name>', type='http', auth="public", methods=['POST'], website=True, csrf=False)
def website_form(self, model_name, **kwargs):
# Partial CSRF check, only performed when session is authenticated, as there
# is no real risk for unauthenticated sessions here. It's a common case for
# embedded forms now: SameSite policy rejects the cookies, so the session
# is lost, and the CSRF check fails, breaking the post for no good reason.
csrf_token = request.params.pop('csrf_token', None)
if request.session.uid and not request.validate_csrf(csrf_token):
raise BadRequest('Session expired (invalid CSRF token)')
try:
# The except clause below should not let what has been done inside
# here be committed. It should not either roll back everything in
# this controller method. Instead, we use a savepoint to roll back
# what has been done inside the try clause.
with request.env.cr.savepoint():
if request.env['ir.http']._verify_request_recaptcha_token('website_form'):
return self._handle_website_form(model_name, **kwargs)
error = _("Suspicious activity detected by Google reCaptcha.")
except (ValidationError, UserError) as e:
error = e.args[0]
return json.dumps({
'error': error,
})
def _handle_website_form(self, model_name, **kwargs):
model_record = request.env['ir.model'].sudo().search([('model', '=', model_name), ('website_form_access', '=', True)])
if not model_record:
return json.dumps({
'error': _("The form's specified model does not exist")
})
try:
data = self.extract_data(model_record, request.params)
# If we encounter an issue while extracting data
except ValidationError as e:
# I couldn't find a cleaner way to pass data to an exception
return json.dumps({'error_fields' : e.args[0]})
try:
id_record = self.insert_record(request, model_record, data['record'], data['custom'], data.get('meta'))
if id_record:
self.insert_attachment(model_record, id_record, data['attachments'])
# in case of an email, we want to send it immediately instead of waiting
# for the email queue to process
if model_name == 'mail.mail':
request.env[model_name].sudo().browse(id_record).send()
# Some fields have additional SQL constraints that we can't check generically
# Ex: crm.lead.probability which is a float between 0 and 1
# TODO: How to get the name of the erroneous field ?
except IntegrityError:
return json.dumps(False)
request.session['form_builder_model_model'] = model_record.model
request.session['form_builder_model'] = model_record.name
request.session['form_builder_id'] = id_record
return json.dumps({'id': id_record})
# Constants string to make metadata readable on a text field
_meta_label = "%s\n________\n\n" % _("Metadata") # Title for meta data
# Dict of dynamically called filters following type of field to be fault tolerent
def identity(self, field_label, field_input):
return field_input
def integer(self, field_label, field_input):
return int(field_input)
def floating(self, field_label, field_input):
return float(field_input)
def html(self, field_label, field_input):
return plaintext2html(field_input)
def boolean(self, field_label, field_input):
return bool(field_input)
def binary(self, field_label, field_input):
return base64.b64encode(field_input.read())
def one2many(self, field_label, field_input):
return [int(i) for i in field_input.split(',')]
def many2many(self, field_label, field_input, *args):
return [(args[0] if args else (6,0)) + (self.one2many(field_label, field_input),)]
_input_filters = {
'char': identity,
'text': identity,
'html': html,
'date': identity,
'datetime': identity,
'many2one': integer,
'one2many': one2many,
'many2many':many2many,
'selection': identity,
'boolean': boolean,
'integer': integer,
'float': floating,
'binary': binary,
'monetary': floating,
}
# Extract all data sent by the form and sort its on several properties
def extract_data(self, model, values):
dest_model = request.env[model.sudo().model]
data = {
'record': {}, # Values to create record
'attachments': [], # Attached files
'custom': '', # Custom fields values
'meta': '', # Add metadata if enabled
}
authorized_fields = model.with_user(SUPERUSER_ID)._get_form_writable_fields()
error_fields = []
custom_fields = []
for field_name, field_value in values.items():
# If the value of the field if a file
if hasattr(field_value, 'filename'):
# Undo file upload field name indexing
field_name = field_name.split('[', 1)[0]
# If it's an actual binary field, convert the input file
# If it's not, we'll use attachments instead
if field_name in authorized_fields and authorized_fields[field_name]['type'] == 'binary':
data['record'][field_name] = base64.b64encode(field_value.read())
field_value.stream.seek(0) # do not consume value forever
if authorized_fields[field_name]['manual'] and field_name + "_filename" in dest_model:
data['record'][field_name + "_filename"] = field_value.filename
else:
field_value.field_name = field_name
data['attachments'].append(field_value)
# If it's a known field
elif field_name in authorized_fields:
try:
input_filter = self._input_filters[authorized_fields[field_name]['type']]
data['record'][field_name] = input_filter(self, field_name, field_value)
except ValueError:
error_fields.append(field_name)
if dest_model._name == 'mail.mail' and field_name == 'email_from':
# As the "email_from" is used to populate the email_from of the
# sent mail.mail, it could be filtered out at sending time if no
# outgoing mail server "from_filter" match the sender email.
# To make sure the email contains that (important) information
# we also add it to the "custom message" that will be included
# in the body of the email sent.
custom_fields.append((_('email'), field_value))
# If it's a custom field
elif field_name != 'context':
custom_fields.append((field_name, field_value))
data['custom'] = "\n".join([u"%s : %s" % v for v in custom_fields])
# Add metadata if enabled # ICP for retrocompatibility
if request.env['ir.config_parameter'].sudo().get_param('website_form_enable_metadata'):
environ = request.httprequest.headers.environ
data['meta'] += "%s : %s\n%s : %s\n%s : %s\n%s : %s\n" % (
"IP" , environ.get("REMOTE_ADDR"),
"USER_AGENT" , environ.get("HTTP_USER_AGENT"),
"ACCEPT_LANGUAGE" , environ.get("HTTP_ACCEPT_LANGUAGE"),
"REFERER" , environ.get("HTTP_REFERER")
)
# This function can be defined on any model to provide
# a model-specific filtering of the record values
# Example:
# def website_form_input_filter(self, values):
# values['name'] = '%s\'s Application' % values['partner_name']
# return values
if hasattr(dest_model, "website_form_input_filter"):
data['record'] = dest_model.website_form_input_filter(request, data['record'])
missing_required_fields = [label for label, field in authorized_fields.items() if field['required'] and not label in data['record']]
if any(error_fields):
raise ValidationError(error_fields + missing_required_fields)
return data
def insert_record(self, request, model, values, custom, meta=None):
model_name = model.sudo().model
if model_name == 'mail.mail':
values.update({'reply_to': values.get('email_from')})
record = request.env[model_name].with_user(SUPERUSER_ID).with_context(
mail_create_nosubscribe=True,
commit_assetsbundle=False,
).create(values)
if custom or meta:
_custom_label = "%s\n___________\n\n" % _("Other Information:") # Title for custom fields
if model_name == 'mail.mail':
_custom_label = "%s\n___________\n\n" % _("This message has been posted on your website!")
default_field = model.website_form_default_field_id
default_field_data = values.get(default_field.name, '')
custom_content = (default_field_data + "\n\n" if default_field_data else '') \
+ (_custom_label + custom + "\n\n" if custom else '') \
+ (self._meta_label + meta if meta else '')
# If there is a default field configured for this model, use it.
# If there isn't, put the custom data in a message instead
if default_field.name:
if default_field.ttype == 'html' or model_name == 'mail.mail':
custom_content = nl2br(custom_content)
record.update({default_field.name: custom_content})
else:
values = {
'body': nl2br(custom_content),
'model': model_name,
'message_type': 'comment',
'res_id': record.id,
}
mail_id = request.env['mail.message'].with_user(SUPERUSER_ID).create(values)
return record.id
# Link all files attached on the form
def insert_attachment(self, model, id_record, files):
orphan_attachment_ids = []
model_name = model.sudo().model
record = model.env[model_name].browse(id_record)
authorized_fields = model.with_user(SUPERUSER_ID)._get_form_writable_fields()
for file in files:
custom_field = file.field_name not in authorized_fields
attachment_value = {
'name': file.filename,
'datas': base64.encodebytes(file.read()),
'res_model': model_name,
'res_id': record.id,
}
attachment_id = request.env['ir.attachment'].sudo().create(attachment_value)
if attachment_id and not custom_field:
record_sudo = record.sudo()
value = [(4, attachment_id.id)]
if record_sudo._fields[file.field_name].type == 'many2one':
value = attachment_id.id
record_sudo[file.field_name] = value
else:
orphan_attachment_ids.append(attachment_id.id)
if model_name != 'mail.mail':
# If some attachments didn't match a field on the model,
# we create a mail.message to link them to the record
if orphan_attachment_ids:
values = {
'body': _('<p>Attached files : </p>'),
'model': model_name,
'message_type': 'comment',
'res_id': id_record,
'attachment_ids': [(6, 0, orphan_attachment_ids)],
'subtype_id': request.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment'),
}
mail_id = request.env['mail.message'].with_user(SUPERUSER_ID).create(values)
else:
# If the model is mail.mail then we have no other choice but to
# attach the custom binary field files on the attachment_ids field.
for attachment_id_id in orphan_attachment_ids:
record.attachment_ids = [(4, attachment_id_id)]
| 46.068966 | 13,360 |
40,995 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import datetime
import json
import os
import logging
import re
import requests
import werkzeug.urls
import werkzeug.utils
import werkzeug.wrappers
from itertools import islice
from lxml import etree
from textwrap import shorten
from xml.etree import ElementTree as ET
import odoo
from odoo import http, models, fields, _
from odoo.http import request
from odoo.osv import expression
from odoo.tools import OrderedSet, escape_psql, html_escape as escape
from odoo.addons.http_routing.models.ir_http import slug, slugify, _guess_mimetype
from odoo.addons.portal.controllers.portal import pager as portal_pager
from odoo.addons.portal.controllers.web import Home
logger = logging.getLogger(__name__)
# Completely arbitrary limits
MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT = IMAGE_LIMITS = (1024, 768)
LOC_PER_SITEMAP = 45000
SITEMAP_CACHE_TIME = datetime.timedelta(hours=12)
class QueryURL(object):
def __init__(self, path='', path_args=None, **args):
self.path = path
self.args = args
self.path_args = OrderedSet(path_args or [])
def __call__(self, path=None, path_args=None, **kw):
path = path or self.path
for key, value in self.args.items():
kw.setdefault(key, value)
path_args = OrderedSet(path_args or []) | self.path_args
paths, fragments = {}, []
for key, value in kw.items():
if value and key in path_args:
if isinstance(value, models.BaseModel):
paths[key] = slug(value)
else:
paths[key] = u"%s" % value
elif value:
if isinstance(value, list) or isinstance(value, set):
fragments.append(werkzeug.urls.url_encode([(key, item) for item in value]))
else:
fragments.append(werkzeug.urls.url_encode([(key, value)]))
for key in path_args:
value = paths.get(key)
if value is not None:
path += '/' + key + '/' + value
if fragments:
path += '?' + '&'.join(fragments)
return path
class Website(Home):
@http.route('/', type='http', auth="public", website=True, sitemap=True)
def index(self, **kw):
# prefetch all menus (it will prefetch website.page too)
top_menu = request.website.menu_id
homepage_id = request.website._get_cached('homepage_id')
homepage = homepage_id and request.env['website.page'].browse(homepage_id)
if homepage and (homepage.sudo().is_visible or request.env.user.has_group('base.group_user')) and homepage.url != '/':
return request.env['ir.http'].reroute(homepage.url)
website_page = request.env['ir.http']._serve_page()
if website_page:
return website_page
else:
first_menu = top_menu and top_menu.child_id and top_menu.child_id.filtered(lambda menu: menu.is_visible)
if first_menu and first_menu[0].url not in ('/', '', '#') and (not (first_menu[0].url.startswith(('/?', '/#', ' ')))):
return request.redirect(first_menu[0].url)
raise request.not_found()
@http.route('/website/force/<int:website_id>', type='http', auth="user", website=True, sitemap=False, multilang=False)
def website_force(self, website_id, path='/', isredir=False, **kw):
""" To switch from a website to another, we need to force the website in
session, AFTER landing on that website domain (if set) as this will be a
different session.
"""
if not (request.env.user.has_group('website.group_multi_website')
and request.env.user.has_group('website.group_website_publisher')):
# The user might not be logged in on the forced website, so he won't
# have rights. We just redirect to the path as the user is already
# on the domain (basically a no-op as it won't change domain or
# force website).
# Website 1 : 127.0.0.1 (admin)
# Website 2 : 127.0.0.2 (not logged in)
# Click on "Website 2" from Website 1
return request.redirect(path)
website = request.env['website'].browse(website_id)
if not isredir and website.domain:
domain_from = request.httprequest.environ.get('HTTP_HOST', '')
domain_to = werkzeug.urls.url_parse(website._get_http_domain()).netloc
if domain_from != domain_to:
# redirect to correct domain for a correct routing map
url_to = werkzeug.urls.url_join(website._get_http_domain(), '/website/force/%s?isredir=1&path=%s' % (website.id, path))
return request.redirect(url_to)
website._force()
return request.redirect(path)
# ------------------------------------------------------
# Login - overwrite of the web login so that regular users are redirected to the backend
# while portal users are redirected to the frontend by default
# ------------------------------------------------------
def _login_redirect(self, uid, redirect=None):
""" Redirect regular users (employees) to the backend) and others to
the frontend
"""
if not redirect and request.params.get('login_success'):
if request.env['res.users'].browse(uid).has_group('base.group_user'):
redirect = '/web?' + request.httprequest.query_string.decode()
else:
redirect = '/my'
return super()._login_redirect(uid, redirect=redirect)
# Force website=True + auth='public', required for login form layout
@http.route(website=True, auth="public", sitemap=False)
def web_login(self, *args, **kw):
return super().web_login(*args, **kw)
# ------------------------------------------------------
# Business
# ------------------------------------------------------
@http.route('/website/get_languages', type='json', auth="user", website=True)
def website_languages(self, **kwargs):
return [(lg.code, lg.url_code, lg.name) for lg in request.website.language_ids]
@http.route('/website/lang/<lang>', type='http', auth="public", website=True, multilang=False)
def change_lang(self, lang, r='/', **kwargs):
""" :param lang: supposed to be value of `url_code` field """
if lang == 'default':
lang = request.website.default_lang_id.url_code
r = '/%s%s' % (lang, r or '/')
lang_code = request.env['res.lang']._lang_get_code(lang)
# replace context with correct lang, to avoid that the url_for of request.redirect remove the
# default lang in case we switch from /fr -> /en with /en as default lang.
request.context = dict(request.context, lang=lang_code)
redirect = request.redirect(r or ('/%s' % lang))
redirect.set_cookie('frontend_lang', lang_code)
return redirect
@http.route(['/website/country_infos/<model("res.country"):country>'], type='json', auth="public", methods=['POST'], website=True)
def country_infos(self, country, **kw):
fields = country.get_address_fields()
return dict(fields=fields, states=[(st.id, st.name, st.code) for st in country.state_ids], phone_code=country.phone_code)
@http.route(['/robots.txt'], type='http', auth="public", website=True, sitemap=False)
def robots(self, **kwargs):
return request.render('website.robots', {'url_root': request.httprequest.url_root}, mimetype='text/plain')
@http.route('/sitemap.xml', type='http', auth="public", website=True, multilang=False, sitemap=False)
def sitemap_xml_index(self, **kwargs):
current_website = request.website
Attachment = request.env['ir.attachment'].sudo()
View = request.env['ir.ui.view'].sudo()
mimetype = 'application/xml;charset=utf-8'
content = None
def create_sitemap(url, content):
return Attachment.create({
'raw': content.encode(),
'mimetype': mimetype,
'type': 'binary',
'name': url,
'url': url,
})
dom = [('url', '=', '/sitemap-%d.xml' % current_website.id), ('type', '=', 'binary')]
sitemap = Attachment.search(dom, limit=1)
if sitemap:
# Check if stored version is still valid
create_date = fields.Datetime.from_string(sitemap.create_date)
delta = datetime.datetime.now() - create_date
if delta < SITEMAP_CACHE_TIME:
content = base64.b64decode(sitemap.datas)
if not content:
# Remove all sitemaps in ir.attachments as we're going to regenerated them
dom = [('type', '=', 'binary'), '|', ('url', '=like', '/sitemap-%d-%%.xml' % current_website.id),
('url', '=', '/sitemap-%d.xml' % current_website.id)]
sitemaps = Attachment.search(dom)
sitemaps.unlink()
pages = 0
locs = request.website.with_context(_filter_duplicate_pages=True).with_user(request.website.user_id)._enumerate_pages()
while True:
values = {
'locs': islice(locs, 0, LOC_PER_SITEMAP),
'url_root': request.httprequest.url_root[:-1],
}
urls = View._render_template('website.sitemap_locs', values)
if urls.strip():
content = View._render_template('website.sitemap_xml', {'content': urls})
pages += 1
last_sitemap = create_sitemap('/sitemap-%d-%d.xml' % (current_website.id, pages), content)
else:
break
if not pages:
return request.not_found()
elif pages == 1:
# rename the -id-page.xml => -id.xml
last_sitemap.write({
'url': "/sitemap-%d.xml" % current_website.id,
'name': "/sitemap-%d.xml" % current_website.id,
})
else:
# TODO: in master/saas-15, move current_website_id in template directly
pages_with_website = ["%d-%d" % (current_website.id, p) for p in range(1, pages + 1)]
# Sitemaps must be split in several smaller files with a sitemap index
content = View._render_template('website.sitemap_index_xml', {
'pages': pages_with_website,
'url_root': request.httprequest.url_root,
})
create_sitemap('/sitemap-%d.xml' % current_website.id, content)
return request.make_response(content, [('Content-Type', mimetype)])
def sitemap_website_info(env, rule, qs):
website = env['website'].get_current_website()
if not (
website.viewref('website.website_info', False).active
and website.viewref('website.show_website_info', False).active
):
# avoid 404 or blank page in sitemap
return False
if not qs or qs.lower() in '/website/info':
yield {'loc': '/website/info'}
@http.route('/website/info', type='http', auth="public", website=True, sitemap=sitemap_website_info)
def website_info(self, **kwargs):
if not request.website.viewref('website.website_info', False).active:
# Deleted or archived view (through manual operation in backend).
# Don't check `show_website_info` view: still need to access if
# disabled to be able to enable it through the customize show.
raise request.not_found()
Module = request.env['ir.module.module'].sudo()
apps = Module.search([('state', '=', 'installed'), ('application', '=', True)])
l10n = Module.search([('state', '=', 'installed'), ('name', '=like', 'l10n_%')])
values = {
'apps': apps,
'l10n': l10n,
'version': odoo.service.common.exp_version()
}
return request.render('website.website_info', values)
@http.route(['/website/configurator', '/website/configurator/<int:step>'], type='http', auth="user", website=True, multilang=False)
def website_configurator(self, step=1, **kwargs):
if not request.env.user.has_group('website.group_website_designer'):
raise werkzeug.exceptions.NotFound()
website_id = request.env['website'].get_current_website()
if website_id.configurator_done:
return request.redirect('/')
if request.env.lang != website_id.default_lang_id.code:
return request.redirect('/%s%s' % (website_id.default_lang_id.url_code, request.httprequest.path))
return request.render('website.website_configurator')
@http.route(['/website/social/<string:social>'], type='http', auth="public", website=True, sitemap=False)
def social(self, social, **kwargs):
url = getattr(request.website, 'social_%s' % social, False)
if not url:
raise werkzeug.exceptions.NotFound()
return request.redirect(url, local=False)
@http.route('/website/get_suggested_links', type='json', auth="user", website=True)
def get_suggested_link(self, needle, limit=10):
current_website = request.website
matching_pages = []
for page in current_website.with_context(_filter_duplicate_pages=True).search_pages(needle, limit=int(limit)):
matching_pages.append({
'value': page['loc'],
'label': 'name' in page and '%s (%s)' % (page['loc'], page['name']) or page['loc'],
})
matching_urls = set(map(lambda match: match['value'], matching_pages))
matching_last_modified = []
last_modified_pages = current_website.with_context(_filter_duplicate_pages=True)._get_website_pages(order='write_date desc', limit=5)
for url, name in last_modified_pages.mapped(lambda p: (p.url, p.name)):
if needle.lower() in name.lower() or needle.lower() in url.lower() and url not in matching_urls:
matching_last_modified.append({
'value': url,
'label': '%s (%s)' % (url, name),
})
suggested_controllers = []
for name, url, mod in current_website.get_suggested_controllers():
if needle.lower() in name.lower() or needle.lower() in url.lower():
module_sudo = mod and request.env.ref('base.module_%s' % mod, False).sudo()
icon = mod and "<img src='%s' width='24px' height='24px' class='mr-2 rounded' /> " % (module_sudo and module_sudo.icon or mod) or ''
suggested_controllers.append({
'value': url,
'label': '%s%s (%s)' % (icon, url, name),
})
return {
'matching_pages': sorted(matching_pages, key=lambda o: o['label']),
'others': [
dict(title=_('Last modified pages'), values=matching_last_modified),
dict(title=_('Apps url'), values=suggested_controllers),
]
}
@http.route('/website/snippet/filters', type='json', auth='public', website=True)
def get_dynamic_filter(self, filter_id, template_key, limit=None, search_domain=None, with_sample=False):
dynamic_filter = request.env['website.snippet.filter'].sudo().search(
[('id', '=', filter_id)] + request.website.website_domain()
)
return dynamic_filter and dynamic_filter._render(template_key, limit, search_domain, with_sample) or []
@http.route('/website/snippet/options_filters', type='json', auth='user', website=True)
def get_dynamic_snippet_filters(self, model_name=None, search_domain=None):
domain = request.website.website_domain()
if search_domain:
domain = expression.AND([domain, search_domain])
if model_name:
domain = expression.AND([
domain,
['|', ('filter_id.model_id', '=', model_name), ('action_server_id.model_id.model', '=', model_name)]
])
dynamic_filter = request.env['website.snippet.filter'].sudo().search_read(
domain, ['id', 'name', 'limit', 'model_name'], order='id asc'
)
return dynamic_filter
@http.route('/website/snippet/filter_templates', type='json', auth='public', website=True)
def get_dynamic_snippet_templates(self, filter_name=False):
domain = [['key', 'ilike', '.dynamic_filter_template_'], ['type', '=', 'qweb']]
if filter_name:
domain.append(['key', 'ilike', escape_psql('_%s_' % filter_name)])
templates = request.env['ir.ui.view'].sudo().search_read(domain, ['key', 'name', 'arch_db'])
for t in templates:
children = etree.fromstring(t.pop('arch_db')).getchildren()
attribs = children and children[0].attrib or {}
t['numOfEl'] = attribs.get('data-number-of-elements')
t['numOfElSm'] = attribs.get('data-number-of-elements-sm')
t['numOfElFetch'] = attribs.get('data-number-of-elements-fetch')
return templates
@http.route('/website/get_current_currency', type='json', auth="public", website=True)
def get_current_currency(self, **kwargs):
return {
'id': request.website.company_id.currency_id.id,
'symbol': request.website.company_id.currency_id.symbol,
'position': request.website.company_id.currency_id.position,
}
# --------------------------------------------------------------------------
# Search Bar
# --------------------------------------------------------------------------
def _get_search_order(self, order):
# OrderBy will be parsed in orm and so no direct sql injection
# id is added to be sure that order is a unique sort key
order = order or 'name ASC'
return 'is_published desc, %s, id desc' % order
@http.route('/website/snippet/autocomplete', type='json', auth='public', website=True)
def autocomplete(self, search_type=None, term=None, order=None, limit=5, max_nb_chars=999, options=None):
"""
Returns list of results according to the term and options
:param str search_type: indicates what to search within, 'all' matches all available types
:param str term: search term written by the user
:param str order:
:param int limit: number of results to consider, defaults to 5
:param int max_nb_chars: max number of characters for text fields
:param dict options: options map containing
allowFuzzy: enables the fuzzy matching when truthy
fuzzy (boolean): True when called after finding a name through fuzzy matching
:returns: dict (or False if no result) containing
- 'results' (list): results (only their needed field values)
note: the monetary fields will be strings properly formatted and
already containing the currency
- 'results_count' (int): the number of results in the database
that matched the search query
- 'parts' (dict): presence of fields across all results
- 'fuzzy_search': search term used instead of requested search
"""
order = self._get_search_order(order)
options = options or {}
results_count, search_results, fuzzy_term = request.website._search_with_fuzzy(search_type, term, limit, order, options)
if not results_count:
return {
'results': [],
'results_count': 0,
'parts': {},
}
term = fuzzy_term or term
search_results = request.website._search_render_results(search_results, limit)
mappings = []
results_data = []
for search_result in search_results:
results_data += search_result['results_data']
mappings.append(search_result['mapping'])
if search_type == 'all':
# Only supported order for 'all' is on name
results_data.sort(key=lambda r: r.get('name', ''), reverse='name desc' in order)
results_data = results_data[:limit]
result = []
def get_mapping_value(field_type, value, field_meta):
if field_type == 'text':
if value and field_meta.get('truncate', True):
value = shorten(value, max_nb_chars, placeholder='...')
if field_meta.get('match') and value and term:
pattern = '|'.join(map(re.escape, term.split()))
if pattern:
parts = re.split(f'({pattern})', value, flags=re.IGNORECASE)
if len(parts) > 1:
value = request.env['ir.ui.view'].sudo()._render_template(
"website.search_text_with_highlight",
{'parts': parts}
)
field_type = 'html'
if field_type not in ('image', 'binary') and ('ir.qweb.field.%s' % field_type) in request.env:
opt = {}
if field_type == 'monetary':
opt['display_currency'] = options['display_currency']
elif field_type == 'html':
opt['template_options'] = {}
value = request.env[('ir.qweb.field.%s' % field_type)].value_to_html(value, opt)
return escape(value)
for record in results_data:
mapping = record['_mapping']
mapped = {
'_fa': record.get('_fa'),
}
for mapped_name, field_meta in mapping.items():
value = record.get(field_meta.get('name'))
if not value:
mapped[mapped_name] = ''
continue
field_type = field_meta.get('type')
if field_type == 'dict':
# Map a field with multiple values, stored in a dict with values type: item_type
item_type = field_meta.get('item_type')
mapped[mapped_name] = {}
for key, item in value.items():
mapped[mapped_name][key] = get_mapping_value(item_type, item, field_meta)
else:
mapped[mapped_name] = get_mapping_value(field_type, value, field_meta)
result.append(mapped)
return {
'results': result,
'results_count': results_count,
'parts': {key: True for mapping in mappings for key in mapping},
'fuzzy_search': fuzzy_term,
}
@http.route(['/pages', '/pages/page/<int:page>'], type='http', auth="public", website=True, sitemap=False)
def pages_list(self, page=1, search='', **kw):
options = {
'displayDescription': False,
'displayDetail': False,
'displayExtraDetail': False,
'displayExtraLink': False,
'displayImage': False,
'allowFuzzy': not kw.get('noFuzzy'),
}
step = 50
pages_count, details, fuzzy_search_term = request.website._search_with_fuzzy(
"pages", search, limit=page * step, order='name asc, website_id desc, id',
options=options)
pages = details[0].get('results', request.env['website.page'])
pager = portal_pager(
url="/pages",
url_args={'search': search},
total=pages_count,
page=page,
step=step
)
pages = pages[(page - 1) * step:page * step]
values = {
'pager': pager,
'pages': pages,
'search': fuzzy_search_term or search,
'search_count': pages_count,
'original_search': fuzzy_search_term and search,
}
return request.render("website.list_website_public_pages", values)
@http.route([
'/website/search',
'/website/search/page/<int:page>',
'/website/search/<string:search_type>',
'/website/search/<string:search_type>/page/<int:page>',
], type='http', auth="public", website=True, sitemap=False)
def hybrid_list(self, page=1, search='', search_type='all', **kw):
if not search:
return request.render("website.list_hybrid")
options = {
'displayDescription': True,
'displayDetail': True,
'displayExtraDetail': True,
'displayExtraLink': True,
'displayImage': True,
'allowFuzzy': not kw.get('noFuzzy'),
}
data = self.autocomplete(search_type=search_type, term=search, order='name asc', limit=500, max_nb_chars=200, options=options)
results = data.get('results', [])
search_count = len(results)
parts = data.get('parts', {})
step = 50
pager = portal_pager(
url="/website/search/%s" % search_type,
url_args={'search': search},
total=search_count,
page=page,
step=step
)
results = results[(page - 1) * step:page * step]
values = {
'pager': pager,
'results': results,
'parts': parts,
'search': search,
'fuzzy_search': data.get('fuzzy_search'),
'search_count': search_count,
}
return request.render("website.list_hybrid", values)
# ------------------------------------------------------
# Edit
# ------------------------------------------------------
@http.route(['/website/pages', '/website/pages/page/<int:page>'], type='http', auth="user", website=True)
def pages_management(self, page=1, sortby='url', search='', **kw):
# only website_designer should access the page Management
if not request.env.user.has_group('website.group_website_designer'):
raise werkzeug.exceptions.NotFound()
Page = request.env['website.page']
searchbar_sortings = {
'url': {'label': _('Sort by Url'), 'order': 'url'},
'name': {'label': _('Sort by Name'), 'order': 'name'},
}
# default sortby order
sort_order = searchbar_sortings.get(sortby, 'url')['order'] + ', website_id desc, id'
domain = request.website.website_domain()
if search:
domain += ['|', ('name', 'ilike', search), ('url', 'ilike', search)]
pages = Page.search(domain, order=sort_order)
if sortby != 'url' or not request.session.debug:
pages = pages._get_most_specific_pages()
pages_count = len(pages)
step = 50
pager = portal_pager(
url="/website/pages",
url_args={'sortby': sortby},
total=pages_count,
page=page,
step=step
)
pages = pages[(page - 1) * step:page * step]
values = {
'pager': pager,
'pages': pages,
'search': search,
'sortby': sortby,
'searchbar_sortings': searchbar_sortings,
'search_count': pages_count,
}
return request.render("website.list_website_pages", values)
@http.route(['/website/add', '/website/add/<path:path>'], type='http', auth="user", website=True, methods=['POST'])
def pagenew(self, path="", noredirect=False, add_menu=False, template=False, **kwargs):
# for supported mimetype, get correct default template
_, ext = os.path.splitext(path)
ext_special_case = ext and ext in _guess_mimetype() and ext != '.html'
if not template and ext_special_case:
default_templ = 'website.default_%s' % ext.lstrip('.')
if request.env.ref(default_templ, False):
template = default_templ
template = template and dict(template=template) or {}
page = request.env['website'].new_page(path, add_menu=add_menu, **template)
url = page['url']
if noredirect:
return werkzeug.wrappers.Response(url, mimetype='text/plain')
if ext_special_case: # redirect non html pages to backend to edit
return request.redirect('/web#id=' + str(page.get('view_id')) + '&view_type=form&model=ir.ui.view')
return request.redirect(url + "?enable_editor=1")
@http.route("/website/get_switchable_related_views", type="json", auth="user", website=True)
def get_switchable_related_views(self, key):
views = request.env["ir.ui.view"].get_related_views(key, bundles=False).filtered(lambda v: v.customize_show)
# TODO remove in master: customize_show was kept by mistake on a view
# in website_crm. It was removed in stable at the same time this hack is
# introduced but would still be shown for existing customers if nothing
# else was done here. For users that disabled the view but were not
# supposed to be able to, we hide it too. The feature does not do much
# and is not a discoverable feature anyway, best removing the confusion
# entirely. If someone somehow wants that very technical feature, they
# can still enable the view again via the backend. We will also
# re-enable the view automatically in master.
crm_contactus_view = request.website.viewref('website_crm.contactus_form', raise_if_not_found=False)
views -= crm_contactus_view
views = views.sorted(key=lambda v: (v.inherit_id.id, v.name))
return views.with_context(display_website=False).read(['name', 'id', 'key', 'xml_id', 'active', 'inherit_id'])
@http.route('/website/toggle_switchable_view', type='json', auth='user', website=True)
def toggle_switchable_view(self, view_key):
if request.website.user_has_groups('website.group_website_designer'):
request.website.viewref(view_key).toggle_active()
else:
return werkzeug.exceptions.Forbidden()
@http.route('/website/reset_template', type='http', auth='user', methods=['POST'], website=True, csrf=False)
def reset_template(self, view_id, mode='soft', redirect='/', **kwargs):
""" This method will try to reset a broken view.
Given the mode, the view can either be:
- Soft reset: restore to previous architeture.
- Hard reset: it will read the original `arch` from the XML file if the
view comes from an XML file (arch_fs).
"""
view = request.env['ir.ui.view'].browse(int(view_id))
# Deactivate COW to not fix a generic view by creating a specific
view.with_context(website_id=None).reset_arch(mode)
return request.redirect(redirect)
@http.route(['/website/publish'], type='json', auth="user", website=True)
def publish(self, id, object):
Model = request.env[object]
record = Model.browse(int(id))
values = {}
if 'website_published' in Model._fields:
values['website_published'] = not record.website_published
record.write(values)
return bool(record.website_published)
return False
@http.route(['/website/seo_suggest'], type='json', auth="user", website=True)
def seo_suggest(self, keywords=None, lang=None):
language = lang.split("_")
url = "http://google.com/complete/search"
try:
req = requests.get(url, params={
'ie': 'utf8', 'oe': 'utf8', 'output': 'toolbar', 'q': keywords, 'hl': language[0], 'gl': language[1]})
req.raise_for_status()
response = req.content
except IOError:
return []
xmlroot = ET.fromstring(response)
return json.dumps([sugg[0].attrib['data'] for sugg in xmlroot if len(sugg) and sugg[0].attrib['data']])
@http.route(['/website/get_seo_data'], type='json', auth="user", website=True)
def get_seo_data(self, res_id, res_model):
if not request.env.user.has_group('website.group_website_publisher'):
raise werkzeug.exceptions.Forbidden()
fields = ['website_meta_title', 'website_meta_description', 'website_meta_keywords', 'website_meta_og_img']
if res_model == 'website.page':
fields.extend(['website_indexed', 'website_id'])
record = request.env[res_model].browse(res_id)
res = record._read_format(fields)[0]
res['has_social_default_image'] = request.website.has_social_default_image
if res_model not in ('website.page', 'ir.ui.view') and 'seo_name' in record: # allow custom slugify
res['seo_name_default'] = slugify(record.display_name) # default slug, if seo_name become empty
res['seo_name'] = record.seo_name and slugify(record.seo_name) or ''
return res
@http.route(['/google<string(length=16):key>.html'], type='http', auth="public", website=True, sitemap=False)
def google_console_search(self, key, **kwargs):
if not request.website.google_search_console:
logger.warning('Google Search Console not enable')
raise werkzeug.exceptions.NotFound()
gsc = request.website.google_search_console
trusted = gsc[gsc.startswith('google') and len('google'):gsc.endswith('.html') and -len('.html') or None]
if key != trusted:
if key.startswith(trusted):
request.website.sudo().google_search_console = "google%s.html" % key
else:
logger.warning('Google Search Console %s not recognize' % key)
raise werkzeug.exceptions.NotFound()
return request.make_response("google-site-verification: %s" % request.website.google_search_console)
@http.route('/website/google_maps_api_key', type='json', auth='public', website=True)
def google_maps_api_key(self):
return json.dumps({
'google_maps_api_key': request.website.google_maps_api_key or ''
})
# ------------------------------------------------------
# Themes
# ------------------------------------------------------
# TODO Remove this function in master because it only stays here for
# compatibility.
def _get_customize_views(self, xml_ids):
self._get_customize_data(self, xml_ids, True)
def _get_customize_data(self, keys, is_view_data):
model = 'ir.ui.view' if is_view_data else 'ir.asset'
Model = request.env[model].with_context(active_test=False)
if not keys:
return Model
domain = [("key", "in", keys)] + request.website.website_domain()
return Model.search(domain).filter_duplicate()
# TODO Remove this route in master because it only stays here for
# compatibility.
@http.route(['/website/theme_customize_get'], type='json', auth='user', website=True)
def theme_customize_get(self, xml_ids):
self.theme_customize_data_get(xml_ids, True)
@http.route(['/website/theme_customize_data_get'], type='json', auth='user', website=True)
def theme_customize_data_get(self, keys, is_view_data):
records = self._get_customize_data(keys, is_view_data)
return records.filtered('active').mapped('key')
# TODO Remove this route in Master because it only stays here for
# compatibility.
@http.route(['/website/theme_customize'], type='json', auth='user', website=True)
def theme_customize(self, enable=None, disable=None, reset_view_arch=False):
self.theme_customize_data(True, enable, disable, reset_view_arch)
@http.route(['/website/theme_customize_data'], type='json', auth='user', website=True)
def theme_customize_data(self, is_view_data, enable=None, disable=None, reset_view_arch=False):
"""
Enables and/or disables views/assets according to list of keys.
:param is_view_data: True = "ir.ui.view", False = "ir.asset"
:param enable: list of views/assets keys to enable
:param disable: list of views/assets keys to disable
:param reset_view_arch: restore the default template after disabling
"""
disabled_data = self._get_customize_data(disable, is_view_data).filtered('active')
if reset_view_arch:
disabled_data.reset_arch(mode='hard')
disabled_data.write({'active': False})
self._get_customize_data(enable, is_view_data).filtered(lambda x: not x.active).write({'active': True})
@http.route(['/website/theme_customize_bundle_reload'], type='json', auth='user', website=True)
def theme_customize_bundle_reload(self):
"""
Reloads asset bundles and returns their unique URLs.
"""
return {
'web.assets_common': request.env['ir.qweb']._get_asset_link_urls('web.assets_common'),
'web.assets_frontend': request.env['ir.qweb']._get_asset_link_urls('web.assets_frontend'),
'website.assets_editor': request.env['ir.qweb']._get_asset_link_urls('website.assets_editor'),
}
@http.route(['/website/make_scss_custo'], type='json', auth='user', website=True)
def make_scss_custo(self, url, values):
"""
Params:
url (str):
the URL of the scss file to customize (supposed to be a variable
file which will appear in the assets_common bundle)
values (dict):
key,value mapping to integrate in the file's map (containing the
word hook). If a key is already in the file's map, its value is
overridden.
Returns:
boolean
"""
request.env['web_editor.assets'].make_scss_customization(url, values)
return True
# ------------------------------------------------------
# Server actions
# ------------------------------------------------------
@http.route([
'/website/action/<path_or_xml_id_or_id>',
'/website/action/<path_or_xml_id_or_id>/<path:path>',
], type='http', auth="public", website=True)
def actions_server(self, path_or_xml_id_or_id, **post):
ServerActions = request.env['ir.actions.server']
action = action_id = None
# find the action_id: either an xml_id, the path, or an ID
if isinstance(path_or_xml_id_or_id, str) and '.' in path_or_xml_id_or_id:
action = request.env.ref(path_or_xml_id_or_id, raise_if_not_found=False).sudo()
if not action:
action = ServerActions.sudo().search(
[('website_path', '=', path_or_xml_id_or_id), ('website_published', '=', True)], limit=1)
if not action:
try:
action_id = int(path_or_xml_id_or_id)
action = ServerActions.sudo().browse(action_id).exists()
except ValueError:
pass
# run it, return only if we got a Response object
if action:
if action.state == 'code' and action.website_published:
# use main session env for execution
action_res = ServerActions.browse(action.id).run()
if isinstance(action_res, werkzeug.wrappers.Response):
return action_res
return request.redirect('/')
# ------------------------------------------------------
# Retrocompatibility routes
# ------------------------------------------------------
class WebsiteBinary(http.Controller):
@http.route([
'/website/image',
'/website/image/<xmlid>',
'/website/image/<xmlid>/<int:width>x<int:height>',
'/website/image/<xmlid>/<field>',
'/website/image/<xmlid>/<field>/<int:width>x<int:height>',
'/website/image/<model>/<id>/<field>',
'/website/image/<model>/<id>/<field>/<int:width>x<int:height>'
], type='http', auth="public", website=False, multilang=False)
def content_image(self, id=None, max_width=0, max_height=0, **kw):
if max_width:
kw['width'] = max_width
if max_height:
kw['height'] = max_height
if id:
id, _, unique = id.partition('_')
kw['id'] = int(id)
if unique:
kw['unique'] = unique
kw['res_id'] = kw.pop('id', None)
return request.env['ir.http']._content_image(**kw)
# if not icon provided in DOM, browser tries to access /favicon.ico, eg when opening an order pdf
@http.route(['/favicon.ico'], type='http', auth='public', website=True, multilang=False, sitemap=False)
def favicon(self, **kw):
website = request.website
response = request.redirect(website.image_url(website, 'favicon'), code=301)
response.headers['Cache-Control'] = 'public, max-age=%s' % http.STATIC_CACHE_LONG
return response
| 46.374434 | 40,995 |
3,370 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Manufacturing',
'version': '2.0',
'website': 'https://www.odoo.com/app/manufacturing',
'category': 'Manufacturing/Manufacturing',
'sequence': 55,
'summary': 'Manufacturing Orders & BOMs',
'depends': ['product', 'stock', 'resource'],
'description': "",
'data': [
'security/mrp_security.xml',
'security/ir.model.access.csv',
'data/digest_data.xml',
'data/mail_templates.xml',
'data/mrp_data.xml',
'wizard/change_production_qty_views.xml',
'wizard/mrp_workcenter_block_view.xml',
'wizard/stock_warn_insufficient_qty_views.xml',
'wizard/mrp_production_backorder.xml',
'wizard/mrp_consumption_warning_views.xml',
'wizard/mrp_immediate_production_views.xml',
'wizard/stock_assign_serial_numbers.xml',
'views/mrp_views_menus.xml',
'views/stock_move_views.xml',
'views/mrp_workorder_views.xml',
'views/mrp_workcenter_views.xml',
'views/mrp_bom_views.xml',
'views/mrp_production_views.xml',
'views/mrp_routing_views.xml',
'views/product_views.xml',
'views/stock_orderpoint_views.xml',
'views/stock_warehouse_views.xml',
'views/stock_picking_views.xml',
'views/mrp_unbuild_views.xml',
'views/ir_attachment_view.xml',
'views/res_config_settings_views.xml',
'views/stock_scrap_views.xml',
'report/report_deliveryslip.xml',
'report/mrp_report_views_main.xml',
'report/mrp_report_bom_structure.xml',
'report/mrp_production_templates.xml',
'report/report_stock_forecasted.xml',
'report/report_stock_reception.xml',
'report/report_stock_rule.xml',
'report/mrp_zebra_production_templates.xml',
],
'demo': [
'data/mrp_demo.xml',
],
'test': [],
'application': True,
'pre_init_hook': '_pre_init_mrp',
'post_init_hook': '_create_warehouse_data',
'uninstall_hook': 'uninstall_hook',
'assets': {
'web.assets_backend': [
'mrp/static/src/scss/mrp_workorder_kanban.scss',
'mrp/static/src/js/mrp.js',
'mrp/static/src/js/mrp_bom_report.js',
'mrp/static/src/js/mrp_workorder_popover.js',
'mrp/static/src/js/mrp_documents_controller_mixin.js',
'mrp/static/src/js/mrp_documents_document_viewer.js',
'mrp/static/src/js/mrp_documents_kanban_controller.js',
'mrp/static/src/js/mrp_documents_kanban_record.js',
'mrp/static/src/js/mrp_documents_kanban_renderer.js',
'mrp/static/src/js/mrp_document_kanban_view.js',
'mrp/static/src/js/mrp_should_consume.js',
'mrp/static/src/js/mrp_field_one2many_with_copy.js',
],
'web.assets_common': [
'mrp/static/src/scss/mrp_bom_report.scss',
'mrp/static/src/scss/mrp_fields.scss',
'mrp/static/src/scss/mrp_gantt.scss',
'mrp/static/src/scss/mrp_document_kanban_view.scss',
],
'web.qunit_suite_tests': [
'mrp/static/tests/**/*',
],
'web.assets_qweb': [
'mrp/static/src/xml/*.xml',
],
},
'license': 'LGPL-3',
}
| 38.295455 | 3,370 |
20,090 |
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, timedelta
from collections import defaultdict
from odoo import models
from odoo.tools import populate, OrderedSet
from odoo.addons.stock.populate.stock import COMPANY_NB_WITH_STOCK
_logger = logging.getLogger(__name__)
class ResCompany(models.Model):
_inherit = 'res.company'
def _populate_factories(self):
return super()._populate_factories() + [
('manufacturing_lead', populate.randint(0, 2)),
]
class ProductProduct(models.Model):
_inherit = 'product.product'
def _populate_factories(self):
return super()._populate_factories() + [
('produce_delay', populate.randint(1, 4)),
]
class Warehouse(models.Model):
_inherit = 'stock.warehouse'
def _populate_factories(self):
return super()._populate_factories() + [
('manufacture_steps', populate.iterate(['mrp_one_step', 'pbm', 'pbm_sam'], [0.6, 0.2, 0.2]))
]
# TODO : stock picking type manufacturing
class MrpBom(models.Model):
_inherit = 'mrp.bom'
_populate_sizes = {'small': 100, 'medium': 2_000, 'large': 20_000}
_populate_dependencies = ['product.product', 'stock.location']
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
product_tmpl_ids = self.env['product.product'].search([
('id', 'in', self.env.registry.populated_models['product.product']),
('type', 'in', ('product', 'consu'))
]).product_tmpl_id.ids
# Use only a 80 % subset of the products - the 20 % remaining will leaves of the bom tree
random = populate.Random('subset_product_bom')
product_tmpl_ids = random.sample(product_tmpl_ids, int(len(product_tmpl_ids) * 0.8))
def get_product_id(values=None, random=None, **kwargs):
if random.random() > 0.5: # 50 % change to target specific product.product
return False
return random.choice(self.env['product.template'].browse(values['product_tmpl_id']).product_variant_ids.ids)
return [
('company_id', populate.randomize(
[False] + company_ids,
[0.9] + [0.1 / (len(company_ids) or 1.0)] * (len(company_ids)) # TODO: Inverse the weight, but need to make the bom tree by company (in bom line populate)
)),
('product_tmpl_id', populate.randomize(product_tmpl_ids)),
('product_id', populate.compute(get_product_id)),
('product_qty', populate.randint(1, 5)),
('sequence', populate.randint(1, 1000)),
('code', populate.constant("R{counter}")),
('ready_to_produce', populate.randomize(['all_available', 'asap'])),
]
class MrpBomLine(models.Model):
_inherit = 'mrp.bom.line'
_populate_sizes = {'small': 500, 'medium': 10_000, 'large': 100_000}
_populate_dependencies = ['mrp.bom']
def _populate_factories(self):
# TODO: tree of product by company to be more closer to the reality
boms = self.env['mrp.bom'].search([('id', 'in', self.env.registry.populated_models['mrp.bom'])], order='sequence, product_id, id')
product_manu_ids = OrderedSet()
for bom in boms:
if bom.product_id:
product_manu_ids.add(bom.product_id.id)
else:
for product_id in bom.product_tmpl_id.product_variant_ids:
product_manu_ids.add(product_id.id)
product_manu_ids = list(product_manu_ids)
product_manu = self.env['product.product'].browse(product_manu_ids)
# product_no_manu is products which don't have any bom (leaves in the BoM trees)
product_no_manu = self.env['product.product'].browse(self.env.registry.populated_models['product.product']) - product_manu
product_no_manu_ids = product_no_manu.ids
def get_product_id(values, counter, random):
bom = self.env['mrp.bom'].browse(values['bom_id'])
last_product_bom = bom.product_id if bom.product_id else bom.product_tmpl_id.product_variant_ids[-1]
# TODO: index in list is in O(n) can be avoid by a cache dict (if performance issue)
index_prod = product_manu_ids.index(last_product_bom.id)
# Always choose a product futher in the recordset `product_manu` to avoid any loops
# Or used a product in the `product_no_manu`
sparsity = 0.4 # Increase the sparsity will decrease the density of the BoM trees => smaller Tree
len_remaining_manu = len(product_manu_ids) - index_prod - 1
len_no_manu = len(product_no_manu_ids)
threshold = len_remaining_manu / (len_remaining_manu + sparsity * len_no_manu)
if random.random() <= threshold:
# TODO: avoid copy the list (if performance issue)
return random.choice(product_manu_ids[index_prod+1:])
else:
return random.choice(product_no_manu_ids)
def get_product_uom_id(values, counter, random):
return self.env['product.product'].browse(values['product_id']).uom_id.id
return [
('bom_id', populate.iterate(boms.ids)),
('sequence', populate.randint(1, 1000)),
('product_id', populate.compute(get_product_id)),
('product_uom_id', populate.compute(get_product_uom_id)),
('product_qty', populate.randint(1, 10)),
]
class MrpWorkcenter(models.Model):
_inherit = 'mrp.workcenter'
_populate_sizes = {'small': 20, 'medium': 100, 'large': 1_000}
def _populate(self, size):
res = super()._populate(size)
# Set alternative workcenters
_logger.info("Set alternative workcenters")
# Valid workcenters by company_id (the workcenter without company can be the alternative of all workcenter)
workcenters_by_company = defaultdict(OrderedSet)
for workcenter in res:
workcenters_by_company[workcenter.company_id.id].add(workcenter.id)
workcenters_by_company = {company_id: self.env['mrp.workcenter'].browse(workcenters) for company_id, workcenters in workcenters_by_company.items()}
workcenters_by_company = {
company_id: workcenters | workcenters_by_company.get(False, self.env['mrp.workcenter'])
for company_id, workcenters in workcenters_by_company.items()}
random = populate.Random('set_alternative_workcenter')
for workcenter in res:
nb_alternative = max(random.randint(0, 3), len(workcenters_by_company[workcenter.company_id.id]) - 1)
if nb_alternative > 0:
alternatives_workcenter_ids = random.sample((workcenters_by_company[workcenter.company_id.id] - workcenter).ids, nb_alternative)
workcenter.alternative_workcenter_ids = [(6, 0, alternatives_workcenter_ids)]
return res
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
resource_calendar_no_company = self.env.ref('resource.resource_calendar_std').copy({'company_id': False})
def get_resource_calendar_id(values, counter, random):
if not values['company_id']:
return resource_calendar_no_company.id
return self.env['res.company'].browse(values['company_id']).resource_calendar_id.id
return [
('name', populate.constant("Workcenter - {counter}")),
('company_id', populate.iterate(company_ids + [False])),
('resource_calendar_id', populate.compute(get_resource_calendar_id)),
('active', populate.iterate([True, False], [0.9, 0.1])),
('code', populate.constant("W/{counter}")),
('capacity', populate.iterate([0.5, 1.0, 2.0, 5.0], [0.2, 0.4, 0.2, 0.2])),
('sequence', populate.randint(1, 1000)),
('color', populate.randint(1, 12)),
('costs_hour', populate.randint(5, 25)),
('time_start', populate.iterate([0.0, 2.0, 10.0], [0.6, 0.2, 0.2])),
('time_stop', populate.iterate([0.0, 2.0, 10.0], [0.6, 0.2, 0.2])),
('oee_target', populate.randint(80, 99)),
]
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
_populate_sizes = {'small': 500, 'medium': 5_000, 'large': 50_000}
_populate_dependencies = ['mrp.workcenter', 'mrp.bom']
def _populate_factories(self):
# Take a subset (70%) of bom to have some of then without any operation
random = populate.Random('operation_subset_bom')
boms_ids = self.env.registry.populated_models['mrp.bom']
boms_ids = random.sample(boms_ids, int(len(boms_ids) * 0.7))
# Valid workcenters by company_id (the workcenter without company can be used by any operation)
workcenters_by_company = defaultdict(OrderedSet)
for workcenter in self.env['mrp.workcenter'].browse(self.env.registry.populated_models['mrp.workcenter']):
workcenters_by_company[workcenter.company_id.id].add(workcenter.id)
workcenters_by_company = {company_id: self.env['mrp.workcenter'].browse(workcenters) for company_id, workcenters in workcenters_by_company.items()}
workcenters_by_company = {
company_id: workcenters | workcenters_by_company.get(False, self.env['mrp.workcenter'])
for company_id, workcenters in workcenters_by_company.items()}
def get_company_id(values, counter, random):
bom = self.env['mrp.bom'].browse(values['bom_id'])
return bom.company_id.id
def get_workcenter_id(values, counter, random):
return random.choice(workcenters_by_company[values['company_id']]).id
return [
('bom_id', populate.iterate(boms_ids)),
('company_id', populate.compute(get_company_id)),
('workcenter_id', populate.compute(get_workcenter_id)),
('name', populate.constant("OP-{counter}")),
('sequence', populate.randint(1, 1000)),
('time_mode', populate.iterate(['auto', 'manual'])),
('time_mode_batch', populate.randint(1, 100)),
('time_cycle_manual', populate.randomize([1.0, 15.0, 60.0, 1440.0])),
]
class MrpBomByproduct(models.Model):
_inherit = 'mrp.bom.byproduct'
_populate_sizes = {'small': 50, 'medium': 1_000, 'large': 5_000}
_populate_dependencies = ['mrp.bom.line', 'mrp.routing.workcenter']
def _populate_factories(self):
# Take a subset (50%) of bom to have some of then without any operation
random = populate.Random('byproduct_subset_bom')
boms_ids = self.env.registry.populated_models['mrp.bom']
boms_ids = random.sample(boms_ids, int(len(boms_ids) * 0.5))
boms = self.env['mrp.bom'].search([('id', 'in', self.env.registry.populated_models['mrp.bom'])], order='sequence, product_id, id')
product_manu_ids = OrderedSet()
for bom in boms:
if bom.product_id:
product_manu_ids.add(bom.product_id.id)
else:
for product_id in bom.product_tmpl_id.product_variant_ids:
product_manu_ids.add(product_id.id)
product_manu = self.env['product.product'].browse(product_manu_ids)
# product_no_manu is products which don't have any bom (leaves in the BoM trees)
product_no_manu = self.env['product.product'].browse(self.env.registry.populated_models['product.product']) - product_manu
product_no_manu_ids = product_no_manu.ids
def get_product_uom_id(values, counter, random):
return self.env['product.product'].browse(values['product_id']).uom_id.id
return [
('bom_id', populate.iterate(boms_ids)),
('product_id', populate.randomize(product_no_manu_ids)),
('product_uom_id', populate.compute(get_product_uom_id)),
('product_qty', populate.randint(1, 10)),
]
class MrpProduction(models.Model):
_inherit = 'mrp.production'
_populate_sizes = {'small': 100, 'medium': 1_000, 'large': 10_000}
_populate_dependencies = ['mrp.routing.workcenter', 'mrp.bom.line']
def _populate(self, size):
productions = super()._populate(size)
def fill_mo_with_bom_info():
productions_with_bom = productions.filtered('bom_id')
_logger.info("Create Raw moves of MO(s) with bom (%d)" % len(productions_with_bom))
self.env['stock.move'].create(productions_with_bom._get_moves_raw_values())
_logger.info("Create Finished moves of MO(s) with bom (%d)" % len(productions_with_bom))
self.env['stock.move'].create(productions_with_bom._get_moves_finished_values())
_logger.info("Create Workorder moves of MO(s) with bom (%d)" % len(productions_with_bom))
productions_with_bom._create_workorder()
fill_mo_with_bom_info()
def confirm_bom_mo(sample_ratio):
# Confirm X % of prototype MO
random = populate.Random('confirm_bom_mo')
mo_ids = productions.filtered('bom_id').ids
mo_to_confirm = self.env['mrp.production'].browse(random.sample(mo_ids, int(len(mo_ids) * 0.8)))
_logger.info("Confirm %d MO with BoM" % len(mo_to_confirm))
mo_to_confirm.action_confirm()
# Uncomment this line to confirm a part of MO, can be useful to check performance
# confirm_bom_mo(0.8)
return productions
def _populate_factories(self):
now = datetime.now()
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
products = self.env['product.product'].browse(self.env.registry.populated_models['product.product'])
product_ids = products.filtered(lambda product: product.type in ('product', 'consu')).ids
boms = self.env['mrp.bom'].browse(self.env.registry.populated_models['mrp.bom'])
boms_by_company = defaultdict(OrderedSet)
for bom in boms:
boms_by_company[bom.company_id.id].add(bom.id)
boms_by_company = {company_id: self.env['mrp.bom'].browse(boms) for company_id, boms in boms_by_company.items()}
boms_by_company = {
company_id: boms | boms_by_company.get(False, self.env['mrp.bom'])
for company_id, boms in boms_by_company.items()}
def get_bom_id(values, counter, random):
if random.random() > 0.7: # 30 % of prototyping
return False
return random.choice(boms_by_company[values['company_id']]).id
def get_consumption(values, counter, random):
if not values['bom_id']:
return 'flexible'
return self.env['mrp.bom'].browse(values['bom_id']).consumption
def get_product_id(values, counter, random):
if not values['bom_id']:
return random.choice(product_ids)
bom = self.env['mrp.bom'].browse(values['bom_id'])
return bom.product_id.id or random.choice(bom.product_tmpl_id.product_variant_ids.ids)
def get_product_uom_id(values, counter, random):
product = self.env['product.product'].browse(values['product_id'])
return product.uom_id.id
# Fetch all stock picking type and group then by company_id
manu_picking_types = self.env['stock.picking.type'].search([('code', '=', 'mrp_operation')])
manu_picking_types_by_company_id = defaultdict(OrderedSet)
for picking_type in manu_picking_types:
manu_picking_types_by_company_id[picking_type.company_id.id].add(picking_type.id)
manu_picking_types_by_company_id = {company_id: list(picking_ids) for company_id, picking_ids in manu_picking_types_by_company_id.items()}
def get_picking_type_id(values, counter, random):
return random.choice(manu_picking_types_by_company_id[values['company_id']])
def get_location_src_id(values, counter, random):
# TODO : add some randomness
picking_type = self.env['stock.picking.type'].browse(values['picking_type_id'])
return picking_type.default_location_src_id.id
def get_location_dest_id(values, counter, random):
# TODO : add some randomness
picking_type = self.env['stock.picking.type'].browse(values['picking_type_id'])
return picking_type.default_location_dest_id.id
def get_date_planned_start(values, counter, random):
# 95.45 % of picking scheduled between (-10, 30) days and follow a gauss distribution (only +-15% picking is late)
delta = random.gauss(10, 10)
return now + timedelta(days=delta)
return [
('company_id', populate.iterate(company_ids)),
('bom_id', populate.compute(get_bom_id)),
('consumption', populate.compute(get_consumption)),
('product_id', populate.compute(get_product_id)),
('product_uom_id', populate.compute(get_product_uom_id)),
('product_qty', populate.randint(1, 10)),
('picking_type_id', populate.compute(get_picking_type_id)),
('date_planned_start', populate.compute(get_date_planned_start)),
('location_src_id', populate.compute(get_location_src_id)),
('location_dest_id', populate.compute(get_location_dest_id)),
('priority', populate.iterate(['0', '1'], [0.95, 0.05])),
]
class StockMove(models.Model):
_inherit = 'stock.move'
_populate_dependencies = ['stock.picking', 'mrp.production']
def _populate(self, size):
moves = super()._populate(size)
def confirm_prototype_mo(sample_ratio):
# Confirm X % of prototype MO
random = populate.Random('confirm_prototype_mo')
mo_ids = moves.raw_material_production_id.ids
mo_to_confirm = self.env['mrp.production'].browse(random.sample(mo_ids, int(len(mo_ids) * 0.8)))
_logger.info("Confirm %d of prototype MO" % len(mo_to_confirm))
mo_to_confirm.action_confirm()
# (Un)comment this line to confirm a part of prototype MO, can be useful to check performance
# confirm_prototype_mo(0.8)
return moves.exists() # Confirm Mo can unlink moves
def _populate_attach_record_weight(self):
fields, weight = super()._populate_attach_record_weight()
return fields + ['raw_material_production_id'], weight + [1]
def _populate_attach_record_generator(self):
productions = self.env['mrp.production'].browse(self.env.registry.populated_models['mrp.production'])
productions = productions.filtered(lambda prod: not prod.bom_id)
def next_production_id():
while productions:
yield from productions.ids
return {**super()._populate_attach_record_generator(), 'raw_material_production_id': next_production_id()}
def _populate_factories(self):
def _compute_production_values(iterator, field_name, model_name):
for values in iterator:
if values.get('raw_material_production_id'):
production = self.env['mrp.production'].browse(values['raw_material_production_id'])
values['location_id'] = production.location_src_id.id
values['location_dest_id'] = production.production_location_id.id
values['picking_type_id'] = production.picking_type_id.id
values['name'] = production.name
values['date'] = production.date_planned_start
values['company_id'] = production.company_id.id
yield values
return super()._populate_factories() + [
('_compute_production_values', _compute_production_values),
]
| 47.04918 | 20,090 |
27,805 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form
from odoo.addons.mrp.tests.common import TestMrpCommon
import logging
_logger = logging.getLogger(__name__)
class TestTraceability(TestMrpCommon):
TRACKING_TYPES = ['none', 'serial', 'lot']
def _create_product(self, tracking):
return self.env['product.product'].create({
'name': 'Product %s' % tracking,
'type': 'product',
'tracking': tracking,
'categ_id': self.env.ref('product.product_category_all').id,
})
def test_tracking_types_on_mo(self):
finished_no_track = self._create_product('none')
finished_lot = self._create_product('lot')
finished_serial = self._create_product('serial')
consumed_no_track = self._create_product('none')
consumed_lot = self._create_product('lot')
consumed_serial = self._create_product('serial')
stock_id = self.env.ref('stock.stock_location_stock').id
Lot = self.env['stock.production.lot']
# create inventory
quants = self.env['stock.quant'].create({
'location_id': stock_id,
'product_id': consumed_no_track.id,
'inventory_quantity': 3
})
quants |= self.env['stock.quant'].create({
'location_id': stock_id,
'product_id': consumed_lot.id,
'inventory_quantity': 3,
'lot_id': Lot.create({'name': 'L1', 'product_id': consumed_lot.id, 'company_id': self.env.company.id}).id
})
quants |= self.env['stock.quant'].create({
'location_id': stock_id,
'product_id': consumed_serial.id,
'inventory_quantity': 1,
'lot_id': Lot.create({'name': 'S1', 'product_id': consumed_serial.id, 'company_id': self.env.company.id}).id
})
quants |= self.env['stock.quant'].create({
'location_id': stock_id,
'product_id': consumed_serial.id,
'inventory_quantity': 1,
'lot_id': Lot.create({'name': 'S2', 'product_id': consumed_serial.id, 'company_id': self.env.company.id}).id
})
quants |= self.env['stock.quant'].create({
'location_id': stock_id,
'product_id': consumed_serial.id,
'inventory_quantity': 1,
'lot_id': Lot.create({'name': 'S3', 'product_id': consumed_serial.id, 'company_id': self.env.company.id}).id
})
quants.action_apply_inventory()
for finished_product in [finished_no_track, finished_lot, finished_serial]:
bom = self.env['mrp.bom'].create({
'product_id': finished_product.id,
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_uom_id': self.env.ref('uom.product_uom_unit').id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': consumed_no_track.id, 'product_qty': 1}),
(0, 0, {'product_id': consumed_lot.id, 'product_qty': 1}),
(0, 0, {'product_id': consumed_serial.id, 'product_qty': 1}),
],
})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished_product
mo_form.bom_id = bom
mo_form.product_uom_id = self.env.ref('uom.product_uom_unit')
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
mo.action_assign()
# Start MO production
mo_form = Form(mo)
mo_form.qty_producing = 1
if finished_product.tracking != 'none':
mo_form.lot_producing_id = self.env['stock.production.lot'].create({'name': 'Serial or Lot finished', 'product_id': finished_product.id, 'company_id': self.env.company.id})
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(mo.move_raw_ids[2], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
details_operation_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check results of traceability
context = ({
'active_id': mo.id,
'model': 'mrp.production',
})
lines = self.env['stock.traceability.report'].with_context(context).get_lines()
self.assertEqual(len(lines), 1, "Should always return 1 line : the final product")
final_product = lines[0]
self.assertEqual(final_product['unfoldable'], True, "Final product should always be unfoldable")
# Find parts of the final products
lines = self.env['stock.traceability.report'].get_lines(final_product['id'], **{
'level': final_product['level'],
'model_id': final_product['model_id'],
'model_name': final_product['model'],
})
self.assertEqual(len(lines), 3, "There should be 3 lines. 1 for untracked, 1 for lot, and 1 for serial")
for line in lines:
tracking = line['columns'][1].split(' ')[1]
self.assertEqual(
line['columns'][-1], "1.00 Units", 'Part with tracking type "%s", should have quantity = 1' % (tracking)
)
unfoldable = False if tracking == 'none' else True
self.assertEqual(
line['unfoldable'],
unfoldable,
'Parts with tracking type "%s", should have be unfoldable : %s' % (tracking, unfoldable)
)
def test_tracking_on_byproducts(self):
product_final = self.env['product.product'].create({
'name': 'Finished Product',
'type': 'product',
'tracking': 'serial',
})
product_1 = self.env['product.product'].create({
'name': 'Raw 1',
'type': 'product',
'tracking': 'serial',
})
product_2 = self.env['product.product'].create({
'name': 'Raw 2',
'type': 'product',
'tracking': 'serial',
})
byproduct_1 = self.env['product.product'].create({
'name': 'Byproduct 1',
'type': 'product',
'tracking': 'serial',
})
byproduct_2 = self.env['product.product'].create({
'name': 'Byproduct 2',
'type': 'product',
'tracking': 'serial',
})
bom_1 = self.env['mrp.bom'].create({
'product_id': product_final.id,
'product_tmpl_id': product_final.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_1.id, 'product_qty': 1}),
(0, 0, {'product_id': product_2.id, 'product_qty': 1})
],
'byproduct_ids': [
(0, 0, {'product_id': byproduct_1.id, 'product_qty': 1, 'product_uom_id': byproduct_1.uom_id.id}),
(0, 0, {'product_id': byproduct_2.id, 'product_qty': 1, 'product_uom_id': byproduct_2.uom_id.id})
]})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_final
mo_form.bom_id = bom_1
mo_form.product_qty = 2
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
mo_form.lot_producing_id = self.env['stock.production.lot'].create({
'product_id': product_final.id,
'name': 'Final_lot_1',
'company_id': self.env.company.id,
})
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': product_1.id,
'name': 'Raw_1_lot_1',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': product_2.id,
'name': 'Raw_2_lot_1',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(
mo.move_finished_ids.filtered(lambda m: m.product_id == byproduct_1),
view=self.env.ref('stock.view_stock_move_operations')
)
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': byproduct_1.id,
'name': 'Byproduct_1_lot_1',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(
mo.move_finished_ids.filtered(lambda m: m.product_id == byproduct_2),
view=self.env.ref('stock.view_stock_move_operations')
)
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': byproduct_2.id,
'name': 'Byproduct_2_lot_1',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo_backorder = mo.procurement_group_id.mrp_production_ids[-1]
mo_form = Form(mo_backorder)
mo_form.lot_producing_id = self.env['stock.production.lot'].create({
'product_id': product_final.id,
'name': 'Final_lot_2',
'company_id': self.env.company.id,
})
mo_form.qty_producing = 1
mo_backorder = mo_form.save()
details_operation_form = Form(
mo_backorder.move_raw_ids.filtered(lambda m: m.product_id == product_1),
view=self.env.ref('stock.view_stock_move_operations')
)
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': product_1.id,
'name': 'Raw_1_lot_2',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(
mo_backorder.move_raw_ids.filtered(lambda m: m.product_id == product_2),
view=self.env.ref('stock.view_stock_move_operations')
)
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': product_2.id,
'name': 'Raw_2_lot_2',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(
mo_backorder.move_finished_ids.filtered(lambda m: m.product_id == byproduct_1),
view=self.env.ref('stock.view_stock_move_operations')
)
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': byproduct_1.id,
'name': 'Byproduct_1_lot_2',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(
mo_backorder.move_finished_ids.filtered(lambda m: m.product_id == byproduct_2),
view=self.env.ref('stock.view_stock_move_operations')
)
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.env['stock.production.lot'].create({
'product_id': byproduct_2.id,
'name': 'Byproduct_2_lot_2',
'company_id': self.env.company.id,
})
ml.qty_done = 1
details_operation_form.save()
mo_backorder.button_mark_done()
# self.assertEqual(len(mo.move_raw_ids.mapped('move_line_ids')), 4)
# self.assertEqual(len(mo.move_finished_ids.mapped('move_line_ids')), 6)
mo = mo | mo_backorder
raw_move_lines = mo.move_raw_ids.mapped('move_line_ids')
raw_line_raw_1_lot_1 = raw_move_lines.filtered(lambda ml: ml.lot_id.name == 'Raw_1_lot_1')
self.assertEqual(set(raw_line_raw_1_lot_1.produce_line_ids.lot_id.mapped('name')), set(['Final_lot_1', 'Byproduct_1_lot_1', 'Byproduct_2_lot_1']))
raw_line_raw_2_lot_1 = raw_move_lines.filtered(lambda ml: ml.lot_id.name == 'Raw_2_lot_1')
self.assertEqual(set(raw_line_raw_2_lot_1.produce_line_ids.lot_id.mapped('name')), set(['Final_lot_1', 'Byproduct_1_lot_1', 'Byproduct_2_lot_1']))
finished_move_lines = mo.move_finished_ids.mapped('move_line_ids')
finished_move_line_lot_1 = finished_move_lines.filtered(lambda ml: ml.lot_id.name == 'Final_lot_1')
self.assertEqual(finished_move_line_lot_1.consume_line_ids.filtered(lambda l: l.qty_done), raw_line_raw_1_lot_1 | raw_line_raw_2_lot_1)
finished_move_line_lot_2 = finished_move_lines.filtered(lambda ml: ml.lot_id.name == 'Final_lot_2')
raw_line_raw_1_lot_2 = raw_move_lines.filtered(lambda ml: ml.lot_id.name == 'Raw_1_lot_2')
raw_line_raw_2_lot_2 = raw_move_lines.filtered(lambda ml: ml.lot_id.name == 'Raw_2_lot_2')
self.assertEqual(finished_move_line_lot_2.consume_line_ids, raw_line_raw_1_lot_2 | raw_line_raw_2_lot_2)
byproduct_move_line_1_lot_1 = finished_move_lines.filtered(lambda ml: ml.lot_id.name == 'Byproduct_1_lot_1')
self.assertEqual(byproduct_move_line_1_lot_1.consume_line_ids.filtered(lambda l: l.qty_done), raw_line_raw_1_lot_1 | raw_line_raw_2_lot_1)
byproduct_move_line_1_lot_2 = finished_move_lines.filtered(lambda ml: ml.lot_id.name == 'Byproduct_1_lot_2')
self.assertEqual(byproduct_move_line_1_lot_2.consume_line_ids, raw_line_raw_1_lot_2 | raw_line_raw_2_lot_2)
byproduct_move_line_2_lot_1 = finished_move_lines.filtered(lambda ml: ml.lot_id.name == 'Byproduct_2_lot_1')
self.assertEqual(byproduct_move_line_2_lot_1.consume_line_ids.filtered(lambda l: l.qty_done), raw_line_raw_1_lot_1 | raw_line_raw_2_lot_1)
byproduct_move_line_2_lot_2 = finished_move_lines.filtered(lambda ml: ml.lot_id.name == 'Byproduct_2_lot_2')
self.assertEqual(byproduct_move_line_2_lot_2.consume_line_ids, raw_line_raw_1_lot_2 | raw_line_raw_2_lot_2)
def test_reuse_unbuilt_usn(self):
"""
Produce a SN product
Unbuilt it
Produce a new SN product with same lot
"""
mo, bom, p_final, p1, p2 = self.generate_mo(qty_base_1=1, qty_base_2=1, qty_final=1, tracking_final='serial')
stock_location = self.env.ref('stock.stock_location_stock')
self.env['stock.quant']._update_available_quantity(p1, stock_location, 1)
self.env['stock.quant']._update_available_quantity(p2, stock_location, 1)
mo.action_assign()
lot = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
mo_form = Form(mo)
mo_form.qty_producing = 1.0
mo_form.lot_producing_id = lot
mo = mo_form.save()
mo.button_mark_done()
unbuild_form = Form(self.env['mrp.unbuild'])
unbuild_form.mo_id = mo
unbuild_form.lot_id = lot
unbuild_form.save().action_unbuild()
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = bom
mo = mo_form.save()
mo.action_confirm()
with self.assertLogs(level="WARNING") as log_catcher:
mo_form = Form(mo)
mo_form.qty_producing = 1.0
mo_form.lot_producing_id = lot
mo = mo_form.save()
_logger.warning('Dummy')
self.assertEqual(len(log_catcher.output), 1, "Useless warnings: \n%s" % "\n".join(log_catcher.output[:-1]))
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
def test_tracked_and_manufactured_component(self):
"""
Suppose this structure:
productA --|- 1 x productB --|- 1 x productC
with productB tracked by lot
Ensure that, when we already have some qty of productB (with different lots),
the user can produce several productA and can then produce some productB again
"""
stock_location = self.env.ref('stock.stock_location_stock')
productA, productB, productC = self.env['product.product'].create([{
'name': 'Product A',
'type': 'product',
}, {
'name': 'Product B',
'type': 'product',
'tracking': 'lot',
}, {
'name': 'Product C',
'type': 'consu',
}])
lot_B01, lot_B02, lot_B03 = self.env['stock.production.lot'].create([{
'name': 'lot %s' % i,
'product_id': productB.id,
'company_id': self.env.company.id,
} for i in [1, 2, 3]])
self.env['mrp.bom'].create([{
'product_id': finished.id,
'product_tmpl_id': finished.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [(0, 0, {'product_id': component.id, 'product_qty': 1})],
} for finished, component in [(productA, productB), (productB, productC)]])
self.env['stock.quant']._update_available_quantity(productB, stock_location, 10, lot_id=lot_B01)
self.env['stock.quant']._update_available_quantity(productB, stock_location, 5, lot_id=lot_B02)
# Produce 15 x productA
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = productA
mo_form.product_qty = 15
mo = mo_form.save()
mo.action_confirm()
action = mo.button_mark_done()
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
wizard.process()
# Produce 15 x productB
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = productB
mo_form.product_qty = 15
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 15
mo_form.lot_producing_id = lot_B03
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(lot_B01.product_qty, 0)
self.assertEqual(lot_B02.product_qty, 0)
self.assertEqual(lot_B03.product_qty, 15)
self.assertEqual(productA.qty_available, 15)
def test_last_delivery_traceability(self):
"""
Suppose this structure (-> means 'produces')
1 x Subcomponent A -> 1 x Component A -> 1 x EndProduct A
All three tracked by lots. Ensure that after validating Picking A (out)
for EndProduct A, all three lots' delivery_ids are set to
Picking A.
"""
stock_location = self.env.ref('stock.stock_location_stock')
customer_location = self.env.ref('stock.stock_location_customers')
# Create the three lot-tracked products.
subcomponentA = self._create_product('lot')
componentA = self._create_product('lot')
endproductA = self._create_product('lot')
# Create production lots.
lot_subcomponentA, lot_componentA, lot_endProductA = self.env['stock.production.lot'].create([{
'name': 'lot %s' % product,
'product_id': product.id,
'company_id': self.env.company.id,
} for product in (subcomponentA, componentA, endproductA)])
# Create two boms, one for Component A and one for EndProduct A
self.env['mrp.bom'].create([{
'product_id': finished.id,
'product_tmpl_id': finished.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [(0, 0, {'product_id': component.id, 'product_qty': 1})],
} for finished, component in [(endproductA, componentA), (componentA, subcomponentA)]])
self.env['stock.quant']._update_available_quantity(subcomponentA, stock_location, 1, lot_id=lot_subcomponentA)
# Produce 1 component A
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = componentA
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 1
mo_form.lot_producing_id = lot_componentA
mo = mo_form.save()
mo.move_raw_ids[0].quantity_done = 1.0
mo.button_mark_done()
# Produce 1 endProduct A
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = endproductA
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 1
mo_form.lot_producing_id = lot_endProductA
mo = mo_form.save()
mo.move_raw_ids[0].quantity_done = 1.0
mo.button_mark_done()
# Create out picking for EndProduct A
pickingA_out = self.env['stock.picking'].create({
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': stock_location.id,
'location_dest_id': customer_location.id})
moveA = self.env['stock.move'].create({
'name': 'Picking A move',
'product_id': endproductA.id,
'product_uom_qty': 1,
'product_uom': endproductA.uom_id.id,
'picking_id': pickingA_out.id,
'location_id': stock_location.id,
'location_dest_id': customer_location.id})
# Confirm and assign pickingA
pickingA_out.action_confirm()
pickingA_out.action_assign()
# Set move_line lot_id to the mrp.production lot_producing_id
moveA.move_line_ids[0].write({
'qty_done': 1.0,
'lot_id': lot_endProductA.id,
})
# Transfer picking
pickingA_out._action_done()
# Use concat so that delivery_ids is computed in batch.
for lot in lot_subcomponentA.concat(lot_componentA, lot_endProductA):
self.assertEqual(lot.delivery_ids.ids, pickingA_out.ids)
def test_unbuild_scrap_and_unscrap_tracked_component(self):
"""
Suppose a tracked-by-SN component C. There is one C in stock with SN01.
Build a product P that uses C with SN, unbuild P, scrap SN, unscrap SN
and rebuild a product with SN in the components
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
stock_location = warehouse.lot_stock_id
component = self.bom_4.bom_line_ids.product_id
component.write({
'type': 'product',
'tracking': 'serial',
})
serial_number = self.env['stock.production.lot'].create({
'product_id': component.id,
'name': 'Super Serial',
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(component, stock_location, 1, lot_id=serial_number)
# produce 1
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_4
mo = mo_form.save()
mo.action_confirm()
mo.action_assign()
self.assertEqual(mo.move_raw_ids.move_line_ids.lot_id, serial_number)
with Form(mo) as mo_form:
mo_form.qty_producing = 1
mo.move_raw_ids.move_line_ids.qty_done = 1
mo.button_mark_done()
# unbuild
action = mo.button_unbuild()
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
wizard.action_validate()
# scrap the component
scrap = self.env['stock.scrap'].create({
'product_id': component.id,
'product_uom_id': component.uom_id.id,
'scrap_qty': 1,
'lot_id': serial_number.id,
})
scrap_location = scrap.scrap_location_id
scrap.do_scrap()
# unscrap the component
internal_move = self.env['stock.move'].create({
'name': component.name,
'location_id': scrap_location.id,
'location_dest_id': stock_location.id,
'product_id': component.id,
'product_uom': component.uom_id.id,
'product_uom_qty': 1.0,
'move_line_ids': [(0, 0, {
'product_id': component.id,
'location_id': scrap_location.id,
'location_dest_id': stock_location.id,
'product_uom_id': component.uom_id.id,
'qty_done': 1.0,
'lot_id': serial_number.id,
})],
})
internal_move._action_confirm()
internal_move._action_done()
# produce one with the unscrapped component
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_4
mo = mo_form.save()
mo.action_confirm()
mo.action_assign()
self.assertEqual(mo.move_raw_ids.move_line_ids.lot_id, serial_number)
with Form(mo) as mo_form:
mo_form.qty_producing = 1
mo.move_raw_ids.move_line_ids.qty_done = 1
mo.button_mark_done()
self.assertRecordValues((mo.move_finished_ids + mo.move_raw_ids).move_line_ids, [
{'product_id': self.bom_4.product_id.id, 'lot_id': False, 'qty_done': 1},
{'product_id': component.id, 'lot_id': serial_number.id, 'qty_done': 1},
])
def test_generate_serial_button(self):
"""Test if lot in form "00000dd" is manually created, the generate serial
button can skip it and create the next one.
"""
mo, _bom, p_final, _p1, _p2 = self.generate_mo(qty_base_1=1, qty_base_2=1, qty_final=1, tracking_final='lot')
# generate lot lot_0 on MO
mo.action_generate_serial()
lot_0 = mo.lot_producing_id.name
# manually create lot_1 (lot_0 + 1)
lot_1 = self.env['stock.production.lot'].create({
'name': str(int(lot_0) + 1).zfill(7),
'product_id': p_final.id,
'company_id': self.env.company.id,
}).name
# generate lot lot_2 on a new MO
mo = mo.copy()
mo.action_confirm()
mo.action_generate_serial()
lot_2 = mo.lot_producing_id.name
self.assertEqual(lot_2, str(int(lot_1) + 1).zfill(7))
| 43.581505 | 27,805 |
26,888 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestMrpProductionBackorder(TestMrpCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.stock_location = cls.env.ref('stock.stock_location_stock')
def setUp(self):
super().setUp()
warehouse_form = Form(self.env['stock.warehouse'])
warehouse_form.name = 'Test Warehouse'
warehouse_form.code = 'TWH'
self.warehouse = warehouse_form.save()
def test_no_tracking_1(self):
"""Create a MO for 4 product. Produce 4. The backorder button should
not appear and hitting mark as done should not open the backorder wizard.
The name of the MO should be MO/001.
"""
mo = self.generate_mo(qty_final=4)[0]
mo_form = Form(mo)
mo_form.qty_producing = 4
mo = mo_form.save()
# No backorder is proposed
self.assertTrue(mo.button_mark_done())
self.assertEqual(mo._get_quantity_to_backorder(), 0)
self.assertTrue("-001" not in mo.name)
def test_no_tracking_2(self):
"""Create a MO for 4 product. Produce 1. The backorder button should
appear and hitting mark as done should open the backorder wizard. In the backorder
wizard, choose to do the backorder. A new MO for 3 self.untracked_bom should be
created.
The sequence of the first MO should be MO/001-01, the sequence of the second MO
should be MO/001-02.
Check that all MO are reachable through the procurement group.
"""
production, _, _, product_to_use_1, _ = self.generate_mo(qty_final=4, qty_base_1=3)
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reserve_visible, True)
# Make some stock and reserve
for product in production.move_raw_ids.product_id:
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'inventory_quantity': 100,
'location_id': production.location_src_id.id,
})._apply_inventory()
production.action_assign()
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reserve_visible, False)
mo_form = Form(production)
mo_form.qty_producing = 1
production = mo_form.save()
action = production.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
# Two related MO to the procurement group
self.assertEqual(len(production.procurement_group_id.mrp_production_ids), 2)
# Check MO backorder
mo_backorder = production.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(mo_backorder.product_id.id, production.product_id.id)
self.assertEqual(mo_backorder.product_qty, 3)
self.assertEqual(sum(mo_backorder.move_raw_ids.filtered(lambda m: m.product_id.id == product_to_use_1.id).mapped("product_uom_qty")), 9)
self.assertEqual(mo_backorder.reserve_visible, False) # the reservation of the first MO should've been moved here
def test_backorder_and_orderpoint(self):
""" Same as test_no_tracking_2, except one of components also has an orderpoint (i.e. reordering rule)
and not enough components are in stock (i.e. so orderpoint is triggered)."""
production, _, product_to_build, product_to_use_1, product_to_use_2 = self.generate_mo(qty_final=4, qty_base_1=1)
# Make some stock and reserve
for product in production.move_raw_ids.product_id:
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'inventory_quantity': 1,
'location_id': production.location_src_id.id,
})
production.action_assign()
self.env['stock.warehouse.orderpoint'].create({
'name': 'product_to_use_1 RR',
'location_id': production.location_src_id.id,
'product_id': product_to_use_1.id,
'product_min_qty': 1,
'product_max_qty': 5,
})
self.env['mrp.bom'].create({
'product_id': product_to_use_1.id,
'product_tmpl_id': product_to_use_1.product_tmpl_id.id,
'product_uom_id': product_to_use_1.uom_id.id,
'product_qty': 1.0,
'type': 'normal',
'consumption': 'flexible',
'bom_line_ids': [
(0, 0, {'product_id': product_to_use_2.id, 'product_qty': 1.0})
]})
product_to_use_1.write({'route_ids': [(4, self.ref('mrp.route_warehouse0_manufacture'))]})
mo_form = Form(production)
mo_form.qty_producing = 1
production = mo_form.save()
action = production.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
# Two related MO, orig + backorder, in same the procurement group
mos = self.env['mrp.production'].search([
('product_id', '=', product_to_build.id),
])
self.assertEqual(len(mos), 2, "Backorder was not created.")
self.assertEqual(len(production.procurement_group_id.mrp_production_ids), 2, "MO backorder not linked to original MO")
# Orderpoint MO is NOT part of procurement group
mo_orderpoint = self.env['mrp.production'].search([
('product_id', '=', product_to_use_1.id),
])
self.assertEqual(len(mo_orderpoint.procurement_group_id.mrp_production_ids), 1, "Reordering rule MO incorrectly linked to other MOs")
def test_no_tracking_pbm_1(self):
"""Create a MO for 4 product. Produce 1. The backorder button should
appear and hitting mark as done should open the backorder wizard. In the backorder
wizard, choose to do the backorder. A new MO for 3 self.untracked_bom should be
created.
The sequence of the first MO should be MO/001-01, the sequence of the second MO
should be MO/001-02.
Check that all MO are reachable through the procurement group.
"""
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm'
production, _, product_to_build, product_to_use_1, product_to_use_2 = self.generate_mo(qty_base_1=4, qty_final=4, picking_type_id=self.warehouse.manu_type_id)
move_raw_ids = production.move_raw_ids
self.assertEqual(len(move_raw_ids), 2)
self.assertEqual(set(move_raw_ids.mapped("product_id")), {product_to_use_1, product_to_use_2})
pbm_move = move_raw_ids.move_orig_ids
self.assertEqual(len(pbm_move), 2)
self.assertEqual(set(pbm_move.mapped("product_id")), {product_to_use_1, product_to_use_2})
self.assertFalse(pbm_move.move_orig_ids)
mo_form = Form(production)
mo_form.qty_producing = 1
production = mo_form.save()
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_1.id).mapped("product_qty")), 16)
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_2.id).mapped("product_qty")), 4)
action = production.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo_backorder = production.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(mo_backorder.delivery_count, 1)
pbm_move |= mo_backorder.move_raw_ids.move_orig_ids
# Check that quantity is correct
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_1.id).mapped("product_qty")), 16)
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_2.id).mapped("product_qty")), 4)
self.assertFalse(pbm_move.move_orig_ids)
def test_no_tracking_pbm_sam_1(self):
"""Create a MO for 4 product. Produce 1. The backorder button should
appear and hitting mark as done should open the backorder wizard. In the backorder
wizard, choose to do the backorder. A new MO for 3 self.untracked_bom should be
created.
The sequence of the first MO should be MO/001-01, the sequence of the second MO
should be MO/001-02.
Check that all MO are reachable through the procurement group.
"""
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
production, _, product_to_build, product_to_use_1, product_to_use_2 = self.generate_mo(qty_base_1=4, qty_final=4, picking_type_id=self.warehouse.manu_type_id)
move_raw_ids = production.move_raw_ids
self.assertEqual(len(move_raw_ids), 2)
self.assertEqual(set(move_raw_ids.mapped("product_id")), {product_to_use_1, product_to_use_2})
pbm_move = move_raw_ids.move_orig_ids
self.assertEqual(len(pbm_move), 2)
self.assertEqual(set(pbm_move.mapped("product_id")), {product_to_use_1, product_to_use_2})
self.assertFalse(pbm_move.move_orig_ids)
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_1.id).mapped("product_qty")), 16)
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_2.id).mapped("product_qty")), 4)
sam_move = production.move_finished_ids.move_dest_ids
self.assertEqual(len(sam_move), 1)
self.assertEqual(sam_move.product_id.id, product_to_build.id)
self.assertEqual(sum(sam_move.mapped("product_qty")), 4)
mo_form = Form(production)
mo_form.qty_producing = 1
production = mo_form.save()
action = production.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo_backorder = production.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(mo_backorder.delivery_count, 2)
pbm_move |= mo_backorder.move_raw_ids.move_orig_ids
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_1.id).mapped("product_qty")), 16)
self.assertEqual(sum(pbm_move.filtered(lambda m: m.product_id.id == product_to_use_2.id).mapped("product_qty")), 4)
sam_move |= mo_backorder.move_finished_ids.move_orig_ids
self.assertEqual(sum(sam_move.mapped("product_qty")), 4)
def test_tracking_backorder_series_lot_1(self):
""" Create a MO of 4 tracked products. all component is tracked by lots
Produce one by one with one bakorder for each until end.
"""
nb_product_todo = 4
production, _, p_final, p1, p2 = self.generate_mo(qty_final=nb_product_todo, tracking_final='lot', tracking_base_1='lot', tracking_base_2='lot')
lot_final = self.env['stock.production.lot'].create({
'name': 'lot_final',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
lot_1 = self.env['stock.production.lot'].create({
'name': 'lot_consumed_1',
'product_id': p1.id,
'company_id': self.env.company.id,
})
lot_2 = self.env['stock.production.lot'].create({
'name': 'lot_consumed_2',
'product_id': p2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, nb_product_todo*4, lot_id=lot_1)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, nb_product_todo, lot_id=lot_2)
production.action_assign()
active_production = production
for i in range(nb_product_todo):
details_operation_form = Form(active_production.move_raw_ids.filtered(lambda m: m.product_id == p1), view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 4
ml.lot_id = lot_1
details_operation_form.save()
details_operation_form = Form(active_production.move_raw_ids.filtered(lambda m: m.product_id == p2), view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
ml.lot_id = lot_2
details_operation_form.save()
production_form = Form(active_production)
production_form.qty_producing = 1
production_form.lot_producing_id = lot_final
active_production = production_form.save()
active_production.button_mark_done()
if i + 1 != nb_product_todo: # If last MO, don't make a backorder
action = active_production.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
active_production = active_production.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final), nb_product_todo, f'You should have the {nb_product_todo} final product in stock')
self.assertEqual(len(production.procurement_group_id.mrp_production_ids), nb_product_todo)
def test_tracking_backorder_series_serial_1(self):
""" Create a MO of 4 tracked products (serial) with pbm_sam.
all component is tracked by serial
Produce one by one with one bakorder for each until end.
"""
nb_product_todo = 4
production, _, p_final, p1, p2 = self.generate_mo(qty_final=nb_product_todo, tracking_final='serial', tracking_base_1='serial', tracking_base_2='serial', qty_base_1=1)
serials_final, serials_p1, serials_p2 = [], [], []
for i in range(nb_product_todo):
serials_final.append(self.env['stock.production.lot'].create({
'name': f'lot_final_{i}',
'product_id': p_final.id,
'company_id': self.env.company.id,
}))
serials_p1.append(self.env['stock.production.lot'].create({
'name': f'lot_consumed_1_{i}',
'product_id': p1.id,
'company_id': self.env.company.id,
}))
serials_p2.append(self.env['stock.production.lot'].create({
'name': f'lot_consumed_2_{i}',
'product_id': p2.id,
'company_id': self.env.company.id,
}))
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 1, lot_id=serials_p1[-1])
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 1, lot_id=serials_p2[-1])
production.action_assign()
active_production = production
for i in range(nb_product_todo):
details_operation_form = Form(active_production.move_raw_ids.filtered(lambda m: m.product_id == p1), view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
ml.lot_id = serials_p1[i]
details_operation_form.save()
details_operation_form = Form(active_production.move_raw_ids.filtered(lambda m: m.product_id == p2), view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
ml.lot_id = serials_p2[i]
details_operation_form.save()
production_form = Form(active_production)
production_form.qty_producing = 1
production_form.lot_producing_id = serials_final[i]
active_production = production_form.save()
active_production.button_mark_done()
if i + 1 != nb_product_todo: # If last MO, don't make a backorder
action = active_production.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
active_production = active_production.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), nb_product_todo, f'You should have the {nb_product_todo} final product in stock')
self.assertEqual(len(production.procurement_group_id.mrp_production_ids), nb_product_todo)
def test_tracking_backorder_immediate_production_serial_1(self):
""" Create a MO to build 2 of a SN tracked product.
Build both the starting MO and its backorder as immediate productions
(i.e. Mark As Done without setting SN/filling any quantities)
"""
mo, _, p_final, p1, p2 = self.generate_mo(qty_final=2, tracking_final='serial', qty_base_1=2, qty_base_2=2)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 2.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 2.0)
mo.action_assign()
res_dict = mo.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
immediate_wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
res_dict = immediate_wizard.process()
self.assertEqual(res_dict.get('res_model'), 'mrp.production.backorder')
backorder_wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context']))
# backorder should automatically open
action = backorder_wizard.save().action_backorder()
self.assertEqual(action.get('res_model'), 'mrp.production')
backorder_mo_form = Form(self.env[action['res_model']].with_context(action['context']).browse(action['res_id']))
backorder_mo = backorder_mo_form.save()
res_dict = backorder_mo.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
immediate_wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
immediate_wizard.process()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 2, "Incorrect number of final product produced.")
self.assertEqual(len(self.env['stock.production.lot'].search([('product_id', '=', p_final.id)])), 2, "Serial Numbers were not correctly produced.")
def test_backorder_name(self):
def produce_one(mo):
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
return mo.procurement_group_id.mrp_production_ids[-1]
default_picking_type_id = self.env['mrp.production']._get_default_picking_type()
default_picking_type = self.env['stock.picking.type'].browse(default_picking_type_id)
mo_sequence = default_picking_type.sequence_id
mo_sequence.prefix = "WH-MO-"
initial_mo_name = mo_sequence.prefix + str(mo_sequence.number_next_actual).zfill(mo_sequence.padding)
production = self.generate_mo(qty_final=5)[0]
self.assertEqual(production.name, initial_mo_name)
backorder = produce_one(production)
self.assertEqual(production.name, initial_mo_name + "-001")
self.assertEqual(backorder.name, initial_mo_name + "-002")
backorder.backorder_sequence = 998
for seq in [998, 999, 1000]:
new_backorder = produce_one(backorder)
self.assertEqual(backorder.name, initial_mo_name + "-" + str(seq))
self.assertEqual(new_backorder.name, initial_mo_name + "-" + str(seq + 1))
backorder = new_backorder
def test_backorder_name_without_procurement_group(self):
production = self.generate_mo(qty_final=5)[0]
mo_form = Form(production)
mo_form.qty_producing = 1
mo = mo_form.save()
# Remove pg to trigger fallback on backorder name
mo.procurement_group_id = False
action = mo.button_mark_done()
backorder_form = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder_form.save().action_backorder()
# The pg is back
self.assertTrue(production.procurement_group_id)
backorder_ids = production.procurement_group_id.mrp_production_ids[1]
self.assertEqual(production.name.split('-')[0], backorder_ids.name.split('-')[0])
self.assertEqual(int(production.name.split('-')[1]) + 1, int(backorder_ids.name.split('-')[1]))
def test_reservation_method_w_mo(self):
""" Create a MO for 2 units, Produce 1 and create a backorder.
The MO and the backorder should be assigned according to the reservation method
defined in the default manufacturing operation type
"""
def create_mo(date_planned_start=False):
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.bom_1.product_id
mo_form.bom_id = self.bom_1
mo_form.product_qty = 2
if date_planned_start:
mo_form.date_planned_start = date_planned_start
mo = mo_form.save()
mo.action_confirm()
return mo
def produce_one(mo):
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
return mo.procurement_group_id.mrp_production_ids[-1]
# Make some stock and reserve
for product in self.bom_1.bom_line_ids.product_id:
product.type = 'product'
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'inventory_quantity': 100,
'location_id': self.stock_location.id,
})._apply_inventory()
default_picking_type_id = self.env['mrp.production']._get_default_picking_type()
default_picking_type = self.env['stock.picking.type'].browse(default_picking_type_id)
# make sure generated MO will auto-assign
default_picking_type.reservation_method = 'at_confirm'
production = create_mo()
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reserve_visible, False)
# check whether the backorder follows the same scenario as the original MO
backorder = produce_one(production)
self.assertEqual(backorder.state, 'confirmed')
self.assertEqual(backorder.reserve_visible, False)
# make sure generated MO will does not auto-assign
default_picking_type.reservation_method = 'manual'
production = create_mo()
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reserve_visible, True)
backorder = produce_one(production)
self.assertEqual(backorder.state, 'confirmed')
self.assertEqual(backorder.reserve_visible, True)
# make sure generated MO auto-assigns according to scheduled date
default_picking_type.reservation_method = 'by_date'
default_picking_type.reservation_days_before = 2
# too early for scheduled date => don't auto-assign
production = create_mo(datetime.now() + timedelta(days=10))
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reserve_visible, True)
backorder = produce_one(production)
self.assertEqual(backorder.state, 'confirmed')
self.assertEqual(backorder.reserve_visible, True)
# within scheduled date + reservation days before => auto-assign
production = create_mo()
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reserve_visible, False)
backorder = produce_one(production)
self.assertEqual(backorder.state, 'confirmed')
self.assertEqual(backorder.reserve_visible, False)
class TestMrpWorkorderBackorder(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestMrpWorkorderBackorder, cls).setUpClass()
cls.uom_unit = cls.env['uom.uom'].search([
('category_id', '=', cls.env.ref('uom.product_uom_categ_unit').id),
('uom_type', '=', 'reference')
], limit=1)
cls.finished1 = cls.env['product.product'].create({
'name': 'finished1',
'type': 'product',
})
cls.compfinished1 = cls.env['product.product'].create({
'name': 'compfinished1',
'type': 'product',
})
cls.compfinished2 = cls.env['product.product'].create({
'name': 'compfinished2',
'type': 'product',
})
cls.workcenter1 = cls.env['mrp.workcenter'].create({
'name': 'workcenter1',
})
cls.workcenter2 = cls.env['mrp.workcenter'].create({
'name': 'workcenter2',
})
cls.bom_finished1 = cls.env['mrp.bom'].create({
'product_id': cls.finished1.id,
'product_tmpl_id': cls.finished1.product_tmpl_id.id,
'product_uom_id': cls.uom_unit.id,
'product_qty': 1,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.compfinished1.id, 'product_qty': 1}),
(0, 0, {'product_id': cls.compfinished2.id, 'product_qty': 1}),
],
'operation_ids': [
(0, 0, {'sequence': 1, 'name': 'finished operation 1', 'workcenter_id': cls.workcenter1.id}),
(0, 0, {'sequence': 2, 'name': 'finished operation 2', 'workcenter_id': cls.workcenter2.id}),
],
})
cls.bom_finished1.bom_line_ids[0].operation_id = cls.bom_finished1.operation_ids[0].id
cls.bom_finished1.bom_line_ids[1].operation_id = cls.bom_finished1.operation_ids[1].id
| 49.977695 | 26,888 |
5,640 |
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 datetime import datetime, timedelta
from odoo.fields import Datetime as Dt
from odoo.exceptions import UserError
from odoo.addons.mrp.tests.common import TestMrpCommon
class TestMrpCancelMO(TestMrpCommon):
def test_cancel_mo_without_routing_1(self):
""" Cancel a Manufacturing Order with no routing, no production.
"""
# Create MO
manufacturing_order = self.generate_mo()[0]
# Do nothing, cancel it
manufacturing_order.action_cancel()
# Check the MO and its moves are cancelled
self.assertEqual(manufacturing_order.state, 'cancel', "MO should be in cancel state.")
self.assertEqual(manufacturing_order.move_raw_ids[0].state, 'cancel',
"Cancelled MO raw moves must be cancelled as well.")
self.assertEqual(manufacturing_order.move_raw_ids[1].state, 'cancel',
"Cancelled MO raw moves must be cancelled as well.")
self.assertEqual(manufacturing_order.move_finished_ids.state, 'cancel',
"Cancelled MO finished move must be cancelled as well.")
def test_cancel_mo_without_routing_2(self):
""" Cancel a Manufacturing Order with no routing but some productions.
"""
# Create MO
manufacturing_order = self.generate_mo()[0]
# Produce some quantity
mo_form = Form(manufacturing_order)
mo_form.qty_producing = 2
manufacturing_order = mo_form.save()
# Cancel it
manufacturing_order.action_cancel()
# Check it's cancelled
self.assertEqual(manufacturing_order.state, 'cancel', "MO should be in cancel state.")
self.assertEqual(manufacturing_order.move_raw_ids[0].state, 'cancel',
"Cancelled MO raw moves must be cancelled as well.")
self.assertEqual(manufacturing_order.move_raw_ids[1].state, 'cancel',
"Cancelled MO raw moves must be cancelled as well.")
self.assertEqual(manufacturing_order.move_finished_ids.state, 'cancel',
"Cancelled MO finished move must be cancelled as well.")
def test_cancel_mo_without_routing_3(self):
""" Cancel a Manufacturing Order with no routing but some productions
after post inventory.
"""
# Create MO
manufacturing_order = self.generate_mo(consumption='strict')[0]
# Produce some quantity (not all to avoid to done the MO when post inventory)
mo_form = Form(manufacturing_order)
mo_form.qty_producing = 2
manufacturing_order = mo_form.save()
# Post Inventory
manufacturing_order._post_inventory()
# Cancel the MO
manufacturing_order.action_cancel()
# Check MO is marked as done and its SML are done or cancelled
self.assertEqual(manufacturing_order.state, 'done', "MO should be in done state.")
self.assertEqual(manufacturing_order.move_raw_ids[0].state, 'done',
"Due to 'post_inventory', some move raw must stay in done state")
self.assertEqual(manufacturing_order.move_raw_ids[1].state, 'done',
"Due to 'post_inventory', some move raw must stay in done state")
self.assertEqual(manufacturing_order.move_raw_ids[2].state, 'cancel',
"The other move raw are cancelled like their MO.")
self.assertEqual(manufacturing_order.move_raw_ids[3].state, 'cancel',
"The other move raw are cancelled like their MO.")
self.assertEqual(manufacturing_order.move_finished_ids[0].state, 'done',
"Due to 'post_inventory', a move finished must stay in done state")
self.assertEqual(manufacturing_order.move_finished_ids[1].state, 'cancel',
"The other move finished is cancelled like its MO.")
def test_unlink_mo(self):
""" Try to unlink a Manufacturing Order, and check it's possible or not
depending of the MO state (must be in cancel state to be unlinked, but
the unlink method will try to cancel MO before unlink them).
"""
# Case #1: Create MO, do nothing and try to unlink it (can be deleted)
manufacturing_order = self.generate_mo()[0]
self.assertEqual(manufacturing_order.exists().state, 'confirmed')
manufacturing_order.unlink()
# Check the MO is deleted.
self.assertEqual(manufacturing_order.exists().state, False)
# Case #2: Create MO, make and post some production, then try to unlink
# it (cannot be deleted)
manufacturing_order = self.generate_mo()[0]
# Produce some quantity (not all to avoid to done the MO when post inventory)
mo_form = Form(manufacturing_order)
mo_form.qty_producing = 2
manufacturing_order = mo_form.save()
# Post Inventory
manufacturing_order._post_inventory()
# Unlink the MO must raises an UserError since it cannot be really cancelled
self.assertEqual(manufacturing_order.exists().state, 'progress')
with self.assertRaises(UserError):
manufacturing_order.unlink()
def test_cancel_mo_without_component(self):
product_form = Form(self.env['product.product'])
product_form.name = "SuperProduct"
product = product_form.save()
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product
mo = mo_form.save()
mo.action_confirm()
mo.action_cancel()
self.assertEqual(mo.move_finished_ids.state, 'cancel')
self.assertEqual(mo.state, 'cancel')
| 47.79661 | 5,640 |
30,600 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form, tagged
from odoo.addons.mrp.tests.common import TestMrpCommon
@tagged('post_install', '-at_install')
class TestMultistepManufacturingWarehouse(TestMrpCommon):
def setUp(self):
super(TestMultistepManufacturingWarehouse, self).setUp()
# Create warehouse
self.customer_location = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers')
warehouse_form = Form(self.env['stock.warehouse'])
warehouse_form.name = 'Test Warehouse'
warehouse_form.code = 'TWH'
self.warehouse = warehouse_form.save()
self.uom_unit = self.env.ref('uom.product_uom_unit')
# Create manufactured product
product_form = Form(self.env['product.product'])
product_form.name = 'Stick'
product_form.uom_id = self.uom_unit
product_form.uom_po_id = self.uom_unit
product_form.detailed_type = 'product'
product_form.route_ids.clear()
product_form.route_ids.add(self.warehouse.manufacture_pull_id.route_id)
product_form.route_ids.add(self.warehouse.mto_pull_id.route_id)
self.finished_product = product_form.save()
# Create raw product for manufactured product
product_form = Form(self.env['product.product'])
product_form.name = 'Raw Stick'
product_form.detailed_type = 'product'
product_form.uom_id = self.uom_unit
product_form.uom_po_id = self.uom_unit
self.raw_product = product_form.save()
# Create bom for manufactured product
bom_product_form = Form(self.env['mrp.bom'])
bom_product_form.product_id = self.finished_product
bom_product_form.product_tmpl_id = self.finished_product.product_tmpl_id
bom_product_form.product_qty = 1.0
bom_product_form.type = 'normal'
with bom_product_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.raw_product
bom_line.product_qty = 2.0
self.bom = bom_product_form.save()
def _check_location_and_routes(self):
# Check manufacturing pull rule.
self.assertTrue(self.warehouse.manufacture_pull_id)
self.assertTrue(self.warehouse.manufacture_pull_id.active, self.warehouse.manufacture_to_resupply)
self.assertTrue(self.warehouse.manufacture_pull_id.route_id)
# Check new routes created or not.
self.assertTrue(self.warehouse.pbm_route_id)
# Check location should be created and linked to warehouse.
self.assertTrue(self.warehouse.pbm_loc_id)
self.assertEqual(self.warehouse.pbm_loc_id.active, self.warehouse.manufacture_steps != 'mrp_one_step', "Input location must be de-active for single step only.")
self.assertTrue(self.warehouse.manu_type_id.active)
def test_00_create_warehouse(self):
""" Warehouse testing for direct manufacturing """
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'mrp_one_step'
self._check_location_and_routes()
# Check locations of existing pull rule
self.assertFalse(self.warehouse.pbm_route_id.rule_ids, 'only the update of global manufacture route should happen.')
self.assertEqual(self.warehouse.manufacture_pull_id.location_id.id, self.warehouse.lot_stock_id.id)
def test_01_warehouse_twostep_manufacturing(self):
""" Warehouse testing for picking before manufacturing """
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm'
self._check_location_and_routes()
self.assertEqual(len(self.warehouse.pbm_route_id.rule_ids), 2)
self.assertEqual(self.warehouse.manufacture_pull_id.location_id.id, self.warehouse.lot_stock_id.id)
def test_02_warehouse_twostep_manufacturing(self):
""" Warehouse testing for picking ans store after manufacturing """
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
self._check_location_and_routes()
self.assertEqual(len(self.warehouse.pbm_route_id.rule_ids), 3)
self.assertEqual(self.warehouse.manufacture_pull_id.location_id.id, self.warehouse.sam_loc_id.id)
def test_manufacturing_3_steps(self):
""" Test MO/picking before manufacturing/picking after manufacturing
components and move_orig/move_dest. Ensure that everything is created
correctly.
"""
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.finished_product
production_form.picking_type_id = self.warehouse.manu_type_id
production = production_form.save()
production.action_confirm()
move_raw_ids = production.move_raw_ids
self.assertEqual(len(move_raw_ids), 1)
self.assertEqual(move_raw_ids.product_id, self.raw_product)
self.assertEqual(move_raw_ids.picking_type_id, self.warehouse.manu_type_id)
pbm_move = move_raw_ids.move_orig_ids
self.assertEqual(len(pbm_move), 1)
self.assertEqual(pbm_move.location_id, self.warehouse.lot_stock_id)
self.assertEqual(pbm_move.location_dest_id, self.warehouse.pbm_loc_id)
self.assertEqual(pbm_move.picking_type_id, self.warehouse.pbm_type_id)
self.assertFalse(pbm_move.move_orig_ids)
move_finished_ids = production.move_finished_ids
self.assertEqual(len(move_finished_ids), 1)
self.assertEqual(move_finished_ids.product_id, self.finished_product)
self.assertEqual(move_finished_ids.picking_type_id, self.warehouse.manu_type_id)
sam_move = move_finished_ids.move_dest_ids
self.assertEqual(len(sam_move), 1)
self.assertEqual(sam_move.location_id, self.warehouse.sam_loc_id)
self.assertEqual(sam_move.location_dest_id, self.warehouse.lot_stock_id)
self.assertEqual(sam_move.picking_type_id, self.warehouse.sam_type_id)
self.assertFalse(sam_move.move_dest_ids)
def test_manufacturing_flow(self):
""" Simulate a pick pack ship delivery combined with a picking before
manufacturing and store after manufacturing. Also ensure that the MO and
the moves to stock are created with the generic pull rules.
In order to trigger the rule we create a picking to the customer with
the 'make to order' procure method
"""
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
warehouse.delivery_steps = 'pick_pack_ship'
self.warehouse.flush()
self.env.ref('stock.route_warehouse0_mto').active = True
self.env['stock.quant']._update_available_quantity(self.raw_product, self.warehouse.lot_stock_id, 4.0)
picking_customer = self.env['stock.picking'].create({
'location_id': self.warehouse.wh_output_stock_loc_id.id,
'location_dest_id': self.customer_location,
'partner_id': self.env['ir.model.data']._xmlid_to_res_id('base.res_partner_4'),
'picking_type_id': self.warehouse.out_type_id.id,
})
self.env['stock.move'].create({
'name': self.finished_product.name,
'product_id': self.finished_product.id,
'product_uom_qty': 2,
'product_uom': self.uom_unit.id,
'picking_id': picking_customer.id,
'location_id': self.warehouse.wh_output_stock_loc_id.id,
'location_dest_id': self.customer_location,
'procure_method': 'make_to_order',
'origin': 'SOURCEDOCUMENT',
'state': 'draft',
})
picking_customer.action_confirm()
production_order = self.env['mrp.production'].search([('product_id', '=', self.finished_product.id)])
self.assertTrue(production_order)
self.assertEqual(production_order.origin, 'SOURCEDOCUMENT', 'The MO origin should be the SO name')
self.assertNotEqual(production_order.name, 'SOURCEDOCUMENT', 'The MO name should not be the origin of the move')
picking_stock_preprod = self.env['stock.move'].search([
('product_id', '=', self.raw_product.id),
('location_id', '=', self.warehouse.lot_stock_id.id),
('location_dest_id', '=', self.warehouse.pbm_loc_id.id),
('picking_type_id', '=', self.warehouse.pbm_type_id.id)
]).picking_id
picking_stock_postprod = self.env['stock.move'].search([
('product_id', '=', self.finished_product.id),
('location_id', '=', self.warehouse.sam_loc_id.id),
('location_dest_id', '=', self.warehouse.lot_stock_id.id),
('picking_type_id', '=', self.warehouse.sam_type_id.id)
]).picking_id
self.assertTrue(picking_stock_preprod)
self.assertTrue(picking_stock_postprod)
self.assertEqual(picking_stock_preprod.state, 'assigned')
self.assertEqual(picking_stock_postprod.state, 'waiting')
self.assertEqual(picking_stock_preprod.origin, production_order.name, 'The pre-prod origin should be the MO name')
self.assertEqual(picking_stock_postprod.origin, 'SOURCEDOCUMENT', 'The post-prod origin should be the SO name')
picking_stock_preprod.action_assign()
picking_stock_preprod.move_line_ids.qty_done = 4
picking_stock_preprod._action_done()
self.assertFalse(sum(self.env['stock.quant']._gather(self.raw_product, self.warehouse.lot_stock_id).mapped('quantity')))
self.assertTrue(self.env['stock.quant']._gather(self.raw_product, self.warehouse.pbm_loc_id))
production_order.action_assign()
self.assertEqual(production_order.reservation_state, 'assigned')
self.assertEqual(picking_stock_postprod.state, 'waiting')
produce_form = Form(production_order)
produce_form.qty_producing = production_order.product_qty
production_order = produce_form.save()
production_order.button_mark_done()
self.assertFalse(sum(self.env['stock.quant']._gather(self.raw_product, self.warehouse.pbm_loc_id).mapped('quantity')))
self.assertEqual(picking_stock_postprod.state, 'assigned')
picking_stock_pick = self.env['stock.move'].search([
('product_id', '=', self.finished_product.id),
('location_id', '=', self.warehouse.lot_stock_id.id),
('location_dest_id', '=', self.warehouse.wh_pack_stock_loc_id.id),
('picking_type_id', '=', self.warehouse.pick_type_id.id)
]).picking_id
self.assertEqual(picking_stock_pick.move_lines.move_orig_ids.picking_id, picking_stock_postprod)
def test_cancel_propagation(self):
""" Test cancelling moves in a 'picking before
manufacturing' and 'store after manufacturing' process. The propagation of
cancel depends on the default values on each rule of the chain.
"""
self.warehouse.manufacture_steps = 'pbm_sam'
self.warehouse.flush()
self.env['stock.quant']._update_available_quantity(self.raw_product, self.warehouse.lot_stock_id, 4.0)
picking_customer = self.env['stock.picking'].create({
'location_id': self.warehouse.lot_stock_id.id,
'location_dest_id': self.customer_location,
'partner_id': self.env['ir.model.data']._xmlid_to_res_id('base.res_partner_4'),
'picking_type_id': self.warehouse.out_type_id.id,
})
self.env['stock.move'].create({
'name': self.finished_product.name,
'product_id': self.finished_product.id,
'product_uom_qty': 2,
'picking_id': picking_customer.id,
'product_uom': self.uom_unit.id,
'location_id': self.warehouse.lot_stock_id.id,
'location_dest_id': self.customer_location,
'procure_method': 'make_to_order',
})
picking_customer.action_confirm()
production_order = self.env['mrp.production'].search([('product_id', '=', self.finished_product.id)])
self.assertTrue(production_order)
move_stock_preprod = self.env['stock.move'].search([
('product_id', '=', self.raw_product.id),
('location_id', '=', self.warehouse.lot_stock_id.id),
('location_dest_id', '=', self.warehouse.pbm_loc_id.id),
('picking_type_id', '=', self.warehouse.pbm_type_id.id)
])
move_stock_postprod = self.env['stock.move'].search([
('product_id', '=', self.finished_product.id),
('location_id', '=', self.warehouse.sam_loc_id.id),
('location_dest_id', '=', self.warehouse.lot_stock_id.id),
('picking_type_id', '=', self.warehouse.sam_type_id.id)
])
self.assertTrue(move_stock_preprod)
self.assertTrue(move_stock_postprod)
self.assertEqual(move_stock_preprod.state, 'assigned')
self.assertEqual(move_stock_postprod.state, 'waiting')
move_stock_preprod._action_cancel()
self.assertEqual(production_order.state, 'confirmed')
production_order.action_cancel()
self.assertTrue(move_stock_postprod.state, 'cancel')
def test_no_initial_demand(self):
""" Test MO/picking before manufacturing/picking after manufacturing
components and move_orig/move_dest. Ensure that everything is created
correctly.
"""
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.finished_product
production_form.picking_type_id = self.warehouse.manu_type_id
production = production_form.save()
production.move_raw_ids.product_uom_qty = 0
production.action_confirm()
production.action_assign()
self.assertFalse(production.move_raw_ids.move_orig_ids)
self.assertEqual(production.state, 'confirmed')
self.assertEqual(production.reservation_state, 'assigned')
def test_manufacturing_3_steps_flexible(self):
""" Test MO/picking before manufacturing/picking after manufacturing
components and move_orig/move_dest. Ensure that additional moves are put
in picking before manufacturing too.
"""
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
bom = self.env['mrp.bom'].search([
('product_id', '=', self.finished_product.id)
])
new_product = self.env['product.product'].create({
'name': 'New product',
'type': 'product',
})
bom.consumption = 'flexible'
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.finished_product
production_form.picking_type_id = self.warehouse.manu_type_id
production = production_form.save()
production.action_confirm()
production.is_locked = False
production_form = Form(production)
with production_form.move_raw_ids.new() as move:
move.product_id = new_product
move.product_uom_qty = 2
production = production_form.save()
move_raw_ids = production.move_raw_ids
self.assertEqual(len(move_raw_ids), 2)
pbm_move = move_raw_ids.move_orig_ids
self.assertEqual(len(pbm_move), 2)
self.assertTrue(new_product in pbm_move.product_id)
def test_3_steps_and_byproduct(self):
""" Suppose a warehouse with Manufacture option set to '3 setps' and a product P01 with a reordering rule.
Suppose P01 has a BoM and this BoM mentions that when some P01 are produced, some P02 are produced too.
This test ensures that when a MO is generated thanks to the reordering rule, 2 pickings are also
generated:
- One to bring the components
- Another to return the P01 and P02 produced
"""
warehouse = self.warehouse
warehouse.manufacture_steps = 'pbm_sam'
warehouse_stock_location = warehouse.lot_stock_id
pre_production_location = warehouse.pbm_loc_id
post_production_location = warehouse.sam_loc_id
one_unit_uom = self.env.ref('uom.product_uom_unit')
[two_units_uom, four_units_uom] = self.env['uom.uom'].create([{
'name': 'x%s' % i,
'category_id': self.ref('uom.product_uom_categ_unit'),
'uom_type': 'bigger',
'factor_inv': i,
} for i in [2, 4]])
finished_product = self.env['product.product'].create({
'name': 'Super Product',
'route_ids': [(4, self.ref('mrp.route_warehouse0_manufacture'))],
'type': 'product',
})
secondary_product = self.env['product.product'].create({
'name': 'Secondary',
'type': 'product',
})
component = self.env['product.product'].create({
'name': 'Component',
'type': 'consu',
})
self.env['mrp.bom'].create({
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': two_units_uom.id,
'bom_line_ids': [(0, 0, {
'product_id': component.id,
'product_qty': 1,
'product_uom_id': one_unit_uom.id,
})],
'byproduct_ids': [(0, 0, {
'product_id': secondary_product.id,
'product_qty': 1,
'product_uom_id': four_units_uom.id,
})],
})
self.env['stock.warehouse.orderpoint'].create({
'warehouse_id': warehouse.id,
'location_id': warehouse_stock_location.id,
'product_id': finished_product.id,
'product_min_qty': 2,
'product_max_qty': 2,
})
self.env['procurement.group'].run_scheduler()
mo = self.env['mrp.production'].search([('product_id', '=', finished_product.id)])
pickings = mo.picking_ids
self.assertEqual(len(pickings), 2)
preprod_picking = pickings[0] if pickings[0].location_id == warehouse_stock_location else pickings[1]
self.assertEqual(preprod_picking.location_id, warehouse_stock_location)
self.assertEqual(preprod_picking.location_dest_id, pre_production_location)
postprod_picking = pickings - preprod_picking
self.assertEqual(postprod_picking.location_id, post_production_location)
self.assertEqual(postprod_picking.location_dest_id, warehouse_stock_location)
byproduct_postprod_move = self.env['stock.move'].search([
('product_id', '=', secondary_product.id),
('location_id', '=', post_production_location.id),
('location_dest_id', '=', warehouse_stock_location.id),
])
self.assertEqual(byproduct_postprod_move.state, 'waiting')
self.assertEqual(byproduct_postprod_move.group_id.name, mo.name)
def test_manufacturing_3_steps_trigger_reordering_rules(self):
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
with Form(self.raw_product) as p:
p.route_ids.clear()
p.route_ids.add(self.warehouse.manufacture_pull_id.route_id)
# Create an additional BoM for component
product_form = Form(self.env['product.product'])
product_form.name = 'Wood'
product_form.detailed_type = 'product'
product_form.uom_id = self.uom_unit
product_form.uom_po_id = self.uom_unit
self.wood_product = product_form.save()
# Create bom for manufactured product
bom_product_form = Form(self.env['mrp.bom'])
bom_product_form.product_id = self.raw_product
bom_product_form.product_tmpl_id = self.raw_product.product_tmpl_id
bom_product_form.product_qty = 1.0
bom_product_form.type = 'normal'
with bom_product_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.wood_product
bom_line.product_qty = 1.0
bom_product_form.save()
self.env['stock.quant']._update_available_quantity(
self.finished_product, self.warehouse.lot_stock_id, -1.0)
rr_form = Form(self.env['stock.warehouse.orderpoint'])
rr_form.product_id = self.wood_product
rr_form.location_id = self.warehouse.lot_stock_id
rr_form.save()
rr_form = Form(self.env['stock.warehouse.orderpoint'])
rr_form.product_id = self.finished_product
rr_form.location_id = self.warehouse.lot_stock_id
rr_finish = rr_form.save()
rr_form = Form(self.env['stock.warehouse.orderpoint'])
rr_form.product_id = self.raw_product
rr_form.location_id = self.warehouse.lot_stock_id
rr_form.save()
self.env['procurement.group'].run_scheduler()
pickings_component = self.env['stock.picking'].search(
[('product_id', '=', self.wood_product.id)])
self.assertTrue(pickings_component)
self.assertTrue(rr_finish.name in pickings_component.origin)
def test_2_steps_and_additional_moves(self):
""" Suppose a 2-steps configuration. If a user adds a product to an existing draft MO and then
confirms it, the associated picking should includes this new product"""
self.warehouse.manufacture_steps = 'pbm'
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.bom.product_id
mo_form.picking_type_id = self.warehouse.manu_type_id
mo = mo_form.save()
component_move = mo.move_raw_ids[0]
mo.with_context(default_raw_material_production_id=mo.id).move_raw_ids = [
[0, 0, {
'location_id': component_move.location_id.id,
'location_dest_id': component_move.location_dest_id.id,
'picking_type_id': component_move.picking_type_id.id,
'product_id': self.product_2.id,
'name': self.product_2.display_name,
'product_uom_qty': 1,
'product_uom': self.product_2.uom_id.id,
'warehouse_id': component_move.warehouse_id.id,
'raw_material_production_id': mo.id,
}]
]
mo.action_confirm()
self.assertEqual(self.bom.bom_line_ids.product_id + self.product_2, mo.picking_ids.move_lines.product_id)
def test_manufacturing_complex_product_3_steps(self):
""" Test MO/picking after manufacturing a complex product which uses
manufactured components. Ensure that everything is created and picked
correctly.
"""
self.warehouse.mto_pull_id.route_id.active = True
# Creating complex product which trigger another manifacture
routes = self.warehouse.manufacture_pull_id.route_id + self.warehouse.mto_pull_id.route_id
self.complex_product = self.env['product.product'].create({
'name': 'Arrow',
'type': 'product',
'route_ids': [(6, 0, routes.ids)],
})
# Create raw product for manufactured product
self.raw_product_2 = self.env['product.product'].create({
'name': 'Raw Iron',
'type': 'product',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
})
self.finished_product.route_ids = [(6, 0, routes.ids)]
# Create bom for manufactured product
bom_product_form = Form(self.env['mrp.bom'])
bom_product_form.product_id = self.complex_product
bom_product_form.product_tmpl_id = self.complex_product.product_tmpl_id
with bom_product_form.bom_line_ids.new() as line:
line.product_id = self.finished_product
line.product_qty = 1.0
with bom_product_form.bom_line_ids.new() as line:
line.product_id = self.raw_product_2
line.product_qty = 1.0
self.complex_bom = bom_product_form.save()
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.complex_product
production_form.picking_type_id = self.warehouse.manu_type_id
production = production_form.save()
production.action_confirm()
move_raw_ids = production.move_raw_ids
self.assertEqual(len(move_raw_ids), 2)
sfp_move_raw_id, raw_move_raw_id = move_raw_ids
self.assertEqual(sfp_move_raw_id.product_id, self.finished_product)
self.assertEqual(raw_move_raw_id.product_id, self.raw_product_2)
for move_raw_id in move_raw_ids:
self.assertEqual(move_raw_id.picking_type_id, self.warehouse.manu_type_id)
pbm_move = move_raw_id.move_orig_ids
self.assertEqual(len(pbm_move), 1)
self.assertEqual(pbm_move.location_id, self.warehouse.lot_stock_id)
self.assertEqual(pbm_move.location_dest_id, self.warehouse.pbm_loc_id)
self.assertEqual(pbm_move.picking_type_id, self.warehouse.pbm_type_id)
# Check move locations
move_finished_ids = production.move_finished_ids
self.assertEqual(len(move_finished_ids), 1)
self.assertEqual(move_finished_ids.product_id, self.complex_product)
self.assertEqual(move_finished_ids.picking_type_id, self.warehouse.manu_type_id)
sam_move = move_finished_ids.move_dest_ids
self.assertEqual(len(sam_move), 1)
self.assertEqual(sam_move.location_id, self.warehouse.sam_loc_id)
self.assertEqual(sam_move.location_dest_id, self.warehouse.lot_stock_id)
self.assertEqual(sam_move.picking_type_id, self.warehouse.sam_type_id)
self.assertFalse(sam_move.move_dest_ids)
subproduction = self.env['mrp.production'].browse(production.id+1)
sfp_pickings = subproduction.picking_ids.sorted('id')
# SFP Production: 2 pickings, 1 group
self.assertEqual(len(sfp_pickings), 2)
self.assertEqual(sfp_pickings.mapped('group_id'), subproduction.procurement_group_id)
# Move Raw Stick - Stock -> Preprocessing
picking = sfp_pickings[0]
self.assertEqual(len(picking.move_lines), 1)
picking.move_lines[0].product_id = self.raw_product
# Move SFP - PostProcessing -> Stock
picking = sfp_pickings[1]
self.assertEqual(len(picking.move_lines), 1)
picking.move_lines[0].product_id = self.finished_product
# Main production 2 pickings, 1 group
pickings = production.picking_ids.sorted('id')
self.assertEqual(len(pickings), 2)
self.assertEqual(pickings.mapped('group_id'), production.procurement_group_id)
# Move 2 components Stock -> Preprocessing
picking = pickings[0]
self.assertEqual(len(picking.move_lines), 2)
picking.move_lines[0].product_id = self.finished_product
picking.move_lines[1].product_id = self.raw_product_2
# Move FP PostProcessing -> Stock
picking = pickings[1]
self.assertEqual(len(picking.move_lines), 1)
picking.product_id = self.complex_product
def test_child_parent_relationship_on_backorder_creation(self):
""" Test Child Mo and Source Mo in 2/3-step production for reorder
rules in backorder using order points with the help of run scheduler """
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
rr_form = Form(self.env['stock.warehouse.orderpoint'])
rr_form.product_id = self.finished_product
rr_form.product_min_qty = 20
rr_form.product_max_qty = 40
rr_form.save()
self.env['procurement.group'].run_scheduler()
mo = self.env['mrp.production'].search([('product_id', '=', self.finished_product.id)])
mo_form = Form(mo)
mo_form.qty_producing = 20
mo = mo_form.save()
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
self.assertEqual(mo.mrp_production_child_count, 0, "Children MOs counted as existing where there should be none")
self.assertEqual(mo.mrp_production_source_count, 0, "Source MOs counted as existing where there should be none")
self.assertEqual(mo.mrp_production_backorder_count, 2)
def test_manufacturing_bom_from_reordering_rules(self):
"""
Check that the manufacturing order is created with the BoM set in the reording rule:
- Create a product with 2 bill of materials,
- Create an orderpoint for this product specifying the 2nd BoM that must be used,
- Check that the MO has been created with the 2nd BoM
"""
manufacturing_route = self.env['stock.rule'].search([
('action', '=', 'manufacture')]).route_id
with Form(self.warehouse) as warehouse:
warehouse.manufacture_steps = 'pbm_sam'
finished_product = self.env['product.product'].create({
'name': 'Product',
'type': 'product',
'route_ids': manufacturing_route,
})
self.env['mrp.bom'].create({
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': finished_product.uom_id.id,
'type': 'normal',
})
bom_2 = self.env['mrp.bom'].create({
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': finished_product.uom_id.id,
'type': 'normal',
})
self.env['stock.warehouse.orderpoint'].create({
'name': 'Orderpoint for P1',
'product_id': self.finished_product.id,
'product_min_qty': 1,
'product_max_qty': 1,
'route_id': manufacturing_route.id,
'bom_id': bom_2.id,
})
self.env['procurement.group'].run_scheduler()
mo = self.env['mrp.production'].search([('product_id', '=', self.finished_product.id)])
self.assertEqual(len(mo), 1)
self.assertEqual(mo.product_qty, 1.0)
self.assertEqual(mo.bom_id, bom_2)
| 46.932515 | 30,600 |
11,362 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import Form
from odoo.addons.stock.tests.test_report import TestReportsCommon
class TestSaleStockReports(TestReportsCommon):
def test_report_forecast_1_mo_count(self):
""" Creates and configures a product who could be produce and could be a component.
Plans some producing and consumming MO and check the report values.
"""
# Create a variant attribute.
product_chocolate = self.env['product.product'].create({
'name': 'Chocolate',
'type': 'consu',
})
product_chococake = self.env['product.product'].create({
'name': 'Choco Cake',
'type': 'product',
})
product_double_chococake = self.env['product.product'].create({
'name': 'Double Choco Cake',
'type': 'product',
})
# Creates two BOM: one creating a regular slime, one using regular slimes.
bom_chococake = self.env['mrp.bom'].create({
'product_id': product_chococake.id,
'product_tmpl_id': product_chococake.product_tmpl_id.id,
'product_uom_id': product_chococake.uom_id.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_chocolate.id, 'product_qty': 4}),
],
})
bom_double_chococake = self.env['mrp.bom'].create({
'product_id': product_double_chococake.id,
'product_tmpl_id': product_double_chococake.product_tmpl_id.id,
'product_uom_id': product_double_chococake.uom_id.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_chococake.id, 'product_qty': 2}),
],
})
# Creates two MO: one for each BOM.
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_chococake
mo_form.bom_id = bom_chococake
mo_form.product_qty = 10
mo_1 = mo_form.save()
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_double_chococake
mo_form.bom_id = bom_double_chococake
mo_form.product_qty = 2
mo_2 = mo_form.save()
report_values, docs, lines = self.get_report_forecast(product_template_ids=product_chococake.product_tmpl_id.ids)
draft_picking_qty = docs['draft_picking_qty']
draft_production_qty = docs['draft_production_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(draft_production_qty['in'], 10)
self.assertEqual(draft_production_qty['out'], 4)
# Confirms the MO and checks the report lines.
mo_1.action_confirm()
mo_2.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=product_chococake.product_tmpl_id.ids)
draft_picking_qty = docs['draft_picking_qty']
draft_production_qty = docs['draft_production_qty']
self.assertEqual(len(lines), 2, "Must have two line.")
line_1 = lines[0]
line_2 = lines[1]
self.assertEqual(line_1['document_in'].id, mo_1.id)
self.assertEqual(line_1['quantity'], 4)
self.assertEqual(line_1['document_out'].id, mo_2.id)
self.assertEqual(line_2['document_in'].id, mo_1.id)
self.assertEqual(line_2['quantity'], 6)
self.assertEqual(line_2['document_out'], False)
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(draft_production_qty['in'], 0)
self.assertEqual(draft_production_qty['out'], 0)
def test_report_forecast_2_production_backorder(self):
""" Creates a manufacturing order and produces half the quantity.
Then creates a backorder and checks the report.
"""
# Configures the warehouse.
warehouse = self.env.ref('stock.warehouse0')
warehouse.manufacture_steps = 'pbm_sam'
# Configures a product.
product_apple_pie = self.env['product.product'].create({
'name': 'Apple Pie',
'type': 'product',
})
product_apple = self.env['product.product'].create({
'name': 'Apple',
'type': 'consu',
})
bom = self.env['mrp.bom'].create({
'product_id': product_apple_pie.id,
'product_tmpl_id': product_apple_pie.product_tmpl_id.id,
'product_uom_id': product_apple_pie.uom_id.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_apple.id, 'product_qty': 5}),
],
})
# Creates a MO and validates the pick components.
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_apple_pie
mo_form.bom_id = bom
mo_form.product_qty = 4
mo_1 = mo_form.save()
mo_1.action_confirm()
pick = mo_1.move_raw_ids.move_orig_ids.picking_id
pick_form = Form(pick)
with pick_form.move_line_ids_without_package.edit(0) as move_line:
move_line.qty_done = 20
pick = pick_form.save()
pick.button_validate()
# Produces 3 products then creates a backorder for the remaining product.
mo_form = Form(mo_1)
mo_form.qty_producing = 3
mo_1 = mo_form.save()
action = mo_1.button_mark_done()
backorder_form = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder = backorder_form.save()
backorder.action_backorder()
mo_2 = (mo_1.procurement_group_id.mrp_production_ids - mo_1)
# Checks the forecast report.
report_values, docs, lines = self.get_report_forecast(product_template_ids=product_apple_pie.product_tmpl_id.ids)
self.assertEqual(len(lines), 1, "Must have only one line about the backorder")
self.assertEqual(lines[0]['document_in'].id, mo_2.id)
self.assertEqual(lines[0]['quantity'], 1)
self.assertEqual(lines[0]['document_out'], False)
# Produces the last unit.
mo_form = Form(mo_2)
mo_form.qty_producing = 1
mo_2 = mo_form.save()
mo_2.button_mark_done()
# Checks the forecast report.
report_values, docs, lines = self.get_report_forecast(product_template_ids=product_apple_pie.product_tmpl_id.ids)
self.assertEqual(len(lines), 0, "Must have no line")
def test_report_forecast_3_report_line_corresponding_to_mo_highlighted(self):
""" When accessing the report from a MO, checks if the correct MO is highlighted in the report
"""
product_banana = self.env['product.product'].create({
'name': 'Banana',
'type': 'product',
})
product_chocolate = self.env['product.product'].create({
'name': 'Chocolate',
'type': 'consu',
})
# We create 2 identical MO
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_banana
mo_form.product_qty = 10
with mo_form.move_raw_ids.new() as move:
move.product_id = product_chocolate
mo_1 = mo_form.save()
mo_2 = mo_1.copy()
(mo_1 | mo_2).action_confirm()
# Check for both MO if the highlight (is_matched) corresponds to the correct MO
for mo in [mo_1, mo_2]:
context = mo.action_product_forecast_report()['context']
_, _, lines = self.get_report_forecast(product_template_ids=product_banana.product_tmpl_id.ids, context=context)
for line in lines:
if line['document_in'] == mo:
self.assertTrue(line['is_matched'], "The corresponding MO line should be matched in the forecast report.")
else:
self.assertFalse(line['is_matched'], "A line of the forecast report not linked to the MO shoud not be matched.")
def test_subkit_in_delivery_slip(self):
"""
Suppose this structure:
Super Kit --|- Compo 01 x1
|- Sub Kit x1 --|- Compo 02 x1
| |- Compo 03 x1
This test ensures that, when delivering one Super Kit, one Sub Kit, one Compo 01 and one Compo 02,
and when putting in pack the third component of the Super Kit, the delivery report is correct.
"""
compo01, compo02, compo03, subkit, superkit = self.env['product.product'].create([{
'name': n,
'type': 'consu',
} for n in ['Compo 01', 'Compo 02', 'Compo 03', 'Sub Kit', 'Super Kit']])
self.env['mrp.bom'].create([{
'product_tmpl_id': subkit.product_tmpl_id.id,
'product_qty': 1,
'type': 'phantom',
'bom_line_ids': [
(0, 0, {'product_id': compo02.id, 'product_qty': 1}),
(0, 0, {'product_id': compo03.id, 'product_qty': 1}),
],
}, {
'product_tmpl_id': superkit.product_tmpl_id.id,
'product_qty': 1,
'type': 'phantom',
'bom_line_ids': [
(0, 0, {'product_id': compo01.id, 'product_qty': 1}),
(0, 0, {'product_id': subkit.id, 'product_qty': 1}),
],
}])
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.picking_type_out
picking_form.partner_id = self.partner
with picking_form.move_ids_without_package.new() as move:
move.product_id = superkit
move.product_uom_qty = 1
with picking_form.move_ids_without_package.new() as move:
move.product_id = subkit
move.product_uom_qty = 1
with picking_form.move_ids_without_package.new() as move:
move.product_id = compo01
move.product_uom_qty = 1
with picking_form.move_ids_without_package.new() as move:
move.product_id = compo02
move.product_uom_qty = 1
picking = picking_form.save()
picking.action_confirm()
picking.move_lines.quantity_done = 1
move = picking.move_lines.filtered(lambda m: m.name == "Super Kit" and m.product_id == compo03)
move.move_line_ids.result_package_id = self.env['stock.quant.package'].create({'name': 'Package0001'})
picking.button_validate()
report = self.env['ir.actions.report']._get_report_from_name('stock.report_deliveryslip')
html_report = report._render_qweb_html(picking.ids)[0].decode('utf-8').split('\n')
keys = [
"Package0001", "Compo 03",
"Products with no package assigned", "Compo 01", "Compo 02",
"Super Kit", "Compo 01",
"Sub Kit", "Compo 02", "Compo 03",
]
for line in html_report:
if not keys:
break
if keys[0] in line:
keys = keys[1:]
self.assertFalse(keys, "All keys should be in the report with the defined order")
| 44.210117 | 11,362 |
3,870 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.tests import Form
from odoo.exceptions import UserError
class TestMrpSerialMassProduce(TestMrpCommon):
def test_smp_serial(self):
"""Create a MO for a product not tracked by serial number.
The smp wizard should not open.
"""
mo = self.generate_mo()[0]
self.assertEqual(mo.state, 'confirmed')
res = mo.action_serial_mass_produce_wizard()
self.assertFalse(res)
def test_smp_no_serial_component(self):
"""Create a MO for a product tracked by serial number with a component also tracked by serial number.
An error should be throwed.
"""
mo = self.generate_mo(tracking_final='serial', tracking_base_2='serial')[0]
with self.assertRaises(UserError):
mo.action_serial_mass_produce_wizard()
def test_smp_produce_all(self):
"""Create a MO for a product tracked by serial number.
Open the smp wizard, generate all serial numbers to produce all quantitites.
"""
mo = self.generate_mo(tracking_final='serial')[0]
count = mo.product_qty
# Make some stock and reserve
for product in mo.move_raw_ids.product_id:
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'inventory_quantity': 100,
'location_id': mo.location_src_id.id,
})._apply_inventory()
mo.action_assign()
# Open the wizard
action = mo.action_serial_mass_produce_wizard()
wizard = Form(self.env['stock.assign.serial'].with_context(**action['context']))
# Let the wizard generate all serial numbers
wizard.next_serial_number = "sn#1"
wizard.next_serial_count = count
action = wizard.save().generate_serial_numbers_production()
# Reload the wizard to apply generated serial numbers
wizard = Form(self.env['stock.assign.serial'].browse(action['res_id']))
wizard.save().apply()
# Initial MO should have a backorder-sequenced name and be in to_close state
self.assertTrue("-001" in mo.name)
self.assertEqual(mo.state, "to_close")
# Each generated serial number should have its own mo
self.assertEqual(len(mo.procurement_group_id.mrp_production_ids), count)
def test_smp_produce_all_but_one(self):
"""Create a MO for a product tracked by serial number.
Open the smp wizard, generate all but one serial numbers and create a back order.
"""
mo = self.generate_mo(tracking_final='serial')[0]
count = mo.product_qty
# Make some stock and reserve
for product in mo.move_raw_ids.product_id:
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'inventory_quantity': 100,
'location_id': mo.location_src_id.id,
})._apply_inventory()
mo.action_assign()
action = mo.action_serial_mass_produce_wizard()
wizard = Form(self.env['stock.assign.serial'].with_context(**action['context']))
wizard.next_serial_number = "sn#1"
wizard.next_serial_count = count - 1
action = wizard.save().generate_serial_numbers_production()
# Reload the wizard to create backorder (applying generated serial numbers)
wizard = Form(self.env['stock.assign.serial'].browse(action['res_id']))
wizard.save().create_backorder()
# Last MO in sequence is the backorder
bo = mo.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(bo.backorder_sequence, count)
self.assertEqual(bo.state, "confirmed")
| 47.195122 | 3,870 |
33,401 |
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 import fields
from odoo.tests import Form
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.exceptions import UserError
class TestProcurement(TestMrpCommon):
def test_procurement(self):
"""This test case when create production order check procurement is create"""
# Update BOM
self.bom_3.bom_line_ids.filtered(lambda x: x.product_id == self.product_5).unlink()
self.bom_1.bom_line_ids.filtered(lambda x: x.product_id == self.product_1).unlink()
# Update route
self.warehouse = self.env.ref('stock.warehouse0')
self.warehouse.mto_pull_id.route_id.active = True
route_manufacture = self.warehouse.manufacture_pull_id.route_id.id
route_mto = self.warehouse.mto_pull_id.route_id.id
self.product_4.write({'route_ids': [(6, 0, [route_manufacture, route_mto])]})
# Create production order
# -------------------------
# Product6 Unit 24
# Product4 8 Dozen
# Product2 12 Unit
# -----------------------
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = self.bom_3
production_form.product_qty = 24
production_form.product_uom_id = self.product_6.uom_id
production_product_6 = production_form.save()
production_product_6.action_confirm()
production_product_6.action_assign()
# check production state is Confirmed
self.assertEqual(production_product_6.state, 'confirmed')
# Check procurement for product 4 created or not.
# Check it created a purchase order
move_raw_product4 = production_product_6.move_raw_ids.filtered(lambda x: x.product_id == self.product_4)
produce_product_4 = self.env['mrp.production'].search([('product_id', '=', self.product_4.id),
('move_dest_ids', '=', move_raw_product4[0].id)])
# produce product
self.assertEqual(produce_product_4.reservation_state, 'confirmed', "Consume material not available")
# Create production order
# -------------------------
# Product 4 96 Unit
# Product2 48 Unit
# ---------------------
# Update Inventory
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_2.id,
'inventory_quantity': 48,
'location_id': self.warehouse.lot_stock_id.id,
}).action_apply_inventory()
produce_product_4.action_assign()
self.assertEqual(produce_product_4.product_qty, 8, "Wrong quantity of finish product.")
self.assertEqual(produce_product_4.product_uom_id, self.uom_dozen, "Wrong quantity of finish product.")
self.assertEqual(produce_product_4.reservation_state, 'assigned', "Consume material not available")
# produce product4
# ---------------
mo_form = Form(produce_product_4)
mo_form.qty_producing = produce_product_4.product_qty
produce_product_4 = mo_form.save()
# Check procurement and Production state for product 4.
produce_product_4.button_mark_done()
self.assertEqual(produce_product_4.state, 'done', 'Production order should be in state done')
# Produce product 6
# ------------------
# Update Inventory
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_2.id,
'inventory_quantity': 12,
'location_id': self.warehouse.lot_stock_id.id,
}).action_apply_inventory()
production_product_6.action_assign()
# ------------------------------------
self.assertEqual(production_product_6.reservation_state, 'assigned', "Consume material not available")
mo_form = Form(production_product_6)
mo_form.qty_producing = production_product_6.product_qty
production_product_6 = mo_form.save()
# Check procurement and Production state for product 6.
production_product_6.button_mark_done()
self.assertEqual(production_product_6.state, 'done', 'Production order should be in state done')
self.assertEqual(self.product_6.qty_available, 24, 'Wrong quantity available of finished product.')
def test_procurement_2(self):
"""Check that a manufacturing order create the right procurements when the route are set on
a parent category of a product"""
# find a child category id
all_categ_id = self.env['product.category'].search([('parent_id', '=', None)], limit=1)
child_categ_id = self.env['product.category'].search([('parent_id', '=', all_categ_id.id)], limit=1)
# set the product of `self.bom_1` to this child category
for bom_line_id in self.bom_1.bom_line_ids:
# check that no routes are defined on the product
self.assertEqual(len(bom_line_id.product_id.route_ids), 0)
# set the category of the product to a child category
bom_line_id.product_id.categ_id = child_categ_id
# set the MTO route to the parent category (all)
self.warehouse = self.env.ref('stock.warehouse0')
mto_route = self.warehouse.mto_pull_id.route_id
mto_route.active = True
mto_route.product_categ_selectable = True
all_categ_id.write({'route_ids': [(6, 0, [mto_route.id])]})
# create MO, but check it raises error as components are in make to order and not everyone has
with self.assertRaises(UserError):
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_4
production_form.product_uom_id = self.product_4.uom_id
production_form.product_qty = 1
production_product_4 = production_form.save()
production_product_4.action_confirm()
def test_procurement_3(self):
warehouse = self.env['stock.warehouse'].search([], limit=1)
warehouse.write({'reception_steps': 'three_steps'})
warehouse.mto_pull_id.route_id.active = True
self.env['stock.location']._parent_store_compute()
warehouse.reception_route_id.rule_ids.filtered(
lambda p: p.location_src_id == warehouse.wh_input_stock_loc_id and
p.location_id == warehouse.wh_qc_stock_loc_id).write({
'procure_method': 'make_to_stock'
})
finished_product = self.env['product.product'].create({
'name': 'Finished Product',
'type': 'product',
})
component = self.env['product.product'].create({
'name': 'Component',
'type': 'product',
'route_ids': [(4, warehouse.mto_pull_id.route_id.id)]
})
self.env['stock.quant']._update_available_quantity(component, warehouse.wh_input_stock_loc_id, 100)
bom = self.env['mrp.bom'].create({
'product_id': finished_product.id,
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 1.0})
]})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished_product
mo_form.bom_id = bom
mo_form.product_qty = 5
mo_form.product_uom_id = finished_product.uom_id
mo_form.location_src_id = warehouse.lot_stock_id
mo = mo_form.save()
mo.action_confirm()
pickings = self.env['stock.picking'].search([('product_id', '=', component.id)])
self.assertEqual(len(pickings), 2.0)
picking_input_to_qc = pickings.filtered(lambda p: p.location_id == warehouse.wh_input_stock_loc_id)
picking_qc_to_stock = pickings - picking_input_to_qc
self.assertTrue(picking_input_to_qc)
self.assertTrue(picking_qc_to_stock)
picking_input_to_qc.action_assign()
self.assertEqual(picking_input_to_qc.state, 'assigned')
picking_input_to_qc.move_line_ids.write({'qty_done': 5.0})
picking_input_to_qc._action_done()
picking_qc_to_stock.action_assign()
self.assertEqual(picking_qc_to_stock.state, 'assigned')
picking_qc_to_stock.move_line_ids.write({'qty_done': 3.0})
picking_qc_to_stock.with_context(skip_backorder=True, picking_ids_not_to_backorder=picking_qc_to_stock.ids).button_validate()
self.assertEqual(picking_qc_to_stock.state, 'done')
mo.action_assign()
self.assertEqual(mo.move_raw_ids.reserved_availability, 3.0)
produce_form = Form(mo)
produce_form.qty_producing = 3.0
mo = produce_form.save()
self.assertEqual(mo.move_raw_ids.quantity_done, 3.0)
picking_qc_to_stock.move_line_ids.qty_done = 5.0
self.assertEqual(mo.move_raw_ids.reserved_availability, 5.0)
self.assertEqual(mo.move_raw_ids.quantity_done, 3.0)
def test_link_date_mo_moves(self):
""" Check link of shedule date for manufaturing with date stock move."""
# create a product with manufacture route
product_1 = self.env['product.product'].create({
'name': 'AAA',
'route_ids': [(4, self.ref('mrp.route_warehouse0_manufacture'))]
})
component_1 = self.env['product.product'].create({
'name': 'component',
})
self.env['mrp.bom'].create({
'product_id': product_1.id,
'product_tmpl_id': product_1.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component_1.id, 'product_qty': 1}),
]})
# create a move for product_1 from stock to output and reserve to trigger the
# rule
move_dest = self.env['stock.move'].create({
'name': 'move_orig',
'product_id': product_1.id,
'product_uom': self.ref('uom.product_uom_unit'),
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 10,
'procure_method': 'make_to_order'
})
move_dest._action_confirm()
mo = self.env['mrp.production'].search([
('product_id', '=', product_1.id),
('state', '=', 'confirmed')
])
self.assertAlmostEqual(mo.move_finished_ids.date, mo.move_raw_ids.date + timedelta(hours=1), delta=timedelta(seconds=1))
self.assertEqual(len(mo), 1, 'the manufacture order is not created')
mo_form = Form(mo)
self.assertEqual(mo_form.product_qty, 10, 'the quantity to produce is not good relative to the move')
mo = mo_form.save()
# Confirming mo create finished move
move_orig = self.env['stock.move'].search([
('move_dest_ids', 'in', move_dest.ids)
], limit=1)
self.assertEqual(len(move_orig), 1, 'the move orig is not created')
self.assertEqual(move_orig.product_qty, 10, 'the quantity to produce is not good relative to the move')
new_sheduled_date = fields.Datetime.to_datetime(mo.date_planned_start) + timedelta(days=5)
mo_form = Form(mo)
mo_form.date_planned_start = new_sheduled_date
mo = mo_form.save()
self.assertAlmostEqual(mo.move_raw_ids.date, mo.date_planned_start, delta=timedelta(seconds=1))
self.assertAlmostEqual(mo.move_finished_ids.date, mo.date_planned_finished, delta=timedelta(seconds=1))
def test_finished_move_cancellation(self):
"""Check state of finished move on cancellation of raw moves. """
product_bottle = self.env['product.product'].create({
'name': 'Plastic Bottle',
'route_ids': [(4, self.ref('mrp.route_warehouse0_manufacture'))]
})
component_mold = self.env['product.product'].create({
'name': 'Plastic Mold',
})
self.env['mrp.bom'].create({
'product_id': product_bottle.id,
'product_tmpl_id': product_bottle.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component_mold.id, 'product_qty': 1}),
]})
move_dest = self.env['stock.move'].create({
'name': 'move_bottle',
'product_id': product_bottle.id,
'product_uom': self.ref('uom.product_uom_unit'),
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 10,
'procure_method': 'make_to_order',
})
move_dest._action_confirm()
mo = self.env['mrp.production'].search([
('product_id', '=', product_bottle.id),
('state', '=', 'confirmed')
])
mo.move_raw_ids[0]._action_cancel()
self.assertEqual(mo.state, 'cancel', 'Manufacturing order should be cancelled.')
self.assertEqual(mo.move_finished_ids[0].state, 'cancel', 'Finished move should be cancelled if mo is cancelled.')
self.assertEqual(mo.move_dest_ids[0].state, 'waiting', 'Destination move should not be cancelled if prapogation cancel is False on manufacturing rule.')
def test_procurement_with_empty_bom(self):
"""Ensure that a procurement request using a product with an empty BoM
will create an empty MO in draft state that can be completed afterwards.
"""
self.warehouse = self.env.ref('stock.warehouse0')
route_manufacture = self.warehouse.manufacture_pull_id.route_id.id
route_mto = self.warehouse.mto_pull_id.route_id.id
product = self.env['product.product'].create({
'name': 'Clafoutis',
'route_ids': [(6, 0, [route_manufacture, route_mto])]
})
self.env['mrp.bom'].create({
'product_id': product.id,
'product_tmpl_id': product.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
})
move_dest = self.env['stock.move'].create({
'name': 'Customer MTO Move',
'product_id': product.id,
'product_uom': self.ref('uom.product_uom_unit'),
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 10,
'procure_method': 'make_to_order',
})
move_dest._action_confirm()
production = self.env['mrp.production'].search([('product_id', '=', product.id)])
self.assertTrue(production)
self.assertFalse(production.move_raw_ids)
self.assertEqual(production.state, 'draft')
comp1 = self.env['product.product'].create({
'name': 'egg',
})
move_values = production._get_move_raw_values(comp1, 40.0, self.env.ref('uom.product_uom_unit'))
self.env['stock.move'].create(move_values)
production.action_confirm()
produce_form = Form(production)
produce_form.qty_producing = production.product_qty
production = produce_form.save()
production.button_mark_done()
move_dest._action_assign()
self.assertEqual(move_dest.reserved_availability, 10.0)
def test_auto_assign(self):
""" When auto reordering rule exists, check for when:
1. There is not enough of a manufactured product to assign (reserve for) a picking => auto-create 1st MO
2. There is not enough of a manufactured component to assign the created MO => auto-create 2nd MO
3. Add an extra manufactured component (not in stock) to 1st MO => auto-create 3rd MO
4. When 2nd MO is completed => auto-assign to 1st MO
5. When 1st MO is completed => auto-assign to picking
6. Additionally check that a MO that has component in stock auto-reserves when MO is confirmed (since default setting = 'at_confirm')"""
self.warehouse = self.env.ref('stock.warehouse0')
route_manufacture = self.warehouse.manufacture_pull_id.route_id
product_1 = self.env['product.product'].create({
'name': 'Cake',
'type': 'product',
'route_ids': [(6, 0, [route_manufacture.id])]
})
product_2 = self.env['product.product'].create({
'name': 'Cake Mix',
'type': 'product',
'route_ids': [(6, 0, [route_manufacture.id])]
})
product_3 = self.env['product.product'].create({
'name': 'Flour',
'type': 'consu',
})
bom1 = self.env['mrp.bom'].create({
'product_id': product_1.id,
'product_tmpl_id': product_1.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_2.id, 'product_qty': 1}),
]})
self.env['mrp.bom'].create({
'product_id': product_2.id,
'product_tmpl_id': product_2.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_3.id, 'product_qty': 1}),
]})
# extra manufactured component added to 1st MO after it is already confirmed
product_4 = self.env['product.product'].create({
'name': 'Flavor Enchancer',
'type': 'product',
'route_ids': [(6, 0, [route_manufacture.id])]
})
product_5 = self.env['product.product'].create({
'name': 'MSG',
'type': 'consu',
})
self.env['mrp.bom'].create({
'product_id': product_4.id,
'product_tmpl_id': product_4.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_5.id, 'product_qty': 1}),
]})
# setup auto orderpoints (reordering rules)
self.env['stock.warehouse.orderpoint'].create({
'name': 'Cake RR',
'location_id': self.warehouse.lot_stock_id.id,
'product_id': product_1.id,
'product_min_qty': 0,
'product_max_qty': 5,
})
self.env['stock.warehouse.orderpoint'].create({
'name': 'Cake Mix RR',
'location_id': self.warehouse.lot_stock_id.id,
'product_id': product_2.id,
'product_min_qty': 0,
'product_max_qty': 5,
})
self.env['stock.warehouse.orderpoint'].create({
'name': 'Flavor Enchancer RR',
'location_id': self.warehouse.lot_stock_id.id,
'product_id': product_4.id,
'product_min_qty': 0,
'product_max_qty': 5,
})
# create picking output to trigger creating MO for reordering product_1
pick_output = self.env['stock.picking'].create({
'name': 'Cake Delivery Order',
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.warehouse.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
'move_lines': [(0, 0, {
'name': '/',
'product_id': product_1.id,
'product_uom': product_1.uom_id.id,
'product_uom_qty': 10.00,
'procure_method': 'make_to_stock',
'location_id': self.warehouse.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
})],
})
pick_output.action_confirm() # should trigger orderpoint to create and confirm 1st MO
pick_output.action_assign()
mo = self.env['mrp.production'].search([
('product_id', '=', product_1.id),
('state', '=', 'confirmed')
])
self.assertEqual(len(mo), 1, "Manufacture order was not automatically created")
mo.action_assign()
mo.is_locked = False
self.assertEqual(mo.move_raw_ids.reserved_availability, 0, "No components should be reserved yet")
self.assertEqual(mo.product_qty, 15, "Quantity to produce should be picking demand + reordering rule max qty")
# 2nd MO for product_2 should have been created and confirmed when 1st MO for product_1 was confirmed
mo2 = self.env['mrp.production'].search([
('product_id', '=', product_2.id),
('state', '=', 'confirmed')
])
self.assertEqual(len(mo2), 1, 'Second manufacture order was not created')
self.assertEqual(mo2.product_qty, 20, "Quantity to produce should be MO's 'to consume' qty + reordering rule max qty")
mo2_form = Form(mo2)
mo2_form.qty_producing = 20
mo2 = mo2_form.save()
mo2.button_mark_done()
self.assertEqual(mo.move_raw_ids.reserved_availability, 15, "Components should have been auto-reserved")
# add new component to 1st MO
mo_form = Form(mo)
with mo_form.move_raw_ids.new() as line:
line.product_id = product_4
line.product_uom_qty = 1
mo_form.save() # should trigger orderpoint to create and confirm 3rd MO
mo3 = self.env['mrp.production'].search([
('product_id', '=', product_4.id),
('state', '=', 'confirmed')
])
self.assertEqual(len(mo3), 1, 'Third manufacture order for added component was not created')
self.assertEqual(mo3.product_qty, 6, "Quantity to produce should be 1 + reordering rule max qty")
mo_form = Form(mo)
mo.move_raw_ids.quantity_done = 15
mo_form.qty_producing = 15
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(pick_output.move_ids_without_package.reserved_availability, 10, "Completed products should have been auto-reserved in picking")
# make sure next MO auto-reserves components now that they are in stock since
# default reservation_method = 'at_confirm'
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_1
mo_form.bom_id = bom1
mo_form.product_qty = 5
mo_form.product_uom_id = product_1.uom_id
mo_assign_at_confirm = mo_form.save()
mo_assign_at_confirm.action_confirm()
self.assertEqual(mo_assign_at_confirm.move_raw_ids.reserved_availability, 5, "Components should have been auto-reserved")
def test_check_update_qty_mto_chain(self):
""" Simulate a mto chain with a manufacturing order. Updating the
initial demand should also impact the initial move but not the
linked manufacturing order.
"""
def create_run_procurement(product, product_qty, values=None):
if not values:
values = {
'warehouse_id': picking_type_out.warehouse_id,
'action': 'pull_push',
'group_id': procurement_group,
}
return self.env['procurement.group'].run([self.env['procurement.group'].Procurement(
product, product_qty, self.uom_unit, vendor.property_stock_customer,
product.name, '/', self.env.company, values)
])
picking_type_out = self.env.ref('stock.picking_type_out')
vendor = self.env['res.partner'].create({
'name': 'Roger'
})
# This needs to be tried with MTO route activated
self.env['stock.location.route'].browse(self.ref('stock.route_warehouse0_mto')).action_unarchive()
# Define products requested for this BoM.
product = self.env['product.product'].create({
'name': 'product',
'type': 'product',
'route_ids': [(4, self.ref('stock.route_warehouse0_mto')), (4, self.ref('mrp.route_warehouse0_manufacture'))],
'categ_id': self.env.ref('product.product_category_all').id
})
component = self.env['product.product'].create({
'name': 'component',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id
})
self.env['mrp.bom'].create({
'product_id': product.id,
'product_tmpl_id': product.product_tmpl_id.id,
'product_uom_id': product.uom_id.id,
'product_qty': 1.0,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 1}),
]
})
procurement_group = self.env['procurement.group'].create({
'move_type': 'direct',
'partner_id': vendor.id
})
# Create initial procurement that will generate the initial move and its picking.
create_run_procurement(product, 10, {
'group_id': procurement_group,
'warehouse_id': picking_type_out.warehouse_id,
'partner_id': vendor
})
customer_move = self.env['stock.move'].search([('group_id', '=', procurement_group.id)])
manufacturing_order = self.env['mrp.production'].search([('product_id', '=', product.id)])
self.assertTrue(manufacturing_order, 'No manufacturing order created.')
# Check manufacturing order data.
self.assertEqual(manufacturing_order.product_qty, 10, 'The manufacturing order qty should be the same as the move.')
# Create procurement to decrease quantity in the initial move but not in the related MO.
create_run_procurement(product, -5.00)
self.assertEqual(customer_move.product_uom_qty, 5, 'The demand on the initial move should have been decreased when merged with the procurement.')
self.assertEqual(manufacturing_order.product_qty, 10, 'The demand on the manufacturing order should not have been decreased.')
# Create procurement to increase quantity on the initial move and should create a new MO for the missing qty.
create_run_procurement(product, 2.00)
self.assertEqual(customer_move.product_uom_qty, 5, 'The demand on the initial move should not have been increased since it should be a new move.')
self.assertEqual(manufacturing_order.product_qty, 10, 'The demand on the initial manufacturing order should not have been increased.')
manufacturing_orders = self.env['mrp.production'].search([('product_id', '=', product.id)])
self.assertEqual(len(manufacturing_orders), 2, 'A new MO should have been created for missing demand.')
def test_rr_with_dependance_between_bom(self):
self.warehouse = self.env.ref('stock.warehouse0')
route_mto = self.warehouse.mto_pull_id.route_id
route_mto.active = True
route_manufacture = self.warehouse.manufacture_pull_id.route_id
product_1 = self.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'route_ids': [(6, 0, [route_manufacture.id])]
})
product_2 = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'route_ids': [(6, 0, [route_manufacture.id, route_mto.id])]
})
product_3 = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'route_ids': [(6, 0, [route_manufacture.id])]
})
product_4 = self.env['product.product'].create({
'name': 'Product C',
'type': 'consu',
})
op1 = self.env['stock.warehouse.orderpoint'].create({
'name': 'Product A',
'location_id': self.warehouse.lot_stock_id.id,
'product_id': product_1.id,
'product_min_qty': 1,
'product_max_qty': 20,
})
op2 = self.env['stock.warehouse.orderpoint'].create({
'name': 'Product B',
'location_id': self.warehouse.lot_stock_id.id,
'product_id': product_3.id,
'product_min_qty': 5,
'product_max_qty': 50,
})
self.env['mrp.bom'].create({
'product_id': product_1.id,
'product_tmpl_id': product_1.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [(0, 0, {'product_id': product_2.id, 'product_qty': 1})]
})
self.env['mrp.bom'].create({
'product_id': product_2.id,
'product_tmpl_id': product_2.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [(0, 0, {'product_id': product_3.id, 'product_qty': 1})]
})
self.env['mrp.bom'].create({
'product_id': product_3.id,
'product_tmpl_id': product_3.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [(0, 0, {'product_id': product_4.id, 'product_qty': 1})]
})
(op1 | op2)._procure_orderpoint_confirm()
mo1 = self.env['mrp.production'].search([('product_id', '=', product_1.id)])
mo3 = self.env['mrp.production'].search([('product_id', '=', product_3.id)])
self.assertEqual(len(mo1), 1)
self.assertEqual(len(mo3), 1)
self.assertEqual(mo1.product_qty, 20)
self.assertEqual(mo3.product_qty, 50)
def test_several_boms_same_finished_product(self):
"""
Suppose a product with two BoMs, each one based on a different operation type
This test ensures that, when running the scheduler, the generated MOs are based
on the correct BoMs
"""
warehouse = self.env.ref('stock.warehouse0')
stock_location01 = warehouse.lot_stock_id
stock_location02 = stock_location01.copy()
manu_operation01 = warehouse.manu_type_id
manu_operation02 = manu_operation01.copy()
with Form(manu_operation02) as form:
form.name = 'Manufacturing 02'
form.sequence_code = 'MO2'
form.default_location_dest_id = stock_location02
manu_rule01 = warehouse.manufacture_pull_id
manu_route = manu_rule01.route_id
manu_rule02 = manu_rule01.copy()
with Form(manu_rule02) as form:
form.picking_type_id = manu_operation02
manu_route.rule_ids = [(6, 0, (manu_rule01 + manu_rule02).ids)]
compo01, compo02, finished = self.env['product.product'].create([{
'name': 'compo 01',
'type': 'consu',
}, {
'name': 'compo 02',
'type': 'consu',
}, {
'name': 'finished',
'type': 'product',
'route_ids': [(6, 0, manu_route.ids)],
}])
bom01_form = Form(self.env['mrp.bom'])
bom01_form.product_tmpl_id = finished.product_tmpl_id
bom01_form.code = '01'
bom01_form.picking_type_id = manu_operation01
with bom01_form.bom_line_ids.new() as line:
line.product_id = compo01
bom01 = bom01_form.save()
bom02_form = Form(self.env['mrp.bom'])
bom02_form.product_tmpl_id = finished.product_tmpl_id
bom02_form.code = '02'
bom02_form.picking_type_id = manu_operation02
with bom02_form.bom_line_ids.new() as line:
line.product_id = compo02
bom02 = bom02_form.save()
self.env['stock.warehouse.orderpoint'].create([{
'warehouse_id': warehouse.id,
'location_id': stock_location01.id,
'product_id': finished.id,
'product_min_qty': 1,
'product_max_qty': 1,
}, {
'warehouse_id': warehouse.id,
'location_id': stock_location02.id,
'product_id': finished.id,
'product_min_qty': 2,
'product_max_qty': 2,
}])
self.env['procurement.group'].run_scheduler()
mos = self.env['mrp.production'].search([('product_id', '=', finished.id)], order='origin')
self.assertRecordValues(mos, [
{'product_qty': 1, 'bom_id': bom01.id, 'picking_type_id': manu_operation01.id, 'location_dest_id': stock_location01.id},
{'product_qty': 2, 'bom_id': bom02.id, 'picking_type_id': manu_operation02.id, 'location_dest_id': stock_location02.id},
])
| 44.357238 | 33,401 |
12,208 |
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 import common
from odoo.exceptions import ValidationError
class TestMrpByProduct(common.TransactionCase):
def setUp(self):
super(TestMrpByProduct, self).setUp()
self.MrpBom = self.env['mrp.bom']
self.warehouse = self.env.ref('stock.warehouse0')
route_manufacture = self.warehouse.manufacture_pull_id.route_id.id
route_mto = self.warehouse.mto_pull_id.route_id.id
self.uom_unit_id = self.ref('uom.product_uom_unit')
def create_product(name, route_ids=[]):
return self.env['product.product'].create({
'name': name,
'type': 'product',
'route_ids': route_ids})
# Create product A, B, C.
# --------------------------
self.product_a = create_product('Product A', route_ids=[(6, 0, [route_manufacture, route_mto])])
self.product_b = create_product('Product B', route_ids=[(6, 0, [route_manufacture, route_mto])])
self.product_c_id = create_product('Product C', route_ids=[]).id
self.bom_byproduct = self.MrpBom.create({
'product_tmpl_id': self.product_a.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'normal',
'product_uom_id': self.uom_unit_id,
'bom_line_ids': [(0, 0, {'product_id': self.product_c_id, 'product_uom_id': self.uom_unit_id, 'product_qty': 2})],
'byproduct_ids': [(0, 0, {'product_id': self.product_b.id, 'product_uom_id': self.uom_unit_id, 'product_qty': 1})]
})
def test_00_mrp_byproduct(self):
""" Test by product with production order."""
# Create BOM for product B
# ------------------------
bom_product_b = self.MrpBom.create({
'product_tmpl_id': self.product_b.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'normal',
'product_uom_id': self.uom_unit_id,
'bom_line_ids': [(0, 0, {'product_id': self.product_c_id, 'product_uom_id': self.uom_unit_id, 'product_qty': 2})]
})
# Create production order for product A
# -------------------------------------
mnf_product_a_form = Form(self.env['mrp.production'])
mnf_product_a_form.product_id = self.product_a
mnf_product_a_form.bom_id = self.bom_byproduct
mnf_product_a_form.product_qty = 2.0
mnf_product_a = mnf_product_a_form.save()
mnf_product_a.action_confirm()
# I confirm the production order.
self.assertEqual(mnf_product_a.state, 'confirmed', 'Production order should be in state confirmed')
# Now I check the stock moves for the byproduct I created in the bill of material.
# This move is created automatically when I confirmed the production order.
moves = mnf_product_a.move_raw_ids | mnf_product_a.move_finished_ids
self.assertTrue(moves, 'No moves are created !')
# I consume and produce the production of products.
# I create record for selecting mode and quantity of products to produce.
mo_form = Form(mnf_product_a)
mnf_product_a.move_byproduct_ids.quantity_done = 2
mo_form.qty_producing = 2.00
mnf_product_a = mo_form.save()
# I finish the production order.
self.assertEqual(len(mnf_product_a.move_raw_ids), 1, "Wrong consume move on production order.")
consume_move_c = mnf_product_a.move_raw_ids
by_product_move = mnf_product_a.move_finished_ids.filtered(lambda x: x.product_id.id == self.product_b.id)
# Check sub production produced quantity...
self.assertEqual(consume_move_c.product_uom_qty, 4, "Wrong consumed quantity of product c.")
self.assertEqual(by_product_move.product_uom_qty, 2, "Wrong produced quantity of sub product.")
mnf_product_a._post_inventory()
# I see that stock moves of External Hard Disk including Headset USB are done now.
self.assertFalse(any(move.state != 'done' for move in moves), 'Moves are not done!')
def test_01_mrp_byproduct(self):
self.env["stock.quant"].create({
"product_id": self.product_c_id,
"location_id": self.warehouse.lot_stock_id.id,
"quantity": 4,
})
bom_product_a = self.MrpBom.create({
'product_tmpl_id': self.product_a.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'normal',
'product_uom_id': self.uom_unit_id,
'bom_line_ids': [(0, 0, {'product_id': self.product_c_id, 'product_uom_id': self.uom_unit_id, 'product_qty': 2})]
})
mnf_product_a_form = Form(self.env['mrp.production'])
mnf_product_a_form.product_id = self.product_a
mnf_product_a_form.bom_id = bom_product_a
mnf_product_a_form.product_qty = 2.0
mnf_product_a = mnf_product_a_form.save()
mnf_product_a.action_confirm()
self.assertEqual(mnf_product_a.state, "confirmed")
mnf_product_a.move_raw_ids._action_assign()
mnf_product_a.move_raw_ids.quantity_done = mnf_product_a.move_raw_ids.product_uom_qty
mnf_product_a.move_raw_ids._action_done()
self.assertEqual(mnf_product_a.state, "progress")
mnf_product_a.qty_producing = 2
mnf_product_a.button_mark_done()
self.assertTrue(mnf_product_a.move_finished_ids)
self.assertEqual(mnf_product_a.state, "done")
def test_change_product(self):
""" Create a production order for a specific product with a BoM. Then change the BoM and the finished product for
other ones and check the finished product of the first mo did not became a byproduct of the second one."""
# Create BOM for product A with product B as component
bom_product_a = self.MrpBom.create({
'product_tmpl_id': self.product_a.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'normal',
'product_uom_id': self.uom_unit_id,
'bom_line_ids': [(0, 0, {'product_id': self.product_b.id, 'product_uom_id': self.uom_unit_id, 'product_qty': 2})],
})
bom_product_a_2 = self.MrpBom.create({
'product_tmpl_id': self.product_b.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'normal',
'product_uom_id': self.uom_unit_id,
'bom_line_ids': [(0, 0, {'product_id': self.product_c_id, 'product_uom_id': self.uom_unit_id, 'product_qty': 2})],
})
# Create production order for product A
# -------------------------------------
mnf_product_a_form = Form(self.env['mrp.production'])
mnf_product_a_form.product_id = self.product_a
mnf_product_a_form.bom_id = bom_product_a
mnf_product_a_form.product_qty = 1.0
mnf_product_a = mnf_product_a_form.save()
mnf_product_a_form = Form(mnf_product_a)
mnf_product_a_form.bom_id = bom_product_a_2
mnf_product_a = mnf_product_a_form.save()
self.assertEqual(mnf_product_a.move_raw_ids.product_id.id, self.product_c_id)
self.assertFalse(mnf_product_a.move_byproduct_ids)
def test_byproduct_putaway(self):
"""
Test the byproducts are dispatched correctly with putaway rules. We have
a byproduct P and two sublocations L01, L02 with a capacity constraint:
max 2 x P by location. There is already 1 x P at L01. Process a MO with
2 x P as byproducts. They should be redirected to L02
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
stor_category = self.env['stock.storage.category'].create({
'name': 'Super Storage Category',
'max_weight': 1000,
'product_capacity_ids': [(0, 0, {
'product_id': self.product_b.id,
'quantity': 2,
})]
})
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': stor_category.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': stor_category.id,
})
self.env['stock.putaway.rule'].create({
'product_id': self.product_b.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': stor_category.id,
})
self.env['stock.putaway.rule'].create({
'product_id': self.product_a.id,
'location_in_id': self.stock_location.id,
'location_out_id': shelf2_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product_b, shelf1_location, 1)
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product_a
mo_form.bom_id = self.bom_byproduct
mo_form.product_qty = 2.0
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
with mo_form.move_byproduct_ids.edit(0) as move:
move.quantity_done = 2
mo_form.qty_producing = 2.00
mo = mo_form.save()
mo._post_inventory()
byproduct_move_line = mo.move_byproduct_ids.move_line_ids
finished_move_line = mo.move_finished_ids.filtered(lambda m: m.product_id == self.product_a).move_line_ids
self.assertEqual(byproduct_move_line.location_dest_id, shelf2_location)
self.assertEqual(finished_move_line.location_dest_id, shelf2_location)
def test_check_byproducts_cost_share(self):
"""
Test that byproducts with total cost_share > 100% or a cost_share < 0%
will throw a ValidationError
"""
# Create new MO
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product_a
mo_form.product_qty = 2.0
mo = mo_form.save()
# Create product
self.product_d = self.env['product.product'].create({
'name': 'Product D',
'type': 'product'})
self.product_e = self.env['product.product'].create({
'name': 'Product E',
'type': 'product'})
# Create byproduct
byproduct_1 = self.env['stock.move'].create({
'name': 'By Product 1',
'product_id': self.product_d.id,
'product_uom': self.ref('uom.product_uom_unit'),
'production_id': mo.id,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 0,
'quantity_done': 0
})
byproduct_2 = self.env['stock.move'].create({
'name': 'By Product 2',
'product_id': self.product_e.id,
'product_uom': self.ref('uom.product_uom_unit'),
'production_id': mo.id,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 0,
'quantity_done': 0
})
# Update byproduct has cost share > 100%
with self.assertRaises(ValidationError), self.cr.savepoint():
byproduct_1.cost_share = 120
mo.write({'move_byproduct_ids': [(4, byproduct_1.id)]})
# Update byproduct has cost share < 0%
with self.assertRaises(ValidationError), self.cr.savepoint():
byproduct_1.cost_share = -10
mo.write({'move_byproduct_ids': [(4, byproduct_1.id)]})
# Update byproducts have total cost share > 100%
with self.assertRaises(ValidationError), self.cr.savepoint():
byproduct_1.cost_share = 60
byproduct_2.cost_share = 70
mo.write({'move_byproduct_ids': [(6, 0, [byproduct_1.id, byproduct_2.id])]})
| 46.067925 | 12,208 |
3,555 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta, time
from pytz import timezone, utc
from odoo import fields
from odoo.addons.mrp.tests.common import TestMrpCommon
class TestOee(TestMrpCommon):
def create_productivity_line(self, loss_reason, date_start=False, date_end=False):
return self.env['mrp.workcenter.productivity'].create({
'workcenter_id': self.workcenter_1.id,
'date_start': date_start,
'date_end': date_end,
'loss_id': loss_reason.id,
'description': loss_reason.name
})
def test_wrokcenter_oee(self):
""" Test case workcenter oee. """
day = datetime.date(datetime.today())
# Make the test work the weekend. It will fails due to workcenter working hours.
if day.weekday() in (5, 6):
day -= timedelta(days=2)
tz = timezone(self.workcenter_1.resource_calendar_id.tz)
def time_to_string_utc_datetime(time):
return fields.Datetime.to_string(
tz.localize(datetime.combine(day, time)).astimezone(utc)
)
start_time = time_to_string_utc_datetime(time(10, 43, 22))
end_time = time_to_string_utc_datetime(time(10, 56, 22))
# Productive time duration (13 min)
self.create_productivity_line(self.env.ref('mrp.block_reason7'), start_time, end_time)
# Material Availability time duration (1.52 min)
# Check working state is blocked or not.
start_time = time_to_string_utc_datetime(time(10, 47, 8))
workcenter_productivity_1 = self.create_productivity_line(self.env.ref('mrp.block_reason0'), start_time)
self.assertEqual(self.workcenter_1.working_state, 'blocked', "Wrong working state of workcenter.")
# Check working state is normal or not.
end_time = time_to_string_utc_datetime(time(10, 48, 39))
workcenter_productivity_1.write({'date_end': end_time})
self.assertEqual(self.workcenter_1.working_state, 'normal', "Wrong working state of workcenter.")
# Process Defect time duration (1.33 min)
start_time = time_to_string_utc_datetime(time(10, 48, 38))
end_time = time_to_string_utc_datetime(time(10, 49, 58))
self.create_productivity_line(self.env.ref('mrp.block_reason5'), start_time, end_time)
# Reduced Speed time duration (3.0 min)
start_time = time_to_string_utc_datetime(time(10, 50, 22))
end_time = time_to_string_utc_datetime(time(10, 53, 22))
self.create_productivity_line(self.env.ref('mrp.block_reason4'), start_time, end_time)
# Block time : ( Process Defact (1.33 min) + Reduced Speed (3.0 min) + Material Availability (1.52 min)) = 5.85 min
blocked_time_in_hour = round(((1.33 + 3.0 + 1.52) / 60.0), 2)
# Productive time : Productive time duration (13 min)
productive_time_in_hour = round((13.0 / 60.0), 2)
# Check blocked time and productive time
self.assertEqual(self.workcenter_1.blocked_time, blocked_time_in_hour, "Wrong block time on workcenter.")
self.assertEqual(self.workcenter_1.productive_time, productive_time_in_hour, "Wrong productive time on workcenter.")
# Check overall equipment effectiveness
computed_oee = round(((productive_time_in_hour * 100.0)/(productive_time_in_hour + blocked_time_in_hour)), 2)
self.assertEqual(self.workcenter_1.oee, computed_oee, "Wrong oee on workcenter.")
| 50.070423 | 3,555 |
9,822 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import Form
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.stock.tests import common2
class TestMrpCommon(common2.TestStockCommon):
@classmethod
def generate_mo(self, tracking_final='none', tracking_base_1='none', tracking_base_2='none', qty_final=5, qty_base_1=4, qty_base_2=1, picking_type_id=False, consumption=False):
""" This function generate a manufacturing order with one final
product and two consumed product. Arguments allows to choose
the tracking/qty for each different products. It returns the
MO, used bom and the tree products.
"""
product_to_build = self.env['product.product'].create({
'name': 'Young Tom',
'type': 'product',
'tracking': tracking_final,
})
product_to_use_1 = self.env['product.product'].create({
'name': 'Botox',
'type': 'product',
'tracking': tracking_base_1,
})
product_to_use_2 = self.env['product.product'].create({
'name': 'Old Tom',
'type': 'product',
'tracking': tracking_base_2,
})
bom_1 = self.env['mrp.bom'].create({
'product_id': product_to_build.id,
'product_tmpl_id': product_to_build.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'consumption': consumption if consumption else 'flexible',
'bom_line_ids': [
(0, 0, {'product_id': product_to_use_2.id, 'product_qty': qty_base_2}),
(0, 0, {'product_id': product_to_use_1.id, 'product_qty': qty_base_1})
]})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_to_build
if picking_type_id:
mo_form.picking_type_id = picking_type_id
mo_form.bom_id = bom_1
mo_form.product_qty = qty_final
mo = mo_form.save()
mo.action_confirm()
return mo, bom_1, product_to_build, product_to_use_1, product_to_use_2
@classmethod
def setUpClass(cls):
super(TestMrpCommon, cls).setUpClass()
# Update demo products
(cls.product_2 | cls.product_3 | cls.product_4 | cls.product_5 | cls.product_6 | cls.product_7_3 | cls.product_8).write({
'type': 'product',
})
# User Data: mrp user and mrp manager
cls.user_mrp_user = mail_new_test_user(
cls.env,
name='Hilda Ferachwal',
login='hilda',
email='[email protected]',
notification_type='inbox',
groups='mrp.group_mrp_user, stock.group_stock_user, mrp.group_mrp_byproducts',
)
cls.user_mrp_manager = mail_new_test_user(
cls.env,
name='Gary Youngwomen',
login='gary',
email='[email protected]',
notification_type='inbox',
groups='mrp.group_mrp_manager, stock.group_stock_user, mrp.group_mrp_byproducts',
)
cls.workcenter_1 = cls.env['mrp.workcenter'].create({
'name': 'Nuclear Workcenter',
'capacity': 2,
'time_start': 10,
'time_stop': 5,
'time_efficiency': 80,
})
cls.workcenter_2 = cls.env['mrp.workcenter'].create({
'name': 'Simple Workcenter',
'capacity': 1,
'time_start': 0,
'time_stop': 0,
'time_efficiency': 100,
})
cls.workcenter_3 = cls.env['mrp.workcenter'].create({
'name': 'Double Workcenter',
'capacity': 2,
'time_start': 0,
'time_stop': 0,
'time_efficiency': 100,
})
cls.bom_1 = cls.env['mrp.bom'].create({
'product_id': cls.product_4.id,
'product_tmpl_id': cls.product_4.product_tmpl_id.id,
'product_uom_id': cls.uom_unit.id,
'product_qty': 4.0,
'consumption': 'flexible',
'operation_ids': [
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_2.id, 'product_qty': 2}),
(0, 0, {'product_id': cls.product_1.id, 'product_qty': 4})
]})
cls.bom_2 = cls.env['mrp.bom'].create({
'product_id': cls.product_5.id,
'product_tmpl_id': cls.product_5.product_tmpl_id.id,
'product_uom_id': cls.product_5.uom_id.id,
'consumption': 'flexible',
'product_qty': 1.0,
'operation_ids': [
(0, 0, {'name': 'Gift Wrap Maching', 'workcenter_id': cls.workcenter_1.id, 'time_cycle': 15, 'sequence': 1}),
],
'type': 'phantom',
'sequence': 2,
'bom_line_ids': [
(0, 0, {'product_id': cls.product_4.id, 'product_qty': 2}),
(0, 0, {'product_id': cls.product_3.id, 'product_qty': 3})
]})
cls.bom_3 = cls.env['mrp.bom'].create({
'product_id': cls.product_6.id,
'product_tmpl_id': cls.product_6.product_tmpl_id.id,
'product_uom_id': cls.uom_dozen.id,
'ready_to_produce': 'asap',
'consumption': 'flexible',
'product_qty': 2.0,
'operation_ids': [
(0, 0, {'name': 'Cutting Machine', 'workcenter_id': cls.workcenter_1.id, 'time_cycle': 12, 'sequence': 1}),
(0, 0, {'name': 'Weld Machine', 'workcenter_id': cls.workcenter_1.id, 'time_cycle': 18, 'sequence': 2}),
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_5.id, 'product_qty': 2}),
(0, 0, {'product_id': cls.product_4.id, 'product_qty': 8}),
(0, 0, {'product_id': cls.product_2.id, 'product_qty': 12})
]})
cls.bom_4 = cls.env['mrp.bom'].create({
'product_id': cls.product_6.id,
'product_tmpl_id': cls.product_6.product_tmpl_id.id,
'consumption': 'flexible',
'product_qty': 1.0,
'operation_ids': [
(0, 0, {'name': 'Rub it gently with a cloth', 'workcenter_id': cls.workcenter_2.id,
'time_mode_batch': 1, 'time_mode': "auto", 'sequence': 1}),
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_1.id, 'product_qty': 1}),
]})
cls.bom_5 = cls.env['mrp.bom'].create({
'product_id': cls.product_6.id,
'product_tmpl_id': cls.product_6.product_tmpl_id.id,
'consumption': 'flexible',
'product_qty': 1.0,
'operation_ids': [
(0, 0, {'name': 'Rub it gently with a cloth two at once', 'workcenter_id': cls.workcenter_3.id,
'time_mode_batch': 2, 'time_mode': "auto", 'sequence': 1}),
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_1.id, 'product_qty': 1}),
]})
cls.bom_6 = cls.env['mrp.bom'].create({
'product_id': cls.product_6.id,
'product_tmpl_id': cls.product_6.product_tmpl_id.id,
'consumption': 'flexible',
'product_qty': 1.0,
'operation_ids': [
(0, 0, {'name': 'Rub it gently with a cloth two at once', 'workcenter_id': cls.workcenter_3.id,
'time_mode_batch': 1, 'time_mode': "auto", 'sequence': 1}),
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_1.id, 'product_qty': 1}),
]})
cls.stock_location_14 = cls.env['stock.location'].create({
'name': 'Shelf 2',
'location_id': cls.env.ref('stock.warehouse0').lot_stock_id.id,
})
cls.stock_location_components = cls.env['stock.location'].create({
'name': 'Shelf 1',
'location_id': cls.env.ref('stock.warehouse0').lot_stock_id.id,
})
cls.laptop = cls.env['product.product'].create({
'name': 'Acoustic Bloc Screens',
'uom_id': cls.env.ref("uom.product_uom_unit").id,
'uom_po_id': cls.env.ref("uom.product_uom_unit").id,
'type': 'product',
'tracking': 'none',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.graphics_card = cls.env['product.product'].create({
'name': 'Individual Workplace',
'uom_id': cls.env.ref("uom.product_uom_unit").id,
'uom_po_id': cls.env.ref("uom.product_uom_unit").id,
'type': 'product',
'tracking': 'none',
'categ_id': cls.env.ref('product.product_category_all').id,
})
@classmethod
def make_prods(cls, n):
return [
cls.env["product.product"].create(
{"name": f"p{k + 1}", "type": "product"}
)
for k in range(n)
]
@classmethod
def make_bom(cls, p, *cs):
return cls.env["mrp.bom"].create(
{
"product_tmpl_id": p.product_tmpl_id.id,
"product_id": p.id,
"product_qty": 1,
"type": "phantom",
"product_uom_id": cls.uom_unit.id,
"bom_line_ids": [
(0, 0, {
"product_id": c.id,
"product_qty": 1,
"product_uom_id": cls.uom_unit.id
})
for c in cs
],
}
)
| 41.096234 | 9,822 |
135,962 |
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 datetime import datetime, timedelta
from freezegun import freeze_time
from odoo import fields
from odoo.exceptions import UserError
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.tools.misc import format_date
class TestMrpOrder(TestMrpCommon):
def test_access_rights_manager(self):
""" Checks an MRP manager can create, confirm and cancel a manufacturing order. """
man_order_form = Form(self.env['mrp.production'].with_user(self.user_mrp_manager))
man_order_form.product_id = self.product_4
man_order_form.product_qty = 5.0
man_order_form.bom_id = self.bom_1
man_order_form.location_src_id = self.location_1
man_order_form.location_dest_id = self.warehouse_1.wh_output_stock_loc_id
man_order = man_order_form.save()
man_order.action_confirm()
man_order.action_cancel()
self.assertEqual(man_order.state, 'cancel', "Production order should be in cancel state.")
man_order.unlink()
def test_access_rights_user(self):
""" Checks an MRP user can create, confirm and cancel a manufacturing order. """
man_order_form = Form(self.env['mrp.production'].with_user(self.user_mrp_user))
man_order_form.product_id = self.product_4
man_order_form.product_qty = 5.0
man_order_form.bom_id = self.bom_1
man_order_form.location_src_id = self.location_1
man_order_form.location_dest_id = self.warehouse_1.wh_output_stock_loc_id
man_order = man_order_form.save()
man_order.action_confirm()
man_order.action_cancel()
self.assertEqual(man_order.state, 'cancel', "Production order should be in cancel state.")
man_order.unlink()
def test_basic(self):
""" Checks a basic manufacturing order: no routing (thus no workorders), no lot and
consume strictly what's needed. """
self.product_1.type = 'product'
self.product_2.type = 'product'
self.env['stock.quant'].create({
'location_id': self.warehouse_1.lot_stock_id.id,
'product_id': self.product_1.id,
'inventory_quantity': 500
}).action_apply_inventory()
self.env['stock.quant'].create({
'location_id': self.warehouse_1.lot_stock_id.id,
'product_id': self.product_2.id,
'inventory_quantity': 500
}).action_apply_inventory()
test_date_planned = fields.Datetime.now() - timedelta(days=1)
test_quantity = 3.0
man_order_form = Form(self.env['mrp.production'].with_user(self.user_mrp_user))
man_order_form.product_id = self.product_4
man_order_form.bom_id = self.bom_1
man_order_form.product_uom_id = self.product_4.uom_id
man_order_form.product_qty = test_quantity
man_order_form.date_planned_start = test_date_planned
man_order_form.location_src_id = self.location_1
man_order_form.location_dest_id = self.warehouse_1.wh_output_stock_loc_id
man_order = man_order_form.save()
self.assertEqual(man_order.state, 'draft', "Production order should be in draft state.")
man_order.action_confirm()
self.assertEqual(man_order.state, 'confirmed', "Production order should be in confirmed state.")
# check production move
production_move = man_order.move_finished_ids
self.assertAlmostEqual(production_move.date, test_date_planned + timedelta(hours=1), delta=timedelta(seconds=10))
self.assertEqual(production_move.product_id, self.product_4)
self.assertEqual(production_move.product_uom, man_order.product_uom_id)
self.assertEqual(production_move.product_qty, man_order.product_qty)
self.assertEqual(production_move.location_id, self.product_4.property_stock_production)
self.assertEqual(production_move.location_dest_id, man_order.location_dest_id)
# check consumption moves
for move in man_order.move_raw_ids:
self.assertEqual(move.date, test_date_planned)
first_move = man_order.move_raw_ids.filtered(lambda move: move.product_id == self.product_2)
self.assertEqual(first_move.product_qty, test_quantity / self.bom_1.product_qty * self.product_4.uom_id.factor_inv * 2)
first_move = man_order.move_raw_ids.filtered(lambda move: move.product_id == self.product_1)
self.assertEqual(first_move.product_qty, test_quantity / self.bom_1.product_qty * self.product_4.uom_id.factor_inv * 4)
# produce product
mo_form = Form(man_order)
mo_form.qty_producing = 2.0
man_order = mo_form.save()
action = man_order.button_mark_done()
self.assertEqual(man_order.state, 'progress', "Production order should be open a backorder wizard, then not done yet.")
quantity_issues = man_order._get_consumption_issues()
action = man_order._action_generate_consumption_wizard(quantity_issues)
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_close_mo()
self.assertEqual(man_order.state, 'done', "Production order should be done.")
# check that copy handles moves correctly
mo_copy = man_order.copy()
self.assertEqual(mo_copy.state, 'draft', "Copied production order should be draft.")
self.assertEqual(len(mo_copy.move_raw_ids), 4,
"Incorrect number of component moves [i.e. all non-0 (even cancelled) moves should be copied].")
self.assertEqual(len(mo_copy.move_finished_ids), 1, "Incorrect number of moves for products to produce [i.e. cancelled moves should not be copied")
self.assertEqual(mo_copy.move_finished_ids.product_uom_qty, 2, "Incorrect qty of products to produce")
# check that a cancelled MO is copied correctly
mo_copy.action_cancel()
self.assertEqual(mo_copy.state, 'cancel')
mo_copy_2 = mo_copy.copy()
self.assertEqual(mo_copy_2.state, 'draft', "Copied production order should be draft.")
self.assertEqual(len(mo_copy_2.move_raw_ids), 4, "Incorrect number of component moves.")
self.assertEqual(len(mo_copy_2.move_finished_ids), 1, "Incorrect number of moves for products to produce [i.e. copying a cancelled MO should copy its cancelled moves]")
self.assertEqual(mo_copy_2.move_finished_ids.product_uom_qty, 2, "Incorrect qty of products to produce")
def test_production_availability(self):
""" Checks the availability of a production order through mutliple calls to `action_assign`.
"""
self.bom_3.bom_line_ids.filtered(lambda x: x.product_id == self.product_5).unlink()
self.bom_3.bom_line_ids.filtered(lambda x: x.product_id == self.product_4).unlink()
self.bom_3.ready_to_produce = 'all_available'
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = self.bom_3
production_form.product_qty = 5.0
production_form.product_uom_id = self.product_6.uom_id
production_2 = production_form.save()
production_2.action_confirm()
production_2.action_assign()
# check sub product availability state is waiting
self.assertEqual(production_2.reservation_state, 'confirmed', 'Production order should be availability for waiting state')
# Update Inventory
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_2.id,
'inventory_quantity': 2.0,
'location_id': self.stock_location_14.id
}).action_apply_inventory()
production_2.action_assign()
# check sub product availability state is partially available
self.assertEqual(production_2.reservation_state, 'confirmed', 'Production order should be availability for partially available state')
# Update Inventory
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_2.id,
'inventory_quantity': 5.0,
'location_id': self.stock_location_14.id
}).action_apply_inventory()
production_2.action_assign()
# check sub product availability state is assigned
self.assertEqual(production_2.reservation_state, 'assigned', 'Production order should be availability for assigned state')
def test_over_consumption(self):
""" Consume more component quantity than the initial demand. No split on moves.
"""
mo, _bom, _p_final, _p1, _p2 = self.generate_mo(qty_base_1=10, qty_final=1, qty_base_2=1)
mo.action_assign()
# check is_quantity_done_editable
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 2
details_operation_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 11
details_operation_form.save()
self.assertEqual(len(mo.move_raw_ids), 2)
self.assertEqual(len(mo.move_raw_ids.mapped('move_line_ids')), 2)
self.assertEqual(mo.move_raw_ids[0].move_line_ids.mapped('qty_done'), [2])
self.assertEqual(mo.move_raw_ids[1].move_line_ids.mapped('qty_done'), [11])
self.assertEqual(mo.move_raw_ids[0].quantity_done, 2)
self.assertEqual(mo.move_raw_ids[1].quantity_done, 11)
mo.button_mark_done()
self.assertEqual(len(mo.move_raw_ids), 2)
self.assertEqual(len(mo.move_raw_ids.mapped('move_line_ids')), 2)
self.assertEqual(mo.move_raw_ids.mapped('quantity_done'), [2, 11])
self.assertEqual(mo.move_raw_ids.mapped('move_line_ids.qty_done'), [2, 11])
def test_under_consumption(self):
""" Consume less component quantity than the initial demand.
Before done:
p1, to consume = 1, consumed = 0
p2, to consume = 10, consumed = 5
After done:
p1, to consume = 1, consumed = 0, state = cancel
p2, to consume = 5, consumed = 5, state = done
p2, to consume = 5, consumed = 0, state = cancel
"""
mo, _bom, _p_final, _p1, _p2 = self.generate_mo(qty_base_1=10, qty_final=1, qty_base_2=1)
mo.action_assign()
# check is_quantity_done_editable
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 0
details_operation_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 5
details_operation_form.save()
self.assertEqual(len(mo.move_raw_ids), 2)
self.assertEqual(len(mo.move_raw_ids.mapped('move_line_ids')), 2)
self.assertEqual(mo.move_raw_ids[0].move_line_ids.mapped('qty_done'), [0])
self.assertEqual(mo.move_raw_ids[1].move_line_ids.mapped('qty_done'), [5])
self.assertEqual(mo.move_raw_ids[0].quantity_done, 0)
self.assertEqual(mo.move_raw_ids[1].quantity_done, 5)
mo.button_mark_done()
self.assertEqual(len(mo.move_raw_ids), 3)
self.assertEqual(len(mo.move_raw_ids.mapped('move_line_ids')), 1)
self.assertEqual(mo.move_raw_ids.mapped('quantity_done'), [0, 5, 0])
self.assertEqual(mo.move_raw_ids.mapped('product_uom_qty'), [1, 5, 5])
self.assertEqual(mo.move_raw_ids.mapped('state'), ['cancel', 'done', 'cancel'])
self.assertEqual(mo.move_raw_ids.mapped('move_line_ids.qty_done'), [5])
def test_update_quantity_1(self):
""" Build 5 final products with different consumed lots,
then edit the finished quantity and update the Manufacturing
order quantity. Then check if the produced quantity do not
change and it is possible to close the MO.
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_base_1='lot')
self.assertEqual(len(mo), 1, 'MO should have been created')
lot_1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p1.id,
'company_id': self.env.company.id,
})
lot_2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': p1.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 10, lot_id=lot_1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 10, lot_id=lot_2)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = lot_1
ml.qty_done = 20
details_operation_form.save()
update_quantity_wizard = self.env['change.production.qty'].create({
'mo_id': mo.id,
'product_qty': 4,
})
update_quantity_wizard.change_prod_qty()
self.assertEqual(mo.move_raw_ids.filtered(lambda m: m.product_id == p1).quantity_done, 20, 'Update the produce quantity should not impact already produced quantity.')
self.assertEqual(mo.move_finished_ids.product_uom_qty, 4)
mo.button_mark_done()
def test_update_quantity_2(self):
""" Build 5 final products with different consumed lots,
then edit the finished quantity and update the Manufacturing
order quantity. Then check if the produced quantity do not
change and it is possible to close the MO.
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=3)
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 20)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 2
mo = mo_form.save()
mo._post_inventory()
update_quantity_wizard = self.env['change.production.qty'].create({
'mo_id': mo.id,
'product_qty': 5,
})
update_quantity_wizard.change_prod_qty()
mo_form = Form(mo)
mo_form.qty_producing = 5
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(sum(mo.move_raw_ids.filtered(lambda m: m.product_id == p1).mapped('quantity_done')), 20)
self.assertEqual(sum(mo.move_finished_ids.mapped('quantity_done')), 5)
def test_update_quantity_3(self):
bom = self.env['mrp.bom'].create({
'product_id': self.product_6.id,
'product_tmpl_id': self.product_6.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': self.product_6.uom_id.id,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 2.03}),
(0, 0, {'product_id': self.product_8.id, 'product_qty': 4.16})
],
'operation_ids': [
(0, 0, {'name': 'Gift Wrap Maching', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 15, 'sequence': 1}),
]
})
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = bom
production_form.product_qty = 1
production_form.product_uom_id = self.product_6.uom_id
production = production_form.save()
self.assertEqual(production.workorder_ids.duration_expected, 90)
mo_form = Form(production)
mo_form.product_qty = 3
production = mo_form.save()
self.assertEqual(production.workorder_ids.duration_expected, 165)
def test_update_quantity_4(self):
bom = self.env['mrp.bom'].create({
'product_id': self.product_6.id,
'product_tmpl_id': self.product_6.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': self.product_6.uom_id.id,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 2.03}),
(0, 0, {'product_id': self.product_8.id, 'product_qty': 4.16})
],
})
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = bom
production_form.product_qty = 1
production_form.product_uom_id = self.product_6.uom_id
production = production_form.save()
production_form = Form(production)
with production_form.workorder_ids.new() as wo:
wo.name = 'OP1'
wo.workcenter_id = self.workcenter_1
wo.duration_expected = 40
production = production_form.save()
self.assertEqual(production.workorder_ids.duration_expected, 40)
mo_form = Form(production)
mo_form.product_qty = 3
production = mo_form.save()
self.assertEqual(production.workorder_ids.duration_expected, 90)
def test_qty_producing(self):
"""Qty producing should be the qty remain to produce, instead of 0"""
bom = self.env['mrp.bom'].create({
'product_id': self.product_6.id,
'product_tmpl_id': self.product_6.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': self.product_6.uom_id.id,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 2.00}),
],
})
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = bom
production_form.product_qty = 5
production_form.product_uom_id = self.product_6.uom_id
production = production_form.save()
production_form = Form(production)
with production_form.workorder_ids.new() as wo:
wo.name = 'OP1'
wo.workcenter_id = self.workcenter_1
wo.duration_expected = 40
production = production_form.save()
production.action_confirm()
production.button_plan()
wo = production.workorder_ids[0]
wo.button_start()
self.assertEqual(wo.qty_producing, 5, "Wrong quantity is suggested to produce.")
# Simulate changing the qty_producing in the frontend
wo.qty_producing = 4
wo.button_pending()
wo.button_start()
self.assertEqual(wo.qty_producing, 4, "Changing the qty_producing in the frontend is not persisted")
def test_update_quantity_5(self):
bom = self.env['mrp.bom'].create({
'product_id': self.product_6.id,
'product_tmpl_id': self.product_6.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': self.product_6.uom_id.id,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 3}),
],
})
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = bom
production_form.product_qty = 1
production_form.product_uom_id = self.product_6.uom_id
production = production_form.save()
production.action_confirm()
production.action_assign()
production.is_locked = False
production_form = Form(production)
# change the quantity producing and the initial demand
# in the same transaction
production_form.qty_producing = 10
with production_form.move_raw_ids.edit(0) as move:
move.product_uom_qty = 2
production = production_form.save()
production.button_mark_done()
def test_update_plan_date(self):
"""Editing the scheduled date after planning the MO should unplan the MO, and adjust the date on the stock moves"""
planned_date = datetime(2023, 5, 15, 9, 0)
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product_4
mo_form.bom_id = self.bom_1
mo_form.product_qty = 1
mo_form.date_planned_start = planned_date
mo = mo_form.save()
self.assertEqual(mo.move_finished_ids[0].date, datetime(2023, 5, 15, 10, 0))
mo.action_confirm()
mo.button_plan()
with Form(mo) as frm:
frm.date_planned_start = datetime(2024, 5, 15, 9, 0)
self.assertEqual(mo.move_finished_ids[0].date, datetime(2024, 5, 15, 10, 0))
def test_rounding(self):
""" Checks we round up when bringing goods to produce and round half-up when producing.
This implementation allows to implement an efficiency notion (see rev 347f140fe63612ee05e).
"""
self.product_6.uom_id.rounding = 1.0
bom_eff = self.env['mrp.bom'].create({
'product_id': self.product_6.id,
'product_tmpl_id': self.product_6.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': self.product_6.uom_id.id,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 2.03}),
(0, 0, {'product_id': self.product_8.id, 'product_qty': 4.16})
]
})
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = bom_eff
production_form.product_qty = 20
production_form.product_uom_id = self.product_6.uom_id
production = production_form.save()
production.action_confirm()
#Check the production order has the right quantities
self.assertEqual(production.move_raw_ids[0].product_qty, 41, 'The quantity should be rounded up')
self.assertEqual(production.move_raw_ids[1].product_qty, 84, 'The quantity should be rounded up')
# produce product
mo_form = Form(production)
mo_form.qty_producing = 8
production = mo_form.save()
self.assertEqual(production.move_raw_ids[0].quantity_done, 16, 'Should use half-up rounding when producing')
self.assertEqual(production.move_raw_ids[1].quantity_done, 34, 'Should use half-up rounding when producing')
def test_product_produce_1(self):
""" Checks the production wizard contains lines even for untracked products. """
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo()
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
# change the quantity done in one line
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
details_operation_form.save()
# change the quantity producing
mo_form = Form(mo)
mo_form.qty_producing = 3
# check than all quantities are update correctly
self.assertEqual(mo_form.move_raw_ids._records[0]['product_uom_qty'], 5, "Wrong quantity to consume")
self.assertEqual(mo_form.move_raw_ids._records[0]['quantity_done'], 3, "Wrong quantity done")
self.assertEqual(mo_form.move_raw_ids._records[1]['product_uom_qty'], 20, "Wrong quantity to consume")
self.assertEqual(mo_form.move_raw_ids._records[1]['quantity_done'], 12, "Wrong quantity done")
def test_product_produce_2(self):
""" Checks that, for a BOM where one of the components is tracked by serial number and the
other is not tracked, when creating a manufacturing order for two finished products and
reserving, the produce wizards proposes the corrects lines when producing one at a time.
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_base_1='serial', qty_base_1=1, qty_final=2)
self.assertEqual(len(mo), 1, 'MO should have been created')
lot_p1_1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p1.id,
'company_id': self.env.company.id,
})
lot_p1_2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': p1.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 1, lot_id=lot_p1_1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 1, lot_id=lot_p1_2)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
self.assertEqual(len(mo.move_raw_ids.move_line_ids), 3, 'You should have 3 stock move lines. One for each serial to consume and for the untracked product.')
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
# get the proposed lot
details_operation_form = Form(mo.move_raw_ids.filtered(lambda move: move.product_id == p1), view=self.env.ref('stock.view_stock_move_operations'))
self.assertEqual(len(details_operation_form.move_line_ids), 2)
with details_operation_form.move_line_ids.edit(0) as ml:
consumed_lots = ml.lot_id
ml.qty_done = 1
details_operation_form.save()
remaining_lot = (lot_p1_1 | lot_p1_2) - consumed_lots
remaining_lot.ensure_one()
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
# Check MO backorder
mo_backorder = mo.procurement_group_id.mrp_production_ids[-1]
mo_form = Form(mo_backorder)
mo_form.qty_producing = 1
mo_backorder = mo_form.save()
details_operation_form = Form(mo_backorder.move_raw_ids.filtered(lambda move: move.product_id == p1), view=self.env.ref('stock.view_stock_move_operations'))
self.assertEqual(len(details_operation_form.move_line_ids), 1)
with details_operation_form.move_line_ids.edit(0) as ml:
self.assertEqual(ml.lot_id, remaining_lot)
def test_product_produce_3(self):
""" Checks that, for a BOM where one of the components is tracked by lot and the other is
not tracked, when creating a manufacturing order for 1 finished product and reserving, the
reserved lines are displayed. Then, over-consume by creating new line.
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
self.stock_shelf_1 = self.stock_location_components
self.stock_shelf_2 = self.stock_location_14
mo, _, p_final, p1, p2 = self.generate_mo(tracking_base_1='lot', qty_base_1=10, qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
first_lot_for_p1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p1.id,
'company_id': self.env.company.id,
})
second_lot_for_p1 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': p1.id,
'company_id': self.env.company.id,
})
final_product_lot = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_shelf_1, 3, lot_id=first_lot_for_p1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_shelf_2, 3, lot_id=first_lot_for_p1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 8, lot_id=second_lot_for_p1)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 1.0
mo_form.lot_producing_id = final_product_lot
mo = mo_form.save()
# p2
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as line:
line.qty_done = line.product_uom_qty
with details_operation_form.move_line_ids.new() as line:
line.qty_done = 1
details_operation_form.save()
# p1
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
for i in range(len(details_operation_form.move_line_ids)):
# reservation in shelf1: 3 lot1, shelf2: 3 lot1, stock: 4 lot2
with details_operation_form.move_line_ids.edit(i) as line:
line.qty_done = line.product_uom_qty
with details_operation_form.move_line_ids.new() as line:
line.qty_done = 2
line.lot_id = first_lot_for_p1
with details_operation_form.move_line_ids.new() as line:
line.qty_done = 1
line.lot_id = second_lot_for_p1
details_operation_form.save()
move_1 = mo.move_raw_ids.filtered(lambda m: m.product_id == p1)
# qty_done/product_uom_qty lot
# 3/3 lot 1 shelf 1
# 1/1 lot 1 shelf 2
# 2/2 lot 1 shelf 2
# 2/0 lot 1 other
# 5/4 lot 2
ml_to_shelf_1 = move_1.move_line_ids.filtered(lambda ml: ml.lot_id == first_lot_for_p1 and ml.location_id == self.stock_shelf_1)
ml_to_shelf_2 = move_1.move_line_ids.filtered(lambda ml: ml.lot_id == first_lot_for_p1 and ml.location_id == self.stock_shelf_2)
self.assertEqual(sum(ml_to_shelf_1.mapped('qty_done')), 3.0, '3 units should be took from shelf1 as reserved.')
self.assertEqual(sum(ml_to_shelf_2.mapped('qty_done')), 3.0, '3 units should be took from shelf2 as reserved.')
self.assertEqual(move_1.quantity_done, 13, 'You should have used the tem units.')
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
def test_product_produce_4(self):
""" Possibility to produce with a given raw material in multiple locations. """
# FIXME sle: how is it possible to consume before producing in the interface?
self.stock_location = self.env.ref('stock.stock_location_stock')
self.stock_shelf_1 = self.stock_location_components
self.stock_shelf_2 = self.stock_location_14
mo, _, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=5)
self.env['stock.quant']._update_available_quantity(p1, self.stock_shelf_1, 2)
self.env['stock.quant']._update_available_quantity(p1, self.stock_shelf_2, 3)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 1)
mo.action_assign()
ml_p1 = mo.move_raw_ids.filtered(lambda x: x.product_id == p1).mapped('move_line_ids')
ml_p2 = mo.move_raw_ids.filtered(lambda x: x.product_id == p2).mapped('move_line_ids')
self.assertEqual(len(ml_p1), 2)
self.assertEqual(len(ml_p2), 1)
# Add some quantity already done to force an extra move line to be created
ml_p1[0].qty_done = 1.0
# Produce baby!
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
m_p1 = mo.move_raw_ids.filtered(lambda x: x.product_id == p1)
ml_p1 = m_p1.mapped('move_line_ids')
self.assertEqual(len(ml_p1), 2)
self.assertEqual(sorted(ml_p1.mapped('qty_done')), [2.0, 3.0], 'Quantity done should be 1.0, 2.0 or 3.0')
self.assertEqual(m_p1.quantity_done, 5.0, 'Total qty done should be 6.0')
self.assertEqual(sum(ml_p1.mapped('product_uom_qty')), 5.0, 'Total qty reserved should be 5.0')
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
def test_product_produce_6(self):
""" Plan 5 finished products, reserve and produce 3. Post the current production.
Simulate an unlock and edit and, on the opened moves, set the consumed quantity
to 3. Now, try to update the quantity to mo2 to 3. It should fail since there
are consumed quantities. Unlock and edit, remove the consumed quantities and
update the quantity to produce to 3."""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo()
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 20)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 3
mo = mo_form.save()
mo._post_inventory()
self.assertEqual(len(mo.move_raw_ids), 4)
mo.move_raw_ids.filtered(lambda m: m.state != 'done')[0].quantity_done = 3
update_quantity_wizard = self.env['change.production.qty'].create({
'mo_id': mo.id,
'product_qty': 3,
})
mo.move_raw_ids.filtered(lambda m: m.state != 'done')[0].quantity_done = 0
update_quantity_wizard.change_prod_qty()
self.assertEqual(len(mo.move_raw_ids), 4)
mo.button_mark_done()
self.assertTrue(all(s in ['done', 'cancel'] for s in mo.move_raw_ids.mapped('state')))
self.assertEqual(sum(mo.move_raw_ids.mapped('move_line_ids.product_uom_qty')), 0)
def test_consumption_strict_1(self):
""" Checks the constraints of a strict BOM without tracking when playing around
quantities to consume."""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(consumption='strict', qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
# try adding another line for a bom product to increase the quantity
mo_form.qty_producing = 1
with mo_form.move_raw_ids.new() as line:
line.product_id = p1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[-1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 1
details_operation_form.save()
# Won't accept to be done, instead return a wizard
mo.button_mark_done()
self.assertEqual(mo.state, 'to_close')
consumption_issues = mo._get_consumption_issues()
action = mo._action_generate_consumption_wizard(consumption_issues)
warning = Form(self.env['mrp.consumption.warning'].with_context(**action['context']))
warning = warning.save()
self.assertEqual(len(warning.mrp_consumption_warning_line_ids), 1)
self.assertEqual(warning.mrp_consumption_warning_line_ids[0].product_consumed_qty_uom, 5)
self.assertEqual(warning.mrp_consumption_warning_line_ids[0].product_expected_qty_uom, 4)
# Force the warning (as a manager)
warning.action_confirm()
self.assertEqual(mo.state, 'done')
def test_consumption_warning_1(self):
""" Checks the constraints of a strict BOM without tracking when playing around
quantities to consume."""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(consumption='warning', qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
# try adding another line for a bom product to increase the quantity
mo_form.qty_producing = 1
with mo_form.move_raw_ids.new() as line:
line.product_id = p1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[-1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 1
details_operation_form.save()
# Won't accept to be done, instead return a wizard
mo.button_mark_done()
self.assertEqual(mo.state, 'to_close')
consumption_issues = mo._get_consumption_issues()
action = mo._action_generate_consumption_wizard(consumption_issues)
warning = Form(self.env['mrp.consumption.warning'].with_context(**action['context']))
warning = warning.save()
self.assertEqual(len(warning.mrp_consumption_warning_line_ids), 1)
self.assertEqual(warning.mrp_consumption_warning_line_ids[0].product_consumed_qty_uom, 5)
self.assertEqual(warning.mrp_consumption_warning_line_ids[0].product_expected_qty_uom, 4)
# Force the warning (as a manager or employee)
warning.action_confirm()
self.assertEqual(mo.state, 'done')
def test_consumption_flexible_1(self):
""" Checks the constraints of a strict BOM without tracking when playing around
quantities to consume."""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(consumption='flexible', qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
# try adding another line for a bom product to increase the quantity
mo_form.qty_producing = 1
with mo_form.move_raw_ids.new() as line:
line.product_id = p1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[-1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 1
details_operation_form.save()
# Won't accept to be done, instead return a wizard
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
def test_consumption_flexible_2(self):
""" Checks the constraints of a strict BOM only apply to the product of the BoM. """
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(consumption='flexible', qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
add_product = self.env['product.product'].create({
'name': 'additional',
'type': 'product',
})
mo.action_assign()
mo_form = Form(mo)
# try adding another line for a bom product to increase the quantity
mo_form.qty_producing = 1
with mo_form.move_raw_ids.new() as line:
line.product_id = p1
with mo_form.move_raw_ids.new() as line:
line.product_id = add_product
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[-1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 1
details_operation_form.save()
# Won't accept to be done, instead return a wizard
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
def test_product_produce_9(self):
""" Checks the production wizard contains lines even for untracked products. """
serial = self.env['product.product'].create({
'name': 'S1',
'tracking': 'serial',
})
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo()
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
# change the quantity done in one line
with self.assertRaises(AssertionError):
with mo_form.move_raw_ids.new() as move:
move.product_id = serial
move.quantity_done = 2
mo_form.save()
def test_product_produce_10(self):
""" Produce byproduct with serial, lot and not tracked.
byproduct1 serial 1.0
byproduct2 lot 2.0
byproduct3 none 1.0 dozen
Check qty producing update and moves finished values.
"""
dozen = self.env.ref('uom.product_uom_dozen')
self.byproduct1 = self.env['product.product'].create({
'name': 'Byproduct 1',
'type': 'product',
'tracking': 'serial'
})
self.serial_1 = self.env['stock.production.lot'].create({
'product_id': self.byproduct1.id,
'name': 'serial 1',
'company_id': self.env.company.id,
})
self.serial_2 = self.env['stock.production.lot'].create({
'product_id': self.byproduct1.id,
'name': 'serial 2',
'company_id': self.env.company.id,
})
self.byproduct2 = self.env['product.product'].create({
'name': 'Byproduct 2',
'type': 'product',
'tracking': 'lot',
})
self.lot_1 = self.env['stock.production.lot'].create({
'product_id': self.byproduct2.id,
'name': 'Lot 1',
'company_id': self.env.company.id,
})
self.lot_2 = self.env['stock.production.lot'].create({
'product_id': self.byproduct2.id,
'name': 'Lot 2',
'company_id': self.env.company.id,
})
self.byproduct3 = self.env['product.product'].create({
'name': 'Byproduct 3',
'type': 'product',
'tracking': 'none',
})
with Form(self.bom_1) as bom:
bom.product_qty = 1.0
with bom.byproduct_ids.new() as bp:
bp.product_id = self.byproduct1
bp.product_qty = 1.0
with bom.byproduct_ids.new() as bp:
bp.product_id = self.byproduct2
bp.product_qty = 2.0
with bom.byproduct_ids.new() as bp:
bp.product_id = self.byproduct3
bp.product_qty = 2.0
bp.product_uom_id = dozen
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product_4
mo_form.bom_id = self.bom_1
mo_form.product_qty = 2
mo = mo_form.save()
mo.action_confirm()
move_byproduct_1 = mo.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct1)
self.assertEqual(len(move_byproduct_1), 1)
self.assertEqual(move_byproduct_1.product_uom_qty, 2.0)
self.assertEqual(move_byproduct_1.quantity_done, 0)
self.assertEqual(len(move_byproduct_1.move_line_ids), 0)
move_byproduct_2 = mo.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct2)
self.assertEqual(len(move_byproduct_2), 1)
self.assertEqual(move_byproduct_2.product_uom_qty, 4.0)
self.assertEqual(move_byproduct_2.quantity_done, 0)
self.assertEqual(len(move_byproduct_2.move_line_ids), 0)
move_byproduct_3 = mo.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct3)
self.assertEqual(move_byproduct_3.product_uom_qty, 4.0)
self.assertEqual(move_byproduct_3.quantity_done, 0)
self.assertEqual(move_byproduct_3.product_uom, dozen)
self.assertEqual(len(move_byproduct_3.move_line_ids), 0)
mo_form = Form(mo)
mo_form.qty_producing = 1.0
mo = mo_form.save()
move_byproduct_1 = mo.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct1)
self.assertEqual(len(move_byproduct_1), 1)
self.assertEqual(move_byproduct_1.product_uom_qty, 2.0)
self.assertEqual(move_byproduct_1.quantity_done, 0)
move_byproduct_2 = mo.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct2)
self.assertEqual(len(move_byproduct_2), 1)
self.assertEqual(move_byproduct_2.product_uom_qty, 4.0)
self.assertEqual(move_byproduct_2.quantity_done, 0)
move_byproduct_3 = mo.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct3)
self.assertEqual(move_byproduct_3.product_uom_qty, 4.0)
self.assertEqual(move_byproduct_3.quantity_done, 2.0)
self.assertEqual(move_byproduct_3.product_uom, dozen)
details_operation_form = Form(move_byproduct_1, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.serial_1
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(move_byproduct_2, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.lot_1
ml.qty_done = 2
details_operation_form.save()
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo2 = mo.procurement_group_id.mrp_production_ids[-1]
mo_form = Form(mo2)
mo_form.qty_producing = 1
mo2 = mo_form.save()
move_byproduct_1 = mo2.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct1)
self.assertEqual(len(move_byproduct_1), 1)
self.assertEqual(move_byproduct_1.product_uom_qty, 1.0)
self.assertEqual(move_byproduct_1.quantity_done, 0)
move_byproduct_2 = mo2.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct2)
self.assertEqual(len(move_byproduct_2), 1)
self.assertEqual(move_byproduct_2.product_uom_qty, 2.0)
self.assertEqual(move_byproduct_2.quantity_done, 0)
move_byproduct_3 = mo2.move_finished_ids.filtered(lambda l: l.product_id == self.byproduct3)
self.assertEqual(move_byproduct_3.product_uom_qty, 2.0)
self.assertEqual(move_byproduct_3.quantity_done, 2.0)
self.assertEqual(move_byproduct_3.product_uom, dozen)
details_operation_form = Form(move_byproduct_1, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.serial_2
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(move_byproduct_2, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = self.lot_2
ml.qty_done = 2
details_operation_form.save()
details_operation_form = Form(move_byproduct_3, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 3
details_operation_form.save()
mo2.button_mark_done()
move_lines_byproduct_1 = (mo | mo2).move_finished_ids.filtered(lambda l: l.product_id == self.byproduct1).mapped('move_line_ids')
move_lines_byproduct_2 = (mo | mo2).move_finished_ids.filtered(lambda l: l.product_id == self.byproduct2).mapped('move_line_ids')
move_lines_byproduct_3 = (mo | mo2).move_finished_ids.filtered(lambda l: l.product_id == self.byproduct3).mapped('move_line_ids')
self.assertEqual(move_lines_byproduct_1.filtered(lambda ml: ml.lot_id == self.serial_1).qty_done, 1.0)
self.assertEqual(move_lines_byproduct_1.filtered(lambda ml: ml.lot_id == self.serial_2).qty_done, 1.0)
self.assertEqual(move_lines_byproduct_2.filtered(lambda ml: ml.lot_id == self.lot_1).qty_done, 2.0)
self.assertEqual(move_lines_byproduct_2.filtered(lambda ml: ml.lot_id == self.lot_2).qty_done, 2.0)
self.assertEqual(sum(move_lines_byproduct_3.mapped('qty_done')), 5.0)
self.assertEqual(move_lines_byproduct_3.mapped('product_uom_id'), dozen)
def test_product_produce_11(self):
""" Checks that, for a BOM with two components, when creating a manufacturing order for one
finished products and without reserving, the produce wizards proposes the corrects lines
even if we change the quantity to produce multiple times.
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 4)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 1)
mo.bom_id.consumption = 'flexible' # Because we'll over-consume with a product not defined in the BOM
mo.action_assign()
mo.is_locked = False
mo_form = Form(mo)
mo_form.qty_producing = 3
self.assertEqual(sum([x['quantity_done'] for x in mo_form.move_raw_ids._records]), 15, 'Update the produce quantity should change the components quantity.')
mo = mo_form.save()
self.assertEqual(sum(mo.move_raw_ids.mapped('reserved_availability')), 5, 'Update the produce quantity should not change the components reserved quantity.')
mo_form = Form(mo)
mo_form.qty_producing = 4
self.assertEqual(sum([x['quantity_done'] for x in mo_form.move_raw_ids._records]), 20, 'Update the produce quantity should change the components quantity.')
mo = mo_form.save()
self.assertEqual(sum(mo.move_raw_ids.mapped('reserved_availability')), 5, 'Update the produce quantity should not change the components reserved quantity.')
mo_form = Form(mo)
mo_form.qty_producing = 1
self.assertEqual(sum([x['quantity_done'] for x in mo_form.move_raw_ids._records]), 5, 'Update the produce quantity should change the components quantity.')
mo = mo_form.save()
self.assertEqual(sum(mo.move_raw_ids.mapped('reserved_availability')), 5, 'Update the produce quantity should not change the components reserved quantity.')
# try adding another product that doesn't belong to the BoM
with mo_form.move_raw_ids.new() as move:
move.product_id = self.product_4
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[-1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 10
details_operation_form.save()
# Check that this new product is not updated by qty_producing
mo_form = Form(mo)
mo_form.qty_producing = 2
for move in mo_form.move_raw_ids._records:
if move['product_id'] == self.product_4.id:
self.assertEqual(move['quantity_done'], 10)
break
mo = mo_form.save()
mo.button_mark_done()
def test_product_produce_duplicate_1(self):
""" produce a finished product tracked by serial number 2 times with the
same SN. Check that an error is raised the second time"""
mo1, bom, p_final, p1, p2 = self.generate_mo(tracking_final='serial', qty_final=1, qty_base_1=1,)
mo_form = Form(mo1)
mo_form.qty_producing = 1
mo1 = mo_form.save()
mo1.action_generate_serial()
sn = mo1.lot_producing_id
mo1.button_mark_done()
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = p_final
mo_form.bom_id = bom
mo_form.product_qty = 1
mo2 = mo_form.save()
mo2.action_confirm()
mo_form = Form(mo2)
with self.assertLogs(level="WARNING"):
mo_form.lot_producing_id = sn
mo2 = mo_form.save()
with self.assertRaises(UserError):
mo2.button_mark_done()
def test_product_produce_duplicate_2(self):
""" produce a finished product with component tracked by serial number 2
times with the same SN. Check that an error is raised the second time"""
mo1, bom, p_final, p1, p2 = self.generate_mo(tracking_base_2='serial', qty_final=1, qty_base_1=1,)
sn = self.env['stock.production.lot'].create({
'name': 'sn used twice',
'product_id': p2.id,
'company_id': self.env.company.id,
})
mo_form = Form(mo1)
mo_form.qty_producing = 1
mo1 = mo_form.save()
details_operation_form = Form(mo1.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = sn
details_operation_form.save()
mo1.button_mark_done()
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = p_final
mo_form.bom_id = bom
mo_form.product_qty = 1
mo2 = mo_form.save()
mo2.action_confirm()
mo_form = Form(mo2)
mo_form.qty_producing = 1
mo2 = mo_form.save()
details_operation_form = Form(mo2.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = sn
details_operation_form.save()
with self.assertRaises(UserError):
mo2.button_mark_done()
def test_product_produce_duplicate_3(self):
""" produce a finished product with by-product tracked by serial number 2
times with the same SN. Check that an error is raised the second time"""
finished_product = self.env['product.product'].create({'name': 'finished product'})
byproduct = self.env['product.product'].create({'name': 'byproduct', 'tracking': 'serial'})
component = self.env['product.product'].create({'name': 'component'})
bom = self.env['mrp.bom'].create({
'product_id': finished_product.id,
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_uom_id': finished_product.uom_id.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 1}),
],
'byproduct_ids': [
(0, 0, {'product_id': byproduct.id, 'product_qty': 1, 'product_uom_id': byproduct.uom_id.id})
]})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished_product
mo_form.bom_id = bom
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
sn = self.env['stock.production.lot'].create({
'name': 'sn used twice',
'product_id': byproduct.id,
'company_id': self.env.company.id,
})
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
move_byproduct = mo.move_finished_ids.filtered(lambda m: m.product_id != mo.product_id)
details_operation_form = Form(move_byproduct, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = sn
details_operation_form.save()
mo.button_mark_done()
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished_product
mo_form.bom_id = bom
mo_form.product_qty = 1
mo2 = mo_form.save()
mo2.action_confirm()
mo_form = Form(mo2)
mo_form.qty_producing = 1
mo2 = mo_form.save()
move_byproduct = mo2.move_finished_ids.filtered(lambda m: m.product_id != mo.product_id)
details_operation_form = Form(move_byproduct, view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = sn
details_operation_form.save()
with self.assertRaises(UserError):
mo2.button_mark_done()
def test_product_produce_duplicate_4(self):
""" Consuming the same serial number two times should not give an error if
a repair order of the first production has been made before the second one"""
mo1, bom, p_final, p1, p2 = self.generate_mo(tracking_base_2='serial', qty_final=1, qty_base_1=1,)
sn = self.env['stock.production.lot'].create({
'name': 'sn used twice',
'product_id': p2.id,
'company_id': self.env.company.id,
})
mo_form = Form(mo1)
mo_form.qty_producing = 1
mo1 = mo_form.save()
details_operation_form = Form(mo1.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = sn
details_operation_form.save()
mo1.button_mark_done()
unbuild_form = Form(self.env['mrp.unbuild'])
unbuild_form.product_id = p_final
unbuild_form.bom_id = bom
unbuild_form.product_qty = 1
unbuild_form.mo_id = mo1
unbuild_order = unbuild_form.save()
unbuild_order.action_unbuild()
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = p_final
mo_form.bom_id = bom
mo_form.product_qty = 1
mo2 = mo_form.save()
mo2.action_confirm()
mo_form = Form(mo2)
mo_form.qty_producing = 1
mo2 = mo_form.save()
details_operation_form = Form(mo2.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = sn
details_operation_form.save()
mo2.button_mark_done()
def test_product_produce_12(self):
""" Checks that, the production is robust against deletion of finished move."""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
# remove the finished move from the available to be updated
mo.move_finished_ids._action_done()
mo.button_mark_done()
def test_product_produce_13(self):
""" Check that the production cannot be completed without any consumption."""
product = self.env['product.product'].create({
'name': 'Product no BoM',
'type': 'product',
})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product
mo = mo_form.save()
move = self.env['stock.move'].create({
'name': 'mrp_move',
'product_id': self.product_2.id,
'product_uom': self.ref('uom.product_uom_unit'),
'production_id': mo.id,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 0,
'quantity_done': 0,
})
mo.move_raw_ids |= move
mo.action_confirm()
mo.qty_producing = 1
# can't produce without any consumption (i.e. components w/ 0 consumed)
with self.assertRaises(UserError):
mo.button_mark_done()
mo.move_raw_ids.quantity_done = 1
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
def test_product_produce_14(self):
""" Check two component move with the same product are not merged."""
product = self.env['product.product'].create({
'name': 'Product no BoM',
'type': 'product',
})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product
mo = mo_form.save()
for i in range(2):
move = self.env['stock.move'].create({
'name': 'mrp_move',
'product_id': self.product_2.id,
'product_uom': self.ref('uom.product_uom_unit'),
'production_id': mo.id,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'product_uom_qty': 0,
'quantity_done': 0,
})
mo.move_raw_ids |= move
mo.action_confirm()
self.assertEqual(len(mo.move_raw_ids), 2)
def test_product_produce_uom(self):
""" Produce a finished product tracked by serial number. Set another
UoM on the bom. The produce wizard should keep the UoM of the product (unit)
and quantity = 1."""
dozen = self.env.ref('uom.product_uom_dozen')
unit = self.env.ref('uom.product_uom_unit')
plastic_laminate = self.env['product.product'].create({
'name': 'Plastic Laminate',
'type': 'product',
'uom_id': unit.id,
'uom_po_id': unit.id,
'tracking': 'serial',
})
ply_veneer = self.env['product.product'].create({
'name': 'Ply Veneer',
'type': 'product',
'uom_id': unit.id,
'uom_po_id': unit.id,
})
bom = self.env['mrp.bom'].create({
'product_tmpl_id': plastic_laminate.product_tmpl_id.id,
'product_uom_id': unit.id,
'sequence': 1,
'bom_line_ids': [(0, 0, {
'product_id': ply_veneer.id,
'product_qty': 1,
'product_uom_id': unit.id,
'sequence': 1,
})]
})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = plastic_laminate
mo_form.bom_id = bom
mo_form.product_uom_id = dozen
mo_form.product_qty = 1
mo = mo_form.save()
final_product_lot = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': plastic_laminate.id,
'company_id': self.env.company.id,
})
mo.action_confirm()
mo.action_assign()
self.assertEqual(mo.move_raw_ids.product_qty, 12, '12 units should be reserved.')
# produce product
mo_form = Form(mo)
mo_form.qty_producing = 1/12.0
mo_form.lot_producing_id = final_product_lot
mo = mo_form.save()
move_line_raw = mo.move_raw_ids.mapped('move_line_ids').filtered(lambda m: m.qty_done)
self.assertEqual(move_line_raw.qty_done, 1)
self.assertEqual(move_line_raw.product_uom_id, unit, 'Should be 1 unit since the tracking is serial.')
mo._post_inventory()
move_line_finished = mo.move_finished_ids.mapped('move_line_ids').filtered(lambda m: m.qty_done)
self.assertEqual(move_line_finished.qty_done, 1)
self.assertEqual(move_line_finished.product_uom_id, unit, 'Should be 1 unit since the tracking is serial.')
def test_product_type_service_1(self):
# Create finished product
finished_product = self.env['product.product'].create({
'name': 'Geyser',
'type': 'product',
})
# Create service type product
product_raw = self.env['product.product'].create({
'name': 'raw Geyser',
'type': 'service',
})
# Create bom for finish product
bom = self.env['mrp.bom'].create({
'product_id': finished_product.id,
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_uom_id': self.env.ref('uom.product_uom_unit').id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [(5, 0), (0, 0, {'product_id': product_raw.id})]
})
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished_product
mo_form.bom_id = bom
mo_form.product_uom_id = self.env.ref('uom.product_uom_unit')
mo_form.product_qty = 1
mo = mo_form.save()
# Check Mo is created or not
self.assertTrue(mo, "Mo is created")
def test_immediate_validate_1(self):
""" In a production with a single available move raw, clicking on mark as done without filling any
quantities should open a wizard asking to process all the reservation (so, the whole move).
"""
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=1, qty_base_2=1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 5.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 5.0)
mo.action_assign()
res_dict = mo.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(mo.move_raw_ids.mapped('state'), ['done', 'done'])
self.assertEqual(mo.move_raw_ids.mapped('quantity_done'), [1, 1])
self.assertEqual(mo.move_finished_ids.state, 'done')
self.assertEqual(mo.move_finished_ids.quantity_done, 1)
def test_immediate_validate_2(self):
""" In a production with a single available move raw, clicking on mark as done after filling quantity
for a stock move only will trigger an error as qty_producing is left to 0."""
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=1, qty_base_2=1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 5.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 5.0)
mo.action_assign()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 1
details_operation_form.save()
with self.assertRaises(UserError):
res_dict = mo.button_mark_done()
def test_immediate_validate_3(self):
""" In a production with a serial number tracked product. Check that the immediate production only creates
one unit of finished product. Test with reservation."""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_final='serial', qty_final=2, qty_base_1=1, qty_base_2=1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 5.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 5.0)
mo.action_assign()
action = mo.button_mark_done()
self.assertEqual(action.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
action = wizard.process()
self.assertEqual(action.get('res_model'), 'mrp.production.backorder')
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
action = wizard.action_backorder()
self.assertEqual(mo.qty_producing, 1)
self.assertEqual(mo.move_raw_ids.mapped('quantity_done'), [1, 1])
self.assertEqual(len(mo.procurement_group_id.mrp_production_ids), 2)
mo_backorder = mo.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(mo_backorder.product_qty, 1)
self.assertEqual(mo_backorder.move_raw_ids.mapped('product_uom_qty'), [1, 1])
def test_immediate_validate_4(self):
""" In a production with a serial number tracked product. Check that the immediate production only creates
one unit of finished product. Test without reservation."""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_final='serial', qty_final=2, qty_base_1=1, qty_base_2=1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 5.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 5.0)
action = mo.button_mark_done()
self.assertEqual(action.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
action = wizard.process()
self.assertEqual(action.get('res_model'), 'mrp.production.backorder')
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
action = wizard.action_backorder()
self.assertEqual(mo.qty_producing, 1)
self.assertEqual(mo.move_raw_ids.mapped('quantity_done'), [1, 1])
self.assertEqual(len(mo.procurement_group_id.mrp_production_ids), 2)
mo_backorder = mo.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(mo_backorder.product_qty, 1)
self.assertEqual(mo_backorder.move_raw_ids.mapped('product_uom_qty'), [1, 1])
def test_immediate_validate_5(self):
"""Validate three productions at once."""
mo1, bom, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=1, qty_base_2=1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 5.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 5.0)
mo1.action_assign()
mo2_form = Form(self.env['mrp.production'])
mo2_form.product_id = p_final
mo2_form.bom_id = bom
mo2_form.product_qty = 1
mo2 = mo2_form.save()
mo2.action_confirm()
mo2.action_assign()
mo3_form = Form(self.env['mrp.production'])
mo3_form.product_id = p_final
mo3_form.bom_id = bom
mo3_form.product_qty = 1
mo3 = mo3_form.save()
mo3.action_confirm()
mo3.action_assign()
mos = mo1 | mo2 | mo3
res_dict = mos.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(mos.move_raw_ids.mapped('state'), ['done'] * 6)
self.assertEqual(mos.move_raw_ids.mapped('quantity_done'), [1] * 6)
self.assertEqual(mos.move_finished_ids.mapped('state'), ['done'] * 3)
self.assertEqual(mos.move_finished_ids.mapped('quantity_done'), [1] * 3)
def test_components_availability(self):
self.bom_2.unlink() # remove the kit bom of product_5
now = fields.Datetime.now()
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_3 # product_5 (2), product_4 (8), product_2 (12)
mo_form.date_planned_start = now
mo = mo_form.save()
self.assertEqual(mo.components_availability, False) # no compute for draft
mo.action_confirm()
self.assertEqual(mo.components_availability, 'Not Available')
tommorrow = fields.Datetime.now() + timedelta(days=1)
after_tommorrow = fields.Datetime.now() + timedelta(days=2)
warehouse = self.env.ref('stock.warehouse0')
move1 = self._create_move(
self.product_5, self.env.ref('stock.stock_location_suppliers'), warehouse.lot_stock_id,
product_uom_qty=2, date=tommorrow
)
move2 = self._create_move(
self.product_4, self.env.ref('stock.stock_location_suppliers'), warehouse.lot_stock_id,
product_uom_qty=8, date=tommorrow
)
move3 = self._create_move(
self.product_2, self.env.ref('stock.stock_location_suppliers'), warehouse.lot_stock_id,
product_uom_qty=12, date=tommorrow
)
(move1 | move2 | move3)._action_confirm()
mo.invalidate_cache(['components_availability', 'components_availability_state'], mo.ids)
self.assertEqual(mo.components_availability, f'Exp {format_date(self.env, tommorrow)}')
self.assertEqual(mo.components_availability_state, 'late')
mo.date_planned_start = after_tommorrow
self.assertEqual(mo.components_availability, f'Exp {format_date(self.env, tommorrow)}')
self.assertEqual(mo.components_availability_state, 'expected')
(move1 | move2 | move3)._set_quantities_to_reservation()
(move1 | move2 | move3)._action_done()
mo.invalidate_cache(['components_availability', 'components_availability_state'], mo.ids)
self.assertEqual(mo.components_availability, 'Available')
self.assertEqual(mo.components_availability_state, 'available')
mo.action_assign()
self.assertEqual(mo.reservation_state, 'assigned')
self.assertEqual(mo.components_availability, 'Available')
self.assertEqual(mo.components_availability_state, 'available')
def test_immediate_validate_6(self):
"""In a production for a tracked product, clicking on mark as done without filling any quantities should
pop up the immediate transfer wizard. Processing should choose a new lot for the finished product. """
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=1, qty_base_2=1, tracking_final='lot')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location_components, 5.0)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location_components, 5.0)
mo.action_assign()
res_dict = mo.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(mo.move_raw_ids.mapped('state'), ['done'] * 2)
self.assertEqual(mo.move_raw_ids.mapped('quantity_done'), [1] * 2)
self.assertEqual(mo.move_finished_ids.state, 'done')
self.assertEqual(mo.move_finished_ids.quantity_done, 1)
self.assertTrue(mo.move_finished_ids.move_line_ids.lot_id != False)
def test_immediate_validate_uom(self):
"""In a production with a different uom than the finished product one, the
immediate production wizard should fill the correct quantities. """
p_final = self.env['product.product'].create({
'name': 'final',
'type': 'product',
})
component = self.env['product.product'].create({
'name': 'component',
'type': 'product',
})
bom = self.env['mrp.bom'].create({
'product_id': p_final.id,
'product_tmpl_id': p_final.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'consumption': 'flexible',
'bom_line_ids': [(0, 0, {'product_id': component.id, 'product_qty': 1})]
})
self.env['stock.quant']._update_available_quantity(component, self.stock_location_components, 25.0)
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = bom
mo_form.product_uom_id = self.uom_dozen
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
mo.action_assign()
res_dict = mo.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(mo.move_raw_ids.state, 'done')
self.assertEqual(mo.move_raw_ids.quantity_done, 12)
self.assertEqual(mo.move_finished_ids.state, 'done')
self.assertEqual(mo.move_finished_ids.quantity_done, 1)
self.assertEqual(component.qty_available, 13)
def test_immediate_validate_uom_2(self):
"""The rounding precision of a component should be based on the UoM used in the MO for this component,
not on the produced product's UoM nor the default UoM of the component"""
uom_units = self.env.ref('uom.product_uom_unit')
uom_L = self.env.ref('uom.product_uom_litre')
uom_cL = self.env['uom.uom'].create({
'name': 'cL',
'category_id': uom_L.category_id.id,
'uom_type': 'smaller',
'factor': 100,
'rounding': 1,
})
uom_units.rounding = 1
uom_L.rounding = 0.01
product = self.env['product.product'].create({
'name': 'SuperProduct',
'uom_id': uom_units.id,
})
consumable_component = self.env['product.product'].create({
'name': 'Consumable Component',
'type': 'consu',
'uom_id': uom_cL.id,
'uom_po_id': uom_cL.id,
})
storable_component = self.env['product.product'].create({
'name': 'Storable Component',
'type': 'product',
'uom_id': uom_cL.id,
'uom_po_id': uom_cL.id,
})
self.env['stock.quant']._update_available_quantity(storable_component, self.env.ref('stock.stock_location_stock'), 100)
for component in [consumable_component, storable_component]:
bom = self.env['mrp.bom'].create({
'product_tmpl_id': product.product_tmpl_id.id,
'bom_line_ids': [(0, 0, {
'product_id': component.id,
'product_qty': 0.2,
'product_uom_id': uom_L.id,
})],
})
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = bom
mo = mo_form.save()
mo.action_confirm()
action = mo.button_mark_done()
self.assertEqual(action.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
action = wizard.process()
self.assertEqual(mo.move_raw_ids.product_uom_qty, 0.2)
self.assertEqual(mo.move_raw_ids.quantity_done, 0.2)
def test_copy(self):
""" Check that copying a done production, create all the stock moves"""
mo, bom, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=1, qty_base_2=1)
mo.action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
mo_copy = mo.copy()
self.assertTrue(mo_copy.move_raw_ids)
self.assertTrue(mo_copy.move_finished_ids)
mo_copy.action_confirm()
mo_form = Form(mo_copy)
mo_form.qty_producing = 1
mo_copy = mo_form.save()
mo_copy.button_mark_done()
self.assertEqual(mo_copy.state, 'done')
def test_product_produce_different_uom(self):
""" Check that for products tracked by lots,
with component product UOM different from UOM used in the BOM,
we do not create a new move line due to extra reserved quantity
caused by decimal rounding conversions.
"""
# the overall decimal accuracy is set to 3 digits
precision = self.env.ref('product.decimal_product_uom')
precision.digits = 3
# define L and ml, L has rounding .001 but ml has rounding .01
# when producing e.g. 187.5ml, it will be rounded to .188L
categ_test = self.env['uom.category'].create({'name': 'Volume Test'})
uom_L = self.env['uom.uom'].create({
'name': 'Test Liters',
'category_id': categ_test.id,
'uom_type': 'reference',
'rounding': 0.001
})
uom_ml = self.env['uom.uom'].create({
'name': 'Test ml',
'category_id': categ_test.id,
'uom_type': 'smaller',
'rounding': 0.01,
'factor_inv': 0.001,
})
# create a product component and the final product using the component
product_comp = self.env['product.product'].create({
'name': 'Product Component',
'type': 'product',
'tracking': 'lot',
'categ_id': self.env.ref('product.product_category_all').id,
'uom_id': uom_L.id,
'uom_po_id': uom_L.id,
})
product_final = self.env['product.product'].create({
'name': 'Product Final',
'type': 'product',
'tracking': 'lot',
'categ_id': self.env.ref('product.product_category_all').id,
'uom_id': uom_L.id,
'uom_po_id': uom_L.id,
})
# the products are tracked by lot, so we go through _generate_consumed_move_line
lot_final = self.env['stock.production.lot'].create({
'name': 'Lot Final',
'product_id': product_final.id,
'company_id': self.env.company.id,
})
lot_comp = self.env['stock.production.lot'].create({
'name': 'Lot Component',
'product_id': product_comp.id,
'company_id': self.env.company.id,
})
# update the quantity on hand for Component, in a lot
self.stock_location = self.env.ref('stock.stock_location_stock')
self.env['stock.quant']._update_available_quantity(product_comp, self.stock_location, 1, lot_id=lot_comp)
# create a BOM for Final, using Component
test_bom = self.env['mrp.bom'].create({
'product_id': product_final.id,
'product_tmpl_id': product_final.product_tmpl_id.id,
'product_uom_id': uom_L.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [(0, 0, {
'product_id': product_comp.id,
'product_qty': 375.00,
'product_uom_id': uom_ml.id
})],
})
# create a MO for this BOM
mo_product_final_form = Form(self.env['mrp.production'])
mo_product_final_form.product_id = product_final
mo_product_final_form.product_uom_id = uom_L
mo_product_final_form.bom_id = test_bom
mo_product_final_form.product_qty = 0.5
mo_product_final_form = mo_product_final_form.save()
mo_product_final_form.action_confirm()
mo_product_final_form.action_assign()
self.assertEqual(mo_product_final_form.reservation_state, 'assigned')
# produce
res_dict = mo_product_final_form.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
# check that in _generate_consumed_move_line,
# we do not create an extra move line because
# of a conversion 187.5ml = 0.188L
# thus creating an extra line with 'product_uom_qty': 0.5
self.assertEqual(len(mo_product_final_form.move_raw_ids.move_line_ids), 1, 'One move line should exist for the MO.')
def test_mo_sn_warning(self):
""" Checks that when a MO where the final product is tracked by serial, a warning pops up if
the `lot_producting_id` has previously been used already (i.e. dupe SN). Also checks if a
scrap linked to a MO has its sn warning correctly pop up.
"""
self.stock_location = self.env.ref('stock.stock_location_stock')
mo, _, p_final, _, _ = self.generate_mo(tracking_final='serial', qty_base_1=1, qty_final=1)
self.assertEqual(len(mo), 1, 'MO should have been created')
sn1 = self.env['stock.production.lot'].create({
'name': 'serial1',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p_final, self.stock_location, 1, lot_id=sn1)
mo.lot_producing_id = sn1
warning = False
warning = mo._onchange_lot_producing()
self.assertTrue(warning, 'Reuse of existing serial number not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
mo.action_generate_serial()
sn2 = mo.lot_producing_id
mo.button_mark_done()
# scrap linked to MO but with wrong SN location
scrap = self.env['stock.scrap'].create({
'product_id': p_final.id,
'product_uom_id': self.uom_unit.id,
'production_id': mo.id,
'location_id': self.stock_location_14.id,
'lot_id': sn2.id
})
warning = False
warning = scrap._onchange_serial_number()
self.assertTrue(warning, 'Use of wrong serial number location not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
self.assertEqual(scrap.location_id, mo.location_dest_id, 'Location was not auto-corrected')
def test_a_multi_button_plan(self):
""" Test batch methods (confirm/validate) of the MO with the same bom """
self.bom_2.type = "normal" # avoid to get the operation of the kit bom
mo_3 = Form(self.env['mrp.production'])
mo_3.bom_id = self.bom_3
mo_3 = mo_3.save()
self.assertEqual(len(mo_3.workorder_ids), 2)
mo_3.button_plan()
self.assertEqual(mo_3.state, 'confirmed')
self.assertEqual(mo_3.workorder_ids[0].state, 'waiting')
mo_1 = Form(self.env['mrp.production'])
mo_1.bom_id = self.bom_3
mo_1 = mo_1.save()
mo_2 = Form(self.env['mrp.production'])
mo_2.bom_id = self.bom_3
mo_2 = mo_2.save()
self.assertEqual(mo_1.product_id, self.product_6)
self.assertEqual(mo_2.product_id, self.product_6)
self.assertEqual(len(self.bom_3.operation_ids), 2)
self.assertEqual(len(mo_1.workorder_ids), 2)
self.assertEqual(len(mo_2.workorder_ids), 2)
(mo_1 | mo_2).button_plan() # Confirm and plan in the same "request"
self.assertEqual(mo_1.state, 'confirmed')
self.assertEqual(mo_2.state, 'confirmed')
self.assertEqual(mo_1.workorder_ids[0].state, 'waiting')
self.assertEqual(mo_2.workorder_ids[0].state, 'waiting')
# produce
res_dict = (mo_1 | mo_2).button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(mo_1.state, 'done')
self.assertEqual(mo_2.state, 'done')
def test_workcenter_timezone(self):
# Workcenter is based in Bangkok
# Possible working hours are Monday to Friday, from 8:00 to 12:00 and from 13:00 to 17:00 (UTC+7)
workcenter = self.workcenter_1
workcenter.resource_calendar_id.tz = 'Asia/Bangkok'
bom = self.env['mrp.bom'].create({
'product_tmpl_id': self.product_1.product_tmpl_id.id,
'bom_line_ids': [(0, 0, {
'product_id': self.product_2.id,
})],
'operation_ids': [(0, 0, {
'name': 'SuperOperation01',
'workcenter_id': workcenter.id,
}), (0, 0, {
'name': 'SuperOperation01',
'workcenter_id': workcenter.id,
})],
})
# Next Monday at 6:00 am UTC
date_planned = (fields.Datetime.now() + timedelta(days=7 - fields.Datetime.now().weekday())).replace(hour=6, minute=0, second=0)
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = bom
mo_form.date_planned_start = date_planned
mo = mo_form.save()
mo.workorder_ids[0].duration_expected = 240
mo.workorder_ids[1].duration_expected = 60
mo.action_confirm()
mo.button_plan()
# Asia/Bangkok is UTC+7 and the start date is on Monday at 06:00 UTC (i.e., 13:00 UTC+7).
# So, in Bangkok, the first workorder uses the entire Monday afternoon slot 13:00 - 17:00 UTC+7 (i.e., 06:00 - 10:00 UTC)
# The second job uses the beginning of the Tuesday morning slot: 08:00 - 09:00 UTC+7 (i.e., 01:00 - 02:00 UTC)
self.assertEqual(mo.workorder_ids[0].date_planned_start, date_planned)
self.assertEqual(mo.workorder_ids[0].date_planned_finished, date_planned + timedelta(hours=4))
tuesday = date_planned + timedelta(days=1)
self.assertEqual(mo.workorder_ids[1].date_planned_start, tuesday.replace(hour=1))
self.assertEqual(mo.workorder_ids[1].date_planned_finished, tuesday.replace(hour=2))
def test_backorder_with_overconsumption(self):
""" Check that the components of the backorder have the correct quantities
when there is overconsumption in the initial MO
"""
mo, _, _, _, _ = self.generate_mo(qty_final=30, qty_base_1=2, qty_base_2=3)
mo.action_confirm()
mo.qty_producing = 10
mo.move_raw_ids[0].quantity_done = 90
mo.move_raw_ids[1].quantity_done = 70
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo_backorder = mo.procurement_group_id.mrp_production_ids[-1]
# Check quantities of the original MO
self.assertEqual(mo.product_uom_qty, 10.0)
self.assertEqual(mo.qty_produced, 10.0)
move_prod_1 = self.env['stock.move'].search([
('product_id', '=', mo.bom_id.bom_line_ids[0].product_id.id),
('raw_material_production_id', '=', mo.id)])
move_prod_2 = self.env['stock.move'].search([
('product_id', '=', mo.bom_id.bom_line_ids[1].product_id.id),
('raw_material_production_id', '=', mo.id)])
self.assertEqual(sum(move_prod_1.mapped('quantity_done')), 90.0)
self.assertEqual(sum(move_prod_1.mapped('product_uom_qty')), 90.0)
self.assertEqual(sum(move_prod_2.mapped('quantity_done')), 70.0)
self.assertEqual(sum(move_prod_2.mapped('product_uom_qty')), 70.0)
# Check quantities of the backorder MO
self.assertEqual(mo_backorder.product_uom_qty, 20.0)
move_prod_1_bo = self.env['stock.move'].search([
('product_id', '=', mo.bom_id.bom_line_ids[0].product_id.id),
('raw_material_production_id', '=', mo_backorder.id)])
move_prod_2_bo = self.env['stock.move'].search([
('product_id', '=', mo.bom_id.bom_line_ids[1].product_id.id),
('raw_material_production_id', '=', mo_backorder.id)])
self.assertEqual(sum(move_prod_1_bo.mapped('product_uom_qty')), 60.0)
self.assertEqual(sum(move_prod_2_bo.mapped('product_uom_qty')), 40.0)
def test_backorder_with_underconsumption(self):
""" Check that the components of the backorder have the correct quantities
when there is underconsumption in the initial MO
"""
mo, _, _, p1, p2 = self.generate_mo(qty_final=20, qty_base_1=1, qty_base_2=1)
mo.action_confirm()
mo.qty_producing = 10
mo.move_raw_ids.filtered(lambda m: m.product_id == p1).quantity_done = 5
mo.move_raw_ids.filtered(lambda m: m.product_id == p2).quantity_done = 10
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo_backorder = mo.procurement_group_id.mrp_production_ids[-1]
# Check quantities of the original MO
self.assertEqual(mo.product_uom_qty, 10.0)
self.assertEqual(mo.qty_produced, 10.0)
move_prod_1_done = mo.move_raw_ids.filtered(lambda m: m.product_id == p1 and m.state == 'done')
self.assertEqual(sum(move_prod_1_done.mapped('quantity_done')), 5)
self.assertEqual(sum(move_prod_1_done.mapped('product_uom_qty')), 5)
move_prod_1_cancel = mo.move_raw_ids.filtered(lambda m: m.product_id == p1 and m.state == 'cancel')
self.assertEqual(sum(move_prod_1_cancel.mapped('quantity_done')), 0)
self.assertEqual(sum(move_prod_1_cancel.mapped('product_uom_qty')), 5)
move_prod_2 = mo.move_raw_ids.filtered(lambda m: m.product_id == p2)
self.assertEqual(sum(move_prod_2.mapped('quantity_done')), 10)
self.assertEqual(sum(move_prod_2.mapped('product_uom_qty')), 10)
# Check quantities of the backorder MO
self.assertEqual(mo_backorder.product_uom_qty, 10.0)
move_prod_1_bo = mo_backorder.move_raw_ids.filtered(lambda m: m.product_id == p1)
move_prod_2_bo = mo_backorder.move_raw_ids.filtered(lambda m: m.product_id == p2)
self.assertEqual(sum(move_prod_1_bo.mapped('product_uom_qty')), 10.0)
self.assertEqual(sum(move_prod_2_bo.mapped('product_uom_qty')), 10.0)
def test_state_workorders(self):
bom = self.env['mrp.bom'].create({
'product_id': self.product_4.id,
'product_tmpl_id': self.product_4.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 1})
],
'operation_ids': [
(0, 0, {'name': 'amUgbidhaW1lIHBhcyBsZSBKUw==', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 15, 'sequence': 1}),
(0, 0, {'name': '137 Python', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 1, 'sequence': 2}),
],
})
self.env['stock.quant'].create({
'location_id': self.stock_location_components.id,
'product_id': self.product_2.id,
'inventory_quantity': 10
}).action_apply_inventory()
mo = Form(self.env['mrp.production'])
mo.bom_id = bom
mo = mo.save()
self.assertEqual(list(mo.workorder_ids.mapped("state")), ["pending", "pending"])
mo.action_confirm()
mo.action_assign()
self.assertEqual(mo.move_raw_ids.state, "assigned")
self.assertEqual(list(mo.workorder_ids.mapped("state")), ["ready", "pending"])
mo.do_unreserve()
self.assertEqual(list(mo.workorder_ids.mapped("state")), ["waiting", "pending"])
mo.workorder_ids[0].unlink()
self.assertEqual(list(mo.workorder_ids.mapped("state")), ["waiting"])
mo.action_assign()
self.assertEqual(list(mo.workorder_ids.mapped("state")), ["ready"])
res_dict = mo.button_mark_done()
self.assertEqual(res_dict.get('res_model'), 'mrp.immediate.production')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(list(mo.workorder_ids.mapped("state")), ["done"])
def test_products_with_variants(self):
"""Check for product with different variants with same bom"""
product = self.env['product.template'].create({
"attribute_line_ids": [
[0, 0, {"attribute_id": 2, "value_ids": [[6, 0, [3, 4]]]}]
],
"name": "Product with variants",
})
variant_1 = product.product_variant_ids[0]
variant_2 = product.product_variant_ids[1]
component = self.env['product.template'].create({
"name": "Component",
})
self.env['mrp.bom'].create({
'product_id': False,
'product_tmpl_id': product.id,
'bom_line_ids': [
(0, 0, {'product_id': component.product_variant_id.id, 'product_qty': 1})
]
})
# First behavior to check, is changing the product (same product but another variant) after saving the MO a first time.
mo_form_1 = Form(self.env['mrp.production'])
mo_form_1.product_id = variant_1
mo_1 = mo_form_1.save()
mo_form_1 = Form(self.env['mrp.production'].browse(mo_1.id))
mo_form_1.product_id = variant_2
mo_1 = mo_form_1.save()
mo_1.action_confirm()
mo_1.action_assign()
mo_form_1 = Form(self.env['mrp.production'].browse(mo_1.id))
mo_form_1.qty_producing = 1
mo_1 = mo_form_1.save()
mo_1.button_mark_done()
move_lines_1 = self.env['stock.move.line'].search([("reference", "=", mo_1.name)])
move_finished_ids_1 = self.env['stock.move'].search([("production_id", "=", mo_1.id)])
self.assertEqual(len(move_lines_1), 2, "There should only be 2 move lines: the component line and produced product line")
self.assertEqual(len(move_finished_ids_1), 1, "There should only be 1 produced product for this MO")
self.assertEqual(move_finished_ids_1.product_id, variant_2, "Incorrect variant produced")
# Second behavior is changing the product before saving the MO
mo_form_2 = Form(self.env['mrp.production'])
mo_form_2.product_id = variant_1
mo_form_2.product_id = variant_2
mo_2 = mo_form_2.save()
mo_2.action_confirm()
mo_2.action_assign()
mo_form_2 = Form(self.env['mrp.production'].browse(mo_2.id))
mo_form_2.qty_producing = 1
mo_2 = mo_form_2.save()
mo_2.button_mark_done()
move_lines_2 = self.env['stock.move.line'].search([("reference", "=", mo_2.name)])
move_finished_ids_2 = self.env['stock.move'].search([("production_id", "=", mo_2.id)])
self.assertEqual(len(move_lines_2), 2, "There should only be 2 move lines: the component line and produced product line")
self.assertEqual(len(move_finished_ids_2), 1, "There should only be 1 produced product for this MO")
self.assertEqual(move_finished_ids_2.product_id, variant_2, "Incorrect variant produced")
# Third behavior is changing the product before saving the MO, then another time after
mo_form_3 = Form(self.env['mrp.production'])
mo_form_3.product_id = variant_1
mo_form_3.product_id = variant_2
mo_3 = mo_form_3.save()
mo_form_3 = Form(self.env['mrp.production'].browse(mo_3.id))
mo_form_3.product_id = variant_1
mo_3 = mo_form_3.save()
mo_3.action_confirm()
mo_3.action_assign()
mo_form_3 = Form(self.env['mrp.production'].browse(mo_3.id))
mo_form_3.qty_producing = 1
mo_3 = mo_form_3.save()
mo_3.button_mark_done()
move_lines_3 = self.env['stock.move.line'].search([("reference", "=", mo_3.name)])
move_finished_ids_3 = self.env['stock.move'].search([("production_id", "=", mo_3.id)])
self.assertEqual(len(move_lines_3), 2, "There should only be 2 move lines: the component line and produced product line")
self.assertEqual(len(move_finished_ids_3), 1, "There should only be 1 produced product for this MO")
self.assertEqual(move_finished_ids_3.product_id, variant_1, "Incorrect variant produced")
def test_manufacturing_order_with_work_orders(self):
"""Test the behavior of a manufacturing order when opening the workorder related to it,
as well as the behavior when a backorder is created
"""
# create a few work centers
work_center_1 = self.env['mrp.workcenter'].create({"name": "WC1"})
work_center_2 = self.env['mrp.workcenter'].create({"name": "WC2"})
work_center_3 = self.env['mrp.workcenter'].create({"name": "WC3"})
# create a product, a bom related to it with 3 components and 3 operations
product = self.env['product.template'].create({"name": "Product"})
component_1 = self.env['product.template'].create({"name": "Component 1", "type": "product"})
component_2 = self.env['product.template'].create({"name": "Component 2", "type": "product"})
component_3 = self.env['product.template'].create({"name": "Component 3", "type": "product"})
self.env['stock.quant'].create({
"product_id": component_1.product_variant_id.id,
"location_id": 8,
"quantity": 100
})
self.env['stock.quant'].create({
"product_id": component_2.product_variant_id.id,
"location_id": 8,
"quantity": 100
})
self.env['stock.quant'].create({
"product_id": component_3.product_variant_id.id,
"location_id": 8,
"quantity": 100
})
self.env['mrp.bom'].create({
"product_tmpl_id": product.id,
"product_id": False,
"product_qty": 1,
"bom_line_ids": [
[0, 0, {"product_id": component_1.product_variant_id.id, "product_qty": 1}],
[0, 0, {"product_id": component_2.product_variant_id.id, "product_qty": 1}],
[0, 0, {"product_id": component_3.product_variant_id.id, "product_qty": 1}]
],
"operation_ids": [
[0, 0, {"name": "Operation 1", "workcenter_id": work_center_1.id}],
[0, 0, {"name": "Operation 2", "workcenter_id": work_center_2.id}],
[0, 0, {"name": "Operation 3", "workcenter_id": work_center_3.id}]
]
})
# create a manufacturing order with 10 product to produce
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product.product_variant_id
mo_form.product_qty = 10
mo = mo_form.save()
self.assertEqual(mo.state, 'draft')
mo.action_confirm()
wo_1 = mo.workorder_ids[0]
wo_2 = mo.workorder_ids[1]
wo_3 = mo.workorder_ids[2]
self.assertEqual(mo.state, 'confirmed')
self.assertEqual(wo_1.state, 'ready')
duration_expected = wo_1.duration_expected
wo_1.button_start()
wo_1.qty_producing = 10
self.assertEqual(mo.state, 'progress')
wo_1.button_finish()
self.assertEqual(duration_expected, wo_1.duration_expected)
duration_expected = wo_2.duration_expected
wo_2.button_start()
wo_2.qty_producing = 8
wo_2.button_finish()
self.assertEqual(duration_expected, wo_2.duration_expected)
duration_expected = wo_3.duration_expected
wo_3.button_start()
wo_3.qty_producing = 8
wo_3.button_finish()
self.assertEqual(duration_expected, wo_3.duration_expected)
self.assertEqual(mo.state, 'to_close')
mo.button_mark_done()
bo = self.env['mrp.production.backorder'].create({
"mrp_production_backorder_line_ids": [
[0, 0, {"mrp_production_id": mo.id, "to_backorder": True}]
]
})
bo.action_backorder()
self.assertEqual(mo.state, 'done')
mo_2 = self.env['mrp.production'].browse(mo.id + 1)
self.assertEqual(mo_2.state, 'progress')
wo_4, wo_5, wo_6 = mo_2.workorder_ids
self.assertEqual(wo_4.state, 'cancel')
wo_5.button_start()
self.assertEqual(mo_2.state, 'progress')
wo_5.button_finish()
wo_6.button_start()
wo_6.button_finish()
self.assertEqual(mo_2.state, 'to_close')
mo_2.button_mark_done()
self.assertEqual(mo_2.state, 'done')
def test_move_finished_onchanges(self):
""" Test that move_finished_ids (i.e. produced products) are still correct even after
multiple onchanges have changed the the moves
"""
product1 = self.env['product.product'].create({
'name': 'Oatmeal Cookie',
})
product2 = self.env['product.product'].create({
'name': 'Chocolate Chip Cookie',
})
# ===== product_id onchange checks ===== #
# check product_id onchange without saving
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product1
mo_form.product_id = product2
mo = mo_form.save()
self.assertEqual(len(mo.move_finished_ids), 1, 'Wrong number of finished product moves created')
self.assertEqual(mo.move_finished_ids.product_id, product2, 'Wrong product to produce in finished product move')
# check product_id onchange after saving
mo_form = Form(self.env['mrp.production'].browse(mo.id))
mo_form.product_id = product1
mo = mo_form.save()
self.assertEqual(len(mo.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo.move_finished_ids.product_id, product1, 'Wrong product to produce in finished product move')
# check product_id onchange when mo._origin.product_id is unchanged
mo_form = Form(self.env['mrp.production'].browse(mo.id))
mo_form.product_id = product2
mo_form.product_id = product1
mo = mo_form.save()
self.assertEqual(len(mo.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo.move_finished_ids.product_id, product1, 'Wrong product to produce in finished product move')
# ===== product_qty onchange checks ===== #
# check product_qty onchange without saving
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product1
mo_form.product_qty = 5
mo_form.product_qty = 10
mo2 = mo_form.save()
self.assertEqual(len(mo2.move_finished_ids), 1, 'Wrong number of finished product moves created')
self.assertEqual(mo2.move_finished_ids.product_qty, 10, 'Wrong qty to produce for the finished product move')
# check product_qty onchange after saving
mo_form = Form(self.env['mrp.production'].browse(mo2.id))
mo_form.product_qty = 5
mo2 = mo_form.save()
self.assertEqual(len(mo2.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo2.move_finished_ids.product_qty, 5, 'Wrong qty to produce for the finished product move')
# check product_qty onchange when mo._origin.product_id is unchanged
mo_form = Form(self.env['mrp.production'].browse(mo2.id))
mo_form.product_qty = 10
mo_form.product_qty = 5
mo2 = mo_form.save()
self.assertEqual(len(mo2.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo2.move_finished_ids.product_qty, 5, 'Wrong qty to produce for the finished product move')
# ===== product_uom_id onchange checks ===== #
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product1
mo_form.product_qty = 1
mo_form.product_uom_id = self.env['uom.uom'].browse(self.ref('uom.product_uom_dozen'))
mo3 = mo_form.save()
self.assertEqual(len(mo3.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo3.move_finished_ids.product_qty, 12, 'Wrong qty to produce for the finished product move')
# ===== bom_id onchange checks ===== #
component = self.env['product.product'].create({
"name": "Sugar",
})
bom1 = self.env['mrp.bom'].create({
'product_id': False,
'product_tmpl_id': product1.product_tmpl_id.id,
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 1})
]
})
bom2 = self.env['mrp.bom'].create({
'product_id': False,
'product_tmpl_id': product1.product_tmpl_id.id,
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 10})
]
})
# check bom_id onchange before product change
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = bom1
mo_form.bom_id = bom2
mo_form.product_id = product2
mo4 = mo_form.save()
self.assertFalse(mo4.bom_id, 'BoM should have been removed')
self.assertEqual(len(mo4.move_finished_ids), 1, 'Wrong number of finished product moves created')
self.assertEqual(mo4.move_finished_ids.product_id, product2, 'Wrong product to produce in finished product move')
# check bom_id onchange after product change
mo_form = Form(self.env['mrp.production'].browse(mo4.id))
mo_form.product_id = product1
mo_form.bom_id = bom1
mo_form.bom_id = bom2
mo4 = mo_form.save()
self.assertEqual(len(mo4.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo4.move_finished_ids.product_id, product1, 'Wrong product to produce in finished product move')
# check product_id onchange when mo._origin.product_id is unchanged
mo_form = Form(self.env['mrp.production'].browse(mo4.id))
mo_form.bom_id = bom2
mo_form.bom_id = bom1
mo4 = mo_form.save()
self.assertEqual(len(mo4.move_finished_ids), 1, 'Wrong number of finish product moves created')
self.assertEqual(mo4.move_finished_ids.product_id, product1, 'Wrong product to produce in finished product move')
def test_compute_tracked_time_1(self):
"""
Checks that the Duration Computation (`time_mode` of mrp.routing.workcenter) with value `auto` with Based On
(`time_mode_batch`) set to 1 actually compute the time based on the last 1 operation, and not more.
Create a first production in 15 minutes (expected should go from 60 to 15
Create a second one in 10 minutes (expected should NOT go from 15 to 12.5, it should go from 15 to 10)
"""
# First production, the default is 60 and there is 0 productions of that operation
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_4
production = production_form.save()
self.assertEqual(production.workorder_ids[0].duration_expected, 60.0, "Default duration is 0+0+1*60.0")
production.action_confirm()
production.button_plan()
# Production planned, time to start, I produce all the 1 product
production_form.qty_producing = 1
with production_form.workorder_ids.edit(0) as wo:
wo.duration = 15 # in 15 minutes
production = production_form.save()
production.button_mark_done()
# It is saved and done, registered in the db. There are now 1 productions of that operation
# Same production, let's see what the duration_expected is, last prod was 15 minutes for 1 item
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_4
production = production_form.save()
self.assertEqual(production.workorder_ids[0].duration_expected, 15.0, "Duration is now 0+0+1*15")
production.action_confirm()
production.button_plan()
# Production planned, time to start, I produce all the 1 product
production_form.qty_producing = 1
with production_form.workorder_ids.edit(0) as wo:
wo.duration = 10 # In 10 minutes this time
production = production_form.save()
production.button_mark_done()
# It is saved and done, registered in the db. There are now 2 productions of that operation
# Same production, let's see what the duration_expected is, last prod was 10 minutes for 1 item
# Total average time would be 12.5 but we compute the duration based on the last 1 item
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_4
production = production_form.save()
self.assertNotEqual(production.workorder_ids[0].duration_expected, 12.5, "Duration expected is based on the last 1 production, not last 2")
self.assertEqual(production.workorder_ids[0].duration_expected, 10.0, "Duration is now 0+0+1*10")
def test_compute_tracked_time_2_under_capacity(self):
"""
Test that when tracking the 2 last production, if we make one with under capacity, and one with normal capacity,
the two are equivalent (1 done with capacity 2 in 10mn = 2 done with capacity 2 in 10mn)
"""
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_5
production = production_form.save()
production.action_confirm()
production.button_plan()
# Production planned, time to start, I produce all the 1 product
production_form.qty_producing = 1
with production_form.workorder_ids.edit(0) as wo:
wo.duration = 10 # in 10 minutes
production = production_form.save()
production.button_mark_done()
# It is saved and done, registered in the db. There are now 1 productions of that operation
# Same production, let's see what the duration_expected is, last prod was 10 minutes for 1 item
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_5
production_form.product_qty = 2 # We want to produce 2 items (the capacity) now
production = production_form.save()
self.assertNotEqual(production.workorder_ids[0].duration_expected, 20.0, "We made 1 item with capacity 2 in 10mn -> so 2 items shouldn't be double that")
self.assertEqual(production.workorder_ids[0].duration_expected, 10.0, "Producing 1 or 2 items with capacity 2 is the same duration")
production.action_confirm()
production.button_plan()
# Production planned, time to start, I produce all the 2 product
production_form.qty_producing = 2
with production_form.workorder_ids.edit(0) as wo:
wo.duration = 10 # In 10 minutes this time
production = production_form.save()
production.button_mark_done()
# It is saved and done, registered in the db. There are now 2 productions of that operation but they have the same duration
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_5
production = production_form.save()
self.assertNotEqual(production.workorder_ids[0].duration_expected, 15, "Producing 1 or 2 in 10mn with capacity 2 take the same amount of time : 10mn")
self.assertEqual(production.workorder_ids[0].duration_expected, 10.0, "Duration is indeed (10+10)/2")
def test_capacity_duration_expected(self):
"""
Test that the duration expected is correctly computed when dealing with below or above capacity
1 -> 10mn
2 -> 10mn
3 -> 20mn
4 -> 20mn
5 -> 30mn
...
"""
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_6
production = production_form.save()
production.action_confirm()
production.button_plan()
# Production planned, time to start, I produce all the 1 product
production_form.qty_producing = 1
with production_form.workorder_ids.edit(0) as wo:
wo.duration = 10 # in 10 minutes
production = production_form.save()
production.button_mark_done()
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_6
production = production_form.save()
# production_form.product_qty = 1 [BY DEFAULT]
self.assertEqual(production.workorder_ids[0].duration_expected, 10.0, "Produce 1 with capacity 2, expected is 10mn for each run -> 10mn")
production_form.product_qty = 2
production = production_form.save()
self.assertEqual(production.workorder_ids[0].duration_expected, 10.0, "Produce 2 with capacity 2, expected is 10mn for each run -> 10mn")
production_form.product_qty = 3
production = production_form.save()
self.assertEqual(production.workorder_ids[0].duration_expected, 20.0, "Produce 3 with capacity 2, expected is 10mn for each run -> 20mn")
production_form.product_qty = 4
production = production_form.save()
self.assertEqual(production.workorder_ids[0].duration_expected, 20.0, "Produce 4 with capacity 2, expected is 10mn for each run -> 20mn")
production_form.product_qty = 5
production = production_form.save()
self.assertEqual(production.workorder_ids[0].duration_expected, 30.0, "Produce 5 with capacity 2, expected is 10mn for each run -> 30mn")
def test_planning_workorder(self):
"""
Check that the fastest work center is used when planning the workorder.
- create two work centers with similar production capacity
but the work_center_2 with a longer start and stop time.
1:/ produce 2 units > work_center_1 faster because
it does not need much time to start and to finish the production.
2/ - update the production capacity of the work_center_2 to 4
- produce 4 units > work_center_2 faster because
it must do a single cycle while the work_center_1 have to do two cycles.
"""
workcenter_1 = self.env['mrp.workcenter'].create({
'name': 'wc1',
'capacity': 2,
'time_start': 1,
'time_stop': 1,
'time_efficiency': 100,
})
workcenter_2 = self.env['mrp.workcenter'].create({
'name': 'wc2',
'capacity': 2,
'time_start': 10,
'time_stop': 5,
'time_efficiency': 100,
'alternative_workcenter_ids': [workcenter_1.id]
})
product_to_build = self.env['product.product'].create({
'name': 'final product',
'type': 'product',
})
product_to_use = self.env['product.product'].create({
'name': 'component',
'type': 'product',
})
bom = self.env['mrp.bom'].create({
'product_id': product_to_build.id,
'product_tmpl_id': product_to_build.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'consumption': 'flexible',
'operation_ids': [
(0, 0, {'name': 'Test', 'workcenter_id': workcenter_2.id, 'time_cycle': 60, 'sequence': 1}),
],
'bom_line_ids': [
(0, 0, {'product_id': product_to_use.id, 'product_qty': 1}),
]})
#MO_1
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_to_build
mo_form.bom_id = bom
mo_form.product_qty = 2
mo = mo_form.save()
mo.action_confirm()
mo.button_plan()
self.assertEqual(mo.workorder_ids[0].workcenter_id.id, workcenter_1.id, 'workcenter_1 is faster than workcenter_2 to manufacture 2 units')
# Unplan the mo to prevent the first workcenter from being busy
mo.button_unplan()
# Update the production capcity
workcenter_2.capacity = 4
#MO_2
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_to_build
mo_form.bom_id = bom
mo_form.product_qty = 4
mo_2 = mo_form.save()
mo_2.action_confirm()
mo_2.button_plan()
self.assertEqual(mo_2.workorder_ids[0].workcenter_id.id, workcenter_2.id, 'workcenter_2 is faster than workcenter_1 to manufacture 4 units')
def test_timers_after_cancelling_mo(self):
"""
Check that the timers in the workorders are stopped after the cancellation of the MO
"""
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_2
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
mo.button_plan()
wo = mo.workorder_ids
wo.button_start()
mo.action_cancel()
self.assertEqual(mo.state, 'cancel', 'Manufacturing order should be cancelled.')
self.assertEqual(wo.state, 'cancel', 'Workorders should be cancelled.')
self.assertTrue(mo.workorder_ids.time_ids.date_end, 'The timers must stop after the cancellation of the MO')
def test_starting_wo_twice(self):
"""
Check that the work order is started only once when clicking the start button several times.
"""
production_form = Form(self.env['mrp.production'])
production_form.bom_id = self.bom_2
production_form.product_qty = 1
production = production_form.save()
production_form = Form(production)
with production_form.workorder_ids.new() as wo:
wo.name = 'OP1'
wo.workcenter_id = self.workcenter_1
wo.duration_expected = 40
production = production_form.save()
production.action_confirm()
production.button_plan()
production.workorder_ids[0].button_start()
production.workorder_ids[0].button_start()
self.assertEqual(len(production.workorder_ids[0].time_ids.filtered(lambda t: t.date_start and not t.date_end)), 1)
def test_qty_update_and_method_reservation(self):
"""
When the reservation method of Manufacturing is 'manual', updating the
quantity of a confirmed MO shouldn't trigger the reservation of the
components
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], order='id', limit=1)
warehouse.manu_type_id.reservation_method = 'manual'
for product in self.product_1 + self.product_2:
product.type = 'product'
self.env['stock.quant']._update_available_quantity(product, warehouse.lot_stock_id, 10)
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_1
mo = mo_form.save()
mo.action_confirm()
self.assertFalse(mo.move_raw_ids.move_line_ids)
wizard = self.env['change.production.qty'].create({
'mo_id': mo.id,
'product_qty': 5,
})
wizard.change_prod_qty()
self.assertFalse(mo.move_raw_ids.move_line_ids)
def test_source_and_child_mo(self):
"""
Suppose three manufactured products A, B and C. C is a component of B
and B is a component of A. If B and C have the routes MTO + Manufacture,
when producing one A, it should generate a MO for B and C. Moreover,
starting from one of the MOs, we should be able to find the source/child
MO.
(The test checks the flow in 1-step, 2-steps and 3-steps manufacturing)
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
mto_route = warehouse.mto_pull_id.route_id
manufacture_route = warehouse.manufacture_pull_id.route_id
mto_route.active = True
grandparent, parent, child = self.env['product.product'].create([{
'name': n,
'type': 'product',
'route_ids': [(6, 0, mto_route.ids + manufacture_route.ids)],
} for n in ['grandparent', 'parent', 'child']])
component = self.env['product.product'].create({
'name': 'component',
'type': 'consu',
})
self.env['mrp.bom'].create([{
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_qty': 1,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': compo.id, 'product_qty': 1}),
],
} for finished_product, compo in [(grandparent, parent), (parent, child), (child, component)]])
none_production = self.env['mrp.production']
for steps, case_description, in [('mrp_one_step', '1-step Manufacturing'), ('pbm', '2-steps Manufacturing'), ('pbm_sam', '3-steps Manufacturing')]:
warehouse.manufacture_steps = steps
grandparent_production_form = Form(self.env['mrp.production'])
grandparent_production_form.product_id = grandparent
grandparent_production = grandparent_production_form.save()
grandparent_production.action_confirm()
child_production, parent_production = self.env['mrp.production'].search([('product_id', 'in', (parent + child).ids)], order='id desc', limit=2)
for source_mo, mo, product, child_mo in [(none_production, grandparent_production, grandparent, parent_production),
(grandparent_production, parent_production, parent, child_production),
(parent_production, child_production, child, none_production)]:
self.assertEqual(mo.product_id, product, '[%s] There should be a MO for product %s' % (case_description, product.display_name))
self.assertEqual(mo.mrp_production_source_count, len(source_mo), '[%s] Incorrect value for product %s' % (case_description, product.display_name))
self.assertEqual(mo.mrp_production_child_count, len(child_mo), '[%s] Incorrect value for product %s' % (case_description, product.display_name))
source_action = mo.action_view_mrp_production_sources()
child_action = mo.action_view_mrp_production_childs()
self.assertEqual(source_action.get('res_id', False), source_mo.id, '[%s] Incorrect value for product %s' % (case_description, product.display_name))
self.assertEqual(child_action.get('res_id', False), child_mo.id, '[%s] Incorrect value for product %s' % (case_description, product.display_name))
@freeze_time('2022-06-28 08:00')
def test_replan_workorders01(self):
"""
Create two MO, each one with one WO. Set the same scheduled start date
to each WO during the creation of the MO. A warning will be displayed.
-> The user replans one of the WO: the warnings should disappear and the
WO should be postponed.
"""
mos = self.env['mrp.production']
for _ in range(2):
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_4
with mo_form.workorder_ids.edit(0) as wo_line:
wo_line.date_planned_start = datetime.now()
mos += mo_form.save()
mos.action_confirm()
mo_01, mo_02 = mos
wo_01 = mo_01.workorder_ids
wo_02 = mo_02.workorder_ids
self.assertTrue(wo_01.show_json_popover)
self.assertTrue(wo_02.show_json_popover)
wo_02.action_replan()
self.assertFalse(wo_01.show_json_popover)
self.assertFalse(wo_02.show_json_popover)
self.assertEqual(wo_01.date_planned_finished, wo_02.date_planned_start)
@freeze_time('2022-06-28 08:00')
def test_replan_workorders02(self):
"""
Create two MO, each one with one WO. Set the same scheduled start date
to each WO after the creation of the MO. A warning will be displayed.
-> The user replans one of the WO: the warnings should disappear and the
WO should be postponed.
"""
mos = self.env['mrp.production']
for _ in range(2):
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_4
mos += mo_form.save()
mos.action_confirm()
mo_01, mo_02 = mos
for mo in mos:
with Form(mo) as mo_form:
with mo_form.workorder_ids.edit(0) as wo_line:
wo_line.date_planned_start = datetime.now()
wo_01 = mo_01.workorder_ids
wo_02 = mo_02.workorder_ids
self.assertTrue(wo_01.show_json_popover)
self.assertTrue(wo_02.show_json_popover)
wo_02.action_replan()
self.assertFalse(wo_01.show_json_popover)
self.assertFalse(wo_02.show_json_popover)
self.assertEqual(wo_01.date_planned_finished, wo_02.date_planned_start)
def test_move_raw_uom_rounding(self):
"""Test that the correct rouding is applied on move_raw in
manufacturing orders"""
self.box250 = self.env['uom.uom'].create({
'name': 'box250',
'category_id': self.env.ref('uom.product_uom_categ_unit').id,
'ratio': 250.0,
'uom_type': 'bigger',
'rounding': 1.0,
})
test_bom = self.env['mrp.bom'].create({
'product_tmpl_id': self.product_7_template.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 250.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': self.product_2.id, 'product_qty': 1.0, 'product_uom_id': self.box250.id}),
]
})
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = test_bom
mo = mo_form.save()
mo.action_confirm()
update_quantity_wizard = self.env['change.production.qty'].create({
'mo_id': mo.id,
'product_qty': 300,
})
update_quantity_wizard.change_prod_qty()
self.assertEqual(mo.move_raw_ids[0].product_uom_qty, 2)
def test_update_qty_to_consume_of_component(self):
"""
The UoM of the finished product has a rounding precision equal to 1.0
and the UoM of the component has a decimal one. When the producing qty
is set, an onchange autocomplete the consumed quantity of the component.
Then, when updating the 'to consume' quantity of the components, their
consumed quantity is updated again. The test ensures that this update
respects the rounding precisions
"""
self.uom_dozen.rounding = 1
self.bom_4.product_uom_id = self.uom_dozen
mo_form = Form(self.env['mrp.production'])
mo_form.bom_id = self.bom_4
mo = mo_form.save()
mo.action_confirm()
mo.action_toggle_is_locked()
with Form(mo) as mo_form:
mo_form.qty_producing = 1
with mo_form.move_raw_ids.edit(0) as raw:
raw.product_uom_qty = 1.25
self.assertEqual(mo.move_raw_ids.quantity_done, 1.25)
def test_onchange_bom_ids_and_picking_type(self):
warehouse01 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse02, warehouse03 = self.env['stock.warehouse'].create([
{'name': 'Second Warehouse', 'code': 'WH02'},
{'name': 'Third Warehouse', 'code': 'WH03'},
])
finished_product = self.env['product.product'].create({'name': 'finished product'})
bom_wh01, bom_wh02 = self.env['mrp.bom'].create([{
'product_id': finished_product.id,
'product_tmpl_id': finished_product.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'bom_line_ids': [(0, 0, {'product_id': self.product_0.id, 'product_qty': 1})],
'picking_type_id': wh.manu_type_id.id,
'sequence': wh.id,
} for wh in [warehouse01, warehouse02]])
# Prioritize BoM of WH02
bom_wh01.sequence = bom_wh02.sequence + 1
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished_product
self.assertEqual(mo_form.bom_id, bom_wh02, 'Should select the first BoM in the list, whatever the picking type is')
self.assertEqual(mo_form.picking_type_id, warehouse02.manu_type_id)
mo_form.bom_id = bom_wh01
self.assertEqual(mo_form.picking_type_id, warehouse01.manu_type_id, 'Should be adapted because of the found BoM')
mo_form.bom_id = bom_wh02
self.assertEqual(mo_form.picking_type_id, warehouse02.manu_type_id, 'Should be adapted because of the found BoM')
mo_form.picking_type_id = warehouse01.manu_type_id
self.assertEqual(mo_form.bom_id, bom_wh02, 'Should not change')
self.assertEqual(mo_form.picking_type_id, warehouse01.manu_type_id, 'Should not change')
mo_form.picking_type_id = warehouse03.manu_type_id
mo_form.bom_id = bom_wh01
self.assertEqual(mo_form.picking_type_id, warehouse01.manu_type_id, 'Should be adapted because of the found BoM '
'(the selected picking type should be ignored)')
mo_form = Form(self.env['mrp.production'].with_context(default_picking_type_id=warehouse03.manu_type_id.id))
mo_form.product_id = finished_product
self.assertFalse(mo_form.bom_id, 'Should not find any BoM, because of the defined picking type')
self.assertEqual(mo_form.picking_type_id, warehouse03.manu_type_id)
mo_form = Form(self.env['mrp.production'].with_context(default_picking_type_id=warehouse01.manu_type_id.id))
mo_form.product_id = finished_product
self.assertEqual(mo_form.bom_id, bom_wh01, 'Should select the BoM that matches the default picking type')
self.assertEqual(mo_form.picking_type_id, warehouse01.manu_type_id, 'Should be the default one')
mo_form.bom_id = bom_wh02
self.assertEqual(mo_form.picking_type_id, warehouse01.manu_type_id, 'Should not change, because of default value')
mo_form.picking_type_id = warehouse02.manu_type_id
self.assertEqual(mo_form.bom_id, bom_wh02, 'Should not change')
self.assertEqual(mo_form.picking_type_id, warehouse02.manu_type_id, 'Should not change')
mo_form.picking_type_id = warehouse02.manu_type_id
mo_form.bom_id = bom_wh02
self.assertEqual(mo_form.picking_type_id, warehouse01.manu_type_id, 'Should be adapted because of the default value')
| 47.29113 | 135,962 |
40,526 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.exceptions import UserError
class TestUnbuild(TestMrpCommon):
def setUp(self):
super(TestUnbuild, self).setUp()
self.stock_location = self.env.ref('stock.stock_location_stock')
self.env.ref('base.group_user').write({
'implied_ids': [(4, self.env.ref('stock.group_production_lot').id)]
})
def test_unbuild_standart(self):
""" This test creates a MO and then creates 3 unbuild
orders for the final product. None of the products for this
test are tracked. It checks the stock state after each order
and ensure it is correct.
"""
mo, bom, p_final, p1, p2 = self.generate_mo()
self.assertEqual(len(mo), 1, 'MO should have been created')
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check quantity in stock before unbuild.
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 5, 'You should have the 5 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 80, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 0, 'You should have consumed all the 5 product in stock')
# ---------------------------------------------------
# unbuild
# ---------------------------------------------------
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 3
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 2, 'You should have consumed 3 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 92, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 3, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 2
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 0, 'You should have 0 finalproduct in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 100, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 5, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 5
x.save().action_unbuild()
# Check quantity in stock after last unbuild.
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, allow_negative=True), -5, 'You should have negative quantity for final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 120, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 10, 'You should have consumed all the 5 product in stock')
def test_unbuild_with_final_lot(self):
""" This test creates a MO and then creates 3 unbuild
orders for the final product. Only the final product is tracked
by lot. It checks the stock state after each order
and ensure it is correct.
"""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_final='lot')
self.assertEqual(len(mo), 1, 'MO should have been created')
lot = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo_form.lot_producing_id = lot
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check quantity in stock before unbuild.
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot), 5, 'You should have the 5 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 80, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 0, 'You should have consumed all the 5 product in stock')
# ---------------------------------------------------
# unbuild
# ---------------------------------------------------
# This should fail since we do not choose a lot to unbuild for final product.
with self.assertRaises(AssertionError):
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 3
unbuild_order = x.save()
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 3
x.lot_id = lot
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot), 2, 'You should have consumed 3 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 92, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 3, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 2
x.lot_id = lot
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot), 0, 'You should have 0 finalproduct in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 100, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 5, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 5
x.lot_id = lot
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot, allow_negative=True), -5, 'You should have negative quantity for final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 120, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 10, 'You should have consumed all the 5 product in stock')
def test_unbuild_with_comnsumed_lot(self):
""" This test creates a MO and then creates 3 unbuild
orders for the final product. Only once of the two consumed
product is tracked by lot. It checks the stock state after each
order and ensure it is correct.
"""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_base_1='lot')
self.assertEqual(len(mo), 1, 'MO should have been created')
lot = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': p1.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100, lot_id=lot)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5)
mo.action_assign()
for ml in mo.move_raw_ids.mapped('move_line_ids'):
if ml.product_id.tracking != 'none':
self.assertEqual(ml.lot_id, lot, 'Wrong reserved lot.')
# FIXME sle: behavior change
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.lot_id = lot
ml.qty_done = 20
details_operation_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check quantity in stock before unbuild.
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 5, 'You should have the 5 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot), 80, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 0, 'You should have consumed all the 5 product in stock')
# ---------------------------------------------------
# unbuild
# ---------------------------------------------------
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.product_qty = 3
unbuild_order = x.save()
# This should fail since we do not provide the MO that we wanted to unbuild. (without MO we do not know which consumed lot we have to restore)
with self.assertRaises(UserError):
unbuild_order.action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 5, 'You should have consumed 3 final product in stock')
unbuild_order.mo_id = mo.id
unbuild_order.action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 2, 'You should have consumed 3 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot), 92, 'You should have 92 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 3, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 2
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 0, 'You should have 0 finalproduct in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot), 100, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 5, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 5
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, allow_negative=True), -5, 'You should have negative quantity for final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot), 120, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location), 10, 'You should have consumed all the 5 product in stock')
def test_unbuild_with_everything_tracked(self):
""" This test creates a MO and then creates 3 unbuild
orders for the final product. All the products for this
test are tracked. It checks the stock state after each order
and ensure it is correct.
"""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_final='lot', tracking_base_2='lot', tracking_base_1='lot')
self.assertEqual(len(mo), 1, 'MO should have been created')
lot_final = self.env['stock.production.lot'].create({
'name': 'lot_final',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
lot_1 = self.env['stock.production.lot'].create({
'name': 'lot_consumed_1',
'product_id': p1.id,
'company_id': self.env.company.id,
})
lot_2 = self.env['stock.production.lot'].create({
'name': 'lot_consumed_2',
'product_id': p2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100, lot_id=lot_1)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 5, lot_id=lot_2)
mo.action_assign()
# FIXME sle: behavior change
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo_form.lot_producing_id = lot_final
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 5
details_operation_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 20
details_operation_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check quantity in stock before unbuild.
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final), 5, 'You should have the 5 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot_1), 80, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_2), 0, 'You should have consumed all the 5 product in stock')
# ---------------------------------------------------
# unbuild
# ---------------------------------------------------
x = Form(self.env['mrp.unbuild'])
with self.assertRaises(AssertionError):
x.product_id = p_final
x.bom_id = bom
x.product_qty = 3
x.save()
with self.assertRaises(AssertionError):
x.product_id = p_final
x.bom_id = bom
x.product_qty = 3
x.save()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final), 5, 'You should have consumed 3 final product in stock')
with self.assertRaises(AssertionError):
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 3
x.save()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final), 5, 'You should have consumed 3 final product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 3
x.lot_id = lot_final
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final), 2, 'You should have consumed 3 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot_1), 92, 'You should have 92 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_2), 3, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 2
x.lot_id = lot_final
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final), 0, 'You should have 0 finalproduct in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot_1), 100, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_2), 5, 'You should have consumed all the 5 product in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 5
x.lot_id = lot_final
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location, lot_id=lot_final, allow_negative=True), -5, 'You should have negative quantity for final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location, lot_id=lot_1), 120, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_2), 10, 'You should have consumed all the 5 product in stock')
def test_unbuild_with_duplicate_move(self):
""" This test creates a MO from 3 different lot on a consumed product (p2).
The unbuild order should revert the correct quantity for each specific lot.
"""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_final='none', tracking_base_2='lot', tracking_base_1='none')
self.assertEqual(len(mo), 1, 'MO should have been created')
lot_1 = self.env['stock.production.lot'].create({
'name': 'lot_1',
'product_id': p2.id,
'company_id': self.env.company.id,
})
lot_2 = self.env['stock.production.lot'].create({
'name': 'lot_2',
'product_id': p2.id,
'company_id': self.env.company.id,
})
lot_3 = self.env['stock.production.lot'].create({
'name': 'lot_3',
'product_id': p2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 100)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 1, lot_id=lot_1)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 3, lot_id=lot_2)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 2, lot_id=lot_3)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids.filtered(lambda ml: ml.product_id == p2), view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = ml.product_uom_qty
with details_operation_form.move_line_ids.edit(1) as ml:
ml.qty_done = ml.product_uom_qty
with details_operation_form.move_line_ids.edit(2) as ml:
ml.qty_done = ml.product_uom_qty
details_operation_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check quantity in stock before unbuild.
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 5, 'You should have the 5 final product in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 80, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_1), 0, 'You should have consumed all the 1 product for lot 1 in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_2), 0, 'You should have consumed all the 3 product for lot 2 in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_3), 1, 'You should have consumed only 1 product for lot3 in stock')
x = Form(self.env['mrp.unbuild'])
x.product_id = p_final
x.bom_id = bom
x.mo_id = mo
x.product_qty = 5
x.save().action_unbuild()
self.assertEqual(self.env['stock.quant']._get_available_quantity(p_final, self.stock_location), 0, 'You should have no more final product in stock after unbuild')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p1, self.stock_location), 100, 'You should have 80 products in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_1), 1, 'You should have get your product with lot 1 in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_2), 3, 'You should have the 3 basic product for lot 2 in stock')
self.assertEqual(self.env['stock.quant']._get_available_quantity(p2, self.stock_location, lot_id=lot_3), 2, 'You should have get one product back for lot 3')
def test_production_links_with_non_tracked_lots(self):
""" This test produces an MO in two times and checks that the move lines are linked in a correct way
"""
mo, bom, p_final, p1, p2 = self.generate_mo(tracking_final='lot', tracking_base_1='none', tracking_base_2='lot')
# Young Tom
# \ Botox - 4 - p1
# \ Old Tom - 1 - p2
lot_1 = self.env['stock.production.lot'].create({
'name': 'lot_1',
'product_id': p2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 3, lot_id=lot_1)
lot_finished_1 = self.env['stock.production.lot'].create({
'name': 'lot_finished_1',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
self.assertEqual(mo.product_qty, 5)
mo_form = Form(mo)
mo_form.qty_producing = 3.0
mo_form.lot_producing_id = lot_finished_1
mo = mo_form.save()
self.assertEqual(mo.move_raw_ids[1].quantity_done, 12)
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 3
ml.lot_id = lot_1
details_operation_form.save()
action = mo.button_mark_done()
backorder = Form(self.env[action['res_model']].with_context(**action['context']))
backorder.save().action_backorder()
lot_2 = self.env['stock.production.lot'].create({
'name': 'lot_2',
'product_id': p2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 4, lot_id=lot_2)
lot_finished_2 = self.env['stock.production.lot'].create({
'name': 'lot_finished_2',
'product_id': p_final.id,
'company_id': self.env.company.id,
})
mo = mo.procurement_group_id.mrp_production_ids[1]
# FIXME sle: issue in backorder?
mo.move_raw_ids.move_line_ids.unlink()
self.assertEqual(mo.product_qty, 2)
mo_form = Form(mo)
mo_form.qty_producing = 2
mo_form.lot_producing_id = lot_finished_2
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 2
ml.lot_id = lot_2
details_operation_form.save()
action = mo.button_mark_done()
mo1 = mo.procurement_group_id.mrp_production_ids[0]
ml = mo1.finished_move_line_ids[0].consume_line_ids.filtered(lambda m: m.product_id == p1 and lot_finished_1 in m.produce_line_ids.lot_id)
self.assertEqual(sum(ml.mapped('qty_done')), 12.0, 'Should have consumed 12 for the first lot')
ml = mo.finished_move_line_ids[0].consume_line_ids.filtered(lambda m: m.product_id == p1 and lot_finished_2 in m.produce_line_ids.lot_id)
self.assertEqual(sum(ml.mapped('qty_done')), 8.0, 'Should have consumed 8 for the second lot')
def test_unbuild_with_routes(self):
""" This test creates a MO of a stockable product (Table). A new route for rule QC/Unbuild -> Stock
is created with Warehouse -> True.
The unbuild order should revert the consumed components into QC/Unbuild location for quality check
and then a picking should be generated for transferring components from QC/Unbuild location to stock.
"""
StockQuant = self.env['stock.quant']
ProductObj = self.env['product.product']
# Create new QC/Unbuild location
warehouse = self.env.ref('stock.warehouse0')
unbuild_location = self.env['stock.location'].create({
'name': 'QC/Unbuild',
'usage': 'internal',
'location_id': warehouse.view_location_id.id
})
# Create a product route containing a stock rule that will move product from QC/Unbuild location to stock
product_route = self.env['stock.location.route'].create({
'name': 'QC/Unbuild -> Stock',
'warehouse_selectable': True,
'warehouse_ids': [(4, warehouse.id)],
'rule_ids': [(0, 0, {
'name': 'Send Matrial QC/Unbuild -> Stock',
'action': 'push',
'picking_type_id': self.ref('stock.picking_type_internal'),
'location_src_id': unbuild_location.id,
'location_id': self.stock_location.id,
})],
})
# Create a stockable product and its components
finshed_product = ProductObj.create({
'name': 'Table',
'type': 'product',
})
component1 = ProductObj.create({
'name': 'Table head',
'type': 'product',
})
component2 = ProductObj.create({
'name': 'Table stand',
'type': 'product',
})
# Create bom and add components
bom = self.env['mrp.bom'].create({
'product_id': finshed_product.id,
'product_tmpl_id': finshed_product.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component1.id, 'product_qty': 1}),
(0, 0, {'product_id': component2.id, 'product_qty': 1})
]})
# Set on hand quantity
StockQuant._update_available_quantity(component1, self.stock_location, 1)
StockQuant._update_available_quantity(component2, self.stock_location, 1)
# Create mo
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finshed_product
mo_form.bom_id = bom
mo_form.product_uom_id = finshed_product.uom_id
mo_form.product_qty = 1.0
mo = mo_form.save()
self.assertEqual(len(mo), 1, 'MO should have been created')
mo.action_confirm()
mo.action_assign()
# Produce the final product
mo_form = Form(mo)
mo_form.qty_producing = 1.0
produce_wizard = mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
# Check quantity in stock before unbuild
self.assertEqual(StockQuant._get_available_quantity(finshed_product, self.stock_location), 1, 'Table should be available in stock')
self.assertEqual(StockQuant._get_available_quantity(component1, self.stock_location), 0, 'Table head should not be available in stock')
self.assertEqual(StockQuant._get_available_quantity(component2, self.stock_location), 0, 'Table stand should not be available in stock')
# ---------------------------------------------------
# Unbuild
# ---------------------------------------------------
# Create an unbuild order of the finished product and set the destination loacation = QC/Unbuild
x = Form(self.env['mrp.unbuild'])
x.product_id = finshed_product
x.bom_id = bom
x.mo_id = mo
x.product_qty = 1
x.location_id = self.stock_location
x.location_dest_id = unbuild_location
x.save().action_unbuild()
# Check the available quantity of components and final product in stock
self.assertEqual(StockQuant._get_available_quantity(finshed_product, self.stock_location), 0, 'Table should not be available in stock as it is unbuild')
self.assertEqual(StockQuant._get_available_quantity(component1, self.stock_location), 0, 'Table head should not be available in stock as it is in QC/Unbuild location')
self.assertEqual(StockQuant._get_available_quantity(component2, self.stock_location), 0, 'Table stand should not be available in stock as it is in QC/Unbuild location')
# Find new generated picking
picking = self.env['stock.picking'].search([('product_id', 'in', [component1.id, component2.id])])
self.assertEqual(picking.location_id.id, unbuild_location.id, 'Wrong source location in picking')
self.assertEqual(picking.location_dest_id.id, self.stock_location.id, 'Wrong destination location in picking')
# Transfer it
for ml in picking.move_ids_without_package:
ml.quantity_done = 1
picking._action_done()
# Check the available quantity of components and final product in stock
self.assertEqual(StockQuant._get_available_quantity(finshed_product, self.stock_location), 0, 'Table should not be available in stock')
self.assertEqual(StockQuant._get_available_quantity(component1, self.stock_location), 1, 'Table head should be available in stock as the picking is transferred')
self.assertEqual(StockQuant._get_available_quantity(component2, self.stock_location), 1, 'Table stand should be available in stock as the picking is transferred')
def test_unbuild_decimal_qty(self):
"""
Use case:
- decimal accuracy of Product UoM > decimal accuracy of Units
- unbuild a product with a decimal quantity of component
"""
self.env['decimal.precision'].search([('name', '=', 'Product Unit of Measure')]).digits = 4
self.uom_unit.rounding = 0.001
self.bom_1.product_qty = 3
self.bom_1.bom_line_ids.product_qty = 5
self.env['stock.quant']._update_available_quantity(self.product_2, self.stock_location, 3)
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.bom_1.product_id
mo_form.bom_id = self.bom_1
mo = mo_form.save()
mo.action_confirm()
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 3
mo_form.save()
mo.button_mark_done()
uo_form = Form(self.env['mrp.unbuild'])
uo_form.mo_id = mo
# Unbuilding one product means a decimal quantity equal to 1 / 3 * 5 for each component
uo_form.product_qty = 1
uo = uo_form.save()
uo.action_unbuild()
self.assertEqual(uo.state, 'done')
def test_unbuild_similar_tracked_components(self):
"""
Suppose a MO with, in the components, two lines for the same tracked-by-usn product
When unbuilding such an MO, all SN used in the MO should be back in stock
"""
compo, finished = self.env['product.product'].create([{
'name': 'compo',
'type': 'product',
'tracking': 'serial',
}, {
'name': 'finished',
'type': 'product',
}])
lot01, lot02 = self.env['stock.production.lot'].create([{
'name': n,
'product_id': compo.id,
'company_id': self.env.company.id,
} for n in ['lot01', 'lot02']])
self.env['stock.quant']._update_available_quantity(compo, self.stock_location, 1, lot_id=lot01)
self.env['stock.quant']._update_available_quantity(compo, self.stock_location, 1, lot_id=lot02)
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = finished
with mo_form.move_raw_ids.new() as line:
line.product_id = compo
line.product_uom_qty = 1
with mo_form.move_raw_ids.new() as line:
line.product_id = compo
line.product_uom_qty = 1
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
mo.action_assign()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
details_operation_form.save()
details_operation_form = Form(mo.move_raw_ids[1], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.qty_done = 1
details_operation_form.save()
mo.button_mark_done()
uo_form = Form(self.env['mrp.unbuild'])
uo_form.mo_id = mo
uo_form.product_qty = 1
uo = uo_form.save()
uo.action_unbuild()
self.assertEqual(uo.produce_line_ids.filtered(lambda sm: sm.product_id == compo).lot_ids, lot01 + lot02)
def test_unbuild_and_multilocations(self):
"""
Basic flow: produce p_final, transfer it to a sub-location and then
unbuild it. The test ensures that the source/destination locations of an
unbuild order are applied on the stock moves
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id, 0)]})
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
prod_location = self.env['stock.location'].search([('usage', '=', 'production'), ('company_id', '=', self.env.user.id)])
subloc01, subloc02, = self.stock_location.child_ids[:2]
mo, _, p_final, p1, p2 = self.generate_mo(qty_final=1, qty_base_1=1, qty_base_2=1)
self.env['stock.quant']._update_available_quantity(p1, self.stock_location, 1)
self.env['stock.quant']._update_available_quantity(p2, self.stock_location, 1)
mo.action_assign()
mo_form = Form(mo)
mo_form.qty_producing = 1.0
mo = mo_form.save()
mo.button_mark_done()
# Transfer the finished product from WH/Stock to `subloc01`
internal_form = Form(self.env['stock.picking'])
internal_form.picking_type_id = warehouse.int_type_id
internal_form.location_id = self.stock_location
internal_form.location_dest_id = subloc01
with internal_form.move_ids_without_package.new() as move:
move.product_id = p_final
move.product_uom_qty = 1.0
internal_transfer = internal_form.save()
internal_transfer.action_confirm()
internal_transfer.action_assign()
internal_transfer.move_line_ids.qty_done = 1.0
internal_transfer.button_validate()
unbuild_order_form = Form(self.env['mrp.unbuild'])
unbuild_order_form.mo_id = mo
unbuild_order_form.location_id = subloc01
unbuild_order_form.location_dest_id = subloc02
unbuild_order = unbuild_order_form.save()
unbuild_order.action_unbuild()
self.assertRecordValues(unbuild_order.produce_line_ids, [
# pylint: disable=bad-whitespace
{'product_id': p_final.id, 'location_id': subloc01.id, 'location_dest_id': prod_location.id},
{'product_id': p2.id, 'location_id': prod_location.id, 'location_dest_id': subloc02.id},
{'product_id': p1.id, 'location_id': prod_location.id, 'location_dest_id': subloc02.id},
])
def test_use_unbuilt_sn_in_mo(self):
"""
use an unbuilt serial number in manufacturing order:
produce a tracked product, unbuild it and then use it as a component with the same SN in a mo.
"""
product_1 = self.env['product.product'].create({
'name': 'Product tracked by sn',
'type': 'product',
'tracking': 'serial',
})
product_1_sn = self.env['stock.production.lot'].create({
'product_id': product_1.id,
'company_id': self.env.company.id})
component = self.env['product.product'].create({
'name': 'Product component',
'type': 'product',
})
bom_1 = self.env['mrp.bom'].create({
'product_id': product_1.id,
'product_tmpl_id': product_1.product_tmpl_id.id,
'product_uom_id': self.env.ref('uom.product_uom_unit').id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 1}),
],
})
product_2 = self.env['product.product'].create({
'name': 'finished Product',
'type': 'product',
})
self.env['mrp.bom'].create({
'product_id': product_2.id,
'product_tmpl_id': product_2.product_tmpl_id.id,
'product_uom_id': self.env.ref('uom.product_uom_unit').id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': product_1.id, 'product_qty': 1}),
],
})
# mo1
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_1
mo_form.bom_id = bom_1
mo_form.product_qty = 1.0
mo = mo_form.save()
mo.action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 1.0
mo_form.lot_producing_id = product_1_sn
mo = mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done', "Production order should be in done state.")
#unbuild order
unbuild_form = Form(self.env['mrp.unbuild'])
unbuild_form.mo_id = mo
unbuild_form.lot_id = product_1_sn
unbuild_form.save().action_unbuild()
#mo2
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = product_2
mo2 = mo_form.save()
mo2.action_confirm()
details_operation_form = Form(mo2.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.lot_id = product_1_sn
ml.qty_done = 1
details_operation_form.save()
mo_form = Form(mo2)
mo_form.qty_producing = 1
mo2 = mo_form.save()
mo2.button_mark_done()
self.assertEqual(mo2.state, 'done', "Production order should be in done state.")
| 49.603427 | 40,526 |
52,156 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import exceptions, Command, fields
from odoo.tests import Form
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.tools import float_compare, float_round, float_repr
from freezegun import freeze_time
@freeze_time(fields.Date.today())
class TestBoM(TestMrpCommon):
def test_01_explode(self):
boms, lines = self.bom_1.explode(self.product_4, 3)
self.assertEqual(set([bom[0].id for bom in boms]), set(self.bom_1.ids))
self.assertEqual(set([line[0].id for line in lines]), set(self.bom_1.bom_line_ids.ids))
boms, lines = self.bom_3.explode(self.product_6, 3)
self.assertEqual(set([bom[0].id for bom in boms]), set((self.bom_2 | self.bom_3).ids))
self.assertEqual(
set([line[0].id for line in lines]),
set((self.bom_2 | self.bom_3).mapped('bom_line_ids').filtered(lambda line: not line.child_bom_id or line.child_bom_id.type != 'phantom').ids))
def test_10_variants(self):
test_bom = self.env['mrp.bom'].create({
'product_tmpl_id': self.product_7_template.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 4.0,
'type': 'normal',
'operation_ids': [
Command.create({
'name': 'Cutting Machine',
'workcenter_id': self.workcenter_1.id,
'time_cycle': 12,
'sequence': 1
}),
Command.create({
'name': 'Weld Machine',
'workcenter_id': self.workcenter_1.id,
'time_cycle': 18,
'sequence': 2,
'bom_product_template_attribute_value_ids': [Command.link(self.product_7_attr1_v1.id)]
}),
Command.create({
'name': 'Taking a coffee',
'workcenter_id': self.workcenter_1.id,
'time_cycle': 5,
'sequence': 3,
'bom_product_template_attribute_value_ids': [Command.link(self.product_7_attr1_v2.id)]
})
],
'byproduct_ids': [
Command.create({
'product_id': self.product_1.id,
'product_uom_id': self.product_1.uom_id.id,
'product_qty': 1,
}),
Command.create({
'product_id': self.product_2.id,
'product_uom_id': self.product_2.uom_id.id,
'product_qty': 1,
'bom_product_template_attribute_value_ids': [Command.link(self.product_7_attr1_v1.id)]
}),
Command.create({
'product_id': self.product_3.id,
'product_uom_id': self.product_3.uom_id.id,
'product_qty': 1,
'bom_product_template_attribute_value_ids': [Command.link(self.product_7_attr1_v2.id)]
}),
],
'bom_line_ids': [
Command.create({
'product_id': self.product_2.id,
'product_qty': 2,
}),
Command.create({
'product_id': self.product_3.id,
'product_qty': 2,
'bom_product_template_attribute_value_ids': [Command.link(self.product_7_attr1_v1.id)],
}),
Command.create({
'product_id': self.product_4.id,
'product_qty': 2,
'bom_product_template_attribute_value_ids': [Command.link(self.product_7_attr1_v2.id)],
}),
]
})
test_bom_l1, test_bom_l2, test_bom_l3 = test_bom.bom_line_ids
boms, lines = test_bom.explode(self.product_7_3, 4)
self.assertIn(test_bom, [b[0]for b in boms])
self.assertIn(test_bom_l1, [l[0] for l in lines])
self.assertNotIn(test_bom_l2, [l[0] for l in lines])
self.assertNotIn(test_bom_l3, [l[0] for l in lines])
boms, lines = test_bom.explode(self.product_7_1, 4)
self.assertIn(test_bom, [b[0]for b in boms])
self.assertIn(test_bom_l1, [l[0] for l in lines])
self.assertIn(test_bom_l2, [l[0] for l in lines])
self.assertNotIn(test_bom_l3, [l[0] for l in lines])
boms, lines = test_bom.explode(self.product_7_2, 4)
self.assertIn(test_bom, [b[0]for b in boms])
self.assertIn(test_bom_l1, [l[0] for l in lines])
self.assertNotIn(test_bom_l2, [l[0] for l in lines])
self.assertIn(test_bom_l3, [l[0] for l in lines])
mrp_order_form = Form(self.env['mrp.production'])
mrp_order_form.product_id = self.product_7_3
mrp_order = mrp_order_form.save()
self.assertEqual(mrp_order.bom_id, test_bom)
self.assertEqual(len(mrp_order.workorder_ids), 1)
self.assertEqual(mrp_order.workorder_ids.operation_id, test_bom.operation_ids[0])
self.assertEqual(len(mrp_order.move_byproduct_ids), 1)
self.assertEqual(mrp_order.move_byproduct_ids.product_id, self.product_1)
mrp_order_form = Form(self.env['mrp.production'])
mrp_order_form.product_id = self.product_7_1
mrp_order_form.product_id = self.env['product.product'] # Check form
mrp_order_form.product_id = self.product_7_1
mrp_order_form.bom_id = self.env['mrp.bom'] # Check form
mrp_order_form.bom_id = test_bom
mrp_order = mrp_order_form.save()
self.assertEqual(mrp_order.bom_id, test_bom)
self.assertEqual(len(mrp_order.workorder_ids), 2)
self.assertEqual(mrp_order.workorder_ids.operation_id, test_bom.operation_ids[:2])
self.assertEqual(len(mrp_order.move_byproduct_ids), 2)
self.assertEqual(mrp_order.move_byproduct_ids.product_id, self.product_1 | self.product_2)
mrp_order_form = Form(self.env['mrp.production'])
mrp_order_form.product_id = self.product_7_2
mrp_order = mrp_order_form.save()
self.assertEqual(mrp_order.bom_id, test_bom)
self.assertEqual(len(mrp_order.workorder_ids), 2)
self.assertEqual(mrp_order.workorder_ids.operation_id, test_bom.operation_ids[0] | test_bom.operation_ids[2])
self.assertEqual(len(mrp_order.move_byproduct_ids), 2)
self.assertEqual(mrp_order.move_byproduct_ids.product_id, self.product_1 | self.product_3)
def test_11_multi_level_variants(self):
tmp_picking_type = self.env['stock.picking.type'].create({
'name': 'Manufacturing',
'code': 'mrp_operation',
'sequence_code': 'TMP',
'sequence_id': self.env['ir.sequence'].create({
'code': 'mrp.production',
'name': 'tmp_production_sequence',
}).id,
})
test_bom_1 = self.env['mrp.bom'].create({
'product_tmpl_id': self.product_5.product_tmpl_id.id,
'product_uom_id': self.product_5.uom_id.id,
'product_qty': 1.0,
'type': 'phantom'
})
test_bom_1.write({
'operation_ids': [
(0, 0, {'name': 'Gift Wrap Maching', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 15, 'sequence': 1}),
],
})
test_bom_1_l1 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_1.id,
'product_id': self.product_3.id,
'product_qty': 3,
})
test_bom_2 = self.env['mrp.bom'].create({
'product_id': self.product_7_3.id,
'product_tmpl_id': self.product_7_template.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 4.0,
'type': 'normal',
})
test_bom_2.write({
'operation_ids': [
(0, 0, {'name': 'Cutting Machine', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 12, 'sequence': 1}),
(0, 0, {'name': 'Weld Machine', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 18, 'sequence': 2}),
]
})
test_bom_2_l1 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_2.id,
'product_id': self.product_2.id,
'product_qty': 2,
})
test_bom_2_l2 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_2.id,
'product_id': self.product_5.id,
'product_qty': 2,
'bom_product_template_attribute_value_ids': [(4, self.product_7_attr1_v1.id)],
})
test_bom_2_l3 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_2.id,
'product_id': self.product_5.id,
'product_qty': 2,
'bom_product_template_attribute_value_ids': [(4, self.product_7_attr1_v2.id)],
})
test_bom_2_l4 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_2.id,
'product_id': self.product_4.id,
'product_qty': 2,
})
# check product > product_tmpl
boms, lines = test_bom_2.explode(self.product_7_1, 4)
self.assertEqual(set((test_bom_2 | self.bom_2).ids), set([b[0].id for b in boms]))
self.assertEqual(set((test_bom_2_l1 | test_bom_2_l4 | self.bom_2.bom_line_ids).ids), set([l[0].id for l in lines]))
# check sequence priority
test_bom_1.write({'sequence': 1})
boms, lines = test_bom_2.explode(self.product_7_1, 4)
self.assertEqual(set((test_bom_2 | test_bom_1).ids), set([b[0].id for b in boms]))
self.assertEqual(set((test_bom_2_l1 | test_bom_2_l4 | test_bom_1.bom_line_ids).ids), set([l[0].id for l in lines]))
# check with another picking_type
test_bom_1.write({'picking_type_id': self.warehouse_1.manu_type_id.id})
self.bom_2.write({'picking_type_id': tmp_picking_type.id})
test_bom_2.write({'picking_type_id': tmp_picking_type.id})
boms, lines = test_bom_2.explode(self.product_7_1, 4)
self.assertEqual(set((test_bom_2 | self.bom_2).ids), set([b[0].id for b in boms]))
self.assertEqual(set((test_bom_2_l1 | test_bom_2_l4 | self.bom_2.bom_line_ids).ids), set([l[0].id for l in lines]))
#check recursion
test_bom_3 = self.env['mrp.bom'].create({
'product_id': self.product_9.id,
'product_tmpl_id': self.product_9.product_tmpl_id.id,
'product_uom_id': self.product_9.uom_id.id,
'product_qty': 1.0,
'consumption': 'flexible',
'type': 'normal'
})
test_bom_4 = self.env['mrp.bom'].create({
'product_id': self.product_10.id,
'product_tmpl_id': self.product_10.product_tmpl_id.id,
'product_uom_id': self.product_10.uom_id.id,
'product_qty': 1.0,
'consumption': 'flexible',
'type': 'phantom'
})
test_bom_3_l1 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_3.id,
'product_id': self.product_10.id,
'product_qty': 1.0,
})
test_bom_4_l1 = self.env['mrp.bom.line'].create({
'bom_id': test_bom_4.id,
'product_id': self.product_9.id,
'product_qty': 1.0,
})
with self.assertRaises(exceptions.UserError):
test_bom_3.explode(self.product_9, 1)
def test_12_multi_level_variants2(self):
"""Test skip bom line with same attribute values in bom lines."""
Product = self.env['product.product']
ProductAttribute = self.env['product.attribute']
ProductAttributeValue = self.env['product.attribute.value']
# Product Attribute
att_color = ProductAttribute.create({'name': 'Color', 'sequence': 1})
att_size = ProductAttribute.create({'name': 'size', 'sequence': 2})
# Product Attribute color Value
att_color_red = ProductAttributeValue.create({'name': 'red', 'attribute_id': att_color.id, 'sequence': 1})
att_color_blue = ProductAttributeValue.create({'name': 'blue', 'attribute_id': att_color.id, 'sequence': 2})
# Product Attribute size Value
att_size_big = ProductAttributeValue.create({'name': 'big', 'attribute_id': att_size.id, 'sequence': 1})
att_size_medium = ProductAttributeValue.create({'name': 'medium', 'attribute_id': att_size.id, 'sequence': 2})
# Create Template Product
product_template = self.env['product.template'].create({
'name': 'Sofa',
'attribute_line_ids': [
(0, 0, {
'attribute_id': att_color.id,
'value_ids': [(6, 0, [att_color_red.id, att_color_blue.id])]
}),
(0, 0, {
'attribute_id': att_size.id,
'value_ids': [(6, 0, [att_size_big.id, att_size_medium.id])]
})
]
})
sofa_red = product_template.attribute_line_ids[0].product_template_value_ids[0]
sofa_blue = product_template.attribute_line_ids[0].product_template_value_ids[1]
sofa_big = product_template.attribute_line_ids[1].product_template_value_ids[0]
sofa_medium = product_template.attribute_line_ids[1].product_template_value_ids[1]
# Create components Of BOM
product_A = Product.create({
'name': 'Wood'})
product_B = Product.create({
'name': 'Clothes'})
# Create BOM
self.env['mrp.bom'].create({
'product_tmpl_id': product_template.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {
'product_id': product_A.id,
'product_qty': 1,
'bom_product_template_attribute_value_ids': [(4, sofa_red.id), (4, sofa_blue.id), (4, sofa_big.id)],
}),
(0, 0, {
'product_id': product_B.id,
'product_qty': 1,
'bom_product_template_attribute_value_ids': [(4, sofa_red.id), (4, sofa_blue.id)]
})
]
})
dict_consumed_products = {
sofa_red + sofa_big: product_A + product_B,
sofa_red + sofa_medium: product_B,
sofa_blue + sofa_big: product_A + product_B,
sofa_blue + sofa_medium: product_B,
}
# Create production order for all variants.
for combination, consumed_products in dict_consumed_products.items():
product = product_template.product_variant_ids.filtered(lambda p: p.product_template_attribute_value_ids == combination)
mrp_order_form = Form(self.env['mrp.production'])
mrp_order_form.product_id = product
mrp_order = mrp_order_form.save()
# Check consumed materials in production order.
self.assertEqual(mrp_order.move_raw_ids.product_id, consumed_products)
def test_13_bom_kit_qty(self):
self.env['mrp.bom'].create({
'product_id': self.product_7_3.id,
'product_tmpl_id': self.product_7_template.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 4.0,
'type': 'phantom',
'bom_line_ids': [
(0, 0, {
'product_id': self.product_2.id,
'product_qty': 2,
}),
(0, 0, {
'product_id': self.product_3.id,
'product_qty': 2,
})
]
})
location = self.env.ref('stock.stock_location_stock')
self.env['stock.quant']._update_available_quantity(self.product_2, location, 4.0)
self.env['stock.quant']._update_available_quantity(self.product_3, location, 8.0)
# Force the kit product available qty to be computed at the same time than its component quantities
# Because `qty_available` of a bom kit "recurse" on `qty_available` of its component,
# and this is a tricky thing for the ORM:
# `qty_available` gets called for `product_7_3`, `product_2` and `product_3`
# which then recurse on calling `qty_available` for `product_2` and `product_3` to compute the quantity of
# the kit `product_7_3`. `product_2` and `product_3` gets protected at the first call of the compute method,
# ending the recurse call to not call the compute method and just left the Falsy value `0.0`
# for the components available qty.
kit_product_qty, _, _ = (self.product_7_3 + self.product_2 + self.product_3).mapped("qty_available")
self.assertEqual(kit_product_qty, 8)
def test_14_bom_kit_qty_multi_uom(self):
uom_dozens = self.env.ref('uom.product_uom_dozen')
uom_unit = self.env.ref('uom.product_uom_unit')
product_unit = self.env['product.product'].create({
'name': 'Test units',
'type': 'product',
'uom_id': uom_unit.id,
})
product_dozens = self.env['product.product'].create({
'name': 'Test dozens',
'type': 'product',
'uom_id': uom_dozens.id,
})
self.env['mrp.bom'].create({
'product_tmpl_id': product_unit.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'phantom',
'bom_line_ids': [
(0, 0, {
'product_id': product_dozens.id,
'product_qty': 1,
'product_uom_id': uom_unit.id,
})
]
})
location = self.env.ref('stock.stock_location_stock')
self.env['stock.quant']._update_available_quantity(product_dozens, location, 1.0)
self.assertEqual(product_unit.qty_available, 12.0)
def test_13_negative_on_hand_qty(self):
# We set the Product Unit of Measure digits to 5.
# Because float_round(-384.0, 5) = -384.00000000000006
# And float_round(-384.0, 2) = -384.0
precision = self.env.ref('product.decimal_product_uom')
precision.digits = 5
# We set the Unit(s) rounding to 0.0001 (digit = 4)
uom_unit = self.env.ref('uom.product_uom_unit')
uom_unit.rounding = 0.0001
_ = self.env['mrp.bom'].create({
'product_id': self.product_2.id,
'product_tmpl_id': self.product_2.product_tmpl_id.id,
'product_uom_id': uom_unit.id,
'product_qty': 1.00,
'type': 'phantom',
'bom_line_ids': [
(0, 0, {
'product_id': self.product_3.id,
'product_qty': 1.000,
}),
]
})
self.env['stock.quant']._update_available_quantity(self.product_3, self.env.ref('stock.stock_location_stock'), -384.0)
kit_product_qty = self.product_2.qty_available # Without product_3 in the prefetch
# Use the float_repr to remove extra small decimal (and represent the front-end behavior)
self.assertEqual(float_repr(float_round(kit_product_qty, precision_digits=precision.digits), precision_digits=precision.digits), '-384.00000')
self.product_2.invalidate_cache(fnames=['qty_available'], ids=self.product_2.ids)
kit_product_qty, _ = (self.product_2 + self.product_3).mapped("qty_available") # With product_3 in the prefetch
self.assertEqual(float_repr(float_round(kit_product_qty, precision_digits=precision.digits), precision_digits=precision.digits), '-384.00000')
def test_13_bom_kit_qty_multi_uom(self):
uom_dozens = self.env.ref('uom.product_uom_dozen')
uom_unit = self.env.ref('uom.product_uom_unit')
product_unit = self.env['product.product'].create({
'name': 'Test units',
'type': 'product',
'uom_id': uom_unit.id,
})
product_dozens = self.env['product.product'].create({
'name': 'Test dozens',
'type': 'product',
'uom_id': uom_dozens.id,
})
self.env['mrp.bom'].create({
'product_tmpl_id': product_unit.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'product_qty': 1.0,
'type': 'phantom',
'bom_line_ids': [
(0, 0, {
'product_id': product_dozens.id,
'product_qty': 1,
'product_uom_id': uom_unit.id,
})
]
})
location = self.env.ref('stock.stock_location_stock')
self.env['stock.quant']._update_available_quantity(product_dozens, location, 1.0)
self.assertEqual(product_unit.qty_available, 12.0)
def test_20_bom_report(self):
""" Simulate a crumble receipt with mrp and open the bom structure
report and check that data insde are correct.
"""
uom_kg = self.env.ref('uom.product_uom_kgm')
uom_litre = self.env.ref('uom.product_uom_litre')
crumble = self.env['product.product'].create({
'name': 'Crumble',
'type': 'product',
'uom_id': uom_kg.id,
'uom_po_id': uom_kg.id,
})
butter = self.env['product.product'].create({
'name': 'Butter',
'type': 'product',
'uom_id': uom_kg.id,
'uom_po_id': uom_kg.id,
'standard_price': 7.01
})
biscuit = self.env['product.product'].create({
'name': 'Biscuit',
'type': 'product',
'uom_id': uom_kg.id,
'uom_po_id': uom_kg.id,
'standard_price': 1.5
})
bom_form_crumble = Form(self.env['mrp.bom'])
bom_form_crumble.product_tmpl_id = crumble.product_tmpl_id
bom_form_crumble.product_qty = 11
bom_form_crumble.product_uom_id = uom_kg
bom_crumble = bom_form_crumble.save()
workcenter = self.env['mrp.workcenter'].create({
'costs_hour': 10,
'name': 'Deserts Table'
})
with Form(bom_crumble) as bom:
with bom.bom_line_ids.new() as line:
line.product_id = butter
line.product_uom_id = uom_kg
line.product_qty = 5
with bom.bom_line_ids.new() as line:
line.product_id = biscuit
line.product_uom_id = uom_kg
line.product_qty = 6
with bom.operation_ids.new() as operation:
operation.workcenter_id = workcenter
operation.name = 'Prepare biscuits'
operation.time_cycle_manual = 5
operation.bom_id = bom_crumble # Can't handle by the testing env
with bom.operation_ids.new() as operation:
operation.workcenter_id = workcenter
operation.name = 'Prepare butter'
operation.time_cycle_manual = 3
operation.bom_id = bom_crumble
with bom.operation_ids.new() as operation:
operation.workcenter_id = workcenter
operation.name = 'Mix manually'
operation.time_cycle_manual = 5
operation.bom_id = bom_crumble
# TEST BOM STRUCTURE VALUE WITH BOM QUANTITY
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_crumble.id, searchQty=11, searchVariant=False)
# 5 min 'Prepare biscuits' + 3 min 'Prepare butter' + 5 min 'Mix manually' = 13 minutes for 1 biscuits so 13 * 11 = 143 minutes
self.assertEqual(report_values['lines']['operations_time'], 143.0, 'Operation time should be the same for 1 unit or for the batch')
# Operation cost is the sum of operation line.
self.assertEqual(float_compare(report_values['lines']['operations_cost'], 23.84, precision_digits=2), 0, '143 minute for 10$/hours -> 23.84')
for component_line in report_values['lines']['components']:
# standard price * bom line quantity * current quantity / bom finished product quantity
if component_line['prod_id'] == butter.id:
# 5 kg of butter at 7.01$ for 11kg of crumble -> 35.05$
self.assertEqual(float_compare(component_line['total'], (7.01 * 5), precision_digits=2), 0)
if component_line['prod_id'] == biscuit.id:
# 6 kg of biscuits at 1.50$ for 11kg of crumble -> 9$
self.assertEqual(float_compare(component_line['total'], (1.5 * 6), precision_digits=2), 0)
# total price = 35.05 + 9 + operation_cost(23.84) = 67.89
self.assertEqual(float_compare(report_values['lines']['total'], 67.89, precision_digits=2), 0, 'Product Bom Price is not correct')
self.assertEqual(float_compare(report_values['lines']['total'] / 11.0, 6.17, precision_digits=2), 0, 'Product Unit Bom Price is not correct')
# TEST BOM STRUCTURE VALUE BY UNIT
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_crumble.id, searchQty=1, searchVariant=False)
# 5 min 'Prepare biscuits' + 3 min 'Prepare butter' + 5 min 'Mix manually' = 13 minutes
self.assertEqual(report_values['lines']['operations_time'], 13.0, 'Operation time should be the same for 1 unit or for the batch')
# Operation cost is the sum of operation line.
operation_cost = float_round(5 / 60 * 10, precision_digits=2) * 2 + float_round(3 / 60 * 10, precision_digits=2)
self.assertEqual(float_compare(report_values['lines']['operations_cost'], operation_cost, precision_digits=2), 0, '13 minute for 10$/hours -> 2.16')
for component_line in report_values['lines']['components']:
# standard price * bom line quantity * current quantity / bom finished product quantity
if component_line['prod_id'] == butter.id:
# 5 kg of butter at 7.01$ for 11kg of crumble -> / 11 for price per unit (3.19)
self.assertEqual(float_compare(component_line['total'], (7.01 * 5) * (1 / 11), precision_digits=2), 0)
if component_line['prod_id'] == biscuit.id:
# 6 kg of biscuits at 1.50$ for 11kg of crumble -> / 11 for price per unit (0.82)
self.assertEqual(float_compare(component_line['total'], (1.5 * 6) * (1 / 11), precision_digits=2), 0)
# total price = 3.19 + 0.82 + operation_cost(0.83 + 0.83 + 0.5 = 2.16) = 6,17
self.assertEqual(float_compare(report_values['lines']['total'], 6.17, precision_digits=2), 0, 'Product Unit Bom Price is not correct')
# TEST OPERATION COST WHEN PRODUCED QTY > BOM QUANTITY
report_values_12 = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_crumble.id, searchQty=12, searchVariant=False)
report_values_22 = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_crumble.id, searchQty=22, searchVariant=False)
#Operation cost = 47.66 € = 256 (min) * 10€/h
self.assertEqual(float_compare(report_values_22['lines']['operations_cost'], 47.66,precision_digits=2),0, 'Operation cost is not correct')
# Create a more complex BoM with a sub product
cheese_cake = self.env['product.product'].create({
'name': 'Cheese Cake 300g',
'type': 'product',
})
cream = self.env['product.product'].create({
'name': 'cream',
'type': 'product',
'uom_id': uom_litre.id,
'uom_po_id': uom_litre.id,
'standard_price': 5.17,
})
bom_form_cheese_cake = Form(self.env['mrp.bom'])
bom_form_cheese_cake.product_tmpl_id = cheese_cake.product_tmpl_id
bom_form_cheese_cake.product_qty = 60
bom_form_cheese_cake.product_uom_id = self.uom_unit
bom_cheese_cake = bom_form_cheese_cake.save()
workcenter_2 = self.env['mrp.workcenter'].create({
'name': 'cake mounting',
'costs_hour': 20,
'time_start': 10,
'time_stop': 15
})
with Form(bom_cheese_cake) as bom:
with bom.bom_line_ids.new() as line:
line.product_id = cream
line.product_uom_id = uom_litre
line.product_qty = 3
with bom.bom_line_ids.new() as line:
line.product_id = crumble
line.product_uom_id = uom_kg
line.product_qty = 5.4
with bom.operation_ids.new() as operation:
operation.workcenter_id = workcenter
operation.name = 'Mix cheese and crumble'
operation.time_cycle_manual = 10
operation.bom_id = bom_cheese_cake
with bom.operation_ids.new() as operation:
operation.workcenter_id = workcenter_2
operation.name = 'Cake mounting'
operation.time_cycle_manual = 5
operation.bom_id = bom_cheese_cake
# TEST CHEESE BOM STRUCTURE VALUE WITH BOM QUANTITY
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_cheese_cake.id, searchQty=60, searchVariant=False)
#Operation time = 15 min * 60 + time_start + time_stop = 925
self.assertEqual(report_values['lines']['operations_time'], 925.0, 'Operation time should be the same for 1 unit or for the batch')
# Operation cost is the sum of operation line : (60 * 10)/60 * 10€ + (10 + 15 + 60 * 5)/60 * 20€ = 208,33€
self.assertEqual(float_compare(report_values['lines']['operations_cost'], 208.33, precision_digits=2), 0)
for component_line in report_values['lines']['components']:
# standard price * bom line quantity * current quantity / bom finished product quantity
if component_line['prod_id'] == cream.id:
# 3 liter of cream at 5.17$ for 60 unit of cheese cake -> 15.51$
self.assertEqual(float_compare(component_line['total'], (3 * 5.17), precision_digits=2), 0)
if component_line['prod_id'] == crumble.id:
# 5.4 kg of crumble at the cost of a batch.
crumble_cost = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_crumble.id, searchQty=5.4, searchVariant=False)['lines']['total']
self.assertEqual(float_compare(component_line['total'], crumble_cost, precision_digits=2), 0)
# total price = Cream (15.51€) + crumble_cost (34.63 €) + operation_cost(208,33) = 258.47€
self.assertEqual(float_compare(report_values['lines']['total'], 258.47, precision_digits=2), 0, 'Product Bom Price is not correct')
def test_bom_report_dozens(self):
""" Simulate a drawer bom with dozens as bom units
"""
uom_dozen = self.env.ref('uom.product_uom_dozen')
uom_unit = self.env.ref('uom.product_uom_unit')
drawer = self.env['product.product'].create({
'name': 'drawer',
'type': 'product',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
})
screw = self.env['product.product'].create({
'name': 'screw',
'type': 'product',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
'standard_price': 7.01
})
bom_form_drawer = Form(self.env['mrp.bom'])
bom_form_drawer.product_tmpl_id = drawer.product_tmpl_id
bom_form_drawer.product_qty = 11
bom_form_drawer.product_uom_id = uom_dozen
bom_drawer = bom_form_drawer.save()
workcenter = self.env['mrp.workcenter'].create({
'costs_hour': 10,
'name': 'Deserts Table'
})
with Form(bom_drawer) as bom:
with bom.bom_line_ids.new() as line:
line.product_id = screw
line.product_uom_id = uom_unit
line.product_qty = 5
with bom.operation_ids.new() as operation:
operation.workcenter_id = workcenter
operation.name = 'Screw drawer'
operation.time_cycle_manual = 5
operation.bom_id = bom_drawer
# TEST BOM STRUCTURE VALUE WITH BOM QUANTITY
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_drawer.id, searchQty=11, searchVariant=False)
# 5 min 'Prepare biscuits' + 3 min 'Prepare butter' + 5 min 'Mix manually' = 13 minutes
self.assertEqual(report_values['lines']['operations_time'], 660.0, 'Operation time should be the same for 1 unit or for the batch')
def test_21_bom_report_variant(self):
""" Test a sub BoM process with multiple variants.
BOM 1:
product template = car
quantity = 5 units
- red paint 50l -> red car (product.product)
- blue paint 50l -> blue car
- red dashboard with gps -> red car with GPS
- red dashboard w/h gps -> red w/h GPS
- blue dashboard with gps -> blue car with GPS
- blue dashboard w/h gps -> blue w/h GPS
BOM 2:
product_tmpl = dashboard
quantity = 2
- red paint 1l -> red dashboard (product.product)
- blue paint 1l -> blue dashboard
- gps -> dashboard with gps
Check the Price for a Blue Car with GPS -> 910$:
10l of blue paint -> 200$
1 blue dashboard GPS -> 710$:
- 0.5l of blue paint -> 10$
- GPS -> 700$
Check the price for a red car -> 10.5l of red paint -> 210$
"""
# Create a product template car with attributes gps(yes, no), color(red, blue)
self.car = self.env['product.template'].create({
'name': 'Car',
})
self.gps_attribute = self.env['product.attribute'].create({'name': 'GPS', 'sequence': 1})
self.gps_yes = self.env['product.attribute.value'].create({
'name': 'Yes',
'attribute_id': self.gps_attribute.id,
'sequence': 1,
})
self.gps_no = self.env['product.attribute.value'].create({
'name': 'No',
'attribute_id': self.gps_attribute.id,
'sequence': 2,
})
self.car_gps_attribute_line = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.car.id,
'attribute_id': self.gps_attribute.id,
'value_ids': [(6, 0, [self.gps_yes.id, self.gps_no.id])],
})
self.car_gps_yes = self.car_gps_attribute_line.product_template_value_ids[0]
self.car_gps_no = self.car_gps_attribute_line.product_template_value_ids[1]
self.color_attribute = self.env['product.attribute'].create({'name': 'Color', 'sequence': 1})
self.color_red = self.env['product.attribute.value'].create({
'name': 'Red',
'attribute_id': self.color_attribute.id,
'sequence': 1,
})
self.color_blue = self.env['product.attribute.value'].create({
'name': 'Blue',
'attribute_id': self.color_attribute.id,
'sequence': 2,
})
self.car_color_attribute_line = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.car.id,
'attribute_id': self.color_attribute.id,
'value_ids': [(6, 0, [self.color_red.id, self.color_blue.id])],
})
self.car_color_red = self.car_color_attribute_line.product_template_value_ids[0]
self.car_color_blue = self.car_color_attribute_line.product_template_value_ids[1]
# Blue and red paint
uom_litre = self.env.ref('uom.product_uom_litre')
self.paint = self.env['product.template'].create({
'name': 'Paint',
'uom_id': uom_litre.id,
'uom_po_id': uom_litre.id
})
self.paint_color_attribute_line = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.paint.id,
'attribute_id': self.color_attribute.id,
'value_ids': [(6, 0, [self.color_red.id, self.color_blue.id])],
})
self.paint_color_red = self.paint_color_attribute_line.product_template_value_ids[0]
self.paint_color_blue = self.paint_color_attribute_line.product_template_value_ids[1]
self.paint.product_variant_ids.write({'standard_price': 20})
self.dashboard = self.env['product.template'].create({
'name': 'Dashboard',
'standard_price': 1000,
})
self.dashboard_gps_attribute_line = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.dashboard.id,
'attribute_id': self.gps_attribute.id,
'value_ids': [(6, 0, [self.gps_yes.id, self.gps_no.id])],
})
self.dashboard_gps_yes = self.dashboard_gps_attribute_line.product_template_value_ids[0]
self.dashboard_gps_no = self.dashboard_gps_attribute_line.product_template_value_ids[1]
self.dashboard_color_attribute_line = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.dashboard.id,
'attribute_id': self.color_attribute.id,
'value_ids': [(6, 0, [self.color_red.id, self.color_blue.id])],
})
self.dashboard_color_red = self.dashboard_color_attribute_line.product_template_value_ids[0]
self.dashboard_color_blue = self.dashboard_color_attribute_line.product_template_value_ids[1]
self.gps = self.env['product.product'].create({
'name': 'GPS',
'standard_price': 700,
})
bom_form_car = Form(self.env['mrp.bom'])
bom_form_car.product_tmpl_id = self.car
bom_form_car.product_qty = 5
with bom_form_car.bom_line_ids.new() as line:
line.product_id = self.paint._get_variant_for_combination(self.paint_color_red)
line.product_uom_id = uom_litre
line.product_qty = 50
line.bom_product_template_attribute_value_ids.add(self.car_color_red)
with bom_form_car.bom_line_ids.new() as line:
line.product_id = self.paint._get_variant_for_combination(self.paint_color_blue)
line.product_uom_id = uom_litre
line.product_qty = 50
line.bom_product_template_attribute_value_ids.add(self.car_color_blue)
with bom_form_car.bom_line_ids.new() as line:
line.product_id = self.dashboard._get_variant_for_combination(self.dashboard_gps_yes + self.dashboard_color_red)
line.product_qty = 5
line.bom_product_template_attribute_value_ids.add(self.car_gps_yes)
line.bom_product_template_attribute_value_ids.add(self.car_color_red)
with bom_form_car.bom_line_ids.new() as line:
line.product_id = self.dashboard._get_variant_for_combination(self.dashboard_gps_yes + self.dashboard_color_blue)
line.product_qty = 5
line.bom_product_template_attribute_value_ids.add(self.car_gps_yes)
line.bom_product_template_attribute_value_ids.add(self.car_color_blue)
with bom_form_car.bom_line_ids.new() as line:
line.product_id = self.dashboard._get_variant_for_combination(self.dashboard_gps_no + self.dashboard_color_red)
line.product_qty = 5
line.bom_product_template_attribute_value_ids.add(self.car_gps_no)
line.bom_product_template_attribute_value_ids.add(self.car_color_red)
with bom_form_car.bom_line_ids.new() as line:
line.product_id = self.dashboard._get_variant_for_combination(self.dashboard_gps_no + self.dashboard_color_blue)
line.product_qty = 5
line.bom_product_template_attribute_value_ids.add(self.car_gps_no)
line.bom_product_template_attribute_value_ids.add(self.car_color_blue)
bom_car = bom_form_car.save()
bom_dashboard = Form(self.env['mrp.bom'])
bom_dashboard.product_tmpl_id = self.dashboard
bom_dashboard.product_qty = 2
with bom_dashboard.bom_line_ids.new() as line:
line.product_id = self.paint._get_variant_for_combination(self.paint_color_red)
line.product_uom_id = uom_litre
line.product_qty = 1
line.bom_product_template_attribute_value_ids.add(self.dashboard_color_red)
with bom_dashboard.bom_line_ids.new() as line:
line.product_id = self.paint._get_variant_for_combination(self.paint_color_blue)
line.product_uom_id = uom_litre
line.product_qty = 1
line.bom_product_template_attribute_value_ids.add(self.dashboard_color_blue)
with bom_dashboard.bom_line_ids.new() as line:
line.product_id = self.gps
line.product_qty = 2
line.bom_product_template_attribute_value_ids.add(self.dashboard_gps_yes)
bom_dashboard = bom_dashboard.save()
blue_car_with_gps = self.car._get_variant_for_combination(self.car_color_blue + self.car_gps_yes)
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_car.id, searchQty=1, searchVariant=blue_car_with_gps.id)
# Two lines. blue dashboard with gps and blue paint.
self.assertEqual(len(report_values['lines']['components']), 2)
# 10l of blue paint
blue_paint = self.paint._get_variant_for_combination(self.paint_color_blue)
self.assertEqual(blue_paint.id, report_values['lines']['components'][0]['prod_id'])
self.assertEqual(report_values['lines']['components'][0]['prod_qty'], 10)
# 1 blue dashboard with GPS
blue_dashboard_gps = self.dashboard._get_variant_for_combination(self.dashboard_color_blue + self.dashboard_gps_yes)
self.assertEqual(blue_dashboard_gps.id, report_values['lines']['components'][1]['prod_id'])
self.assertEqual(report_values['lines']['components'][1]['prod_qty'], 1)
component = report_values['lines']['components'][1]
report_values_dashboad = self.env['report.mrp.report_bom_structure']._get_bom(
component['child_bom'], component['prod_id'], component['prod_qty'],
component['line_id'], component['level'] + 1)
self.assertEqual(len(report_values_dashboad['components']), 2)
self.assertEqual(blue_paint.id, report_values_dashboad['components'][0]['prod_id'])
self.assertEqual(self.gps.id, report_values_dashboad['components'][1]['prod_id'])
# 0.5l of paint at price of 20$/litre -> 10$
self.assertEqual(report_values_dashboad['components'][0]['total'], 10)
# GPS 700$
self.assertEqual(report_values_dashboad['components'][1]['total'], 700)
# Dashboard blue with GPS should have a BoM cost of 710$
self.assertEqual(report_values['lines']['components'][1]['total'], 710)
# 10l of paint at price of 20$/litre -> 200$
self.assertEqual(report_values['lines']['components'][0]['total'], 200)
# Total cost of blue car with GPS: 10 + 700 + 200 = 910
self.assertEqual(report_values['lines']['total'], 910)
red_car_without_gps = self.car._get_variant_for_combination(self.car_color_red + self.car_gps_no)
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_car.id, searchQty=1, searchVariant=red_car_without_gps.id)
# Same math than before but without GPS
self.assertEqual(report_values['lines']['total'], 210)
def test_22_bom_report_recursive_bom(self):
""" Test report with recursive BoM and different quantities.
BoM 1:
product = Finished (units)
quantity = 100 units
- Semi-Finished 5 kg
BoM 2:
product = Semi-Finished (kg)
quantity = 11 kg
- Assembly 2 dozens
BoM 3:
product = Assembly (dozens)
quantity = 5 dozens
- Raw Material 4 litres (product.product 5$/litre)
Check the Price for 80 units of Finished -> 2.92$:
"""
# Create a products templates
uom_unit = self.env.ref('uom.product_uom_unit')
uom_kg = self.env.ref('uom.product_uom_kgm')
uom_dozen = self.env.ref('uom.product_uom_dozen')
uom_litre = self.env.ref('uom.product_uom_litre')
finished = self.env['product.product'].create({
'name': 'Finished',
'type': 'product',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
})
semi_finished = self.env['product.product'].create({
'name': 'Semi-Finished',
'type': 'product',
'uom_id': uom_kg.id,
'uom_po_id': uom_kg.id,
})
assembly = self.env['product.product'].create({
'name': 'Assembly',
'type': 'product',
'uom_id': uom_dozen.id,
'uom_po_id': uom_dozen.id,
})
raw_material = self.env['product.product'].create({
'name': 'Raw Material',
'type': 'product',
'uom_id': uom_litre.id,
'uom_po_id': uom_litre.id,
'standard_price': 5,
})
#Create bom
bom_finished = Form(self.env['mrp.bom'])
bom_finished.product_tmpl_id = finished.product_tmpl_id
bom_finished.product_qty = 100
with bom_finished.bom_line_ids.new() as line:
line.product_id = semi_finished
line.product_uom_id = uom_kg
line.product_qty = 5
bom_finished = bom_finished.save()
bom_semi_finished = Form(self.env['mrp.bom'])
bom_semi_finished.product_tmpl_id = semi_finished.product_tmpl_id
bom_semi_finished.product_qty = 11
with bom_semi_finished.bom_line_ids.new() as line:
line.product_id = assembly
line.product_uom_id = uom_dozen
line.product_qty = 2
bom_semi_finished = bom_semi_finished.save()
bom_assembly = Form(self.env['mrp.bom'])
bom_assembly.product_tmpl_id = assembly.product_tmpl_id
bom_assembly.product_qty = 5
with bom_assembly.bom_line_ids.new() as line:
line.product_id = raw_material
line.product_uom_id = uom_litre
line.product_qty = 4
bom_assembly = bom_assembly.save()
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom_id=bom_finished.id, searchQty=80)
self.assertAlmostEqual(report_values['lines']['total'], 2.92)
def test_validate_no_bom_line_with_same_product(self):
"""
Cannot set a BOM line on a BOM with the same product as the BOM itself
"""
uom_unit = self.env.ref('uom.product_uom_unit')
finished = self.env['product.product'].create({
'name': 'Finished',
'type': 'product',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
})
bom_finished = Form(self.env['mrp.bom'])
bom_finished.product_tmpl_id = finished.product_tmpl_id
bom_finished.product_qty = 100
with bom_finished.bom_line_ids.new() as line:
line.product_id = finished
line.product_uom_id = uom_unit
line.product_qty = 5
with self.assertRaises(exceptions.ValidationError), self.cr.savepoint():
bom_finished = bom_finished.save()
def test_validate_no_bom_line_with_same_product_variant(self):
"""
Cannot set a BOM line on a BOM with the same product variant as the BOM itself
"""
uom_unit = self.env.ref('uom.product_uom_unit')
bom_finished = Form(self.env['mrp.bom'])
bom_finished.product_tmpl_id = self.product_7_template
bom_finished.product_id = self.product_7_3
bom_finished.product_qty = 100
with bom_finished.bom_line_ids.new() as line:
line.product_id = self.product_7_3
line.product_uom_id = uom_unit
line.product_qty = 5
with self.assertRaises(exceptions.ValidationError), self.cr.savepoint():
bom_finished = bom_finished.save()
def test_validate_bom_line_with_different_product_variant(self):
"""
Can set a BOM line on a BOM with a different product variant as the BOM itself (same product)
Usecase for example A black T-shirt made from a white T-shirt and
black color.
"""
uom_unit = self.env.ref('uom.product_uom_unit')
bom_finished = Form(self.env['mrp.bom'])
bom_finished.product_tmpl_id = self.product_7_template
bom_finished.product_id = self.product_7_3
bom_finished.product_qty = 100
with bom_finished.bom_line_ids.new() as line:
line.product_id = self.product_7_2
line.product_uom_id = uom_unit
line.product_qty = 5
bom_finished = bom_finished.save()
def test_validate_bom_line_with_variant_of_bom_product(self):
"""
Can set a BOM line on a BOM with a product variant when the BOM has no variant selected
"""
uom_unit = self.env.ref('uom.product_uom_unit')
bom_finished = Form(self.env['mrp.bom'])
bom_finished.product_tmpl_id = self.product_6.product_tmpl_id
# no product_id
bom_finished.product_qty = 100
with bom_finished.bom_line_ids.new() as line:
line.product_id = self.product_7_2
line.product_uom_id = uom_unit
line.product_qty = 5
bom_finished = bom_finished.save()
def test_replenishment(self):
""" Tests the auto generation of manual orderpoints.
The multiple quantity of the orderpoint should be the
quantity of the BoM in the UoM of the product.
"""
uom_kg = self.env.ref('uom.product_uom_kgm')
uom_gram = self.env.ref('uom.product_uom_gram')
product_gram = self.env['product.product'].create({
'name': 'Product sold in grams',
'type': 'product',
'uom_id': uom_gram.id,
'uom_po_id': uom_gram.id,
})
# We create a BoM that manufactures 2kg of product
self.env['mrp.bom'].create({
'product_id': product_gram.id,
'product_tmpl_id': product_gram.product_tmpl_id.id,
'product_uom_id': uom_kg.id,
'product_qty': 2.0,
'type': 'normal',
})
# We create a delivery order of 2300 grams
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_out')
with picking_form.move_ids_without_package.new() as move:
move.product_id = product_gram
move.product_uom_qty = 2300.0
customer_picking = picking_form.save()
customer_picking.action_confirm()
# We check the created orderpoint
self.env['report.stock.quantity'].flush()
self.env['stock.warehouse.orderpoint']._get_orderpoint_action()
orderpoint = self.env['stock.warehouse.orderpoint'].search([('product_id', '=', product_gram.id)])
manufacturing_route_id = self.ref('mrp.route_warehouse0_manufacture')
self.assertEqual(orderpoint.route_id.id, manufacturing_route_id)
self.assertEqual(orderpoint.qty_multiple, 2000.0)
self.assertEqual(orderpoint.qty_to_order, 4000.0)
def test_bom_kit_with_sub_kit(self):
p1, p2, p3, p4 = self.make_prods(4)
self.make_bom(p1, p2, p3)
self.make_bom(p2, p3, p4)
loc = self.env.ref("stock.stock_location_stock")
self.env["stock.quant"]._update_available_quantity(p3, loc, 10)
self.env["stock.quant"]._update_available_quantity(p4, loc, 10)
self.assertEqual(p1.qty_available, 5.0)
self.assertEqual(p2.qty_available, 10.0)
self.assertEqual(p3.qty_available, 10.0)
| 47.572993 | 52,140 |
16,308 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import common
from odoo.exceptions import UserError
from odoo.tests import Form
class TestWarehouse(common.TestMrpCommon):
def setUp(self):
super(TestWarehouse, self).setUp()
unit = self.env.ref("uom.product_uom_unit")
self.stock_location = self.env.ref('stock.stock_location_stock')
self.depot_location = self.env['stock.location'].create({
'name': 'Depot',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env["stock.putaway.rule"].create({
"location_in_id": self.stock_location.id,
"location_out_id": self.depot_location.id,
'category_id': self.env.ref('product.product_category_all').id,
})
mrp_workcenter = self.env['mrp.workcenter'].create({
'name': 'Assembly Line 1',
'resource_calendar_id': self.env.ref('resource.resource_calendar_std').id,
})
self.env['stock.quant'].create({
'location_id': self.stock_location_14.id,
'product_id': self.graphics_card.id,
'inventory_quantity': 16.0
}).action_apply_inventory()
self.bom_laptop = self.env['mrp.bom'].create({
'product_tmpl_id': self.laptop.product_tmpl_id.id,
'product_qty': 1,
'product_uom_id': unit.id,
'consumption': 'flexible',
'bom_line_ids': [(0, 0, {
'product_id': self.graphics_card.id,
'product_qty': 1,
'product_uom_id': unit.id
})],
'operation_ids': [
(0, 0, {'name': 'Cutting Machine', 'workcenter_id': self.workcenter_1.id, 'time_cycle': 12, 'sequence': 1}),
],
})
def new_mo_laptop(self):
form = Form(self.env['mrp.production'])
form.product_id = self.laptop
form.product_qty = 1
form.bom_id = self.bom_laptop
p = form.save()
p.action_confirm()
p.action_assign()
return p
def test_manufacturing_route(self):
warehouse_1_stock_manager = self.warehouse_1.with_user(self.user_stock_manager)
manu_rule = self.env['stock.rule'].search([
('action', '=', 'manufacture'),
('warehouse_id', '=', self.warehouse_1.id)])
self.assertEqual(self.warehouse_1.manufacture_pull_id, manu_rule)
manu_route = manu_rule.route_id
self.assertIn(manu_route, warehouse_1_stock_manager._get_all_routes())
warehouse_1_stock_manager.write({
'manufacture_to_resupply': False
})
self.assertFalse(self.warehouse_1.manufacture_pull_id.active)
self.assertFalse(self.warehouse_1.manu_type_id.active)
self.assertNotIn(manu_route, warehouse_1_stock_manager._get_all_routes())
warehouse_1_stock_manager.write({
'manufacture_to_resupply': True
})
manu_rule = self.env['stock.rule'].search([
('action', '=', 'manufacture'),
('warehouse_id', '=', self.warehouse_1.id)])
self.assertEqual(self.warehouse_1.manufacture_pull_id, manu_rule)
self.assertTrue(self.warehouse_1.manu_type_id.active)
self.assertIn(manu_route, warehouse_1_stock_manager._get_all_routes())
def test_manufacturing_scrap(self):
"""
Testing to do a scrap of consumed material.
"""
# Update demo products
(self.product_4 | self.product_2).write({
'tracking': 'lot',
})
# Update Bill Of Material to remove product with phantom bom.
self.bom_3.bom_line_ids.filtered(lambda x: x.product_id == self.product_5).unlink()
# Create Inventory Adjustment For Stick and Stone Tools with lot.
lot_product_4 = self.env['stock.production.lot'].create({
'name': '0000000000001',
'product_id': self.product_4.id,
'company_id': self.env.company.id,
})
lot_product_2 = self.env['stock.production.lot'].create({
'name': '0000000000002',
'product_id': self.product_2.id,
'company_id': self.env.company.id,
})
# Inventory for Stick
self.env['stock.quant'].create({
'location_id': self.stock_location_14.id,
'product_id': self.product_4.id,
'inventory_quantity': 8,
'lot_id': lot_product_4.id
}).action_apply_inventory()
# Inventory for Stone Tools
self.env['stock.quant'].create({
'location_id': self.stock_location_14.id,
'product_id': self.product_2.id,
'inventory_quantity': 12,
'lot_id': lot_product_2.id
}).action_apply_inventory()
#Create Manufacturing order.
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_6
production_form.bom_id = self.bom_3
production_form.product_qty = 12
production_form.product_uom_id = self.product_6.uom_id
production_3 = production_form.save()
production_3.action_confirm()
production_3.action_assign()
# Check Manufacturing order's availability.
self.assertEqual(production_3.reservation_state, 'assigned', "Production order's availability should be Available.")
location_id = production_3.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel')) and production_3.location_src_id.id or production_3.location_dest_id.id,
# Scrap Product Wood without lot to check assert raise ?.
scrap_id = self.env['stock.scrap'].with_context(active_model='mrp.production', active_id=production_3.id).create({'product_id': self.product_2.id, 'scrap_qty': 1.0, 'product_uom_id': self.product_2.uom_id.id, 'location_id': location_id, 'production_id': production_3.id})
with self.assertRaises(UserError):
scrap_id.do_scrap()
# Scrap Product Wood with lot.
self.env['stock.scrap'].with_context(active_model='mrp.production', active_id=production_3.id).create({'product_id': self.product_2.id, 'scrap_qty': 1.0, 'product_uom_id': self.product_2.uom_id.id, 'location_id': location_id, 'lot_id': lot_product_2.id, 'production_id': production_3.id})
#Check scrap move is created for this production order.
#TODO: should check with scrap objects link in between
# scrap_move = production_3.move_raw_ids.filtered(lambda x: x.product_id == self.product_2 and x.scrapped)
# self.assertTrue(scrap_move, "There are no any scrap move created for production order.")
def test_putaway_after_manufacturing_3(self):
""" This test checks a tracked manufactured product will go to location
defined in putaway strategy when the production is recorded with
product.produce wizard.
"""
self.laptop.tracking = 'serial'
mo_laptop = self.new_mo_laptop()
serial = self.env['stock.production.lot'].create({'product_id': self.laptop.id, 'company_id': self.env.company.id})
mo_form = Form(mo_laptop)
mo_form.qty_producing = 1
mo_form.lot_producing_id = serial
mo_laptop = mo_form.save()
mo_laptop.button_mark_done()
# We check if the laptop go in the depot and not in the stock
move = mo_laptop.move_finished_ids
location_dest = move.move_line_ids.location_dest_id
self.assertEqual(location_dest.id, self.depot_location.id)
self.assertNotEqual(location_dest.id, self.stock_location.id)
class TestKitPicking(common.TestMrpCommon):
def setUp(self):
super(TestKitPicking, self).setUp()
def create_product(name):
p = Form(self.env['product.product'])
p.name = name
p.detailed_type = 'product'
return p.save()
# Create a kit 'kit_parent' :
# ---------------------------
#
# kit_parent --|- kit_2 x2 --|- component_d x1
# | |- kit_1 x2 -------|- component_a x2
# | |- component_b x1
# | |- component_c x3
# |
# |- kit_3 x1 --|- component_f x1
# | |- component_g x2
# |
# |- component_e x1
# Creating all components
component_a = create_product('Comp A')
component_b = create_product('Comp B')
component_c = create_product('Comp C')
component_d = create_product('Comp D')
component_e = create_product('Comp E')
component_f = create_product('Comp F')
component_g = create_product('Comp G')
# Creating all kits
kit_1 = create_product('Kit 1')
kit_2 = create_product('Kit 2')
kit_3 = create_product('kit 3')
self.kit_parent = create_product('Kit Parent')
# Linking the kits and the components via some 'phantom' BoMs
bom_kit_1 = self.env['mrp.bom'].create({
'product_tmpl_id': kit_1.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine = self.env['mrp.bom.line']
BomLine.create({
'product_id': component_a.id,
'product_qty': 2.0,
'bom_id': bom_kit_1.id})
BomLine.create({
'product_id': component_b.id,
'product_qty': 1.0,
'bom_id': bom_kit_1.id})
BomLine.create({
'product_id': component_c.id,
'product_qty': 3.0,
'bom_id': bom_kit_1.id})
bom_kit_2 = self.env['mrp.bom'].create({
'product_tmpl_id': kit_2.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine.create({
'product_id': component_d.id,
'product_qty': 1.0,
'bom_id': bom_kit_2.id})
BomLine.create({
'product_id': kit_1.id,
'product_qty': 2.0,
'bom_id': bom_kit_2.id})
bom_kit_parent = self.env['mrp.bom'].create({
'product_tmpl_id': self.kit_parent.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine.create({
'product_id': component_e.id,
'product_qty': 1.0,
'bom_id': bom_kit_parent.id})
BomLine.create({
'product_id': kit_2.id,
'product_qty': 2.0,
'bom_id': bom_kit_parent.id})
bom_kit_3 = self.env['mrp.bom'].create({
'product_tmpl_id': kit_3.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine.create({
'product_id': component_f.id,
'product_qty': 1.0,
'bom_id': bom_kit_3.id})
BomLine.create({
'product_id': component_g.id,
'product_qty': 2.0,
'bom_id': bom_kit_3.id})
BomLine.create({
'product_id': kit_3.id,
'product_qty': 1.0,
'bom_id': bom_kit_parent.id})
# We create an 'immediate transfer' receipt for x3 kit_parent
self.test_partner = self.env['res.partner'].create({
'name': 'Notthat Guyagain',
})
self.test_supplier = self.env['stock.location'].create({
'name': 'supplier',
'usage': 'supplier',
'location_id': self.env.ref('stock.stock_location_stock').id,
})
self.expected_quantities = {
component_a: 24,
component_b: 12,
component_c: 36,
component_d: 6,
component_e: 3,
component_f: 3,
component_g: 6
}
def test_kit_immediate_transfer(self):
""" Make sure a kit is split in the corrects quantity_done by components in case of an
immediate transfer.
"""
picking = self.env['stock.picking'].create({
'location_id': self.test_supplier.id,
'location_dest_id': self.warehouse_1.wh_input_stock_loc_id.id,
'partner_id': self.test_partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'immediate_transfer': True
})
move_receipt_1 = self.env['stock.move'].create({
'name': self.kit_parent.name,
'product_id': self.kit_parent.id,
'quantity_done': 3,
'product_uom': self.kit_parent.uom_id.id,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'location_id': self.test_supplier.id,
'location_dest_id': self.warehouse_1.wh_input_stock_loc_id.id,
})
picking.button_validate()
# We check that the picking has the correct quantities after its move were splitted.
self.assertEqual(len(picking.move_lines), 7)
for move_line in picking.move_lines:
self.assertEqual(move_line.quantity_done, self.expected_quantities[move_line.product_id])
def test_kit_planned_transfer(self):
""" Make sure a kit is split in the corrects product_qty by components in case of a
planned transfer.
"""
picking = self.env['stock.picking'].create({
'location_id': self.test_supplier.id,
'location_dest_id': self.warehouse_1.wh_input_stock_loc_id.id,
'partner_id': self.test_partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'immediate_transfer': False,
})
move_receipt_1 = self.env['stock.move'].create({
'name': self.kit_parent.name,
'product_id': self.kit_parent.id,
'product_uom_qty': 3,
'product_uom': self.kit_parent.uom_id.id,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'location_id': self.test_supplier.id,
'location_dest_id': self.warehouse_1.wh_input_stock_loc_id.id,
})
picking.action_confirm()
# We check that the picking has the correct quantities after its move were splitted.
self.assertEqual(len(picking.move_lines), 7)
for move_line in picking.move_lines:
self.assertEqual(move_line.product_qty, self.expected_quantities[move_line.product_id])
def test_add_sml_with_kit_to_confirmed_picking(self):
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
customer_location = self.env.ref('stock.stock_location_customers')
stock_location = warehouse.lot_stock_id
in_type = warehouse.in_type_id
self.bom_4.type = 'phantom'
kit = self.bom_4.product_id
compo = self.bom_4.bom_line_ids.product_id
product = self.env['product.product'].create({'name': 'Super Product', 'type': 'product'})
receipt = self.env['stock.picking'].create({
'picking_type_id': in_type.id,
'location_id': customer_location.id,
'location_dest_id': stock_location.id,
'move_lines': [(0, 0, {
'name': product.name,
'product_id': product.id,
'product_uom_qty': 1,
'product_uom': product.uom_id.id,
'location_id': customer_location.id,
'location_dest_id': stock_location.id,
})]
})
receipt.action_confirm()
receipt.move_line_ids.qty_done = 1
receipt.move_line_ids = [(0, 0, {
'product_id': kit.id,
'qty_done': 1,
'product_uom_id': kit.uom_id.id,
'location_id': customer_location.id,
'location_dest_id': stock_location.id,
})]
receipt.button_validate()
self.assertEqual(receipt.state, 'done')
self.assertRecordValues(receipt.move_lines, [
{'product_id': product.id, 'quantity_done': 1, 'state': 'done'},
{'product_id': compo.id, 'quantity_done': 1, 'state': 'done'},
])
| 42.248705 | 16,308 |
7,503 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common, Form
from odoo.exceptions import UserError
class TestMrpMulticompany(common.TransactionCase):
def setUp(self):
super(TestMrpMulticompany, self).setUp()
group_user = self.env.ref('base.group_user')
group_mrp_manager = self.env.ref('mrp.group_mrp_manager')
self.company_a = self.env['res.company'].create({'name': 'Company A'})
self.company_b = self.env['res.company'].create({'name': 'Company B'})
self.warehouse_a = self.env['stock.warehouse'].search([('company_id', '=', self.company_a.id)], limit=1)
self.warehouse_b = self.env['stock.warehouse'].search([('company_id', '=', self.company_b.id)], limit=1)
self.stock_location_a = self.warehouse_a.lot_stock_id
self.stock_location_b = self.warehouse_b.lot_stock_id
self.user_a = self.env['res.users'].create({
'name': 'user company a with access to company b',
'login': 'user a',
'groups_id': [(6, 0, [group_user.id, group_mrp_manager.id])],
'company_id': self.company_a.id,
'company_ids': [(6, 0, [self.company_a.id, self.company_b.id])]
})
self.user_b = self.env['res.users'].create({
'name': 'user company a with access to company b',
'login': 'user b',
'groups_id': [(6, 0, [group_user.id, group_mrp_manager.id])],
'company_id': self.company_b.id,
'company_ids': [(6, 0, [self.company_a.id, self.company_b.id])]
})
def test_bom_1(self):
"""Check it is not possible to use a product of Company B in a
bom of Company A. """
product_b = self.env['product.product'].create({
'name': 'p1',
'company_id': self.company_b.id,
})
with self.assertRaises(UserError):
self.env['mrp.bom'].create({
'product_id': product_b.id,
'product_tmpl_id': product_b.product_tmpl_id.id,
'company_id': self.company_a.id,
})
def test_bom_2(self):
"""Check it is not possible to use a product of Company B as a component
in a bom of Company A. """
product_a = self.env['product.product'].create({
'name': 'p1',
'company_id': self.company_a.id,
})
product_b = self.env['product.product'].create({
'name': 'p2',
'company_id': self.company_b.id,
})
with self.assertRaises(UserError):
self.env['mrp.bom'].create({
'product_id': product_a.id,
'product_tmpl_id': product_b.product_tmpl_id.id,
'company_id': self.company_a.id,
'bom_line_ids': [(0, 0, {'product_id': product_b.id})]
})
def test_production_1(self):
"""Check it is not possible to confirm a production of Company B with
product of Company A. """
product_a = self.env['product.product'].create({
'name': 'p1',
'company_id': self.company_a.id,
})
mo = self.env['mrp.production'].create({
'product_id': product_a.id,
'product_uom_id': product_a.uom_id.id,
'company_id': self.company_b.id,
})
with self.assertRaises(UserError):
mo.action_confirm()
def test_production_2(self):
"""Check that confirming a production in company b with user_a will create
stock moves on company b. """
product_a = self.env['product.product'].create({
'name': 'p1',
'company_id': self.company_a.id,
})
component_a = self.env['product.product'].create({
'name': 'p2',
'company_id': self.company_a.id,
})
self.env['mrp.bom'].create({
'product_id': product_a.id,
'product_tmpl_id': product_a.product_tmpl_id.id,
'company_id': self.company_a.id,
'bom_line_ids': [(0, 0, {'product_id': component_a.id})]
})
mo_form = Form(self.env['mrp.production'].with_user(self.user_a))
mo_form.product_id = product_a
mo = mo_form.save()
mo.with_user(self.user_b).action_confirm()
self.assertEqual(mo.move_raw_ids.company_id, self.company_a)
self.assertEqual(mo.move_finished_ids.company_id, self.company_a)
def test_product_produce_1(self):
"""Check that using a finished lot of company b in the produce wizard of a production
of company a is not allowed """
product = self.env['product.product'].create({
'name': 'p1',
'tracking': 'lot',
})
component = self.env['product.product'].create({
'name': 'p2',
})
lot_b = self.env['stock.production.lot'].create({
'product_id': product.id,
'company_id': self.company_b.id,
})
self.env['mrp.bom'].create({
'product_id': product.id,
'product_tmpl_id': product.product_tmpl_id.id,
'company_id': self.company_a.id,
'bom_line_ids': [(0, 0, {'product_id': component.id})]
})
mo_form = Form(self.env['mrp.production'].with_user(self.user_a))
mo_form.product_id = product
mo_form.lot_producing_id = lot_b
mo = mo_form.save()
with self.assertRaises(UserError):
mo.with_user(self.user_b).action_confirm()
def test_product_produce_2(self):
"""Check that using a component lot of company b in the produce wizard of a production
of company a is not allowed """
product = self.env['product.product'].create({
'name': 'p1',
})
component = self.env['product.product'].create({
'name': 'p2',
'tracking': 'lot',
})
lot_b = self.env['stock.production.lot'].create({
'product_id': component.id,
'company_id': self.company_b.id,
})
self.env['mrp.bom'].create({
'product_id': product.id,
'product_tmpl_id': product.product_tmpl_id.id,
'company_id': self.company_a.id,
'bom_line_ids': [(0, 0, {'product_id': component.id})]
})
mo_form = Form(self.env['mrp.production'].with_user(self.user_a))
mo_form.product_id = product
mo = mo_form.save()
mo.with_user(self.user_b).action_confirm()
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.edit(0) as ml:
ml.lot_id = lot_b
ml.qty_done = 1
details_operation_form.save()
with self.assertRaises(UserError):
mo.button_mark_done()
def test_partner_1(self):
""" On a product without company, as a user of Company B, check it is not possible to use a
location limited to Company A as `property_stock_production` """
shared_product = self.env['product.product'].create({
'name': 'Shared Product',
'company_id': False,
})
with self.assertRaises(UserError):
shared_product.with_user(self.user_b).property_stock_production = self.stock_location_a
| 40.122995 | 7,503 |
4,063 |
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.tools import float_compare
class MrpImmediateProductionLine(models.TransientModel):
_name = 'mrp.immediate.production.line'
_description = 'Immediate Production Line'
immediate_production_id = fields.Many2one('mrp.immediate.production', 'Immediate Production', required=True)
production_id = fields.Many2one('mrp.production', 'Production', required=True)
to_immediate = fields.Boolean('To Process')
class MrpImmediateProduction(models.TransientModel):
_name = 'mrp.immediate.production'
_description = 'Immediate Production'
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if 'immediate_production_line_ids' in fields:
if self.env.context.get('default_mo_ids'):
res['mo_ids'] = self.env.context['default_mo_ids']
res['immediate_production_line_ids'] = [(0, 0, {'to_immediate': True, 'production_id': mo_id[1]}) for mo_id in res['mo_ids']]
return res
mo_ids = fields.Many2many('mrp.production', 'mrp_production_production_rel')
show_productions = fields.Boolean(compute='_compute_show_production')
immediate_production_line_ids = fields.One2many(
'mrp.immediate.production.line',
'immediate_production_id',
string="Immediate Production Lines")
@api.depends('immediate_production_line_ids')
def _compute_show_production(self):
for wizard in self:
wizard.show_productions = len(wizard.immediate_production_line_ids.production_id) > 1
def process(self):
productions_to_do = self.env['mrp.production']
productions_not_to_do = self.env['mrp.production']
for line in self.immediate_production_line_ids:
if line.to_immediate is True:
productions_to_do |= line.production_id
else:
productions_not_to_do |= line.production_id
for production in productions_to_do:
error_msg = ""
if production.product_tracking in ('lot', 'serial') and not production.lot_producing_id:
production.action_generate_serial()
if production.product_tracking == 'serial' and float_compare(production.qty_producing, 1, precision_rounding=production.product_uom_id.rounding) == 1:
production.qty_producing = 1
else:
production.qty_producing = production.product_qty - production.qty_produced
production._set_qty_producing()
for move in production.move_raw_ids.filtered(lambda m: m.state not in ['done', 'cancel']):
rounding = move.product_uom.rounding
for move_line in move.move_line_ids:
if move_line.product_uom_qty:
move_line.qty_done = min(move_line.product_uom_qty, move_line.move_id.should_consume_qty)
if float_compare(move.quantity_done, move.should_consume_qty, precision_rounding=rounding) >= 0:
break
if float_compare(move.product_uom_qty, move.quantity_done, precision_rounding=move.product_uom.rounding) == 1:
if move.has_tracking in ('serial', 'lot'):
error_msg += "\n - %s" % move.product_id.display_name
if error_msg:
error_msg = _('You need to supply Lot/Serial Number for products:') + error_msg
raise UserError(error_msg)
productions_to_validate = self.env.context.get('button_mark_done_production_ids')
if productions_to_validate:
productions_to_validate = self.env['mrp.production'].browse(productions_to_validate)
productions_to_validate = productions_to_validate - productions_not_to_do
return productions_to_validate.with_context(skip_immediate=True).button_mark_done()
return True
| 49.54878 | 4,063 |
607 |
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 StockWarnInsufficientQtyUnbuild(models.TransientModel):
_name = 'stock.warn.insufficient.qty.unbuild'
_inherit = 'stock.warn.insufficient.qty'
_description = 'Warn Insufficient Unbuild Quantity'
unbuild_id = fields.Many2one('mrp.unbuild', 'Unbuild')
def _get_reference_document_company_id(self):
return self.unbuild_id.company_id
def action_done(self):
self.ensure_one()
return self.unbuild_id.action_unbuild()
| 31.947368 | 607 |
6,588 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_is_zero, float_round
class ChangeProductionQty(models.TransientModel):
_name = 'change.production.qty'
_description = 'Change Production Qty'
mo_id = fields.Many2one('mrp.production', 'Manufacturing Order',
required=True, ondelete='cascade')
product_qty = fields.Float(
'Quantity To Produce',
digits='Product Unit of Measure', required=True)
@api.model
def default_get(self, fields):
res = super(ChangeProductionQty, self).default_get(fields)
if 'mo_id' in fields and not res.get('mo_id') and self._context.get('active_model') == 'mrp.production' and self._context.get('active_id'):
res['mo_id'] = self._context['active_id']
if 'product_qty' in fields and not res.get('product_qty') and res.get('mo_id'):
res['product_qty'] = self.env['mrp.production'].browse(res['mo_id']).product_qty
return res
@api.model
def _update_finished_moves(self, production, new_qty, old_qty):
""" Update finished product and its byproducts. This method only update
the finished moves not done or cancel and just increase or decrease
their quantity according the unit_ratio. It does not use the BoM, BoM
modification during production would not be taken into consideration.
"""
modification = {}
for move in production.move_finished_ids:
if move.state in ('done', 'cancel'):
continue
done_qty = sum(production.move_finished_ids.filtered(
lambda r:
r.product_id == move.product_id and
r.state == 'done'
).mapped('product_uom_qty')
)
qty = (new_qty - old_qty) * move.unit_factor + done_qty
modification[move] = (move.product_uom_qty + qty, move.product_uom_qty)
if (move.product_uom_qty + qty) > 0:
move.write({'product_uom_qty': move.product_uom_qty + qty})
else:
move._action_cancel()
return modification
def change_prod_qty(self):
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for wizard in self:
production = wizard.mo_id
produced = sum(production.move_finished_ids.filtered(lambda m: m.product_id == production.product_id).mapped('quantity_done'))
if wizard.product_qty < produced:
format_qty = '%.{precision}f'.format(precision=precision)
raise UserError(_(
"You have already processed %(quantity)s. Please input a quantity higher than %(minimum)s ",
quantity=format_qty % produced,
minimum=format_qty % produced
))
old_production_qty = production.product_qty
new_production_qty = wizard.product_qty
done_moves = production.move_finished_ids.filtered(lambda x: x.state == 'done' and x.product_id == production.product_id)
qty_produced = production.product_id.uom_id._compute_quantity(sum(done_moves.mapped('product_qty')), production.product_uom_id)
factor = (new_production_qty - qty_produced) / (old_production_qty - qty_produced)
update_info = production._update_raw_moves(factor)
documents = {}
for move, old_qty, new_qty in update_info:
iterate_key = production._get_document_iterate_key(move)
if iterate_key:
document = self.env['stock.picking']._log_activity_get_documents({move: (new_qty, old_qty)}, iterate_key, 'UP')
for key, value in document.items():
if documents.get(key):
documents[key] += [value]
else:
documents[key] = [value]
production._log_manufacture_exception(documents)
finished_moves_modification = self._update_finished_moves(production, new_production_qty - qty_produced, old_production_qty - qty_produced)
if finished_moves_modification:
production._log_downside_manufactured_quantity(finished_moves_modification)
production.write({'product_qty': new_production_qty})
for wo in production.workorder_ids:
operation = wo.operation_id
wo.duration_expected = wo._get_duration_expected(ratio=new_production_qty / old_production_qty)
quantity = wo.qty_production - wo.qty_produced
if production.product_id.tracking == 'serial':
quantity = 1.0 if not float_is_zero(quantity, precision_digits=precision) else 0.0
else:
quantity = quantity if (quantity > 0 and not float_is_zero(quantity, precision_digits=precision)) else 0
wo._update_qty_producing(quantity)
if wo.qty_produced < wo.qty_production and wo.state == 'done':
wo.state = 'progress'
if wo.qty_produced == wo.qty_production and wo.state == 'progress':
wo.state = 'done'
if wo.next_work_order_id.state == 'pending':
wo.next_work_order_id.state = 'ready'
# assign moves; last operation receive all unassigned moves
# TODO: following could be put in a function as it is similar as code in _workorders_create
# TODO: only needed when creating new moves
moves_raw = production.move_raw_ids.filtered(lambda move: move.operation_id == operation and move.state not in ('done', 'cancel'))
if wo == production.workorder_ids[-1]:
moves_raw |= production.move_raw_ids.filtered(lambda move: not move.operation_id)
moves_finished = production.move_finished_ids.filtered(lambda move: move.operation_id == operation) #TODO: code does nothing, unless maybe by_products?
moves_raw.mapped('move_line_ids').write({'workorder_id': wo.id})
(moves_finished + moves_raw).write({'workorder_id': wo.id})
# run scheduler for moves forecasted to not have enough in stock
self.mo_id.filtered(lambda mo: mo.state in ['confirmed', 'progress']).move_raw_ids._trigger_scheduler()
return {}
| 56.307692 | 6,588 |
4,482 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import Counter
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class StockAssignSerialNumbers(models.TransientModel):
_inherit = 'stock.assign.serial'
production_id = fields.Many2one('mrp.production', 'Production')
expected_qty = fields.Float('Expected Quantity', digits='Product Unit of Measure')
serial_numbers = fields.Text('Produced Serial Numbers')
produced_qty = fields.Float('Produced Quantity', digits='Product Unit of Measure')
show_apply = fields.Boolean(help="Technical field to show the Apply button")
show_backorders = fields.Boolean(help="Technical field to show the Create Backorder and No Backorder buttons")
def generate_serial_numbers_production(self):
if self.next_serial_number and self.next_serial_count:
generated_serial_numbers = "\n".join(self.env['stock.production.lot'].generate_lot_names(self.next_serial_number, self.next_serial_count))
self.serial_numbers = "\n".join([self.serial_numbers, generated_serial_numbers]) if self.serial_numbers else generated_serial_numbers
self._onchange_serial_numbers()
action = self.env["ir.actions.actions"]._for_xml_id("mrp.act_assign_serial_numbers_production")
action['res_id'] = self.id
return action
def _get_serial_numbers(self):
if self.serial_numbers:
return list(filter(lambda serial_number: len(serial_number.strip()) > 0, self.serial_numbers.split('\n')))
return []
@api.onchange('serial_numbers')
def _onchange_serial_numbers(self):
self.show_apply = False
self.show_backorders = False
serial_numbers = self._get_serial_numbers()
duplicate_serial_numbers = [serial_number for serial_number, counter in Counter(serial_numbers).items() if counter > 1]
if duplicate_serial_numbers:
self.serial_numbers = ""
self.produced_qty = 0
raise UserError(_('Duplicate Serial Numbers (%s)') % ','.join(duplicate_serial_numbers))
existing_serial_numbers = self.env['stock.production.lot'].search([
('company_id', '=', self.production_id.company_id.id),
('product_id', '=', self.production_id.product_id.id),
('name', 'in', serial_numbers),
])
if existing_serial_numbers:
self.serial_numbers = ""
self.produced_qty = 0
raise UserError(_('Existing Serial Numbers (%s)') % ','.join(existing_serial_numbers.mapped('display_name')))
if len(serial_numbers) > self.expected_qty:
self.serial_numbers = ""
self.produced_qty = 0
raise UserError(_('There are more Serial Numbers than the Quantity to Produce'))
self.produced_qty = len(serial_numbers)
self.show_apply = self.produced_qty == self.expected_qty
self.show_backorders = self.produced_qty > 0 and self.produced_qty < self.expected_qty
def _assign_serial_numbers(self, cancel_remaining_quantity=False):
serial_numbers = self._get_serial_numbers()
productions = self.production_id._split_productions(
{self.production_id: [1] * len(serial_numbers)}, cancel_remaining_quantity, set_consumed_qty=True)
production_lots_vals = []
for serial_name in serial_numbers:
production_lots_vals.append({
'product_id': self.production_id.product_id.id,
'company_id': self.production_id.company_id.id,
'name': serial_name,
})
production_lots = self.env['stock.production.lot'].create(production_lots_vals)
for production, production_lot in zip(productions, production_lots):
production.lot_producing_id = production_lot.id
production.qty_producing = production.product_qty
for workorder in production.workorder_ids:
workorder.qty_produced = workorder.qty_producing
if productions and len(production_lots) < len(productions):
productions[-1].move_raw_ids.move_line_ids.write({'qty_done': 0})
productions[-1].state = "confirmed"
def apply(self):
self._assign_serial_numbers()
def create_backorder(self):
self._assign_serial_numbers(False)
def no_backorder(self):
self._assign_serial_numbers(True)
| 49.8 | 4,482 |
3,199 |
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 MrpConsumptionWarning(models.TransientModel):
_name = 'mrp.consumption.warning'
_description = "Wizard in case of consumption in warning/strict and more component has been used for a MO (related to the bom)"
mrp_production_ids = fields.Many2many('mrp.production')
mrp_production_count = fields.Integer(compute="_compute_mrp_production_count")
consumption = fields.Selection([
('flexible', 'Allowed'),
('warning', 'Allowed with warning'),
('strict', 'Blocked')], compute="_compute_consumption")
mrp_consumption_warning_line_ids = fields.One2many('mrp.consumption.warning.line', 'mrp_consumption_warning_id')
@api.depends("mrp_production_ids")
def _compute_mrp_production_count(self):
for wizard in self:
wizard.mrp_production_count = len(wizard.mrp_production_ids)
@api.depends("mrp_consumption_warning_line_ids.consumption")
def _compute_consumption(self):
for wizard in self:
consumption_map = set(wizard.mrp_consumption_warning_line_ids.mapped("consumption"))
wizard.consumption = "strict" in consumption_map and "strict" or "warning" in consumption_map and "warning" or "flexible"
def action_confirm(self):
ctx = dict(self.env.context)
ctx.pop('default_mrp_production_ids', None)
action_from_do_finish = False
if self.env.context.get('from_workorder'):
if self.env.context.get('active_model') == 'mrp.workorder':
action_from_do_finish = self.env['mrp.workorder'].browse(self.env.context.get('active_id')).do_finish()
action_from_mark_done = self.mrp_production_ids.with_context(ctx, skip_consumption=True).button_mark_done()
return action_from_do_finish or action_from_mark_done
def action_cancel(self):
if self.env.context.get('from_workorder') and len(self.mrp_production_ids) == 1:
return {
'type': 'ir.actions.act_window',
'res_model': 'mrp.production',
'views': [[self.env.ref('mrp.mrp_production_form_view').id, 'form']],
'res_id': self.mrp_production_ids.id,
'target': 'main',
}
class MrpConsumptionWarningLine(models.TransientModel):
_name = 'mrp.consumption.warning.line'
_description = "Line of issue consumption"
mrp_consumption_warning_id = fields.Many2one('mrp.consumption.warning', "Parent Wizard", readonly=True, required=True, ondelete="cascade")
mrp_production_id = fields.Many2one('mrp.production', "Manufacturing Order", readonly=True, required=True, ondelete="cascade")
consumption = fields.Selection(related="mrp_production_id.consumption")
product_id = fields.Many2one('product.product', "Product", readonly=True, required=True)
product_uom_id = fields.Many2one('uom.uom', "Unit of Measure", related="product_id.uom_id", readonly=True)
product_consumed_qty_uom = fields.Float("Consumed", readonly=True)
product_expected_qty_uom = fields.Float("To Consume", readonly=True)
| 51.596774 | 3,199 |
1,842 |
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 MrpProductionBackorderLine(models.TransientModel):
_name = 'mrp.production.backorder.line'
_description = "Backorder Confirmation Line"
mrp_production_backorder_id = fields.Many2one('mrp.production.backorder', 'MO Backorder', required=True, ondelete="cascade")
mrp_production_id = fields.Many2one('mrp.production', 'Manufacturing Order', required=True, ondelete="cascade", readonly=True)
to_backorder = fields.Boolean('To Backorder')
class MrpProductionBackorder(models.TransientModel):
_name = 'mrp.production.backorder'
_description = "Wizard to mark as done or create back order"
mrp_production_ids = fields.Many2many('mrp.production')
mrp_production_backorder_line_ids = fields.One2many(
'mrp.production.backorder.line',
'mrp_production_backorder_id',
string="Backorder Confirmation Lines")
show_backorder_lines = fields.Boolean("Show backorder lines", compute="_compute_show_backorder_lines")
@api.depends('mrp_production_backorder_line_ids')
def _compute_show_backorder_lines(self):
for wizard in self:
wizard.show_backorder_lines = len(wizard.mrp_production_backorder_line_ids) > 1
def action_close_mo(self):
return self.mrp_production_ids.with_context(skip_backorder=True).button_mark_done()
def action_backorder(self):
ctx = dict(self.env.context)
ctx.pop('default_mrp_production_ids', None)
mo_ids_to_backorder = self.mrp_production_backorder_line_ids.filtered(lambda l: l.to_backorder).mrp_production_id.ids
return self.mrp_production_ids.with_context(ctx, skip_backorder=True, mo_ids_to_backorder=mo_ids_to_backorder).button_mark_done()
| 46.05 | 1,842 |
16,341 |
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, ValidationError
from odoo.tools import float_compare, float_round
from odoo.osv import expression
from collections import defaultdict
class MrpUnbuild(models.Model):
_name = "mrp.unbuild"
_description = "Unbuild Order"
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = 'id desc'
name = fields.Char('Reference', copy=False, readonly=True, default=lambda x: _('New'))
product_id = fields.Many2one(
'product.product', 'Product', check_company=True,
domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
required=True, states={'done': [('readonly', True)]})
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda s: s.env.company,
required=True, index=True, states={'done': [('readonly', True)]})
product_qty = fields.Float(
'Quantity', default=1.0,
required=True, states={'done': [('readonly', True)]})
product_uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
required=True, states={'done': [('readonly', True)]})
bom_id = fields.Many2one(
'mrp.bom', 'Bill of Material',
domain="""[
'|',
('product_id', '=', product_id),
'&',
('product_tmpl_id.product_variant_ids', '=', product_id),
('product_id','=',False),
('type', '=', 'normal'),
'|',
('company_id', '=', company_id),
('company_id', '=', False)
]
""",
states={'done': [('readonly', True)]}, check_company=True)
mo_id = fields.Many2one(
'mrp.production', 'Manufacturing Order',
domain="[('state', '=', 'done'), ('company_id', '=', company_id), ('product_id', '=?', product_id), ('bom_id', '=?', bom_id)]",
states={'done': [('readonly', True)]}, check_company=True)
mo_bom_id = fields.Many2one('mrp.bom', 'Bill of Material used on the Production Order', related='mo_id.bom_id')
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial Number',
domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]", check_company=True,
states={'done': [('readonly', True)]}, help="Lot/Serial Number of the product to unbuild.")
has_tracking=fields.Selection(related='product_id.tracking', readonly=True)
location_id = fields.Many2one(
'stock.location', 'Source Location',
domain="[('usage','=','internal'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
check_company=True,
required=True, states={'done': [('readonly', True)]}, help="Location where the product you want to unbuild is.")
location_dest_id = fields.Many2one(
'stock.location', 'Destination Location',
domain="[('usage','=','internal'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
check_company=True,
required=True, states={'done': [('readonly', True)]}, help="Location where you want to send the components resulting from the unbuild order.")
consume_line_ids = fields.One2many(
'stock.move', 'consume_unbuild_id', readonly=True,
string='Consumed Disassembly Lines')
produce_line_ids = fields.One2many(
'stock.move', 'unbuild_id', readonly=True,
string='Processed Disassembly Lines')
state = fields.Selection([
('draft', 'Draft'),
('done', 'Done')], string='Status', default='draft')
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
if self.location_id.company_id != self.company_id:
self.location_id = warehouse.lot_stock_id
if self.location_dest_id.company_id != self.company_id:
self.location_dest_id = warehouse.lot_stock_id
else:
self.location_id = False
self.location_dest_id = False
@api.onchange('mo_id')
def _onchange_mo_id(self):
if self.mo_id:
self.product_id = self.mo_id.product_id.id
self.bom_id = self.mo_id.bom_id
self.product_uom_id = self.mo_id.product_uom_id
if self.has_tracking == 'serial':
self.product_qty = 1
else:
self.product_qty = self.mo_id.product_qty
if self.lot_id and self.lot_id not in self.mo_id.move_finished_ids.move_line_ids.lot_id:
return {'warning': {
'title': _("Warning"),
'message': _("The selected serial number does not correspond to the one used in the manufacturing order, please select another one.")
}}
@api.onchange('lot_id')
def _onchange_lot_id(self):
if self.mo_id and self.lot_id and self.lot_id not in self.mo_id.move_finished_ids.move_line_ids.lot_id:
return {'warning': {
'title': _("Warning"),
'message': _("The selected serial number does not correspond to the one used in the manufacturing order, please select another one.")
}}
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
self.bom_id = self.env['mrp.bom']._bom_find(self.product_id, company_id=self.company_id.id)[self.product_id]
self.product_uom_id = self.mo_id.product_id == self.product_id and self.mo_id.product_uom_id.id or self.product_id.uom_id.id
@api.constrains('product_qty')
def _check_qty(self):
for unbuild in self:
if unbuild.product_qty <= 0:
raise ValidationError(_('Unbuild Order product quantity has to be strictly positive.'))
@api.model
def create(self, vals):
if not vals.get('name') or vals['name'] == _('New'):
vals['name'] = self.env['ir.sequence'].next_by_code('mrp.unbuild') or _('New')
return super(MrpUnbuild, self).create(vals)
@api.ondelete(at_uninstall=False)
def _unlink_except_done(self):
if 'done' in self.mapped('state'):
raise UserError(_("You cannot delete an unbuild order if the state is 'Done'."))
def action_unbuild(self):
self.ensure_one()
self._check_company()
if self.product_id.tracking != 'none' and not self.lot_id.id:
raise UserError(_('You should provide a lot number for the final product.'))
if self.mo_id:
if self.mo_id.state != 'done':
raise UserError(_('You cannot unbuild a undone manufacturing order.'))
consume_moves = self._generate_consume_moves()
consume_moves._action_confirm()
produce_moves = self._generate_produce_moves()
produce_moves._action_confirm()
finished_moves = consume_moves.filtered(lambda m: m.product_id == self.product_id)
consume_moves -= finished_moves
if any(produce_move.has_tracking != 'none' and not self.mo_id for produce_move in produce_moves):
raise UserError(_('Some of your components are tracked, you have to specify a manufacturing order in order to retrieve the correct components.'))
if any(consume_move.has_tracking != 'none' and not self.mo_id for consume_move in consume_moves):
raise UserError(_('Some of your byproducts are tracked, you have to specify a manufacturing order in order to retrieve the correct byproducts.'))
for finished_move in finished_moves:
if finished_move.has_tracking != 'none':
self.env['stock.move.line'].create({
'move_id': finished_move.id,
'lot_id': self.lot_id.id,
'qty_done': finished_move.product_uom_qty,
'product_id': finished_move.product_id.id,
'product_uom_id': finished_move.product_uom.id,
'location_id': finished_move.location_id.id,
'location_dest_id': finished_move.location_dest_id.id,
})
else:
finished_move.quantity_done = finished_move.product_uom_qty
# TODO: Will fail if user do more than one unbuild with lot on the same MO. Need to check what other unbuild has aready took
qty_already_used = defaultdict(float)
for move in produce_moves | consume_moves:
if move.has_tracking != 'none':
original_move = move in produce_moves and self.mo_id.move_raw_ids or self.mo_id.move_finished_ids
original_move = original_move.filtered(lambda m: m.product_id == move.product_id)
needed_quantity = move.product_uom_qty
moves_lines = original_move.mapped('move_line_ids')
if move in produce_moves and self.lot_id:
moves_lines = moves_lines.filtered(lambda ml: self.lot_id in ml.produce_line_ids.lot_id) # FIXME sle: double check with arm
for move_line in moves_lines:
# Iterate over all move_lines until we unbuilded the correct quantity.
taken_quantity = min(needed_quantity, move_line.qty_done - qty_already_used[move_line])
if taken_quantity:
self.env['stock.move.line'].create({
'move_id': move.id,
'lot_id': move_line.lot_id.id,
'qty_done': taken_quantity,
'product_id': move.product_id.id,
'product_uom_id': move_line.product_uom_id.id,
'location_id': move.location_id.id,
'location_dest_id': move.location_dest_id.id,
})
needed_quantity -= taken_quantity
qty_already_used[move_line] += taken_quantity
else:
move.quantity_done = float_round(move.product_uom_qty, precision_rounding=move.product_uom.rounding)
finished_moves._action_done()
consume_moves._action_done()
produce_moves._action_done()
produced_move_line_ids = produce_moves.mapped('move_line_ids').filtered(lambda ml: ml.qty_done > 0)
consume_moves.mapped('move_line_ids').write({'produce_line_ids': [(6, 0, produced_move_line_ids.ids)]})
if self.mo_id:
unbuild_msg = _(
"%s %s unbuilt in", self.product_qty, self.product_uom_id.name) + " <a href=# data-oe-model=mrp.unbuild data-oe-id=%d>%s</a>" % (self.id, self.display_name)
self.mo_id.message_post(
body=unbuild_msg,
subtype_id=self.env.ref('mail.mt_note').id)
return self.write({'state': 'done'})
def _generate_consume_moves(self):
moves = self.env['stock.move']
for unbuild in self:
if unbuild.mo_id:
finished_moves = unbuild.mo_id.move_finished_ids.filtered(lambda move: move.state == 'done')
factor = unbuild.product_qty / unbuild.mo_id.product_uom_id._compute_quantity(unbuild.mo_id.product_qty, unbuild.product_uom_id)
for finished_move in finished_moves:
moves += unbuild._generate_move_from_existing_move(finished_move, factor, unbuild.location_id, finished_move.location_id)
else:
factor = unbuild.product_uom_id._compute_quantity(unbuild.product_qty, unbuild.bom_id.product_uom_id) / unbuild.bom_id.product_qty
moves += unbuild._generate_move_from_bom_line(self.product_id, self.product_uom_id, unbuild.product_qty)
for byproduct in unbuild.bom_id.byproduct_ids:
if byproduct._skip_byproduct_line(unbuild.product_id):
continue
quantity = byproduct.product_qty * factor
moves += unbuild._generate_move_from_bom_line(byproduct.product_id, byproduct.product_uom_id, quantity, byproduct_id=byproduct.id)
return moves
def _generate_produce_moves(self):
moves = self.env['stock.move']
for unbuild in self:
if unbuild.mo_id:
raw_moves = unbuild.mo_id.move_raw_ids.filtered(lambda move: move.state == 'done')
factor = unbuild.product_qty / unbuild.mo_id.product_uom_id._compute_quantity(unbuild.mo_id.product_qty, unbuild.product_uom_id)
for raw_move in raw_moves:
moves += unbuild._generate_move_from_existing_move(raw_move, factor, raw_move.location_dest_id, self.location_dest_id)
else:
factor = unbuild.product_uom_id._compute_quantity(unbuild.product_qty, unbuild.bom_id.product_uom_id) / unbuild.bom_id.product_qty
boms, lines = unbuild.bom_id.explode(unbuild.product_id, factor, picking_type=unbuild.bom_id.picking_type_id)
for line, line_data in lines:
moves += unbuild._generate_move_from_bom_line(line.product_id, line.product_uom_id, line_data['qty'], bom_line_id=line.id)
return moves
def _generate_move_from_existing_move(self, move, factor, location_id, location_dest_id):
return self.env['stock.move'].create({
'name': self.name,
'date': self.create_date,
'product_id': move.product_id.id,
'product_uom_qty': move.product_uom_qty * factor,
'product_uom': move.product_uom.id,
'procure_method': 'make_to_stock',
'location_dest_id': location_dest_id.id,
'location_id': location_id.id,
'warehouse_id': location_dest_id.warehouse_id.id,
'unbuild_id': self.id,
'company_id': move.company_id.id,
})
def _generate_move_from_bom_line(self, product, product_uom, quantity, bom_line_id=False, byproduct_id=False):
product_prod_location = product.with_company(self.company_id).property_stock_production
location_id = bom_line_id and product_prod_location or self.location_id
location_dest_id = bom_line_id and self.location_dest_id or product_prod_location
warehouse = location_dest_id.warehouse_id
return self.env['stock.move'].create({
'name': self.name,
'date': self.create_date,
'bom_line_id': bom_line_id,
'byproduct_id': byproduct_id,
'product_id': product.id,
'product_uom_qty': quantity,
'product_uom': product_uom.id,
'procure_method': 'make_to_stock',
'location_dest_id': location_dest_id.id,
'location_id': location_id.id,
'warehouse_id': warehouse.id,
'unbuild_id': self.id,
'company_id': self.company_id.id,
})
def action_validate(self):
self.ensure_one()
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
available_qty = self.env['stock.quant']._get_available_quantity(self.product_id, self.location_id, self.lot_id, strict=True)
unbuild_qty = self.product_uom_id._compute_quantity(self.product_qty, self.product_id.uom_id)
if float_compare(available_qty, unbuild_qty, precision_digits=precision) >= 0:
return self.action_unbuild()
else:
return {
'name': self.product_id.display_name + _(': Insufficient Quantity To Unbuild'),
'view_mode': 'form',
'res_model': 'stock.warn.insufficient.qty.unbuild',
'view_id': self.env.ref('mrp.stock_warn_insufficient_qty_unbuild_form_view').id,
'type': 'ir.actions.act_window',
'context': {
'default_product_id': self.product_id.id,
'default_location_id': self.location_id.id,
'default_unbuild_id': self.id,
'default_quantity': unbuild_qty,
'default_product_uom_name': self.product_id.uom_name
},
'target': 'new'
}
| 53.228013 | 16,341 |
15,944 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError, UserError
class StockWarehouse(models.Model):
_inherit = 'stock.warehouse'
manufacture_to_resupply = fields.Boolean(
'Manufacture to Resupply', default=True,
help="When products are manufactured, they can be manufactured in this warehouse.")
manufacture_pull_id = fields.Many2one(
'stock.rule', 'Manufacture Rule')
manufacture_mto_pull_id = fields.Many2one(
'stock.rule', 'Manufacture MTO Rule')
pbm_mto_pull_id = fields.Many2one(
'stock.rule', 'Picking Before Manufacturing MTO Rule')
sam_rule_id = fields.Many2one(
'stock.rule', 'Stock After Manufacturing Rule')
manu_type_id = fields.Many2one(
'stock.picking.type', 'Manufacturing Operation Type',
domain="[('code', '=', 'mrp_operation'), ('company_id', '=', company_id)]", check_company=True)
pbm_type_id = fields.Many2one('stock.picking.type', 'Picking Before Manufacturing Operation Type', check_company=True)
sam_type_id = fields.Many2one('stock.picking.type', 'Stock After Manufacturing Operation Type', check_company=True)
manufacture_steps = fields.Selection([
('mrp_one_step', 'Manufacture (1 step)'),
('pbm', 'Pick components and then manufacture (2 steps)'),
('pbm_sam', 'Pick components, manufacture and then store products (3 steps)')],
'Manufacture', default='mrp_one_step', required=True,
help="Produce : Move the components to the production location\
directly and start the manufacturing process.\nPick / Produce : Unload\
the components from the Stock to Input location first, and then\
transfer it to the Production location.")
pbm_route_id = fields.Many2one('stock.location.route', 'Picking Before Manufacturing Route', ondelete='restrict')
pbm_loc_id = fields.Many2one('stock.location', 'Picking before Manufacturing Location', check_company=True)
sam_loc_id = fields.Many2one('stock.location', 'Stock after Manufacturing Location', check_company=True)
def get_rules_dict(self):
result = super(StockWarehouse, self).get_rules_dict()
production_location_id = self._get_production_location()
for warehouse in self:
result[warehouse.id].update({
'mrp_one_step': [],
'pbm': [
self.Routing(warehouse.lot_stock_id, warehouse.pbm_loc_id, warehouse.pbm_type_id, 'pull'),
self.Routing(warehouse.pbm_loc_id, production_location_id, warehouse.manu_type_id, 'pull'),
],
'pbm_sam': [
self.Routing(warehouse.lot_stock_id, warehouse.pbm_loc_id, warehouse.pbm_type_id, 'pull'),
self.Routing(warehouse.pbm_loc_id, production_location_id, warehouse.manu_type_id, 'pull'),
self.Routing(warehouse.sam_loc_id, warehouse.lot_stock_id, warehouse.sam_type_id, 'push'),
],
})
result[warehouse.id].update(warehouse._get_receive_rules_dict())
return result
@api.model
def _get_production_location(self):
location = self.env['stock.location'].search([('usage', '=', 'production'), ('company_id', '=', self.company_id.id)], limit=1)
if not location:
raise UserError(_('Can\'t find any production location.'))
return location
def _get_routes_values(self):
routes = super(StockWarehouse, self)._get_routes_values()
routes.update({
'pbm_route_id': {
'routing_key': self.manufacture_steps,
'depends': ['manufacture_steps', 'manufacture_to_resupply'],
'route_update_values': {
'name': self._format_routename(route_type=self.manufacture_steps),
'active': self.manufacture_steps != 'mrp_one_step',
},
'route_create_values': {
'product_categ_selectable': True,
'warehouse_selectable': True,
'product_selectable': False,
'company_id': self.company_id.id,
'sequence': 10,
},
'rules_values': {
'active': True,
}
}
})
routes.update(self._get_receive_routes_values('manufacture_to_resupply'))
return routes
def _get_route_name(self, route_type):
names = {
'mrp_one_step': _('Manufacture (1 step)'),
'pbm': _('Pick components and then manufacture'),
'pbm_sam': _('Pick components, manufacture and then store products (3 steps)'),
}
if route_type in names:
return names[route_type]
else:
return super(StockWarehouse, self)._get_route_name(route_type)
def _get_global_route_rules_values(self):
rules = super(StockWarehouse, self)._get_global_route_rules_values()
location_src = self.manufacture_steps == 'mrp_one_step' and self.lot_stock_id or self.pbm_loc_id
production_location = self._get_production_location()
location_id = self.manufacture_steps == 'pbm_sam' and self.sam_loc_id or self.lot_stock_id
rules.update({
'manufacture_pull_id': {
'depends': ['manufacture_steps', 'manufacture_to_resupply'],
'create_values': {
'action': 'manufacture',
'procure_method': 'make_to_order',
'company_id': self.company_id.id,
'picking_type_id': self.manu_type_id.id,
'route_id': self._find_global_route('mrp.route_warehouse0_manufacture', _('Manufacture')).id
},
'update_values': {
'active': self.manufacture_to_resupply,
'name': self._format_rulename(location_id, False, 'Production'),
'location_id': location_id.id,
'propagate_cancel': self.manufacture_steps == 'pbm_sam'
},
},
'manufacture_mto_pull_id': {
'depends': ['manufacture_steps', 'manufacture_to_resupply'],
'create_values': {
'procure_method': 'mts_else_mto',
'company_id': self.company_id.id,
'action': 'pull',
'auto': 'manual',
'route_id': self._find_global_route('stock.route_warehouse0_mto', _('Make To Order')).id,
'location_id': production_location.id,
'location_src_id': location_src.id,
'picking_type_id': self.manu_type_id.id
},
'update_values': {
'name': self._format_rulename(location_src, production_location, 'MTO'),
'active': self.manufacture_to_resupply,
},
},
'pbm_mto_pull_id': {
'depends': ['manufacture_steps', 'manufacture_to_resupply'],
'create_values': {
'procure_method': 'make_to_order',
'company_id': self.company_id.id,
'action': 'pull',
'auto': 'manual',
'route_id': self._find_global_route('stock.route_warehouse0_mto', _('Make To Order')).id,
'name': self._format_rulename(self.lot_stock_id, self.pbm_loc_id, 'MTO'),
'location_id': self.pbm_loc_id.id,
'location_src_id': self.lot_stock_id.id,
'picking_type_id': self.pbm_type_id.id
},
'update_values': {
'active': self.manufacture_steps != 'mrp_one_step' and self.manufacture_to_resupply,
}
},
# The purpose to move sam rule in the manufacture route instead of
# pbm_route_id is to avoid conflict with receipt in multiple
# step. For example if the product is manufacture and receipt in two
# step it would conflict in WH/Stock since product could come from
# WH/post-prod or WH/input. We do not have this conflict with
# manufacture route since it is set on the product.
'sam_rule_id': {
'depends': ['manufacture_steps', 'manufacture_to_resupply'],
'create_values': {
'procure_method': 'make_to_order',
'company_id': self.company_id.id,
'action': 'pull',
'auto': 'manual',
'route_id': self._find_global_route('mrp.route_warehouse0_manufacture', _('Manufacture')).id,
'name': self._format_rulename(self.sam_loc_id, self.lot_stock_id, False),
'location_id': self.lot_stock_id.id,
'location_src_id': self.sam_loc_id.id,
'picking_type_id': self.sam_type_id.id
},
'update_values': {
'active': self.manufacture_steps == 'pbm_sam' and self.manufacture_to_resupply,
}
}
})
return rules
def _get_locations_values(self, vals, code=False):
values = super(StockWarehouse, self)._get_locations_values(vals, code=code)
def_values = self.default_get(['company_id', 'manufacture_steps'])
manufacture_steps = vals.get('manufacture_steps', def_values['manufacture_steps'])
code = vals.get('code') or code or ''
code = code.replace(' ', '').upper()
company_id = vals.get('company_id', def_values['company_id'])
values.update({
'pbm_loc_id': {
'name': _('Pre-Production'),
'active': manufacture_steps in ('pbm', 'pbm_sam'),
'usage': 'internal',
'barcode': self._valid_barcode(code + '-PREPRODUCTION', company_id)
},
'sam_loc_id': {
'name': _('Post-Production'),
'active': manufacture_steps == 'pbm_sam',
'usage': 'internal',
'barcode': self._valid_barcode(code + '-POSTPRODUCTION', company_id)
},
})
return values
def _get_sequence_values(self):
values = super(StockWarehouse, self)._get_sequence_values()
values.update({
'pbm_type_id': {'name': self.name + ' ' + _('Sequence picking before manufacturing'), 'prefix': self.code + '/PC/', 'padding': 5, 'company_id': self.company_id.id},
'sam_type_id': {'name': self.name + ' ' + _('Sequence stock after manufacturing'), 'prefix': self.code + '/SFP/', 'padding': 5, 'company_id': self.company_id.id},
'manu_type_id': {'name': self.name + ' ' + _('Sequence production'), 'prefix': self.code + '/MO/', 'padding': 5, 'company_id': self.company_id.id},
})
return values
def _get_picking_type_create_values(self, max_sequence):
data, next_sequence = super(StockWarehouse, self)._get_picking_type_create_values(max_sequence)
data.update({
'pbm_type_id': {
'name': _('Pick Components'),
'code': 'internal',
'use_create_lots': True,
'use_existing_lots': True,
'default_location_src_id': self.lot_stock_id.id,
'default_location_dest_id': self.pbm_loc_id.id,
'sequence': next_sequence + 1,
'sequence_code': 'PC',
'company_id': self.company_id.id,
},
'sam_type_id': {
'name': _('Store Finished Product'),
'code': 'internal',
'use_create_lots': True,
'use_existing_lots': True,
'default_location_src_id': self.sam_loc_id.id,
'default_location_dest_id': self.lot_stock_id.id,
'sequence': next_sequence + 3,
'sequence_code': 'SFP',
'company_id': self.company_id.id,
},
'manu_type_id': {
'name': _('Manufacturing'),
'code': 'mrp_operation',
'use_create_lots': True,
'use_existing_lots': True,
'sequence': next_sequence + 2,
'sequence_code': 'MO',
'company_id': self.company_id.id,
},
})
return data, max_sequence + 4
def _get_picking_type_update_values(self):
data = super(StockWarehouse, self)._get_picking_type_update_values()
data.update({
'pbm_type_id': {
'active': self.manufacture_to_resupply and self.manufacture_steps in ('pbm', 'pbm_sam') and self.active,
'barcode': self.code.replace(" ", "").upper() + "-PC",
},
'sam_type_id': {
'active': self.manufacture_to_resupply and self.manufacture_steps == 'pbm_sam' and self.active,
'barcode': self.code.replace(" ", "").upper() + "-SFP",
},
'manu_type_id': {
'active': self.manufacture_to_resupply and self.active,
'default_location_src_id': self.manufacture_steps in ('pbm', 'pbm_sam') and self.pbm_loc_id.id or self.lot_stock_id.id,
'default_location_dest_id': self.manufacture_steps == 'pbm_sam' and self.sam_loc_id.id or self.lot_stock_id.id,
},
})
return data
def _create_missing_locations(self, vals):
super()._create_missing_locations(vals)
for company_id in self.company_id:
location = self.env['stock.location'].search([('usage', '=', 'production'), ('company_id', '=', company_id.id)], limit=1)
if not location:
company_id._create_production_location()
def write(self, vals):
if any(field in vals for field in ('manufacture_steps', 'manufacture_to_resupply')):
for warehouse in self:
warehouse._update_location_manufacture(vals.get('manufacture_steps', warehouse.manufacture_steps))
return super(StockWarehouse, self).write(vals)
def _get_all_routes(self):
routes = super(StockWarehouse, self)._get_all_routes()
routes |= self.filtered(lambda self: self.manufacture_to_resupply and self.manufacture_pull_id and self.manufacture_pull_id.route_id).mapped('manufacture_pull_id').mapped('route_id')
return routes
def _update_location_manufacture(self, new_manufacture_step):
self.mapped('pbm_loc_id').write({'active': new_manufacture_step != 'mrp_one_step'})
self.mapped('sam_loc_id').write({'active': new_manufacture_step == 'pbm_sam'})
def _update_name_and_code(self, name=False, code=False):
res = super(StockWarehouse, self)._update_name_and_code(name, code)
# change the manufacture stock rule name
for warehouse in self:
if warehouse.manufacture_pull_id and name:
warehouse.manufacture_pull_id.write({'name': warehouse.manufacture_pull_id.name.replace(warehouse.name, name, 1)})
return res
class Orderpoint(models.Model):
_inherit = "stock.warehouse.orderpoint"
@api.constrains('product_id')
def check_product_is_not_kit(self):
if self.env['mrp.bom'].search(['|', ('product_id', 'in', self.product_id.ids),
'&', ('product_id', '=', False), ('product_tmpl_id', 'in', self.product_id.product_tmpl_id.ids),
('type', '=', 'phantom')], count=True):
raise ValidationError(_("A product with a kit-type bill of materials can not have a reordering rule."))
| 50.615873 | 15,944 |
1,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 MrpDocument(models.Model):
""" Extension of ir.attachment only used in MRP to handle archivage
and basic versioning.
"""
_name = 'mrp.document'
_description = "Production Document"
_inherits = {
'ir.attachment': 'ir_attachment_id',
}
_order = "priority desc, id desc"
def copy(self, default=None):
ir_default = default
if ir_default:
ir_fields = list(self.env['ir.attachment']._fields)
ir_default = {field : default[field] for field in default.keys() if field in ir_fields}
new_attach = self.ir_attachment_id.with_context(no_document=True).copy(ir_default)
return super().copy(dict(default, ir_attachment_id=new_attach.id))
ir_attachment_id = fields.Many2one('ir.attachment', string='Related attachment', required=True, ondelete='cascade')
active = fields.Boolean('Active', default=True)
priority = fields.Selection([
('0', 'Normal'),
('1', 'Low'),
('2', 'High'),
('3', 'Very High')], string="Priority", help='Gives the sequence order when displaying a list of MRP documents.')
def unlink(self):
self.mapped('ir_attachment_id').unlink()
return super(MrpDocument, self).unlink()
| 38.472222 | 1,385 |
6,251 |
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 MrpRoutingWorkcenter(models.Model):
_name = 'mrp.routing.workcenter'
_description = 'Work Center Usage'
_order = 'bom_id, sequence, id'
_check_company_auto = True
name = fields.Char('Operation', required=True)
active = fields.Boolean(default=True)
workcenter_id = fields.Many2one('mrp.workcenter', 'Work Center', required=True, check_company=True)
sequence = fields.Integer(
'Sequence', default=100,
help="Gives the sequence order when displaying a list of routing Work Centers.")
bom_id = fields.Many2one(
'mrp.bom', 'Bill of Material',
index=True, ondelete='cascade', required=True, check_company=True,
help="The Bill of Material this operation is linked to")
company_id = fields.Many2one('res.company', 'Company', related='bom_id.company_id')
worksheet_type = fields.Selection([
('pdf', 'PDF'), ('google_slide', 'Google Slide'), ('text', 'Text')],
string="Work Sheet", default="text",
help="Defines if you want to use a PDF or a Google Slide as work sheet."
)
note = fields.Html('Description', help="Text worksheet description")
worksheet = fields.Binary('PDF')
worksheet_google_slide = fields.Char('Google Slide', help="Paste the url of your Google Slide. Make sure the access to the document is public.")
time_mode = fields.Selection([
('auto', 'Compute based on tracked time'),
('manual', 'Set duration manually')], string='Duration Computation',
default='manual')
time_mode_batch = fields.Integer('Based on', default=10)
time_computed_on = fields.Char('Computed on last', compute='_compute_time_computed_on')
time_cycle_manual = fields.Float(
'Manual Duration', default=60,
help="Time in minutes:"
"- In manual mode, time used"
"- In automatic mode, supposed first time when there aren't any work orders yet")
time_cycle = fields.Float('Duration', compute="_compute_time_cycle")
workorder_count = fields.Integer("# Work Orders", compute="_compute_workorder_count")
workorder_ids = fields.One2many('mrp.workorder', 'operation_id', string="Work Orders")
possible_bom_product_template_attribute_value_ids = fields.Many2many(related='bom_id.possible_product_template_attribute_value_ids')
bom_product_template_attribute_value_ids = fields.Many2many(
'product.template.attribute.value', string="Apply on Variants", ondelete='restrict',
domain="[('id', 'in', possible_bom_product_template_attribute_value_ids)]",
help="BOM Product Variants needed to apply this line.")
@api.depends('time_mode', 'time_mode_batch')
def _compute_time_computed_on(self):
for operation in self:
operation.time_computed_on = _('%i work orders') % operation.time_mode_batch if operation.time_mode != 'manual' else False
@api.depends('time_cycle_manual', 'time_mode', 'workorder_ids')
def _compute_time_cycle(self):
manual_ops = self.filtered(lambda operation: operation.time_mode == 'manual')
for operation in manual_ops:
operation.time_cycle = operation.time_cycle_manual
for operation in self - manual_ops:
data = self.env['mrp.workorder'].search([
('operation_id', '=', operation.id),
('qty_produced', '>', 0),
('state', '=', 'done')],
limit=operation.time_mode_batch,
order="date_finished desc")
# To compute the time_cycle, we can take the total duration of previous operations
# but for the quantity, we will take in consideration the qty_produced like if the capacity was 1.
# So producing 50 in 00:10 with capacity 2, for the time_cycle, we assume it is 25 in 00:10
# When recomputing the expected duration, the capacity is used again to divide the qty to produce
# so that if we need 50 with capacity 2, it will compute the expected of 25 which is 00:10
total_duration = 0 # Can be 0 since it's not an invalid duration for BoM
cycle_number = 0 # Never 0 unless infinite item['workcenter_id'].capacity
for item in data:
total_duration += item['duration']
cycle_number += tools.float_round((item['qty_produced'] / item['workcenter_id'].capacity or 1.0), precision_digits=0, rounding_method='UP')
if cycle_number:
operation.time_cycle = total_duration / cycle_number
else:
operation.time_cycle = operation.time_cycle_manual
def _compute_workorder_count(self):
data = self.env['mrp.workorder'].read_group([
('operation_id', 'in', self.ids),
('state', '=', 'done')], ['operation_id'], ['operation_id'])
count_data = dict((item['operation_id'][0], item['operation_id_count']) for item in data)
for operation in self:
operation.workorder_count = count_data.get(operation.id, 0)
def copy_to_bom(self):
if 'bom_id' in self.env.context:
bom_id = self.env.context.get('bom_id')
for operation in self:
operation.copy({'bom_id': bom_id})
return {
'view_mode': 'form',
'res_model': 'mrp.bom',
'views': [(False, 'form')],
'type': 'ir.actions.act_window',
'res_id': bom_id,
}
def _skip_operation_line(self, product):
""" Control if a operation should be processed, can be inherited to add
custom control.
"""
self.ensure_one()
if product._name == 'product.template':
return False
return not product._match_all_variant_values(self.bom_product_template_attribute_value_ids)
def _get_comparison_values(self):
if not self:
return False
self.ensure_one()
return tuple(self[key] for key in ('name', 'company_id', 'workcenter_id', 'time_mode', 'time_cycle_manual', 'bom_product_template_attribute_value_ids'))
| 52.974576 | 6,251 |
2,574 |
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 StockScrap(models.Model):
_inherit = 'stock.scrap'
production_id = fields.Many2one(
'mrp.production', 'Manufacturing Order',
states={'done': [('readonly', True)]}, check_company=True)
workorder_id = fields.Many2one(
'mrp.workorder', 'Work Order',
states={'done': [('readonly', True)]},
help='Not to restrict or prefer quants, but informative.', check_company=True)
@api.onchange('workorder_id')
def _onchange_workorder_id(self):
if self.workorder_id:
self.location_id = self.workorder_id.production_id.location_src_id.id
@api.onchange('production_id')
def _onchange_production_id(self):
if self.production_id:
self.location_id = self.production_id.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel')) and self.production_id.location_src_id.id or self.production_id.location_dest_id.id
def _prepare_move_values(self):
vals = super(StockScrap, self)._prepare_move_values()
if self.production_id:
vals['origin'] = vals['origin'] or self.production_id.name
if self.product_id in self.production_id.move_finished_ids.mapped('product_id'):
vals.update({'production_id': self.production_id.id})
else:
vals.update({'raw_material_production_id': self.production_id.id})
return vals
@api.onchange('lot_id')
def _onchange_serial_number(self):
if self.product_id.tracking == 'serial' and self.lot_id:
if self.production_id:
message, recommended_location = self.env['stock.quant']._check_serial_number(self.product_id,
self.lot_id,
self.company_id,
self.location_id,
self.production_id.location_dest_id)
if message:
if recommended_location:
self.location_id = recommended_location
return {'warning': {'title': _('Warning'), 'message': message}}
else:
return super()._onchange_serial_number()
| 49.5 | 2,574 |
26,277 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, Command, fields, models, _
from odoo.osv import expression
from odoo.tools import float_compare, float_round, float_is_zero, OrderedSet
class StockMoveLine(models.Model):
_inherit = 'stock.move.line'
workorder_id = fields.Many2one('mrp.workorder', 'Work Order', check_company=True)
production_id = fields.Many2one('mrp.production', 'Production Order', check_company=True)
description_bom_line = fields.Char(related='move_id.description_bom_line')
@api.depends('production_id')
def _compute_picking_type_id(self):
line_to_remove = self.env['stock.move.line']
for line in self:
if not line.production_id:
continue
line.picking_type_id = line.production_id.picking_type_id
line_to_remove |= line
return super(StockMoveLine, self - line_to_remove)._compute_picking_type_id()
def _search_picking_type_id(self, operator, value):
res = super()._search_picking_type_id(operator=operator, value=value)
if operator in ['not in', '!=', 'not ilike']:
if value is False:
return expression.OR([[('production_id.picking_type_id', operator, value)], res])
else:
return expression.AND([[('production_id.picking_type_id', operator, value)], res])
else:
if value is False:
return expression.AND([[('production_id.picking_type_id', operator, value)], res])
else:
return expression.OR([[('production_id.picking_type_id', operator, value)], res])
@api.model_create_multi
def create(self, values):
res = super(StockMoveLine, self).create(values)
for line in res:
# If the line is added in a done production, we need to map it
# manually to the produced move lines in order to see them in the
# traceability report
if line.move_id.raw_material_production_id and line.state == 'done':
mo = line.move_id.raw_material_production_id
finished_lots = mo.lot_producing_id
finished_lots |= mo.move_finished_ids.filtered(lambda m: m.product_id != mo.product_id).move_line_ids.lot_id
if finished_lots:
produced_move_lines = mo.move_finished_ids.move_line_ids.filtered(lambda sml: sml.lot_id in finished_lots)
line.produce_line_ids = [(6, 0, produced_move_lines.ids)]
else:
produced_move_lines = mo.move_finished_ids.move_line_ids
line.produce_line_ids = [(6, 0, produced_move_lines.ids)]
return res
def _get_similar_move_lines(self):
lines = super(StockMoveLine, self)._get_similar_move_lines()
if self.move_id.production_id:
finished_moves = self.move_id.production_id.move_finished_ids
finished_move_lines = finished_moves.mapped('move_line_ids')
lines |= finished_move_lines.filtered(lambda ml: ml.product_id == self.product_id and (ml.lot_id or ml.lot_name))
if self.move_id.raw_material_production_id:
raw_moves = self.move_id.raw_material_production_id.move_raw_ids
raw_moves_lines = raw_moves.mapped('move_line_ids')
lines |= raw_moves_lines.filtered(lambda ml: ml.product_id == self.product_id and (ml.lot_id or ml.lot_name))
return lines
def _reservation_is_updatable(self, quantity, reserved_quant):
self.ensure_one()
if self.produce_line_ids.lot_id:
ml_remaining_qty = self.qty_done - self.product_uom_qty
ml_remaining_qty = self.product_uom_id._compute_quantity(ml_remaining_qty, self.product_id.uom_id, rounding_method="HALF-UP")
if float_compare(ml_remaining_qty, quantity, precision_rounding=self.product_id.uom_id.rounding) < 0:
return False
return super(StockMoveLine, self)._reservation_is_updatable(quantity, reserved_quant)
def write(self, vals):
for move_line in self:
production = move_line.move_id.production_id or move_line.move_id.raw_material_production_id
if production and move_line.state == 'done' and any(field in vals for field in ('lot_id', 'location_id', 'qty_done')):
move_line._log_message(production, move_line, 'mrp.track_production_move_template', vals)
return super(StockMoveLine, self).write(vals)
def _get_aggregated_product_quantities(self, **kwargs):
"""Returns dictionary of products and corresponding values of interest grouped by optional kit_name
Removes descriptions where description == kit_name. kit_name is expected to be passed as a
kwargs value because this is not directly stored in move_line_ids. Unfortunately because we
are working with aggregated data, we have to loop through the aggregation to do this removal.
arguments: kit_name (optional): string value of a kit name passed as a kwarg
returns: dictionary {same_key_as_super: {same_values_as_super, ...}
"""
aggregated_move_lines = super()._get_aggregated_product_quantities(**kwargs)
kit_name = kwargs.get('kit_name')
if kit_name:
for aggregated_move_line in aggregated_move_lines:
if aggregated_move_lines[aggregated_move_line]['description'] == kit_name:
aggregated_move_lines[aggregated_move_line]['description'] = ""
return aggregated_move_lines
class StockMove(models.Model):
_inherit = 'stock.move'
created_production_id = fields.Many2one('mrp.production', 'Created Production Order', check_company=True, index=True)
production_id = fields.Many2one(
'mrp.production', 'Production Order for finished products', check_company=True, index=True)
raw_material_production_id = fields.Many2one(
'mrp.production', 'Production Order for components', check_company=True, index=True)
unbuild_id = fields.Many2one(
'mrp.unbuild', 'Disassembly Order', check_company=True)
consume_unbuild_id = fields.Many2one(
'mrp.unbuild', 'Consumed Disassembly Order', check_company=True)
allowed_operation_ids = fields.One2many(
'mrp.routing.workcenter', related='raw_material_production_id.bom_id.operation_ids')
operation_id = fields.Many2one(
'mrp.routing.workcenter', 'Operation To Consume', check_company=True,
domain="[('id', 'in', allowed_operation_ids)]")
workorder_id = fields.Many2one(
'mrp.workorder', 'Work Order To Consume', copy=False, check_company=True)
# Quantities to process, in normalized UoMs
bom_line_id = fields.Many2one('mrp.bom.line', 'BoM Line', check_company=True)
byproduct_id = fields.Many2one(
'mrp.bom.byproduct', 'By-products', check_company=True,
help="By-product line that generated the move in a manufacturing order")
unit_factor = fields.Float('Unit Factor', compute='_compute_unit_factor', store=True)
is_done = fields.Boolean(
'Done', compute='_compute_is_done',
store=True,
help='Technical Field to order moves')
order_finished_lot_ids = fields.Many2many('stock.production.lot', string="Finished Lot/Serial Number", compute='_compute_order_finished_lot_ids')
should_consume_qty = fields.Float('Quantity To Consume', compute='_compute_should_consume_qty', digits='Product Unit of Measure')
cost_share = fields.Float(
"Cost Share (%)", digits=(5, 2), # decimal = 2 is important for rounding calculations!!
help="The percentage of the final production cost for this by-product. The total of all by-products' cost share must be smaller or equal to 100.")
product_qty_available = fields.Float('Product On Hand Quantity', related='product_id.qty_available', depends=['product_id'])
product_virtual_available = fields.Float('Product Forecasted Quantity', related='product_id.virtual_available', depends=['product_id'])
description_bom_line = fields.Char('Kit', compute='_compute_description_bom_line')
@api.depends('bom_line_id')
def _compute_description_bom_line(self):
bom_line_description = {}
for bom in self.bom_line_id.bom_id:
if bom.type != 'phantom':
continue
line_ids = bom.bom_line_ids.ids
total = len(line_ids)
name = bom.display_name
for i, line_id in enumerate(line_ids):
bom_line_description[line_id] = '%s - %d/%d' % (name, i+1, total)
for move in self:
move.description_bom_line = bom_line_description.get(move.bom_line_id.id)
@api.depends('raw_material_production_id.priority')
def _compute_priority(self):
super()._compute_priority()
for move in self:
move.priority = move.raw_material_production_id.priority or move.priority or '0'
@api.depends('raw_material_production_id.picking_type_id', 'production_id.picking_type_id')
def _compute_picking_type_id(self):
super()._compute_picking_type_id()
for move in self:
if move.raw_material_production_id or move.production_id:
move.picking_type_id = (move.raw_material_production_id or move.production_id).picking_type_id
@api.depends('raw_material_production_id.lot_producing_id')
def _compute_order_finished_lot_ids(self):
for move in self:
move.order_finished_lot_ids = move.raw_material_production_id.lot_producing_id
@api.depends('raw_material_production_id', 'production_id')
def _compute_is_locked(self):
super(StockMove, self)._compute_is_locked()
for move in self:
if move.raw_material_production_id:
move.is_locked = move.raw_material_production_id.is_locked
if move.production_id:
move.is_locked = move.production_id.is_locked
@api.depends('state')
def _compute_is_done(self):
for move in self:
move.is_done = (move.state in ('done', 'cancel'))
@api.depends('product_uom_qty',
'raw_material_production_id', 'raw_material_production_id.product_qty', 'raw_material_production_id.qty_produced',
'production_id', 'production_id.product_qty', 'production_id.qty_produced')
def _compute_unit_factor(self):
for move in self:
mo = move.raw_material_production_id or move.production_id
if mo:
move.unit_factor = move.product_uom_qty / ((mo.product_qty - mo.qty_produced) or 1)
else:
move.unit_factor = 1.0
@api.depends('raw_material_production_id', 'raw_material_production_id.name', 'production_id', 'production_id.name')
def _compute_reference(self):
moves_with_reference = self.env['stock.move']
for move in self:
if move.raw_material_production_id and move.raw_material_production_id.name:
move.reference = move.raw_material_production_id.name
moves_with_reference |= move
if move.production_id and move.production_id.name:
move.reference = move.production_id.name
moves_with_reference |= move
super(StockMove, self - moves_with_reference)._compute_reference()
@api.depends('raw_material_production_id.qty_producing', 'product_uom_qty', 'product_uom')
def _compute_should_consume_qty(self):
for move in self:
mo = move.raw_material_production_id
if not mo or not move.product_uom:
move.should_consume_qty = 0
continue
move.should_consume_qty = float_round((mo.qty_producing - mo.qty_produced) * move.unit_factor, precision_rounding=move.product_uom.rounding)
@api.onchange('product_uom_qty')
def _onchange_product_uom_qty(self):
if self.raw_material_production_id and self.has_tracking == 'none':
mo = self.raw_material_production_id
self._update_quantity_done(mo)
@api.model
def default_get(self, fields_list):
defaults = super(StockMove, self).default_get(fields_list)
if self.env.context.get('default_raw_material_production_id') or self.env.context.get('default_production_id'):
production_id = self.env['mrp.production'].browse(self.env.context.get('default_raw_material_production_id') or self.env.context.get('default_production_id'))
if production_id.state not in ('draft', 'cancel'):
if production_id.state != 'done':
defaults['state'] = 'draft'
else:
defaults['state'] = 'done'
defaults['additional'] = True
defaults['product_uom_qty'] = 0.0
elif production_id.state == 'draft':
defaults['group_id'] = production_id.procurement_group_id.id
defaults['reference'] = production_id.name
return defaults
def write(self, vals):
if 'product_uom_qty' in vals and 'move_line_ids' in vals:
# first update lines then product_uom_qty as the later will unreserve
# so possibly unlink lines
move_line_vals = vals.pop('move_line_ids')
super().write({'move_line_ids': move_line_vals})
return super().write(vals)
def _action_assign(self):
res = super(StockMove, self)._action_assign()
for move in self.filtered(lambda x: x.production_id or x.raw_material_production_id):
if move.move_line_ids:
move.move_line_ids.write({'production_id': move.raw_material_production_id.id,
'workorder_id': move.workorder_id.id,})
return res
def _action_confirm(self, merge=True, merge_into=False):
moves = self.action_explode()
merge_into = merge_into and merge_into.action_explode()
# we go further with the list of ids potentially changed by action_explode
return super(StockMove, moves)._action_confirm(merge=merge, merge_into=merge_into)
def action_explode(self):
""" Explodes pickings """
# in order to explode a move, we must have a picking_type_id on that move because otherwise the move
# won't be assigned to a picking and it would be weird to explode a move into several if they aren't
# all grouped in the same picking.
moves_ids_to_return = OrderedSet()
moves_ids_to_unlink = OrderedSet()
phantom_moves_vals_list = []
for move in self:
if not move.picking_type_id or (move.production_id and move.production_id.product_id == move.product_id):
moves_ids_to_return.add(move.id)
continue
bom = self.env['mrp.bom'].sudo()._bom_find(move.product_id, company_id=move.company_id.id, bom_type='phantom')[move.product_id]
if not bom:
moves_ids_to_return.add(move.id)
continue
if move.picking_id.immediate_transfer or float_is_zero(move.product_uom_qty, precision_rounding=move.product_uom.rounding):
factor = move.product_uom._compute_quantity(move.quantity_done, bom.product_uom_id) / bom.product_qty
else:
factor = move.product_uom._compute_quantity(move.product_uom_qty, bom.product_uom_id) / bom.product_qty
boms, lines = bom.sudo().explode(move.product_id, factor, picking_type=bom.picking_type_id)
for bom_line, line_data in lines:
if move.picking_id.immediate_transfer or float_is_zero(move.product_uom_qty, precision_rounding=move.product_uom.rounding):
phantom_moves_vals_list += move._generate_move_phantom(bom_line, 0, line_data['qty'])
else:
phantom_moves_vals_list += move._generate_move_phantom(bom_line, line_data['qty'], 0)
# delete the move with original product which is not relevant anymore
moves_ids_to_unlink.add(move.id)
move_to_unlink = self.env['stock.move'].browse(moves_ids_to_unlink).sudo()
move_to_unlink.quantity_done = 0
move_to_unlink._action_cancel()
move_to_unlink.unlink()
if phantom_moves_vals_list:
phantom_moves = self.env['stock.move'].create(phantom_moves_vals_list)
phantom_moves._adjust_procure_method()
moves_ids_to_return |= phantom_moves.action_explode().ids
return self.env['stock.move'].browse(moves_ids_to_return)
def action_show_details(self):
self.ensure_one()
action = super().action_show_details()
if self.raw_material_production_id:
action['views'] = [(self.env.ref('mrp.view_stock_move_operations_raw').id, 'form')]
action['context']['show_destination_location'] = False
action['context']['active_mo_id'] = self.raw_material_production_id.id
elif self.production_id:
action['views'] = [(self.env.ref('mrp.view_stock_move_operations_finished').id, 'form')]
action['context']['show_source_location'] = False
action['context']['show_reserved_quantity'] = False
return action
def _action_cancel(self):
res = super(StockMove, self)._action_cancel()
mo_to_cancel = self.mapped('raw_material_production_id').filtered(lambda p: all(m.state == 'cancel' for m in p.move_raw_ids))
if mo_to_cancel:
mo_to_cancel._action_cancel()
return res
def _prepare_move_split_vals(self, qty):
defaults = super()._prepare_move_split_vals(qty)
defaults['workorder_id'] = False
return defaults
def _prepare_procurement_origin(self):
self.ensure_one()
if self.raw_material_production_id and self.raw_material_production_id.orderpoint_id:
return self.origin
return super()._prepare_procurement_origin()
def _prepare_phantom_move_values(self, bom_line, product_qty, quantity_done):
return {
'picking_id': self.picking_id.id if self.picking_id else False,
'product_id': bom_line.product_id.id,
'product_uom': bom_line.product_uom_id.id,
'product_uom_qty': product_qty,
'quantity_done': quantity_done,
'state': 'draft', # will be confirmed below
'name': self.name,
'bom_line_id': bom_line.id,
}
def _generate_move_phantom(self, bom_line, product_qty, quantity_done):
vals = []
if bom_line.product_id.type in ['product', 'consu']:
vals = self.copy_data(default=self._prepare_phantom_move_values(bom_line, product_qty, quantity_done))
if self.state == 'assigned':
for v in vals:
v['state'] = 'assigned'
return vals
@api.model
def _consuming_picking_types(self):
res = super()._consuming_picking_types()
res.append('mrp_operation')
return res
def _get_backorder_move_vals(self):
self.ensure_one()
return {
'state': 'confirmed',
'reservation_date': self.reservation_date,
'move_orig_ids': [Command.link(m.id) for m in self.mapped('move_orig_ids')],
'move_dest_ids': [Command.link(m.id) for m in self.mapped('move_dest_ids')]
}
def _get_source_document(self):
res = super()._get_source_document()
return res or self.production_id or self.raw_material_production_id
def _get_upstream_documents_and_responsibles(self, visited):
if self.production_id and self.production_id.state not in ('done', 'cancel'):
return [(self.production_id, self.production_id.user_id, visited)]
else:
return super(StockMove, self)._get_upstream_documents_and_responsibles(visited)
def _delay_alert_get_documents(self):
res = super(StockMove, self)._delay_alert_get_documents()
productions = self.raw_material_production_id | self.production_id
return res + list(productions)
def _should_be_assigned(self):
res = super(StockMove, self)._should_be_assigned()
return bool(res and not (self.production_id or self.raw_material_production_id))
def _should_bypass_set_qty_producing(self):
if self.state in ('done', 'cancel'):
return True
# Do not update extra product quantities
if float_is_zero(self.product_uom_qty, precision_rounding=self.product_uom.rounding):
return True
if self.has_tracking != 'none' or self.state == 'done':
return True
return False
def _should_bypass_reservation(self, forced_location=False):
res = super(StockMove, self)._should_bypass_reservation(
forced_location=forced_location)
return bool(res and not self.production_id)
def _key_assign_picking(self):
keys = super(StockMove, self)._key_assign_picking()
return keys + (self.created_production_id,)
@api.model
def _prepare_merge_moves_distinct_fields(self):
res = super()._prepare_merge_moves_distinct_fields()
res += ['created_production_id', 'cost_share']
if self.bom_line_id and ("phantom" in self.bom_line_id.bom_id.mapped('type')):
res.append('bom_line_id')
return res
@api.model
def _prepare_merge_negative_moves_excluded_distinct_fields(self):
return super()._prepare_merge_negative_moves_excluded_distinct_fields() + ['created_production_id']
def _compute_kit_quantities(self, product_id, kit_qty, kit_bom, filters):
""" Computes the quantity delivered or received when a kit is sold or purchased.
A ratio 'qty_processed/qty_needed' is computed for each component, and the lowest one is kept
to define the kit's quantity delivered or received.
:param product_id: The kit itself a.k.a. the finished product
:param kit_qty: The quantity from the order line
:param kit_bom: The kit's BoM
:param filters: Dict of lambda expression to define the moves to consider and the ones to ignore
:return: The quantity delivered or received
"""
qty_ratios = []
boms, bom_sub_lines = kit_bom.explode(product_id, kit_qty)
for bom_line, bom_line_data in bom_sub_lines:
# skip service since we never deliver them
if bom_line.product_id.type == 'service':
continue
if float_is_zero(bom_line_data['qty'], precision_rounding=bom_line.product_uom_id.rounding):
# As BoMs allow components with 0 qty, a.k.a. optionnal components, we simply skip those
# to avoid a division by zero.
continue
bom_line_moves = self.filtered(lambda m: m.bom_line_id == bom_line)
if bom_line_moves:
# We compute the quantities needed of each components to make one kit.
# Then, we collect every relevant moves related to a specific component
# to know how many are considered delivered.
uom_qty_per_kit = bom_line_data['qty'] / bom_line_data['original_qty']
qty_per_kit = bom_line.product_uom_id._compute_quantity(uom_qty_per_kit, bom_line.product_id.uom_id, round=False)
if not qty_per_kit:
continue
incoming_moves = bom_line_moves.filtered(filters['incoming_moves'])
outgoing_moves = bom_line_moves.filtered(filters['outgoing_moves'])
qty_processed = sum(incoming_moves.mapped('product_qty')) - sum(outgoing_moves.mapped('product_qty'))
# We compute a ratio to know how many kits we can produce with this quantity of that specific component
qty_ratios.append(float_round(qty_processed / qty_per_kit, precision_rounding=bom_line.product_id.uom_id.rounding))
else:
return 0.0
if qty_ratios:
# Now that we have every ratio by components, we keep the lowest one to know how many kits we can produce
# with the quantities delivered of each component. We use the floor division here because a 'partial kit'
# doesn't make sense.
return min(qty_ratios) // 1
else:
return 0.0
def _show_details_in_draft(self):
self.ensure_one()
production = self.raw_material_production_id or self.production_id
if production and (self.state != 'draft' or production.state != 'draft'):
return True
elif production:
return False
else:
return super()._show_details_in_draft()
def _update_quantity_done(self, mo):
self.ensure_one()
new_qty = float_round((mo.qty_producing - mo.qty_produced) * self.unit_factor, precision_rounding=self.product_uom.rounding)
if not self.is_quantity_done_editable:
self.move_line_ids.filtered(lambda ml: ml.state not in ('done', 'cancel')).qty_done = 0
self.move_line_ids = self._set_quantity_done_prepare_vals(new_qty)
else:
self.quantity_done = new_qty
def _update_candidate_moves_list(self, candidate_moves_list):
super()._update_candidate_moves_list(candidate_moves_list)
for production in self.mapped('raw_material_production_id'):
candidate_moves_list.append(production.move_raw_ids)
for production in self.mapped('production_id'):
candidate_moves_list.append(production.move_finished_ids)
def _multi_line_quantity_done_set(self, quantity_done):
if self.raw_material_production_id:
self.move_line_ids.filtered(lambda ml: ml.state not in ('done', 'cancel')).qty_done = 0
self.move_line_ids = self._set_quantity_done_prepare_vals(quantity_done)
else:
super()._multi_line_quantity_done_set(quantity_done)
def _prepare_procurement_values(self):
res = super()._prepare_procurement_values()
res['bom_line_id'] = self.bom_line_id.id
return res
| 52.240557 | 26,277 |
1,356 |
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 Company(models.Model):
_inherit = 'res.company'
manufacturing_lead = fields.Float(
'Manufacturing Lead Time', default=0.0, required=True,
help="Security days for each manufacturing operation.")
def _create_unbuild_sequence(self):
unbuild_vals = []
for company in self:
unbuild_vals.append({
'name': 'Unbuild',
'code': 'mrp.unbuild',
'company_id': company.id,
'prefix': 'UB/',
'padding': 5,
'number_next': 1,
'number_increment': 1
})
if unbuild_vals:
self.env['ir.sequence'].create(unbuild_vals)
@api.model
def create_missing_unbuild_sequences(self):
company_ids = self.env['res.company'].search([])
company_has_unbuild_seq = self.env['ir.sequence'].search([('code', '=', 'mrp.unbuild')]).mapped('company_id')
company_todo_sequence = company_ids - company_has_unbuild_seq
company_todo_sequence._create_unbuild_sequence()
def _create_per_company_sequences(self):
super(Company, self)._create_per_company_sequences()
self._create_unbuild_sequence()
| 35.684211 | 1,356 |
7,147 |
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.float_utils import float_is_zero
from odoo.osv.expression import AND
class StockWarehouseOrderpoint(models.Model):
_inherit = 'stock.warehouse.orderpoint'
show_bom = fields.Boolean('Show BoM column', compute='_compute_show_bom')
bom_id = fields.Many2one(
'mrp.bom', string='Bill of Materials', check_company=True,
domain="[('type', '=', 'normal'), '&', '|', ('company_id', '=', company_id), ('company_id', '=', False), '|', ('product_id', '=', product_id), '&', ('product_id', '=', False), ('product_tmpl_id', '=', product_tmpl_id)]")
def _get_replenishment_order_notification(self):
self.ensure_one()
domain = [('orderpoint_id', 'in', self.ids)]
if self.env.context.get('written_after'):
domain = AND([domain, [('write_date', '>', self.env.context.get('written_after'))]])
production = self.env['mrp.production'].search(domain, limit=1)
if production:
action = self.env.ref('mrp.action_mrp_production_form')
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _('The following replenishment order has been generated'),
'message': '%s',
'links': [{
'label': production.name,
'url': f'#action={action.id}&id={production.id}&model=mrp.production'
}],
'sticky': False,
}
}
return super()._get_replenishment_order_notification()
@api.depends('route_id')
def _compute_show_bom(self):
manufacture_route = []
for res in self.env['stock.rule'].search_read([('action', '=', 'manufacture')], ['route_id']):
manufacture_route.append(res['route_id'][0])
for orderpoint in self:
orderpoint.show_bom = orderpoint.route_id.id in manufacture_route
def _quantity_in_progress(self):
bom_kits = self.env['mrp.bom']._bom_find(self.product_id, bom_type='phantom')
bom_kit_orderpoints = {
orderpoint: bom_kits[orderpoint.product_id]
for orderpoint in self
if orderpoint.product_id in bom_kits
}
orderpoints_without_kit = self - self.env['stock.warehouse.orderpoint'].concat(*bom_kit_orderpoints.keys())
res = super(StockWarehouseOrderpoint, orderpoints_without_kit)._quantity_in_progress()
for orderpoint in bom_kit_orderpoints:
dummy, bom_sub_lines = bom_kit_orderpoints[orderpoint].explode(orderpoint.product_id, 1)
ratios_qty_available = []
# total = qty_available + in_progress
ratios_total = []
for bom_line, bom_line_data in bom_sub_lines:
component = bom_line.product_id
if component.type != 'product' or float_is_zero(bom_line_data['qty'], precision_rounding=bom_line.product_uom_id.rounding):
continue
uom_qty_per_kit = bom_line_data['qty'] / bom_line_data['original_qty']
qty_per_kit = bom_line.product_uom_id._compute_quantity(uom_qty_per_kit, bom_line.product_id.uom_id, raise_if_failure=False)
if not qty_per_kit:
continue
qty_by_product_location, dummy = component._get_quantity_in_progress(orderpoint.location_id.ids)
qty_in_progress = qty_by_product_location.get((component.id, orderpoint.location_id.id), 0.0)
qty_available = component.qty_available / qty_per_kit
ratios_qty_available.append(qty_available)
ratios_total.append(qty_available + (qty_in_progress / qty_per_kit))
# For a kit, the quantity in progress is :
# (the quantity if we have received all in-progress components) - (the quantity using only available components)
product_qty = min(ratios_total or [0]) - min(ratios_qty_available or [0])
res[orderpoint.id] = orderpoint.product_id.uom_id._compute_quantity(product_qty, orderpoint.product_uom, round=False)
bom_manufacture = self.env['mrp.bom']._bom_find(orderpoints_without_kit.product_id, bom_type='normal')
bom_manufacture = self.env['mrp.bom'].concat(*bom_manufacture.values())
productions_group = self.env['mrp.production'].read_group(
[('bom_id', 'in', bom_manufacture.ids), ('state', '=', 'draft'), ('orderpoint_id', 'in', orderpoints_without_kit.ids)],
['orderpoint_id', 'product_qty', 'product_uom_id'],
['orderpoint_id', 'product_uom_id'], lazy=False)
for p in productions_group:
uom = self.env['uom.uom'].browse(p['product_uom_id'][0])
orderpoint = self.env['stock.warehouse.orderpoint'].browse(p['orderpoint_id'][0])
res[orderpoint.id] += uom._compute_quantity(
p['product_qty'], orderpoint.product_uom, round=False)
return res
def _get_qty_multiple_to_order(self):
""" Calculates the minimum quantity that can be ordered according to the qty and UoM of the BoM
"""
self.ensure_one()
qty_multiple_to_order = super()._get_qty_multiple_to_order()
if 'manufacture' in self.rule_ids.mapped('action'):
bom = self.env['mrp.bom']._bom_find(self.product_id, bom_type='normal')[self.product_id]
return bom.product_uom_id._compute_quantity(bom.product_qty, self.product_uom)
return qty_multiple_to_order
def _set_default_route_id(self):
route_id = self.env['stock.rule'].search([
('action', '=', 'manufacture')
]).route_id
orderpoint_wh_bom = self.filtered(lambda o: o.product_id.bom_ids)
if route_id and orderpoint_wh_bom:
orderpoint_wh_bom.route_id = route_id[0].id
return super()._set_default_route_id()
def _prepare_procurement_values(self, date=False, group=False):
values = super()._prepare_procurement_values(date=date, group=group)
values['bom_id'] = self.bom_id
return values
def _post_process_scheduler(self):
""" Confirm the productions only after all the orderpoints have run their
procurement to avoid the new procurement created from the production conflict
with them. """
self.env['mrp.production'].sudo().search([
('orderpoint_id', 'in', self.ids),
('move_raw_ids', '!=', False),
('state', '=', 'draft'),
]).action_confirm()
return super()._post_process_scheduler()
def _product_exclude_list(self):
# don't create an order point for kit products
boms = self.env['mrp.bom'].search([('type', '=', 'phantom')])
variant_boms = boms.filtered(lambda x: x.product_id)
return super()._product_exclude_list() + variant_boms.product_id.ids + (boms - variant_boms).product_tmpl_id.product_variant_ids.ids
| 54.143939 | 7,147 |
834 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
from odoo.exceptions import UserError
class StockProductionLot(models.Model):
_inherit = 'stock.production.lot'
def _check_create(self):
active_mo_id = self.env.context.get('active_mo_id')
if active_mo_id:
active_mo = self.env['mrp.production'].browse(active_mo_id)
if not active_mo.picking_type_id.use_create_components_lots:
raise UserError(_('You are not allowed to create or edit a lot or serial number for the components with the operation type "Manufacturing". To change this, go on the operation type and tick the box "Create New Lots/Serial Numbers for Components".'))
return super(StockProductionLot, self)._check_create()
| 49.058824 | 834 |
3,799 |
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'
code = fields.Selection(selection_add=[
('mrp_operation', 'Manufacturing')
], ondelete={'mrp_operation': 'cascade'})
count_mo_todo = fields.Integer(string="Number of Manufacturing Orders to Process",
compute='_get_mo_count')
count_mo_waiting = fields.Integer(string="Number of Manufacturing Orders Waiting",
compute='_get_mo_count')
count_mo_late = fields.Integer(string="Number of Manufacturing Orders Late",
compute='_get_mo_count')
use_create_components_lots = fields.Boolean(
string="Create New Lots/Serial Numbers for Components",
help="Allow to create new lot/serial numbers for the components",
default=False,
)
def _get_mo_count(self):
mrp_picking_types = self.filtered(lambda picking: picking.code == 'mrp_operation')
if not mrp_picking_types:
self.count_mo_waiting = False
self.count_mo_todo = False
self.count_mo_late = False
return
domains = {
'count_mo_waiting': [('reservation_state', '=', 'waiting')],
'count_mo_todo': ['|', ('state', 'in', ('confirmed', 'draft', 'progress', 'to_close')), ('is_planned', '=', True)],
'count_mo_late': [('date_planned_start', '<', fields.Date.today()), ('state', '=', 'confirmed')],
}
for field in domains:
data = self.env['mrp.production'].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'] and x['picking_type_id'][0]: x['picking_type_id_count'] for x in data}
for record in mrp_picking_types:
record[field] = count.get(record.id, 0)
remaining = (self - mrp_picking_types)
if remaining:
remaining.count_mo_waiting = False
remaining.count_mo_todo = False
remaining.count_mo_late = False
def get_mrp_stock_picking_action_picking_type(self):
action = self.env["ir.actions.actions"]._for_xml_id('mrp.mrp_production_action_picking_deshboard')
if self:
action['display_name'] = self.display_name
return action
@api.onchange('code')
def _onchange_code(self):
if self.code == 'mrp_operation':
self.use_create_lots = True
self.use_existing_lots = True
class StockPicking(models.Model):
_inherit = 'stock.picking'
has_kits = fields.Boolean(compute='_compute_has_kits')
@api.depends('move_lines')
def _compute_has_kits(self):
for picking in self:
picking.has_kits = any(picking.move_lines.mapped('bom_line_id'))
def _less_quantities_than_expected_add_documents(self, moves, documents):
documents = super(StockPicking, self)._less_quantities_than_expected_add_documents(moves, documents)
def _keys_in_sorted(move):
""" sort by picking and the responsible for the product the
move.
"""
return (move.raw_material_production_id.id, move.product_id.responsible_id.id)
def _keys_in_groupby(move):
""" group by picking and the responsible for the product the
move.
"""
return (move.raw_material_production_id, move.product_id.responsible_id)
production_documents = self._log_activity_get_documents(moves, 'move_dest_ids', 'DOWN', _keys_in_sorted, _keys_in_groupby)
return {**documents, **production_documents}
| 43.170455 | 3,799 |
1,764 |
py
|
PYTHON
|
15.0
|
from odoo import models, api
class MrpStockReport(models.TransientModel):
_inherit = 'stock.traceability.report'
@api.model
def _get_reference(self, move_line):
res_model, res_id, ref = super(MrpStockReport, self)._get_reference(move_line)
if move_line.move_id.production_id and not move_line.move_id.scrapped:
res_model = 'mrp.production'
res_id = move_line.move_id.production_id.id
ref = move_line.move_id.production_id.name
if move_line.move_id.raw_material_production_id and not move_line.move_id.scrapped:
res_model = 'mrp.production'
res_id = move_line.move_id.raw_material_production_id.id
ref = move_line.move_id.raw_material_production_id.name
if move_line.move_id.unbuild_id:
res_model = 'mrp.unbuild'
res_id = move_line.move_id.unbuild_id.id
ref = move_line.move_id.unbuild_id.name
if move_line.move_id.consume_unbuild_id:
res_model = 'mrp.unbuild'
res_id = move_line.move_id.consume_unbuild_id.id
ref = move_line.move_id.consume_unbuild_id.name
return res_model, res_id, ref
@api.model
def _get_linked_move_lines(self, move_line):
move_lines, is_used = super(MrpStockReport, self)._get_linked_move_lines(move_line)
if not move_lines:
move_lines = (move_line.move_id.consume_unbuild_id and move_line.produce_line_ids) or (move_line.move_id.production_id and move_line.consume_line_ids)
if not is_used:
is_used = (move_line.move_id.unbuild_id and move_line.consume_line_ids) or (move_line.move_id.raw_material_production_id and move_line.produce_line_ids)
return move_lines, is_used
| 51.882353 | 1,764 |
18,165 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import collections
from datetime import timedelta
from itertools import groupby
import operator as py_operator
from odoo import fields, models, _
from odoo.tools.float_utils import float_round, float_is_zero
OPERATORS = {
'<': py_operator.lt,
'>': py_operator.gt,
'<=': py_operator.le,
'>=': py_operator.ge,
'=': py_operator.eq,
'!=': py_operator.ne
}
class ProductTemplate(models.Model):
_inherit = "product.template"
bom_line_ids = fields.One2many('mrp.bom.line', 'product_tmpl_id', 'BoM Components')
bom_ids = fields.One2many('mrp.bom', 'product_tmpl_id', 'Bill of Materials')
bom_count = fields.Integer('# Bill of Material',
compute='_compute_bom_count', compute_sudo=False)
used_in_bom_count = fields.Integer('# of BoM Where is Used',
compute='_compute_used_in_bom_count', compute_sudo=False)
mrp_product_qty = fields.Float('Manufactured',
compute='_compute_mrp_product_qty', compute_sudo=False)
produce_delay = fields.Float(
'Manufacturing Lead Time', default=0.0,
help="Average lead time in days to manufacture this product. In the case of multi-level BOM, the manufacturing lead times of the components will be added.")
is_kits = fields.Boolean(compute='_compute_is_kits', compute_sudo=False)
def _compute_bom_count(self):
for product in self:
product.bom_count = self.env['mrp.bom'].search_count(['|', ('product_tmpl_id', '=', product.id), ('byproduct_ids.product_id.product_tmpl_id', '=', product.id)])
def _compute_is_kits(self):
domain = [('product_tmpl_id', 'in', self.ids), ('type', '=', 'phantom')]
bom_mapping = self.env['mrp.bom'].search_read(domain, ['product_tmpl_id'])
kits_ids = set(b['product_tmpl_id'][0] for b in bom_mapping)
for template in self:
template.is_kits = (template.id in kits_ids)
def _compute_show_qty_status_button(self):
super()._compute_show_qty_status_button()
for template in self:
if template.is_kits:
template.show_on_hand_qty_status_button = template.product_variant_count <= 1
template.show_forecasted_qty_status_button = False
def _compute_used_in_bom_count(self):
for template in self:
template.used_in_bom_count = self.env['mrp.bom'].search_count(
[('bom_line_ids.product_tmpl_id', '=', template.id)])
def write(self, values):
if 'active' in values:
self.filtered(lambda p: p.active != values['active']).with_context(active_test=False).bom_ids.write({
'active': values['active']
})
return super().write(values)
def action_used_in_bom(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
action['domain'] = [('bom_line_ids.product_tmpl_id', '=', self.id)]
return action
def _compute_mrp_product_qty(self):
for template in self:
template.mrp_product_qty = float_round(sum(template.mapped('product_variant_ids').mapped('mrp_product_qty')), precision_rounding=template.uom_id.rounding)
def action_view_mos(self):
action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_production_report")
action['domain'] = [('state', '=', 'done'), ('product_tmpl_id', 'in', self.ids)]
action['context'] = {
'graph_measure': 'product_uom_qty',
'search_default_filter_plan_date': 1,
}
return action
def action_archive(self):
filtered_products = self.env['mrp.bom.line'].search([('product_id', 'in', self.product_variant_ids.ids)]).product_id.mapped('display_name')
res = super().action_archive()
if filtered_products:
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _("Note that product(s): '%s' is/are still linked to active Bill of Materials, "
"which means that the product can still be used on it/them.", filtered_products),
'type': 'warning',
'sticky': True, #True/False will display for few seconds if false
'next': {'type': 'ir.actions.act_window_close'},
},
}
return res
class ProductProduct(models.Model):
_inherit = "product.product"
variant_bom_ids = fields.One2many('mrp.bom', 'product_id', 'BOM Product Variants')
bom_line_ids = fields.One2many('mrp.bom.line', 'product_id', 'BoM Components')
bom_count = fields.Integer('# Bill of Material',
compute='_compute_bom_count', compute_sudo=False)
used_in_bom_count = fields.Integer('# BoM Where Used',
compute='_compute_used_in_bom_count', compute_sudo=False)
mrp_product_qty = fields.Float('Manufactured',
compute='_compute_mrp_product_qty', compute_sudo=False)
is_kits = fields.Boolean(compute="_compute_is_kits", compute_sudo=False)
def _compute_bom_count(self):
for product in self:
product.bom_count = self.env['mrp.bom'].search_count(['|', '|', ('byproduct_ids.product_id', '=', product.id), ('product_id', '=', product.id), '&', ('product_id', '=', False), ('product_tmpl_id', '=', product.product_tmpl_id.id)])
def _compute_is_kits(self):
domain = ['&', ('type', '=', 'phantom'),
'|', ('product_id', 'in', self.ids),
'&', ('product_id', '=', False),
('product_tmpl_id', 'in', self.product_tmpl_id.ids)]
bom_mapping = self.env['mrp.bom'].search_read(domain, ['product_tmpl_id', 'product_id'])
kits_template_ids = set([])
kits_product_ids = set([])
for bom_data in bom_mapping:
if bom_data['product_id']:
kits_product_ids.add(bom_data['product_id'][0])
else:
kits_template_ids.add(bom_data['product_tmpl_id'][0])
for product in self:
product.is_kits = (product.id in kits_product_ids or product.product_tmpl_id.id in kits_template_ids)
def _compute_show_qty_status_button(self):
super()._compute_show_qty_status_button()
for product in self:
if product.is_kits:
product.show_on_hand_qty_status_button = True
product.show_forecasted_qty_status_button = False
def _compute_used_in_bom_count(self):
for product in self:
product.used_in_bom_count = self.env['mrp.bom'].search_count([('bom_line_ids.product_id', '=', product.id)])
def write(self, values):
if 'active' in values:
self.filtered(lambda p: p.active != values['active']).with_context(active_test=False).variant_bom_ids.write({
'active': values['active']
})
return super().write(values)
def get_components(self):
""" Return the components list ids in case of kit product.
Return the product itself otherwise"""
self.ensure_one()
bom_kit = self.env['mrp.bom']._bom_find(self, bom_type='phantom')[self]
if bom_kit:
boms, bom_sub_lines = bom_kit.explode(self, 1)
return [bom_line.product_id.id for bom_line, data in bom_sub_lines if bom_line.product_id.type == 'product']
else:
return super(ProductProduct, self).get_components()
def action_used_in_bom(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
action['domain'] = [('bom_line_ids.product_id', '=', self.id)]
return action
def _compute_mrp_product_qty(self):
date_from = fields.Datetime.to_string(fields.datetime.now() - timedelta(days=365))
#TODO: state = done?
domain = [('state', '=', 'done'), ('product_id', 'in', self.ids), ('date_planned_start', '>', date_from)]
read_group_res = self.env['mrp.production'].read_group(domain, ['product_id', 'product_uom_qty'], ['product_id'])
mapped_data = dict([(data['product_id'][0], data['product_uom_qty']) for data in read_group_res])
for product in self:
if not product.id:
product.mrp_product_qty = 0.0
continue
product.mrp_product_qty = float_round(mapped_data.get(product.id, 0), precision_rounding=product.uom_id.rounding)
def _compute_quantities_dict(self, lot_id, owner_id, package_id, from_date=False, to_date=False):
""" When the product is a kit, this override computes the fields :
- 'virtual_available'
- 'qty_available'
- 'incoming_qty'
- 'outgoing_qty'
- 'free_qty'
This override is used to get the correct quantities of products
with 'phantom' as BoM type.
"""
bom_kits = self.env['mrp.bom']._bom_find(self, bom_type='phantom')
kits = self.filtered(lambda p: bom_kits.get(p))
regular_products = self - kits
res = (
super(ProductProduct, regular_products)._compute_quantities_dict(lot_id, owner_id, package_id, from_date=from_date, to_date=to_date)
if regular_products
else {}
)
qties = self.env.context.get("mrp_compute_quantities", {})
qties.update(res)
# pre-compute bom lines and identify missing kit components to prefetch
bom_sub_lines_per_kit = {}
prefetch_component_ids = set()
for product in bom_kits:
__, bom_sub_lines = bom_kits[product].explode(product, 1)
bom_sub_lines_per_kit[product] = bom_sub_lines
for bom_line, __ in bom_sub_lines:
if bom_line.product_id.id not in qties:
prefetch_component_ids.add(bom_line.product_id.id)
# compute kit quantities
for product in bom_kits:
bom_sub_lines = bom_sub_lines_per_kit[product]
# group lines by component
bom_sub_lines_grouped = collections.defaultdict(list)
for info in bom_sub_lines:
bom_sub_lines_grouped[info[0].product_id].append(info)
ratios_virtual_available = []
ratios_qty_available = []
ratios_incoming_qty = []
ratios_outgoing_qty = []
ratios_free_qty = []
for component, bom_sub_lines in bom_sub_lines_grouped.items():
component = component.with_context(mrp_compute_quantities=qties).with_prefetch(prefetch_component_ids)
qty_per_kit = 0
for bom_line, bom_line_data in bom_sub_lines:
if component.type != 'product' or float_is_zero(bom_line_data['qty'], precision_rounding=bom_line.product_uom_id.rounding):
# As BoMs allow components with 0 qty, a.k.a. optionnal components, we simply skip those
# to avoid a division by zero. The same logic is applied to non-storable products as those
# products have 0 qty available.
continue
uom_qty_per_kit = bom_line_data['qty'] / bom_line_data['original_qty']
qty_per_kit += bom_line.product_uom_id._compute_quantity(uom_qty_per_kit, bom_line.product_id.uom_id, round=False, raise_if_failure=False)
if not qty_per_kit:
continue
rounding = component.uom_id.rounding
component_res = (
qties.get(component.id)
if component.id in qties
else {
"virtual_available": float_round(component.virtual_available, precision_rounding=rounding),
"qty_available": float_round(component.qty_available, precision_rounding=rounding),
"incoming_qty": float_round(component.incoming_qty, precision_rounding=rounding),
"outgoing_qty": float_round(component.outgoing_qty, precision_rounding=rounding),
"free_qty": float_round(component.free_qty, precision_rounding=rounding),
}
)
ratios_virtual_available.append(component_res["virtual_available"] / qty_per_kit)
ratios_qty_available.append(component_res["qty_available"] / qty_per_kit)
ratios_incoming_qty.append(component_res["incoming_qty"] / qty_per_kit)
ratios_outgoing_qty.append(component_res["outgoing_qty"] / qty_per_kit)
ratios_free_qty.append(component_res["free_qty"] / qty_per_kit)
if bom_sub_lines and ratios_virtual_available: # Guard against all cnsumable bom: at least one ratio should be present.
res[product.id] = {
'virtual_available': min(ratios_virtual_available) * bom_kits[product].product_qty // 1,
'qty_available': min(ratios_qty_available) * bom_kits[product].product_qty // 1,
'incoming_qty': min(ratios_incoming_qty) * bom_kits[product].product_qty // 1,
'outgoing_qty': min(ratios_outgoing_qty) * bom_kits[product].product_qty // 1,
'free_qty': min(ratios_free_qty) * bom_kits[product].product_qty // 1,
}
else:
res[product.id] = {
'virtual_available': 0,
'qty_available': 0,
'incoming_qty': 0,
'outgoing_qty': 0,
'free_qty': 0,
}
return res
def action_view_bom(self):
action = self.env["ir.actions.actions"]._for_xml_id("mrp.product_open_bom")
template_ids = self.mapped('product_tmpl_id').ids
# bom specific to this variant or global to template or that contains the product as a byproduct
action['context'] = {
'default_product_tmpl_id': template_ids[0],
'default_product_id': self.ids[0],
}
action['domain'] = ['|', '|', ('byproduct_ids.product_id', 'in', self.ids), ('product_id', 'in', self.ids), '&', ('product_id', '=', False), ('product_tmpl_id', 'in', template_ids)]
return action
def action_view_mos(self):
action = self.product_tmpl_id.action_view_mos()
action['domain'] = [('state', '=', 'done'), ('product_id', 'in', self.ids)]
return action
def action_open_quants(self):
bom_kits = self.env['mrp.bom']._bom_find(self, bom_type='phantom')
components = self - self.env['product.product'].concat(*list(bom_kits.keys()))
for product in bom_kits:
boms, bom_sub_lines = bom_kits[product].explode(product, 1)
components |= self.env['product.product'].concat(*[l[0].product_id for l in bom_sub_lines])
res = super(ProductProduct, components).action_open_quants()
if bom_kits:
res['context']['single_product'] = False
res['context'].pop('default_product_tmpl_id', None)
return res
def _match_all_variant_values(self, product_template_attribute_value_ids):
""" It currently checks that all variant values (`product_template_attribute_value_ids`)
are in the product (`self`).
If multiple values are encoded for the same attribute line, only one of
them has to be found on the variant.
"""
self.ensure_one()
# The intersection of the values of the product and those of the line satisfy:
# * the number of items equals the number of attributes (since a product cannot
# have multiple values for the same attribute),
# * the attributes are a subset of the attributes of the line.
return len(self.product_template_attribute_value_ids & product_template_attribute_value_ids) == len(product_template_attribute_value_ids.attribute_id)
def _count_returned_sn_products(self, sn_lot):
res = self.env['stock.move.line'].search_count([
('lot_id', '=', sn_lot.id),
('qty_done', '=', 1),
('state', '=', 'done'),
('production_id', '=', False),
('location_id.usage', '=', 'production'),
('move_id.unbuild_id', '!=', False),
])
return super()._count_returned_sn_products(sn_lot) + res
def _search_qty_available_new(self, operator, value, lot_id=False, owner_id=False, package_id=False):
'''extending the method in stock.product to take into account kits'''
product_ids = super(ProductProduct, self)._search_qty_available_new(operator, value, lot_id, owner_id, package_id)
kit_boms = self.env['mrp.bom'].search([('type', "=", 'phantom')])
kit_products = self.env['product.product']
for kit in kit_boms:
if kit.product_id:
kit_products |= kit.product_id
else:
kit_products |= kit.product_tmpl_id.product_variant_ids
for product in kit_products:
if OPERATORS[operator](product.qty_available, value):
product_ids.append(product.id)
return list(set(product_ids))
def action_archive(self):
filtered_products = self.env['mrp.bom.line'].search([('product_id', 'in', self.ids)]).product_id.mapped('display_name')
res = super().action_archive()
if filtered_products:
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _("Note that product(s): '%s' is/are still linked to active Bill of Materials, "
"which means that the product can still be used on it/them.", filtered_products),
'type': 'warning',
'sticky': True, #True/False will display for few seconds if false
'next': {'type': 'ir.actions.act_window_close'},
},
}
return res
| 50.598886 | 18,165 |
13,005 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.osv import expression
from odoo.addons.stock.models.stock_rule import ProcurementException
from odoo.tools import float_compare, OrderedSet
class StockRule(models.Model):
_inherit = 'stock.rule'
action = fields.Selection(selection_add=[
('manufacture', 'Manufacture')
], ondelete={'manufacture': 'cascade'})
def _get_message_dict(self):
message_dict = super(StockRule, self)._get_message_dict()
source, destination, operation = self._get_message_values()
manufacture_message = _('When products are needed in <b>%s</b>, <br/> a manufacturing order is created to fulfill the need.') % (destination)
if self.location_src_id:
manufacture_message += _(' <br/><br/> The components will be taken from <b>%s</b>.') % (source)
message_dict.update({
'manufacture': manufacture_message
})
return message_dict
@api.depends('action')
def _compute_picking_type_code_domain(self):
remaining = self.browse()
for rule in self:
if rule.action == 'manufacture':
rule.picking_type_code_domain = 'mrp_operation'
else:
remaining |= rule
super(StockRule, remaining)._compute_picking_type_code_domain()
def _should_auto_confirm_procurement_mo(self, p):
return (not p.orderpoint_id and p.move_raw_ids) or (p.move_dest_ids.procure_method != 'make_to_order' and not p.move_raw_ids and not p.workorder_ids)
@api.model
def _run_manufacture(self, procurements):
productions_values_by_company = defaultdict(list)
errors = []
for procurement, rule in procurements:
if float_compare(procurement.product_qty, 0, precision_rounding=procurement.product_uom.rounding) <= 0:
# If procurement contains negative quantity, don't create a MO that would be for a negative value.
continue
bom = rule._get_matching_bom(procurement.product_id, procurement.company_id, procurement.values)
productions_values_by_company[procurement.company_id.id].append(rule._prepare_mo_vals(*procurement, bom))
if errors:
raise ProcurementException(errors)
for company_id, productions_values in productions_values_by_company.items():
# create the MO as SUPERUSER because the current user may not have the rights to do it (mto product launched by a sale for example)
productions = self.env['mrp.production'].with_user(SUPERUSER_ID).sudo().with_company(company_id).create(productions_values)
self.env['stock.move'].sudo().create(productions._get_moves_raw_values())
self.env['stock.move'].sudo().create(productions._get_moves_finished_values())
productions._create_workorder()
productions.filtered(self._should_auto_confirm_procurement_mo).action_confirm()
for production in productions:
origin_production = production.move_dest_ids and production.move_dest_ids[0].raw_material_production_id or False
orderpoint = production.orderpoint_id
if orderpoint and orderpoint.create_uid.id == SUPERUSER_ID and orderpoint.trigger == 'manual':
production.message_post(
body=_('This production order has been created from Replenishment Report.'),
message_type='comment',
subtype_xmlid='mail.mt_note')
elif orderpoint:
production.message_post_with_view(
'mail.message_origin_link',
values={'self': production, 'origin': orderpoint},
subtype_id=self.env.ref('mail.mt_note').id)
elif origin_production:
production.message_post_with_view(
'mail.message_origin_link',
values={'self': production, 'origin': origin_production},
subtype_id=self.env.ref('mail.mt_note').id)
return True
@api.model
def _run_pull(self, procurements):
# Override to correctly assign the move generated from the pull
# in its production order (pbm_sam only)
for procurement, rule in procurements:
warehouse_id = rule.warehouse_id
if not warehouse_id:
warehouse_id = rule.location_id.warehouse_id
if rule.picking_type_id == warehouse_id.sam_type_id:
if float_compare(procurement.product_qty, 0, precision_rounding=procurement.product_uom.rounding) < 0:
procurement.values['group_id'] = procurement.values['group_id'].stock_move_ids.filtered(
lambda m: m.state not in ['done', 'cancel']).move_orig_ids.group_id[:1]
continue
manu_type_id = warehouse_id.manu_type_id
if manu_type_id:
name = manu_type_id.sequence_id.next_by_id()
else:
name = self.env['ir.sequence'].next_by_code('mrp.production') or _('New')
# Create now the procurement group that will be assigned to the new MO
# This ensure that the outgoing move PostProduction -> Stock is linked to its MO
# rather than the original record (MO or SO)
group = procurement.values.get('group_id')
if group:
procurement.values['group_id'] = group.copy({'name': name})
else:
procurement.values['group_id'] = self.env["procurement.group"].create({'name': name})
return super()._run_pull(procurements)
def _get_custom_move_fields(self):
fields = super(StockRule, self)._get_custom_move_fields()
fields += ['bom_line_id']
return fields
def _get_matching_bom(self, product_id, company_id, values):
if values.get('bom_id', False):
return values['bom_id']
if values.get('orderpoint_id', False) and values['orderpoint_id'].bom_id:
return values['orderpoint_id'].bom_id
return self.env['mrp.bom']._bom_find(product_id, picking_type=self.picking_type_id, bom_type='normal', company_id=company_id.id)[product_id]
def _prepare_mo_vals(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom):
date_planned = self._get_date_planned(product_id, company_id, values)
date_deadline = values.get('date_deadline') or date_planned + relativedelta(days=company_id.manufacturing_lead) + relativedelta(days=product_id.produce_delay)
mo_values = {
'origin': origin,
'product_id': product_id.id,
'product_description_variants': values.get('product_description_variants'),
'product_qty': product_qty,
'product_uom_id': product_uom.id,
'location_src_id': self.location_src_id.id or self.picking_type_id.default_location_src_id.id or location_id.id,
'location_dest_id': location_id.id,
'bom_id': bom.id,
'date_deadline': date_deadline,
'date_planned_start': date_planned,
'date_planned_finished': fields.Datetime.from_string(values['date_planned']),
'procurement_group_id': False,
'propagate_cancel': self.propagate_cancel,
'orderpoint_id': values.get('orderpoint_id', False) and values.get('orderpoint_id').id,
'picking_type_id': self.picking_type_id.id or values['warehouse_id'].manu_type_id.id,
'company_id': company_id.id,
'move_dest_ids': values.get('move_dest_ids') and [(4, x.id) for x in values['move_dest_ids']] or False,
'user_id': False,
}
# Use the procurement group created in _run_pull mrp override
# Preserve the origin from the original stock move, if available
if location_id.warehouse_id.manufacture_steps == 'pbm_sam' and values.get('move_dest_ids') and values.get('group_id') and values['move_dest_ids'][0].origin != values['group_id'].name:
origin = values['move_dest_ids'][0].origin
mo_values.update({
'name': values['group_id'].name,
'procurement_group_id': values['group_id'].id,
'origin': origin,
})
return mo_values
def _get_date_planned(self, product_id, company_id, values):
format_date_planned = fields.Datetime.from_string(values['date_planned'])
date_planned = format_date_planned - relativedelta(days=product_id.produce_delay)
date_planned = date_planned - relativedelta(days=company_id.manufacturing_lead)
if date_planned == format_date_planned:
date_planned = date_planned - relativedelta(hours=1)
return date_planned
def _get_lead_days(self, product, **values):
"""Add the product and company manufacture delay to the cumulative delay
and cumulative description.
"""
delay, delay_description = super()._get_lead_days(product, **values)
bypass_delay_description = self.env.context.get('bypass_delay_description')
manufacture_rule = self.filtered(lambda r: r.action == 'manufacture')
if not manufacture_rule:
return delay, delay_description
manufacture_rule.ensure_one()
manufacture_delay = product.produce_delay
delay += manufacture_delay
if not bypass_delay_description:
delay_description.append((_('Manufacturing Lead Time'), _('+ %d day(s)', manufacture_delay)))
security_delay = manufacture_rule.picking_type_id.company_id.manufacturing_lead
delay += security_delay
if not bypass_delay_description:
delay_description.append((_('Manufacture Security Lead Time'), _('+ %d day(s)', security_delay)))
return delay, delay_description
def _push_prepare_move_copy_values(self, move_to_copy, new_date):
new_move_vals = super(StockRule, self)._push_prepare_move_copy_values(move_to_copy, new_date)
new_move_vals['production_id'] = False
return new_move_vals
class ProcurementGroup(models.Model):
_inherit = 'procurement.group'
mrp_production_ids = fields.One2many('mrp.production', 'procurement_group_id')
@api.model
def run(self, procurements, raise_user_error=True):
""" If 'run' is called on a kit, this override is made in order to call
the original 'run' method with the values of the components of that kit.
"""
procurements_without_kit = []
product_by_company = defaultdict(OrderedSet)
for procurement in procurements:
product_by_company[procurement.company_id].add(procurement.product_id.id)
kits_by_company = {
company: self.env['mrp.bom']._bom_find(self.env['product.product'].browse(product_ids), company_id=company.id, bom_type='phantom')
for company, product_ids in product_by_company.items()
}
for procurement in procurements:
bom_kit = kits_by_company[procurement.company_id].get(procurement.product_id)
if bom_kit:
order_qty = procurement.product_uom._compute_quantity(procurement.product_qty, bom_kit.product_uom_id, round=False)
qty_to_produce = (order_qty / bom_kit.product_qty)
boms, bom_sub_lines = bom_kit.explode(procurement.product_id, qty_to_produce)
for bom_line, bom_line_data in bom_sub_lines:
bom_line_uom = bom_line.product_uom_id
quant_uom = bom_line.product_id.uom_id
# recreate dict of values since each child has its own bom_line_id
values = dict(procurement.values, bom_line_id=bom_line.id)
component_qty, procurement_uom = bom_line_uom._adjust_uom_quantities(bom_line_data['qty'], quant_uom)
procurements_without_kit.append(self.env['procurement.group'].Procurement(
bom_line.product_id, component_qty, procurement_uom,
procurement.location_id, procurement.name,
procurement.origin, procurement.company_id, values))
else:
procurements_without_kit.append(procurement)
return super(ProcurementGroup, self).run(procurements_without_kit, raise_user_error=raise_user_error)
def _get_moves_to_assign_domain(self, company_id):
domain = super(ProcurementGroup, self)._get_moves_to_assign_domain(company_id)
domain = expression.AND([domain, [('production_id', '=', False)]])
return domain
| 55.340426 | 13,005 |
2,606 |
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'
manufacturing_lead = fields.Float(related='company_id.manufacturing_lead', string="Manufacturing Lead Time", readonly=False)
use_manufacturing_lead = fields.Boolean(string="Default Manufacturing Lead Time", config_parameter='mrp.use_manufacturing_lead')
group_mrp_byproducts = fields.Boolean("By-Products",
implied_group='mrp.group_mrp_byproducts')
module_mrp_mps = fields.Boolean("Master Production Schedule")
module_mrp_plm = fields.Boolean("Product Lifecycle Management (PLM)")
module_mrp_workorder = fields.Boolean("Work Orders")
module_quality_control = fields.Boolean("Quality")
module_quality_control_worksheet = fields.Boolean("Quality Worksheet")
module_mrp_subcontracting = fields.Boolean("Subcontracting")
group_mrp_routings = fields.Boolean("MRP Work Orders",
implied_group='mrp.group_mrp_routings')
group_unlocked_by_default = fields.Boolean("Unlock Manufacturing Orders", implied_group='mrp.group_unlocked_by_default')
@api.onchange('use_manufacturing_lead')
def _onchange_use_manufacturing_lead(self):
if not self.use_manufacturing_lead:
self.manufacturing_lead = 0.0
@api.onchange('group_mrp_routings')
def _onchange_group_mrp_routings(self):
# If we activate 'MRP Work Orders', it means that we need to install 'mrp_workorder'.
# The opposite is not always true: other modules (such as 'quality_mrp_workorder') may
# depend on 'mrp_workorder', so we should not automatically uninstall the module if 'MRP
# Work Orders' is deactivated.
# Long story short: if 'mrp_workorder' is already installed, we don't uninstall it based on
# group_mrp_routings
if self.group_mrp_routings:
self.module_mrp_workorder = True
else:
self.module_mrp_workorder = False
@api.onchange('group_unlocked_by_default')
def _onchange_group_unlocked_by_default(self):
""" When changing this setting, we want existing MOs to automatically update to match setting. """
if self.group_unlocked_by_default:
self.env['mrp.production'].search([('state', 'not in', ('cancel', 'done')), ('is_locked', '=', True)]).is_locked = False
else:
self.env['mrp.production'].search([('state', 'not in', ('cancel', 'done')), ('is_locked', '=', False)]).is_locked = True
| 54.291667 | 2,606 |
116,320 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import datetime
import math
import re
import warnings
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare, float_round, float_is_zero, format_datetime
from odoo.tools.misc import OrderedSet, format_date, groupby as tools_groupby
from odoo.addons.stock.models.stock_move import PROCUREMENT_PRIORITIES
SIZE_BACK_ORDER_NUMERING = 3
class MrpProduction(models.Model):
""" Manufacturing Orders """
_name = 'mrp.production'
_description = 'Production Order'
_date_name = 'date_planned_start'
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = 'priority desc, date_planned_start asc,id'
@api.model
def _get_default_picking_type(self):
company_id = self.env.context.get('default_company_id', self.env.company.id)
return self.env['stock.picking.type'].search([
('code', '=', 'mrp_operation'),
('warehouse_id.company_id', '=', company_id),
], limit=1).id
@api.model
def _get_default_location_src_id(self):
location = False
company_id = self.env.context.get('default_company_id', self.env.company.id)
if self.env.context.get('default_picking_type_id'):
location = self.env['stock.picking.type'].browse(self.env.context['default_picking_type_id']).default_location_src_id
if not location:
location = self.env['stock.warehouse'].search([('company_id', '=', company_id)], limit=1).lot_stock_id
return location and location.id or False
@api.model
def _get_default_location_dest_id(self):
location = False
company_id = self.env.context.get('default_company_id', self.env.company.id)
if self._context.get('default_picking_type_id'):
location = self.env['stock.picking.type'].browse(self.env.context['default_picking_type_id']).default_location_dest_id
if not location:
location = self.env['stock.warehouse'].search([('company_id', '=', company_id)], limit=1).lot_stock_id
return location and location.id or False
@api.model
def _get_default_date_planned_finished(self):
if self.env.context.get('default_date_planned_start'):
return fields.Datetime.to_datetime(self.env.context.get('default_date_planned_start')) + datetime.timedelta(hours=1)
return datetime.datetime.now() + datetime.timedelta(hours=1)
@api.model
def _get_default_date_planned_start(self):
if self.env.context.get('default_date_deadline'):
return fields.Datetime.to_datetime(self.env.context.get('default_date_deadline'))
return datetime.datetime.now()
@api.model
def _get_default_is_locked(self):
return not self.user_has_groups('mrp.group_unlocked_by_default')
name = fields.Char(
'Reference', copy=False, readonly=True, default=lambda x: _('New'))
priority = fields.Selection(
PROCUREMENT_PRIORITIES, string='Priority', default='0',
help="Components will be reserved first for the MO with the highest priorities.")
backorder_sequence = fields.Integer("Backorder Sequence", default=0, copy=False, help="Backorder sequence, if equals to 0 means there is not related backorder")
origin = fields.Char(
'Source', copy=False,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="Reference of the document that generated this production order request.")
product_id = fields.Many2one(
'product.product', 'Product',
domain="""[
('type', 'in', ['product', 'consu']),
'|',
('company_id', '=', False),
('company_id', '=', company_id)
]
""",
readonly=True, required=True, check_company=True,
states={'draft': [('readonly', False)]})
product_tracking = fields.Selection(related='product_id.tracking')
product_tmpl_id = fields.Many2one('product.template', 'Product Template', related='product_id.product_tmpl_id')
product_qty = fields.Float(
'Quantity To Produce',
default=1.0, digits='Product Unit of Measure',
readonly=True, required=True, tracking=True,
states={'draft': [('readonly', False)]})
product_uom_id = fields.Many2one(
'uom.uom', 'Product Unit of Measure',
readonly=True, required=True,
states={'draft': [('readonly', False)]}, domain="[('category_id', '=', product_uom_category_id)]")
lot_producing_id = fields.Many2one(
'stock.production.lot', string='Lot/Serial Number', copy=False,
domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]", check_company=True)
qty_producing = fields.Float(string="Quantity Producing", digits='Product Unit of Measure', copy=False)
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
product_uom_qty = fields.Float(string='Total Quantity', compute='_compute_product_uom_qty', store=True)
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type',
domain="[('code', '=', 'mrp_operation'), ('company_id', '=', company_id)]",
default=_get_default_picking_type, required=True, check_company=True,
readonly=True, states={'draft': [('readonly', False)]})
use_create_components_lots = fields.Boolean(related='picking_type_id.use_create_components_lots')
location_src_id = fields.Many2one(
'stock.location', 'Components Location',
default=_get_default_location_src_id,
readonly=True, required=True,
domain="[('usage','=','internal'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
states={'draft': [('readonly', False)]}, check_company=True,
help="Location where the system will look for components.")
location_dest_id = fields.Many2one(
'stock.location', 'Finished Products Location',
default=_get_default_location_dest_id,
readonly=True, required=True,
domain="[('usage','=','internal'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
states={'draft': [('readonly', False)]}, check_company=True,
help="Location where the system will stock the finished products.")
date_planned_start = fields.Datetime(
'Scheduled Date', copy=False, default=_get_default_date_planned_start,
help="Date at which you plan to start the production.",
index=True, required=True)
date_planned_finished = fields.Datetime(
'Scheduled End Date',
default=_get_default_date_planned_finished,
help="Date at which you plan to finish the production.",
copy=False)
date_deadline = fields.Datetime(
'Deadline', copy=False, store=True, readonly=True, compute='_compute_date_deadline', inverse='_set_date_deadline',
help="Informative date allowing to define when the manufacturing order should be processed at the latest to fulfill delivery on time.")
date_start = fields.Datetime('Start Date', copy=False, readonly=True, help="Date of the WO")
date_finished = fields.Datetime('End Date', copy=False, readonly=True, help="Date when the MO has been close")
production_duration_expected = fields.Float("Expected Duration", help="Total expected duration (in minutes)", compute='_compute_production_duration_expected')
production_real_duration = fields.Float("Real Duration", help="Total real duration (in minutes)", compute='_compute_production_real_duration')
bom_id = fields.Many2one(
'mrp.bom', 'Bill of Material',
readonly=True, states={'draft': [('readonly', False)]},
domain="""[
'&',
'|',
('company_id', '=', False),
('company_id', '=', company_id),
'&',
'|',
('product_id','=',product_id),
'&',
('product_tmpl_id.product_variant_ids','=',product_id),
('product_id','=',False),
('type', '=', 'normal')]""",
check_company=True,
help="Bill of Materials allow you to define the list of required components to make a finished product.")
state = fields.Selection([
('draft', 'Draft'),
('confirmed', 'Confirmed'),
('progress', 'In Progress'),
('to_close', 'To Close'),
('done', 'Done'),
('cancel', 'Cancelled')], string='State',
compute='_compute_state', copy=False, index=True, readonly=True,
store=True, tracking=True,
help=" * Draft: The MO is not confirmed yet.\n"
" * Confirmed: The MO is confirmed, the stock rules and the reordering of the components are trigerred.\n"
" * In Progress: The production has started (on the MO or on the WO).\n"
" * To Close: The production is done, the MO has to be closed.\n"
" * Done: The MO is closed, the stock moves are posted. \n"
" * Cancelled: The MO has been cancelled, can't be confirmed anymore.")
reservation_state = fields.Selection([
('confirmed', 'Waiting'),
('assigned', 'Ready'),
('waiting', 'Waiting Another Operation')],
string='MO Readiness',
compute='_compute_reservation_state', copy=False, index=True, readonly=True,
store=True, tracking=True,
help="Manufacturing readiness for this MO, as per bill of material configuration:\n\
* Ready: The material is available to start the production.\n\
* Waiting: The material is not available to start the production.\n")
move_raw_ids = fields.One2many(
'stock.move', 'raw_material_production_id', 'Components',
copy=False, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
domain=[('scrapped', '=', False)])
move_finished_ids = fields.One2many(
'stock.move', 'production_id', 'Finished Products',
copy=False, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
domain=[('scrapped', '=', False)])
move_byproduct_ids = fields.One2many('stock.move', compute='_compute_move_byproduct_ids', inverse='_set_move_byproduct_ids')
finished_move_line_ids = fields.One2many(
'stock.move.line', compute='_compute_lines', inverse='_inverse_lines', string="Finished Product"
)
workorder_ids = fields.One2many(
'mrp.workorder', 'production_id', 'Work Orders', copy=True)
move_dest_ids = fields.One2many('stock.move', 'created_production_id',
string="Stock Movements of Produced Goods")
unreserve_visible = fields.Boolean(
'Allowed to Unreserve Production', compute='_compute_unreserve_visible',
help='Technical field to check when we can unreserve')
reserve_visible = fields.Boolean(
'Allowed to Reserve Production', compute='_compute_unreserve_visible',
help='Technical field to check when we can reserve quantities')
user_id = fields.Many2one(
'res.users', 'Responsible', default=lambda self: self.env.user,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
domain=lambda self: [('groups_id', 'in', self.env.ref('mrp.group_mrp_user').id)])
company_id = fields.Many2one(
'res.company', 'Company', default=lambda self: self.env.company,
index=True, required=True)
qty_produced = fields.Float(compute="_get_produced_qty", string="Quantity Produced")
procurement_group_id = fields.Many2one(
'procurement.group', 'Procurement Group',
copy=False)
product_description_variants = fields.Char('Custom Description')
orderpoint_id = fields.Many2one('stock.warehouse.orderpoint', 'Orderpoint', index=True, copy=False)
propagate_cancel = fields.Boolean(
'Propagate cancel and split',
help='If checked, when the previous move of the move (which was generated by a next procurement) is cancelled or split, the move generated by this move will too')
delay_alert_date = fields.Datetime('Delay Alert Date', compute='_compute_delay_alert_date', search='_search_delay_alert_date')
json_popover = fields.Char('JSON data for the popover widget', compute='_compute_json_popover')
scrap_ids = fields.One2many('stock.scrap', 'production_id', 'Scraps')
scrap_count = fields.Integer(compute='_compute_scrap_move_count', string='Scrap Move')
is_locked = fields.Boolean('Is Locked', default=_get_default_is_locked, copy=False)
is_planned = fields.Boolean('Its Operations are Planned', compute="_compute_is_planned", store=True)
show_final_lots = fields.Boolean('Show Final Lots', compute='_compute_show_lots')
production_location_id = fields.Many2one('stock.location', "Production Location", compute="_compute_production_location", store=True)
picking_ids = fields.Many2many('stock.picking', compute='_compute_picking_ids', string='Picking associated to this manufacturing order')
delivery_count = fields.Integer(string='Delivery Orders', compute='_compute_picking_ids')
confirm_cancel = fields.Boolean(compute='_compute_confirm_cancel')
consumption = fields.Selection([
('flexible', 'Allowed'),
('warning', 'Allowed with warning'),
('strict', 'Blocked')],
required=True,
readonly=True,
default='flexible',
)
mrp_production_child_count = fields.Integer("Number of generated MO", compute='_compute_mrp_production_child_count')
mrp_production_source_count = fields.Integer("Number of source MO", compute='_compute_mrp_production_source_count')
mrp_production_backorder_count = fields.Integer("Count of linked backorder", compute='_compute_mrp_production_backorder')
show_lock = fields.Boolean('Show Lock/unlock buttons', compute='_compute_show_lock')
components_availability = fields.Char(
string="Component Status", compute='_compute_components_availability',
help="Latest component availability status for this MO. If green, then the MO's readiness status is ready, as per BOM configuration.")
components_availability_state = fields.Selection([
('available', 'Available'),
('expected', 'Expected'),
('late', 'Late')], compute='_compute_components_availability')
show_lot_ids = fields.Boolean('Display the serial number shortcut on the moves', compute='_compute_show_lot_ids')
forecasted_issue = fields.Boolean(compute='_compute_forecasted_issue')
show_serial_mass_produce = fields.Boolean('Display the serial mass product wizard action moves', compute='_compute_show_serial_mass_produce')
@api.depends('procurement_group_id.stock_move_ids.created_production_id.procurement_group_id.mrp_production_ids',
'procurement_group_id.stock_move_ids.move_orig_ids.created_production_id.procurement_group_id.mrp_production_ids')
def _compute_mrp_production_child_count(self):
for production in self:
production.mrp_production_child_count = len(production._get_children())
@api.depends('procurement_group_id.mrp_production_ids.move_dest_ids.group_id.mrp_production_ids',
'procurement_group_id.stock_move_ids.move_dest_ids.group_id.mrp_production_ids')
def _compute_mrp_production_source_count(self):
for production in self:
production.mrp_production_source_count = len(production._get_sources())
@api.depends('procurement_group_id.mrp_production_ids')
def _compute_mrp_production_backorder(self):
for production in self:
production.mrp_production_backorder_count = len(production.procurement_group_id.mrp_production_ids)
@api.depends('state', 'reservation_state', 'date_planned_start', 'move_raw_ids', 'move_raw_ids.forecast_availability', 'move_raw_ids.forecast_expected_date')
def _compute_components_availability(self):
productions = self.filtered(lambda mo: mo.state not in ('cancel', 'done', 'draft'))
productions.components_availability_state = 'available'
productions.components_availability = _('Available')
other_productions = self - productions
other_productions.components_availability = False
other_productions.components_availability_state = False
all_raw_moves = productions.move_raw_ids
# Force to prefetch more than 1000 by 1000
all_raw_moves._fields['forecast_availability'].compute_value(all_raw_moves)
for production in productions:
if any(float_compare(move.forecast_availability, 0 if move.state == 'draft' else move.product_qty, precision_rounding=move.product_id.uom_id.rounding) == -1 for move in production.move_raw_ids):
production.components_availability = _('Not Available')
production.components_availability_state = 'late'
else:
forecast_date = max(production.move_raw_ids.filtered('forecast_expected_date').mapped('forecast_expected_date'), default=False)
if forecast_date:
production.components_availability = _('Exp %s', format_date(self.env, forecast_date))
if production.date_planned_start:
production.components_availability_state = 'late' if forecast_date > production.date_planned_start else 'expected'
@api.depends('move_finished_ids.date_deadline')
def _compute_date_deadline(self):
for production in self:
production.date_deadline = min(production.move_finished_ids.filtered('date_deadline').mapped('date_deadline'), default=production.date_deadline or False)
def _set_date_deadline(self):
for production in self:
production.move_finished_ids.date_deadline = production.date_deadline
@api.depends('workorder_ids.duration_expected')
def _compute_production_duration_expected(self):
for production in self:
production.production_duration_expected = sum(production.workorder_ids.mapped('duration_expected'))
@api.depends('workorder_ids.duration')
def _compute_production_real_duration(self):
for production in self:
production.production_real_duration = sum(production.workorder_ids.mapped('duration'))
@api.depends("workorder_ids.date_planned_start", "workorder_ids.date_planned_finished")
def _compute_is_planned(self):
for production in self:
if production.workorder_ids:
production.is_planned = any(wo.date_planned_start and wo.date_planned_finished for wo in production.workorder_ids)
else:
production.is_planned = False
@api.depends('move_raw_ids.delay_alert_date')
def _compute_delay_alert_date(self):
delay_alert_date_data = self.env['stock.move'].read_group([('id', 'in', self.move_raw_ids.ids), ('delay_alert_date', '!=', False)], ['delay_alert_date:max'], 'raw_material_production_id')
delay_alert_date_data = {data['raw_material_production_id'][0]: data['delay_alert_date'] for data in delay_alert_date_data}
for production in self:
production.delay_alert_date = delay_alert_date_data.get(production.id, False)
def _compute_json_popover(self):
production_no_alert = self.filtered(lambda m: m.state in ('done', 'cancel') or not m.delay_alert_date)
production_no_alert.json_popover = False
for production in (self - production_no_alert):
production.json_popover = json.dumps({
'popoverTemplate': 'stock.PopoverStockRescheduling',
'delay_alert_date': format_datetime(self.env, production.delay_alert_date, dt_format=False),
'late_elements': [{
'id': late_document.id,
'name': late_document.display_name,
'model': late_document._name,
} for late_document in production.move_raw_ids.filtered(lambda m: m.delay_alert_date).move_orig_ids._delay_alert_get_documents()
]
})
@api.depends('move_raw_ids.state', 'move_finished_ids.state')
def _compute_confirm_cancel(self):
""" If the manufacturing order contains some done move (via an intermediate
post inventory), the user has to confirm the cancellation.
"""
domain = [
('state', '=', 'done'),
'|',
('production_id', 'in', self.ids),
('raw_material_production_id', 'in', self.ids)
]
res = self.env['stock.move'].read_group(domain, ['state', 'production_id', 'raw_material_production_id'], ['production_id', 'raw_material_production_id'], lazy=False)
productions_with_done_move = {}
for rec in res:
production_record = rec['production_id'] or rec['raw_material_production_id']
if production_record:
productions_with_done_move[production_record[0]] = True
for production in self:
production.confirm_cancel = productions_with_done_move.get(production.id, False)
@api.depends('procurement_group_id')
def _compute_picking_ids(self):
for order in self:
order.picking_ids = self.env['stock.picking'].search([
('group_id', '=', order.procurement_group_id.id), ('group_id', '!=', False),
])
order.delivery_count = len(order.picking_ids)
def action_view_mo_delivery(self):
""" This function returns an action that display picking related to
manufacturing order orders. It can either be a in a list or in a form
view, if there is only one picking to show.
"""
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_picking_tree_all")
pickings = self.mapped('picking_ids')
if len(pickings) > 1:
action['domain'] = [('id', 'in', pickings.ids)]
elif pickings:
form_view = [(self.env.ref('stock.view_picking_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'] = pickings.id
action['context'] = dict(self._context, default_origin=self.name, create=False)
return action
@api.depends('product_uom_id', 'product_qty', 'product_id.uom_id')
def _compute_product_uom_qty(self):
for production in self:
if production.product_id.uom_id != production.product_uom_id:
production.product_uom_qty = production.product_uom_id._compute_quantity(production.product_qty, production.product_id.uom_id)
else:
production.product_uom_qty = production.product_qty
@api.depends('product_id', 'company_id')
def _compute_production_location(self):
if not self.company_id:
return
location_by_company = self.env['stock.location'].read_group([
('company_id', 'in', self.company_id.ids),
('usage', '=', 'production')
], ['company_id', 'ids:array_agg(id)'], ['company_id'])
location_by_company = {lbc['company_id'][0]: lbc['ids'] for lbc in location_by_company}
for production in self:
if production.product_id:
production.production_location_id = production.product_id.with_company(production.company_id).property_stock_production
else:
production.production_location_id = location_by_company.get(production.company_id.id)[0]
@api.depends('product_id.tracking')
def _compute_show_lots(self):
for production in self:
production.show_final_lots = production.product_id.tracking != 'none'
def _inverse_lines(self):
""" Little hack to make sure that when you change something on these objects, it gets saved"""
pass
@api.depends('move_finished_ids.move_line_ids')
def _compute_lines(self):
for production in self:
production.finished_move_line_ids = production.move_finished_ids.mapped('move_line_ids')
@api.depends(
'move_raw_ids.state', 'move_raw_ids.quantity_done', 'move_finished_ids.state',
'workorder_ids.state', 'product_qty', 'qty_producing')
def _compute_state(self):
""" Compute the production state. This uses a similar process to stock
picking, but has been adapted to support having no moves. This adaption
includes some state changes outside of this compute.
There exist 3 extra steps for production:
- progress: At least one item is produced or consumed.
- to_close: The quantity produced is greater than the quantity to
produce and all work orders has been finished.
"""
for production in self:
if not production.state or not production.product_uom_id:
production.state = 'draft'
elif production.state == 'cancel' or (production.move_finished_ids and all(move.state == 'cancel' for move in production.move_finished_ids)):
production.state = 'cancel'
elif (
production.state == 'done'
or (production.move_raw_ids and all(move.state in ('cancel', 'done') for move in production.move_raw_ids))
and all(move.state in ('cancel', 'done') for move in production.move_finished_ids)
):
production.state = 'done'
elif production.workorder_ids and all(wo_state in ('done', 'cancel') for wo_state in production.workorder_ids.mapped('state')):
production.state = 'to_close'
elif not production.workorder_ids and float_compare(production.qty_producing, production.product_qty, precision_rounding=production.product_uom_id.rounding) >= 0:
production.state = 'to_close'
elif any(wo_state in ('progress', 'done') for wo_state in production.workorder_ids.mapped('state')):
production.state = 'progress'
elif production.product_uom_id and not float_is_zero(production.qty_producing, precision_rounding=production.product_uom_id.rounding):
production.state = 'progress'
elif any(not float_is_zero(move.quantity_done, precision_rounding=move.product_uom.rounding or move.product_id.uom_id.rounding) for move in production.move_raw_ids):
production.state = 'progress'
@api.depends('state', 'move_raw_ids.state')
def _compute_reservation_state(self):
self.reservation_state = False
for production in self:
if production.state in ('draft', 'done', 'cancel'):
continue
relevant_move_state = production.move_raw_ids._get_relevant_state_among_moves()
# Compute reservation state according to its component's moves.
if relevant_move_state == 'partially_available':
if production.workorder_ids.operation_id and production.bom_id.ready_to_produce == 'asap':
production.reservation_state = production._get_ready_to_produce_state()
else:
production.reservation_state = 'confirmed'
elif relevant_move_state != 'draft':
production.reservation_state = relevant_move_state
@api.depends('move_raw_ids', 'state', 'move_raw_ids.product_uom_qty')
def _compute_unreserve_visible(self):
for order in self:
already_reserved = order.state not in ('done', 'cancel') and order.mapped('move_raw_ids.move_line_ids')
any_quantity_done = any(m.quantity_done > 0 for m in order.move_raw_ids)
order.unreserve_visible = not any_quantity_done and already_reserved
order.reserve_visible = order.state in ('confirmed', 'progress', 'to_close') and any(move.product_uom_qty and move.state in ['confirmed', 'partially_available'] for move in order.move_raw_ids)
@api.depends('workorder_ids.state', 'move_finished_ids', 'move_finished_ids.quantity_done')
def _get_produced_qty(self):
for production in self:
done_moves = production.move_finished_ids.filtered(lambda x: x.state != 'cancel' and x.product_id.id == production.product_id.id)
qty_produced = sum(done_moves.mapped('quantity_done'))
production.qty_produced = qty_produced
return True
def _compute_scrap_move_count(self):
data = self.env['stock.scrap'].read_group([('production_id', 'in', self.ids)], ['production_id'], ['production_id'])
count_data = dict((item['production_id'][0], item['production_id_count']) for item in data)
for production in self:
production.scrap_count = count_data.get(production.id, 0)
@api.depends('move_finished_ids')
def _compute_move_byproduct_ids(self):
for order in self:
order.move_byproduct_ids = order.move_finished_ids.filtered(lambda m: m.product_id != order.product_id)
def _set_move_byproduct_ids(self):
move_finished_ids = self.move_finished_ids.filtered(lambda m: m.product_id == self.product_id)
self.move_finished_ids = move_finished_ids | self.move_byproduct_ids
@api.depends('state')
def _compute_show_lock(self):
for order in self:
order.show_lock = order.state == 'done' or (
not self.env.user.has_group('mrp.group_unlocked_by_default')
and order.id is not False
and order.state not in {'cancel', 'draft'}
)
@api.depends('state','move_raw_ids')
def _compute_show_lot_ids(self):
for order in self:
order.show_lot_ids = order.state != 'draft' and any(m.product_id.tracking == 'serial' for m in order.move_raw_ids)
@api.depends('state', 'move_raw_ids')
def _compute_show_serial_mass_produce(self):
self.show_serial_mass_produce = False
for order in self:
if order.state == 'confirmed' and order.product_id.tracking == 'serial' and \
float_compare(order.product_qty, 1, precision_rounding=order.product_uom_id.rounding) > 0 and \
float_compare(order.qty_producing, order.product_qty, precision_rounding=order.product_uom_id.rounding) < 0:
have_serial_components, dummy, dummy, dummy = order._check_serial_mass_produce_components()
if not have_serial_components:
order.show_serial_mass_produce = True
_sql_constraints = [
('name_uniq', 'unique(name, company_id)', 'Reference must be unique per Company!'),
('qty_positive', 'check (product_qty > 0)', 'The quantity to produce must be positive!'),
]
@api.depends('product_uom_qty', 'date_planned_start')
def _compute_forecasted_issue(self):
for order in self:
warehouse = order.location_dest_id.warehouse_id
order.forecasted_issue = False
if order.product_id:
virtual_available = order.product_id.with_context(warehouse=warehouse.id, to_date=order.date_planned_start).virtual_available
if order.state == 'draft':
virtual_available += order.product_uom_qty
if virtual_available < 0:
order.forecasted_issue = True
@api.model
def _search_delay_alert_date(self, operator, value):
late_stock_moves = self.env['stock.move'].search([('delay_alert_date', operator, value)])
return ['|', ('move_raw_ids', 'in', late_stock_moves.ids), ('move_finished_ids', 'in', late_stock_moves.ids)]
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
if self.move_raw_ids:
self.move_raw_ids.update({'company_id': self.company_id})
if self.picking_type_id and self.picking_type_id.company_id != self.company_id:
self.picking_type_id = self.env['stock.picking.type'].search([
('code', '=', 'mrp_operation'),
('warehouse_id.company_id', '=', self.company_id.id),
], limit=1).id
@api.onchange('product_id', 'picking_type_id', 'company_id')
def _onchange_product_id(self):
""" Finds UoM of changed product. """
if not self.product_id:
self.bom_id = False
elif not self.bom_id or self.bom_id.product_tmpl_id != self.product_tmpl_id or (self.bom_id.product_id and self.bom_id.product_id != self.product_id):
picking_type_id = self._context.get('default_picking_type_id')
picking_type = picking_type_id and self.env['stock.picking.type'].browse(picking_type_id)
bom = self.env['mrp.bom']._bom_find(self.product_id, picking_type=picking_type, company_id=self.company_id.id, bom_type='normal')[self.product_id]
if bom:
self.bom_id = bom.id
self.product_qty = self.bom_id.product_qty
self.product_uom_id = self.bom_id.product_uom_id.id
else:
self.bom_id = False
self.product_uom_id = self.product_id.uom_id.id
@api.onchange('product_qty', 'product_uom_id')
def _onchange_product_qty(self):
for workorder in self.workorder_ids:
workorder.product_uom_id = self.product_uom_id
if self._origin.product_qty:
workorder.duration_expected = workorder._get_duration_expected(ratio=self.product_qty / self._origin.product_qty)
else:
workorder.duration_expected = workorder._get_duration_expected()
if workorder.date_planned_start and workorder.duration_expected:
workorder.date_planned_finished = workorder.date_planned_start + relativedelta(minutes=workorder.duration_expected)
@api.onchange('bom_id')
def _onchange_bom_id(self):
if not self.product_id and self.bom_id:
self.product_id = self.bom_id.product_id or self.bom_id.product_tmpl_id.product_variant_ids[:1]
self.product_qty = self.bom_id.product_qty or 1.0
self.product_uom_id = self.bom_id and self.bom_id.product_uom_id.id or self.product_id.uom_id.id
self.move_raw_ids = [(2, move.id) for move in self.move_raw_ids.filtered(lambda m: m.bom_line_id)]
self.move_finished_ids = [(2, move.id) for move in self.move_finished_ids]
picking_type_id = self._context.get('default_picking_type_id')
picking_type = picking_type_id and self.env['stock.picking.type'].browse(picking_type_id)
self.picking_type_id = picking_type or self.bom_id.picking_type_id or self.picking_type_id
@api.onchange('date_planned_start', 'product_id')
def _onchange_date_planned_start(self):
if self.date_planned_start and not self.is_planned:
date_planned_finished = self.date_planned_start + relativedelta(days=self.product_id.produce_delay)
date_planned_finished = date_planned_finished + relativedelta(days=self.company_id.manufacturing_lead)
if date_planned_finished == self.date_planned_start:
date_planned_finished = date_planned_finished + relativedelta(hours=1)
self.date_planned_finished = date_planned_finished
self.move_raw_ids = [(1, m.id, {'date': self.date_planned_start}) for m in self.move_raw_ids]
self.move_finished_ids = [(1, m.id, {'date': date_planned_finished}) for m in self.move_finished_ids]
@api.onchange('bom_id', 'product_id', 'product_qty', 'product_uom_id')
def _onchange_move_raw(self):
if not self.bom_id and not self._origin.product_id:
return
# Clear move raws if we are changing the product. In case of creation (self._origin is empty),
# we need to avoid keeping incorrect lines, so clearing is necessary too.
if self.product_id != self._origin.product_id:
self.move_raw_ids = [(5,)]
if self.bom_id and self.product_id and self.product_qty > 0:
# keep manual entries
list_move_raw = [(4, move.id) for move in self.move_raw_ids.filtered(lambda m: not m.bom_line_id)]
moves_raw_values = self._get_moves_raw_values()
move_raw_dict = {move.bom_line_id.id: move for move in self.move_raw_ids.filtered(lambda m: m.bom_line_id)}
for move_raw_values in moves_raw_values:
if move_raw_values['bom_line_id'] in move_raw_dict:
# update existing entries
list_move_raw += [(1, move_raw_dict[move_raw_values['bom_line_id']].id, move_raw_values)]
else:
# add new entries
list_move_raw += [(0, 0, move_raw_values)]
self.move_raw_ids = list_move_raw
else:
self.move_raw_ids = [(2, move.id) for move in self.move_raw_ids.filtered(lambda m: m.bom_line_id)]
@api.onchange('product_id')
def _onchange_move_finished_product(self):
self.move_finished_ids = [(5,)]
if self.product_id:
self._create_update_move_finished()
@api.onchange('bom_id', 'product_qty', 'product_uom_id')
def _onchange_move_finished(self):
if self.product_id and self.product_qty > 0:
self._create_update_move_finished()
else:
self.move_finished_ids = [(2, move.id) for move in self.move_finished_ids.filtered(lambda m: m.bom_line_id)]
@api.onchange('location_src_id', 'move_raw_ids', 'bom_id')
def _onchange_location(self):
source_location = self.location_src_id
self.move_raw_ids.update({
'warehouse_id': source_location.warehouse_id.id,
'location_id': source_location.id,
})
@api.onchange('location_dest_id', 'move_finished_ids', 'bom_id')
def _onchange_location_dest(self):
destination_location = self.location_dest_id
update_value_list = []
for move in self.move_finished_ids:
update_value_list += [(1, move.id, ({
'warehouse_id': destination_location.warehouse_id.id,
'location_dest_id': destination_location.id,
}))]
self.move_finished_ids = update_value_list
@api.onchange('picking_type_id')
def _onchange_picking_type(self):
if not self.picking_type_id.default_location_src_id or not self.picking_type_id.default_location_dest_id.id:
company_id = self.company_id.id if (self.company_id and self.company_id in self.env.companies) else self.env.company.id
fallback_loc = self.env['stock.warehouse'].search([('company_id', '=', company_id)], limit=1).lot_stock_id
self.location_src_id = self.picking_type_id.default_location_src_id.id or fallback_loc.id
self.location_dest_id = self.picking_type_id.default_location_dest_id.id or fallback_loc.id
@api.onchange('qty_producing', 'lot_producing_id')
def _onchange_producing(self):
self._set_qty_producing()
@api.onchange('lot_producing_id')
def _onchange_lot_producing(self):
res = self._can_produce_serial_number()
if res is not True:
return res
def _can_produce_serial_number(self, sn=None):
self.ensure_one()
sn = sn or self.lot_producing_id
if self.product_id.tracking == 'serial' and sn:
message, dummy = self.env['stock.quant']._check_serial_number(self.product_id, sn, self.company_id)
if message:
return {'warning': {'title': _('Warning'), 'message': message}}
return True
@api.onchange('bom_id', 'product_id')
def _onchange_workorder_ids(self):
if self.bom_id and self.product_id:
self._create_workorder()
else:
self.workorder_ids = False
@api.constrains('move_finished_ids')
def _check_byproducts(self):
for order in self:
if any(move.cost_share < 0 for move in order.move_byproduct_ids):
raise ValidationError(_("By-products cost shares must be positive."))
if sum(order.move_byproduct_ids.mapped('cost_share')) > 100:
raise ValidationError(_("The total cost share for a manufacturing order's by-products cannot exceed 100."))
@api.constrains('product_id', 'move_raw_ids')
def _check_production_lines(self):
for production in self:
for move in production.move_raw_ids:
if production.product_id == move.product_id:
raise ValidationError(_("The component %s should not be the same as the product to produce.") % production.product_id.display_name)
def write(self, vals):
if 'move_byproduct_ids' in vals and 'move_finished_ids' not in vals:
vals['move_finished_ids'] = vals['move_byproduct_ids']
del vals['move_byproduct_ids']
if 'workorder_ids' in self:
production_to_replan = self.filtered(lambda p: p.is_planned)
res = super(MrpProduction, self).write(vals)
for production in self:
if 'date_planned_start' in vals and not self.env.context.get('force_date', False):
if production.state in ['done', 'cancel']:
raise UserError(_('You cannot move a manufacturing order once it is cancelled or done.'))
if production.is_planned:
production.button_unplan()
if vals.get('date_planned_start'):
production.move_raw_ids.write({'date': production.date_planned_start, 'date_deadline': production.date_planned_start})
if vals.get('date_planned_finished'):
production.move_finished_ids.write({'date': production.date_planned_finished})
if any(field in ['move_raw_ids', 'move_finished_ids', 'workorder_ids'] for field in vals) and production.state != 'draft':
if production.state == 'done':
# for some reason moves added after state = 'done' won't save group_id, reference if added in
# "stock_move.default_get()"
production.move_raw_ids.filtered(lambda move: move.additional and move.date > production.date_planned_start).write({
'group_id': production.procurement_group_id.id,
'reference': production.name,
'date': production.date_planned_start,
'date_deadline': production.date_planned_start
})
production.move_finished_ids.filtered(lambda move: move.additional and move.date > production.date_planned_finished).write({
'reference': production.name,
'date': production.date_planned_finished,
'date_deadline': production.date_deadline
})
production._autoconfirm_production()
if production in production_to_replan:
production._plan_workorders(replan=True)
if production.state == 'done' and ('lot_producing_id' in vals or 'qty_producing' in vals):
finished_move_lines = production.move_finished_ids.filtered(
lambda move: move.product_id == production.product_id and move.state == 'done').mapped('move_line_ids')
if 'lot_producing_id' in vals:
finished_move_lines.write({'lot_id': vals.get('lot_producing_id')})
if 'qty_producing' in vals:
finished_move_lines.write({'qty_done': vals.get('qty_producing')})
if not production.workorder_ids.operation_id and vals.get('date_planned_start') and not vals.get('date_planned_finished'):
new_date_planned_start = fields.Datetime.to_datetime(vals.get('date_planned_start'))
if not production.date_planned_finished or new_date_planned_start >= production.date_planned_finished:
production.date_planned_finished = new_date_planned_start + datetime.timedelta(hours=1)
return res
@api.model
def create(self, values):
# Remove from `move_finished_ids` the by-product moves and then move `move_byproduct_ids`
# into `move_finished_ids` to avoid duplicate and inconsistency.
if values.get('move_finished_ids', False):
values['move_finished_ids'] = list(filter(lambda move: move[2].get('byproduct_id', False) is False, values['move_finished_ids']))
if values.get('move_byproduct_ids', False):
values['move_finished_ids'] = values.get('move_finished_ids', []) + values['move_byproduct_ids']
del values['move_byproduct_ids']
if not values.get('name', False) or values['name'] == _('New'):
picking_type_id = values.get('picking_type_id') or self._get_default_picking_type()
picking_type_id = self.env['stock.picking.type'].browse(picking_type_id)
if picking_type_id:
values['name'] = picking_type_id.sequence_id.next_by_id()
else:
values['name'] = self.env['ir.sequence'].next_by_code('mrp.production') or _('New')
if not values.get('procurement_group_id'):
procurement_group_vals = self._prepare_procurement_group_vals(values)
values['procurement_group_id'] = self.env["procurement.group"].create(procurement_group_vals).id
production = super(MrpProduction, self).create(values)
(production.move_raw_ids | production.move_finished_ids).write({
'group_id': production.procurement_group_id.id,
'origin': production.name
})
production.move_raw_ids.write({'date': production.date_planned_start})
production.move_finished_ids.write({'date': production.date_planned_finished})
# Trigger SM & WO creation when importing a file
if 'import_file' in self.env.context:
production._onchange_move_raw()
production._onchange_move_finished()
production._onchange_workorder_ids()
return production
@api.ondelete(at_uninstall=False)
def _unlink_except_done(self):
if any(production.state == 'done' for production in self):
raise UserError(_('Cannot delete a manufacturing order in done state.'))
not_cancel = self.filtered(lambda m: m.state != 'cancel')
if not_cancel:
productions_name = ', '.join([prod.display_name for prod in not_cancel])
raise UserError(_('%s cannot be deleted. Try to cancel them before.', productions_name))
def unlink(self):
self.action_cancel()
workorders_to_delete = self.workorder_ids.filtered(lambda wo: wo.state != 'done')
if workorders_to_delete:
workorders_to_delete.unlink()
return super(MrpProduction, self).unlink()
def copy_data(self, default=None):
default = dict(default or {})
# covers at least 2 cases: backorders generation (follow default logic for moves copying)
# and copying a done MO via the form (i.e. copy only the non-cancelled moves since no backorder = cancelled finished moves)
if not default or 'move_finished_ids' not in default:
move_finished_ids = self.move_finished_ids
if self.state != 'cancel':
move_finished_ids = self.move_finished_ids.filtered(lambda m: m.state != 'cancel' and m.product_qty != 0.0)
default['move_finished_ids'] = [(0, 0, move.copy_data()[0]) for move in move_finished_ids]
if not default or 'move_raw_ids' not in default:
default['move_raw_ids'] = [(0, 0, move.copy_data()[0]) for move in self.move_raw_ids.filtered(lambda m: m.product_qty != 0.0)]
return super(MrpProduction, self).copy_data(default=default)
def action_toggle_is_locked(self):
self.ensure_one()
self.is_locked = not self.is_locked
return True
def action_product_forecast_report(self):
self.ensure_one()
action = self.product_id.action_product_forecast_report()
action['context'] = {
'active_id': self.product_id.id,
'active_model': 'product.product',
'move_to_match_ids': self.move_finished_ids.filtered(lambda m: m.product_id == self.product_id).ids
}
warehouse = self.picking_type_id.warehouse_id
if warehouse:
action['context']['warehouse'] = warehouse.id
return action
def _create_workorder(self):
for production in self:
if not production.bom_id or not production.product_id:
continue
workorders_values = []
product_qty = production.product_uom_id._compute_quantity(production.product_qty, production.bom_id.product_uom_id)
exploded_boms, dummy = production.bom_id.explode(production.product_id, product_qty / production.bom_id.product_qty, picking_type=production.bom_id.picking_type_id)
for bom, bom_data in exploded_boms:
# If the operations of the parent BoM and phantom BoM are the same, don't recreate work orders.
if not (bom.operation_ids and (not bom_data['parent_line'] or bom_data['parent_line'].bom_id.operation_ids != bom.operation_ids)):
continue
for operation in bom.operation_ids:
if operation._skip_operation_line(bom_data['product']):
continue
workorders_values += [{
'name': operation.name,
'production_id': production.id,
'workcenter_id': operation.workcenter_id.id,
'product_uom_id': production.product_uom_id.id,
'operation_id': operation.id,
'state': 'pending',
}]
production.workorder_ids = [(5, 0)] + [(0, 0, value) for value in workorders_values]
for workorder in production.workorder_ids:
workorder.duration_expected = workorder._get_duration_expected()
def _get_move_finished_values(self, product_id, product_uom_qty, product_uom, operation_id=False, byproduct_id=False, cost_share=0):
group_orders = self.procurement_group_id.mrp_production_ids
move_dest_ids = self.move_dest_ids
if len(group_orders) > 1:
move_dest_ids |= group_orders[0].move_finished_ids.filtered(lambda m: m.product_id == self.product_id).move_dest_ids
date_planned_finished = self.date_planned_start + relativedelta(days=self.product_id.produce_delay)
date_planned_finished = date_planned_finished + relativedelta(days=self.company_id.manufacturing_lead)
if date_planned_finished == self.date_planned_start:
date_planned_finished = date_planned_finished + relativedelta(hours=1)
return {
'product_id': product_id,
'product_uom_qty': product_uom_qty,
'product_uom': product_uom,
'operation_id': operation_id,
'byproduct_id': byproduct_id,
'name': self.name,
'date': date_planned_finished,
'date_deadline': self.date_deadline,
'picking_type_id': self.picking_type_id.id,
'location_id': self.product_id.with_company(self.company_id).property_stock_production.id,
'location_dest_id': self.location_dest_id.id,
'company_id': self.company_id.id,
'production_id': self.id,
'warehouse_id': self.location_dest_id.warehouse_id.id,
'origin': self.name,
'group_id': self.procurement_group_id.id,
'propagate_cancel': self.propagate_cancel,
'move_dest_ids': [(4, x.id) for x in self.move_dest_ids if not byproduct_id],
'cost_share': cost_share,
}
def _get_moves_finished_values(self):
moves = []
for production in self:
if production.product_id in production.bom_id.byproduct_ids.mapped('product_id'):
raise UserError(_("You cannot have %s as the finished product and in the Byproducts", self.product_id.name))
moves.append(production._get_move_finished_values(production.product_id.id, production.product_qty, production.product_uom_id.id))
for byproduct in production.bom_id.byproduct_ids:
if byproduct._skip_byproduct_line(production.product_id):
continue
product_uom_factor = production.product_uom_id._compute_quantity(production.product_qty, production.bom_id.product_uom_id)
qty = byproduct.product_qty * (product_uom_factor / production.bom_id.product_qty)
moves.append(production._get_move_finished_values(
byproduct.product_id.id, qty, byproduct.product_uom_id.id,
byproduct.operation_id.id, byproduct.id, byproduct.cost_share))
return moves
def _create_update_move_finished(self):
""" This is a helper function to support complexity of onchange logic for MOs.
It is important that the special *2Many commands used here remain as long as function
is used within onchanges.
"""
# keep manual entries
list_move_finished = [(4, move.id) for move in self.move_finished_ids.filtered(
lambda m: not m.byproduct_id and m.product_id != self.product_id)]
list_move_finished = []
moves_finished_values = self._get_moves_finished_values()
moves_byproduct_dict = {move.byproduct_id.id: move for move in self.move_finished_ids.filtered(lambda m: m.byproduct_id)}
move_finished = self.move_finished_ids.filtered(lambda m: m.product_id == self.product_id)
for move_finished_values in moves_finished_values:
if move_finished_values.get('byproduct_id') in moves_byproduct_dict:
# update existing entries
list_move_finished += [(1, moves_byproduct_dict[move_finished_values['byproduct_id']].id, move_finished_values)]
elif move_finished_values.get('product_id') == self.product_id.id and move_finished:
list_move_finished += [(1, move_finished.id, move_finished_values)]
else:
# add new entries
list_move_finished += [(0, 0, move_finished_values)]
self.move_finished_ids = list_move_finished
def _get_moves_raw_values(self):
moves = []
for production in self:
if not production.bom_id:
continue
factor = production.product_uom_id._compute_quantity(production.product_qty, production.bom_id.product_uom_id) / production.bom_id.product_qty
boms, lines = production.bom_id.explode(production.product_id, factor, picking_type=production.bom_id.picking_type_id)
for bom_line, line_data in lines:
if bom_line.child_bom_id and bom_line.child_bom_id.type == 'phantom' or\
bom_line.product_id.type not in ['product', 'consu']:
continue
operation = bom_line.operation_id.id or line_data['parent_line'] and line_data['parent_line'].operation_id.id
moves.append(production._get_move_raw_values(
bom_line.product_id,
line_data['qty'],
bom_line.product_uom_id,
operation,
bom_line
))
return moves
def _get_move_raw_values(self, product_id, product_uom_qty, product_uom, operation_id=False, bom_line=False):
source_location = self.location_src_id
origin = self.name
if self.orderpoint_id and self.origin:
origin = self.origin.replace(
'%s - ' % (self.orderpoint_id.display_name), '')
origin = '%s,%s' % (origin, self.name)
data = {
'sequence': bom_line.sequence if bom_line else 10,
'name': self.name,
'date': self.date_planned_start,
'date_deadline': self.date_planned_start,
'bom_line_id': bom_line.id if bom_line else False,
'picking_type_id': self.picking_type_id.id,
'product_id': product_id.id,
'product_uom_qty': product_uom_qty,
'product_uom': product_uom.id,
'location_id': source_location.id,
'location_dest_id': self.product_id.with_company(self.company_id).property_stock_production.id,
'raw_material_production_id': self.id,
'company_id': self.company_id.id,
'operation_id': operation_id,
'price_unit': product_id.standard_price,
'procure_method': 'make_to_stock',
'origin': origin,
'state': 'draft',
'warehouse_id': source_location.warehouse_id.id,
'group_id': self.procurement_group_id.id,
'propagate_cancel': self.propagate_cancel,
}
return data
def _set_qty_producing(self):
if self.product_id.tracking == 'serial':
qty_producing_uom = self.product_uom_id._compute_quantity(self.qty_producing, self.product_id.uom_id, rounding_method='HALF-UP')
if qty_producing_uom != 1:
self.qty_producing = self.product_id.uom_id._compute_quantity(1, self.product_uom_id, rounding_method='HALF-UP')
for move in (self.move_raw_ids | self.move_finished_ids.filtered(lambda m: m.product_id != self.product_id)):
if move._should_bypass_set_qty_producing() or not move.product_uom:
continue
new_qty = float_round((self.qty_producing - self.qty_produced) * move.unit_factor, precision_rounding=move.product_uom.rounding)
move.move_line_ids.filtered(lambda ml: ml.state not in ('done', 'cancel')).qty_done = 0
move._set_quantity_done(new_qty)
def _update_raw_moves(self, factor):
self.ensure_one()
update_info = []
moves_to_assign = self.env['stock.move']
for move in self.move_raw_ids.filtered(lambda m: m.state not in ('done', 'cancel')):
old_qty = move.product_uom_qty
new_qty = float_round(old_qty * factor, precision_rounding=move.product_uom.rounding, rounding_method='UP')
if new_qty > 0:
move.write({'product_uom_qty': new_qty})
if move._should_bypass_reservation() \
or move.picking_type_id.reservation_method == 'at_confirm' \
or (move.reservation_date and move.reservation_date <= fields.Date.today()):
moves_to_assign |= move
update_info.append((move, old_qty, new_qty))
moves_to_assign._action_assign()
return update_info
def _get_ready_to_produce_state(self):
""" returns 'assigned' if enough components are reserved in order to complete
the first operation of the bom. If not returns 'waiting'
"""
self.ensure_one()
operations = self.workorder_ids.operation_id
if len(operations) == 1:
moves_in_first_operation = self.move_raw_ids
else:
first_operation = operations[0]
moves_in_first_operation = self.move_raw_ids.filtered(lambda move: move.operation_id == first_operation)
moves_in_first_operation = moves_in_first_operation.filtered(
lambda move: move.bom_line_id and
not move.bom_line_id._skip_bom_line(self.product_id)
)
if all(move.state == 'assigned' for move in moves_in_first_operation):
return 'assigned'
return 'confirmed'
def _autoconfirm_production(self):
"""Automatically run `action_confirm` on `self`.
If the production has one of its move was added after the initial call
to `action_confirm`.
"""
moves_to_confirm = self.env['stock.move']
for production in self:
if production.state in ('done', 'cancel'):
continue
additional_moves = production.move_raw_ids.filtered(
lambda move: move.state == 'draft'
)
additional_moves.write({
'group_id': production.procurement_group_id.id,
})
additional_moves._adjust_procure_method()
moves_to_confirm |= additional_moves
additional_byproducts = production.move_finished_ids.filtered(
lambda move: move.state == 'draft'
)
moves_to_confirm |= additional_byproducts
if moves_to_confirm:
moves_to_confirm = moves_to_confirm._action_confirm()
# run scheduler for moves forecasted to not have enough in stock
moves_to_confirm._trigger_scheduler()
self.workorder_ids.filtered(lambda w: w.state not in ['done', 'cancel'])._action_confirm()
def _get_children(self):
self.ensure_one()
procurement_moves = self.procurement_group_id.stock_move_ids
child_moves = procurement_moves.move_orig_ids
return (procurement_moves | child_moves).created_production_id.procurement_group_id.mrp_production_ids.filtered(lambda p: p.origin != self.origin) - self
def _get_sources(self):
self.ensure_one()
dest_moves = self.procurement_group_id.mrp_production_ids.move_dest_ids
parent_moves = self.procurement_group_id.stock_move_ids.move_dest_ids
return (dest_moves | parent_moves).group_id.mrp_production_ids.filtered(lambda p: p.origin != self.origin) - self
def action_view_mrp_production_childs(self):
self.ensure_one()
mrp_production_ids = self._get_children().ids
action = {
'res_model': 'mrp.production',
'type': 'ir.actions.act_window',
}
if len(mrp_production_ids) == 1:
action.update({
'view_mode': 'form',
'res_id': mrp_production_ids[0],
})
else:
action.update({
'name': _("%s Child MO's") % self.name,
'domain': [('id', 'in', mrp_production_ids)],
'view_mode': 'tree,form',
})
return action
def action_view_mrp_production_sources(self):
self.ensure_one()
mrp_production_ids = self._get_sources().ids
action = {
'res_model': 'mrp.production',
'type': 'ir.actions.act_window',
}
if len(mrp_production_ids) == 1:
action.update({
'view_mode': 'form',
'res_id': mrp_production_ids[0],
})
else:
action.update({
'name': _("MO Generated by %s") % self.name,
'domain': [('id', 'in', mrp_production_ids)],
'view_mode': 'tree,form',
})
return action
def action_view_mrp_production_backorders(self):
backorder_ids = self.procurement_group_id.mrp_production_ids.ids
return {
'res_model': 'mrp.production',
'type': 'ir.actions.act_window',
'name': _("Backorder MO's"),
'domain': [('id', 'in', backorder_ids)],
'view_mode': 'tree,form',
}
def action_generate_serial(self):
self.ensure_one()
if self.product_id.tracking == 'lot':
name = self.env['ir.sequence'].next_by_code('stock.lot.serial')
exist_lot = self.env['stock.production.lot'].search([
('product_id', '=', self.product_id.id),
('company_id', '=', self.company_id.id),
('name', '=', name),
], limit=1)
if exist_lot:
name = self.env['stock.production.lot']._get_next_serial(self.company_id, self.product_id)
else:
name = self.env['stock.production.lot']._get_next_serial(self.company_id, self.product_id) or self.env['ir.sequence'].next_by_code('stock.lot.serial')
self.lot_producing_id = self.env['stock.production.lot'].create({
'product_id': self.product_id.id,
'company_id': self.company_id.id,
'name': name,
})
if self.move_finished_ids.filtered(lambda m: m.product_id == self.product_id).move_line_ids:
self.move_finished_ids.filtered(lambda m: m.product_id == self.product_id).move_line_ids.lot_id = self.lot_producing_id
if self.product_id.tracking == 'serial':
self._set_qty_producing()
def _action_generate_immediate_wizard(self):
view = self.env.ref('mrp.view_immediate_production')
return {
'name': _('Immediate Production?'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mrp.immediate.production',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'context': dict(self.env.context, default_mo_ids=[(4, mo.id) for mo in self]),
}
def action_confirm(self):
self._check_company()
for production in self:
if production.bom_id:
production.consumption = production.bom_id.consumption
# In case of Serial number tracking, force the UoM to the UoM of product
if production.product_tracking == 'serial' and production.product_uom_id != production.product_id.uom_id:
production.write({
'product_qty': production.product_uom_id._compute_quantity(production.product_qty, production.product_id.uom_id),
'product_uom_id': production.product_id.uom_id
})
for move_finish in production.move_finished_ids.filtered(lambda m: m.product_id == production.product_id):
move_finish.write({
'product_uom_qty': move_finish.product_uom._compute_quantity(move_finish.product_uom_qty, move_finish.product_id.uom_id),
'product_uom': move_finish.product_id.uom_id
})
production.move_raw_ids._adjust_procure_method()
(production.move_raw_ids | production.move_finished_ids)._action_confirm(merge=False)
production.workorder_ids._action_confirm()
# run scheduler for moves forecasted to not have enough in stock
self.move_raw_ids._trigger_scheduler()
self.picking_ids.filtered(
lambda p: p.state not in ['cancel', 'done']).action_confirm()
# Force confirm state only for draft production not for more advanced state like
# 'progress' (in case of backorders with some qty_producing)
self.filtered(lambda mo: mo.state == 'draft').state = 'confirmed'
return True
def action_assign(self):
for production in self:
production.move_raw_ids._action_assign()
return True
def button_plan(self):
""" Create work orders. And probably do stuff, like things. """
orders_to_plan = self.filtered(lambda order: not order.is_planned)
orders_to_confirm = orders_to_plan.filtered(lambda mo: mo.state == 'draft')
orders_to_confirm.action_confirm()
for order in orders_to_plan:
order._plan_workorders()
return True
def _plan_workorders(self, replan=False):
""" Plan all the production's workorders depending on the workcenters
work schedule.
:param replan: If it is a replan, only ready and pending workorder will be taken into account
:type replan: bool.
"""
self.ensure_one()
if not self.workorder_ids:
return
# Schedule all work orders (new ones and those already created)
qty_to_produce = max(self.product_qty - self.qty_produced, 0)
qty_to_produce = self.product_uom_id._compute_quantity(qty_to_produce, self.product_id.uom_id)
start_date = max(self.date_planned_start, datetime.datetime.now())
if replan:
workorder_ids = self.workorder_ids.filtered(lambda wo: wo.state in ('pending', 'waiting', 'ready'))
# We plan the manufacturing order according to its `date_planned_start`, but if
# `date_planned_start` is in the past, we plan it as soon as possible.
workorder_ids.leave_id.unlink()
else:
workorder_ids = self.workorder_ids.filtered(lambda wo: not wo.date_planned_start)
for workorder in workorder_ids:
workcenters = workorder.workcenter_id | workorder.workcenter_id.alternative_workcenter_ids
best_finished_date = datetime.datetime.max
vals = {}
for workcenter in workcenters:
# compute theoretical duration
if workorder.workcenter_id == workcenter:
duration_expected = workorder.duration_expected
else:
duration_expected = workorder._get_duration_expected(alternative_workcenter=workcenter)
from_date, to_date = workcenter._get_first_available_slot(start_date, duration_expected)
# If the workcenter is unavailable, try planning on the next one
if not from_date:
continue
# Check if this workcenter is better than the previous ones
if to_date and to_date < best_finished_date:
best_start_date = from_date
best_finished_date = to_date
best_workcenter = workcenter
vals = {
'workcenter_id': workcenter.id,
'duration_expected': duration_expected,
}
# If none of the workcenter are available, raise
if best_finished_date == datetime.datetime.max:
raise UserError(_('Impossible to plan the workorder. Please check the workcenter availabilities.'))
# Instantiate start_date for the next workorder planning
if workorder.next_work_order_id:
start_date = best_finished_date
# Create leave on chosen workcenter calendar
leave = self.env['resource.calendar.leaves'].create({
'name': workorder.display_name,
'calendar_id': best_workcenter.resource_calendar_id.id,
'date_from': best_start_date,
'date_to': best_finished_date,
'resource_id': best_workcenter.resource_id.id,
'time_type': 'other'
})
vals['leave_id'] = leave.id
workorder.write(vals)
self.with_context(force_date=True).write({
'date_planned_start': self.workorder_ids[0].date_planned_start,
'date_planned_finished': self.workorder_ids[-1].date_planned_finished
})
def button_unplan(self):
if any(wo.state == 'done' for wo in self.workorder_ids):
raise UserError(_("Some work orders are already done, you cannot unplan this manufacturing order."))
elif any(wo.state == 'progress' for wo in self.workorder_ids):
raise UserError(_("Some work orders have already started, you cannot unplan this manufacturing order."))
self.workorder_ids.leave_id.unlink()
self.workorder_ids.write({
'date_planned_start': False,
'date_planned_finished': False,
})
def _get_consumption_issues(self):
"""Compare the quantity consumed of the components, the expected quantity
on the BoM and the consumption parameter on the order.
:return: list of tuples (order_id, product_id, consumed_qty, expected_qty) where the
consumption isn't honored. order_id and product_id are recordset of mrp.production
and product.product respectively
:rtype: list
"""
issues = []
if self.env.context.get('skip_consumption', False) or self.env.context.get('skip_immediate', False):
return issues
for order in self:
if order.consumption == 'flexible' or not order.bom_id or not order.bom_id.bom_line_ids:
continue
expected_move_values = order._get_moves_raw_values()
expected_qty_by_product = defaultdict(float)
for move_values in expected_move_values:
move_product = self.env['product.product'].browse(move_values['product_id'])
move_uom = self.env['uom.uom'].browse(move_values['product_uom'])
move_product_qty = move_uom._compute_quantity(move_values['product_uom_qty'], move_product.uom_id)
expected_qty_by_product[move_product] += move_product_qty * order.qty_producing / order.product_qty
done_qty_by_product = defaultdict(float)
for move in order.move_raw_ids:
qty_done = move.product_uom._compute_quantity(move.quantity_done, move.product_id.uom_id)
rounding = move.product_id.uom_id.rounding
if not (move.product_id in expected_qty_by_product or float_is_zero(qty_done, precision_rounding=rounding)):
issues.append((order, move.product_id, qty_done, 0.0))
continue
done_qty_by_product[move.product_id] += qty_done
for product, qty_to_consume in expected_qty_by_product.items():
qty_done = done_qty_by_product.get(product, 0.0)
if float_compare(qty_to_consume, qty_done, precision_rounding=product.uom_id.rounding) != 0:
issues.append((order, product, qty_done, qty_to_consume))
return issues
def _action_generate_consumption_wizard(self, consumption_issues):
ctx = self.env.context.copy()
lines = []
for order, product_id, consumed_qty, expected_qty in consumption_issues:
lines.append((0, 0, {
'mrp_production_id': order.id,
'product_id': product_id.id,
'consumption': order.consumption,
'product_uom_id': product_id.uom_id.id,
'product_consumed_qty_uom': consumed_qty,
'product_expected_qty_uom': expected_qty
}))
ctx.update({'default_mrp_production_ids': self.ids,
'default_mrp_consumption_warning_line_ids': lines,
'form_view_ref': False})
action = self.env["ir.actions.actions"]._for_xml_id("mrp.action_mrp_consumption_warning")
action['context'] = ctx
return action
def _get_quantity_produced_issues(self):
quantity_issues = []
if self.env.context.get('skip_backorder', False):
return quantity_issues
for order in self:
if not float_is_zero(order._get_quantity_to_backorder(), precision_rounding=order.product_uom_id.rounding):
quantity_issues.append(order)
return quantity_issues
def _action_generate_backorder_wizard(self, quantity_issues):
ctx = self.env.context.copy()
lines = []
for order in quantity_issues:
lines.append((0, 0, {
'mrp_production_id': order.id,
'to_backorder': True
}))
ctx.update({'default_mrp_production_ids': self.ids, 'default_mrp_production_backorder_line_ids': lines})
action = self.env["ir.actions.actions"]._for_xml_id("mrp.action_mrp_production_backorder")
action['context'] = ctx
return action
def action_cancel(self):
""" Cancels production order, unfinished stock moves and set procurement
orders in exception """
self._action_cancel()
return True
def _action_cancel(self):
documents_by_production = {}
for production in self:
documents = defaultdict(list)
for move_raw_id in self.move_raw_ids.filtered(lambda m: m.state not in ('done', 'cancel')):
iterate_key = self._get_document_iterate_key(move_raw_id)
if iterate_key:
document = self.env['stock.picking']._log_activity_get_documents({move_raw_id: (move_raw_id.product_uom_qty, 0)}, iterate_key, 'UP')
for key, value in document.items():
documents[key] += [value]
if documents:
documents_by_production[production] = documents
# log an activity on Parent MO if child MO is cancelled.
finish_moves = production.move_finished_ids.filtered(lambda x: x.state not in ('done', 'cancel'))
if finish_moves:
production._log_downside_manufactured_quantity({finish_move: (production.product_uom_qty, 0.0) for finish_move in finish_moves}, cancel=True)
self.workorder_ids.filtered(lambda x: x.state not in ['done', 'cancel']).action_cancel()
finish_moves = self.move_finished_ids.filtered(lambda x: x.state not in ('done', 'cancel'))
raw_moves = self.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel'))
(finish_moves | raw_moves)._action_cancel()
picking_ids = self.picking_ids.filtered(lambda x: x.state not in ('done', 'cancel'))
picking_ids.action_cancel()
for production, documents in documents_by_production.items():
filtered_documents = {}
for (parent, responsible), rendering_context in documents.items():
if not parent or parent._name == 'stock.picking' and parent.state == 'cancel' or parent == production:
continue
filtered_documents[(parent, responsible)] = rendering_context
production._log_manufacture_exception(filtered_documents, cancel=True)
# In case of a flexible BOM, we don't know from the state of the moves if the MO should
# remain in progress or done. Indeed, if all moves are done/cancel but the quantity produced
# is lower than expected, it might mean:
# - we have used all components but we still want to produce the quantity expected
# - we have used all components and we won't be able to produce the last units
#
# However, if the user clicks on 'Cancel', it is expected that the MO is either done or
# canceled. If the MO is still in progress at this point, it means that the move raws
# are either all done or a mix of done / canceled => the MO should be done.
self.filtered(lambda p: p.state not in ['done', 'cancel'] and p.bom_id.consumption == 'flexible').write({'state': 'done'})
return True
def _get_document_iterate_key(self, move_raw_id):
return move_raw_id.move_orig_ids and 'move_orig_ids' or False
def _cal_price(self, consumed_moves):
self.ensure_one()
return True
def _post_inventory(self, cancel_backorder=False):
moves_to_do, moves_not_to_do = set(), set()
for move in self.move_raw_ids:
if move.state == 'done':
moves_not_to_do.add(move.id)
elif move.state != 'cancel':
moves_to_do.add(move.id)
if move.product_qty == 0.0 and move.quantity_done > 0:
move.product_uom_qty = move.quantity_done
self.env['stock.move'].browse(moves_to_do)._action_done(cancel_backorder=cancel_backorder)
moves_to_do = self.move_raw_ids.filtered(lambda x: x.state == 'done') - self.env['stock.move'].browse(moves_not_to_do)
# Create a dict to avoid calling filtered inside for loops.
moves_to_do_by_order = defaultdict(lambda: self.env['stock.move'], [
(key, self.env['stock.move'].concat(*values))
for key, values in tools_groupby(moves_to_do, key=lambda m: m.raw_material_production_id.id)
])
for order in self:
finish_moves = order.move_finished_ids.filtered(lambda m: m.product_id == order.product_id and m.state not in ('done', 'cancel'))
# the finish move can already be completed by the workorder.
if finish_moves and not finish_moves.quantity_done:
finish_moves._set_quantity_done(float_round(order.qty_producing - order.qty_produced, precision_rounding=order.product_uom_id.rounding, rounding_method='HALF-UP'))
finish_moves.move_line_ids.lot_id = order.lot_producing_id
order._cal_price(moves_to_do_by_order[order.id])
moves_to_finish = self.move_finished_ids.filtered(lambda x: x.state not in ('done', 'cancel'))
moves_to_finish = moves_to_finish._action_done(cancel_backorder=cancel_backorder)
self.action_assign()
for order in self:
consume_move_lines = moves_to_do_by_order[order.id].mapped('move_line_ids')
order.move_finished_ids.move_line_ids.consume_line_ids = [(6, 0, consume_move_lines.ids)]
return True
@api.model
def _get_name_backorder(self, name, sequence):
if not sequence:
return name
seq_back = "-" + "0" * (SIZE_BACK_ORDER_NUMERING - 1 - int(math.log10(sequence))) + str(sequence)
regex = re.compile(r"-\d+$")
if regex.search(name) and sequence > 1:
return regex.sub(seq_back, name)
return name + seq_back
def _get_backorder_mo_vals(self):
self.ensure_one()
if not self.procurement_group_id:
# in the rare case that the procurement group has been removed somehow, create a new one
self.procurement_group_id = self.env["procurement.group"].create({'name': self.name})
next_seq = max(self.procurement_group_id.mrp_production_ids.mapped("backorder_sequence"), default=1)
return {
'name': self._get_name_backorder(self.name, next_seq + 1),
'backorder_sequence': next_seq + 1,
'procurement_group_id': self.procurement_group_id.id,
'move_raw_ids': None,
'move_finished_ids': None,
'product_qty': self._get_quantity_to_backorder(),
'lot_producing_id': False,
'origin': self.origin
}
def _generate_backorder_productions(self, close_mo=True):
backorders = self.env['mrp.production']
bo_to_assign = self.env['mrp.production']
for production in self:
if production.backorder_sequence == 0: # Activate backorder naming
production.backorder_sequence = 1
production.name = self._get_name_backorder(production.name, production.backorder_sequence)
backorder_mo = production.copy(default=production._get_backorder_mo_vals())
if close_mo:
production.move_raw_ids.filtered(lambda m: m.state not in ('done', 'cancel')).write({
'raw_material_production_id': backorder_mo.id,
})
production.move_finished_ids.filtered(lambda m: m.state not in ('done', 'cancel')).write({
'production_id': backorder_mo.id,
})
else:
new_moves_vals = []
for move in production.move_raw_ids | production.move_finished_ids:
if not move.additional:
qty_to_split = move.product_uom_qty - move.unit_factor * production.qty_producing
qty_to_split = move.product_uom._compute_quantity(qty_to_split, move.product_id.uom_id, rounding_method='HALF-UP')
move_vals = move._split(qty_to_split)
if not move_vals:
continue
if move.raw_material_production_id:
move_vals[0]['raw_material_production_id'] = backorder_mo.id
else:
move_vals[0]['production_id'] = backorder_mo.id
new_moves_vals.append(move_vals[0])
self.env['stock.move'].create(new_moves_vals)
backorders |= backorder_mo
if backorder_mo.picking_type_id.reservation_method == 'at_confirm':
bo_to_assign |= backorder_mo
# We need to adapt `duration_expected` on both the original workorders and their
# backordered workorders. To do that, we use the original `duration_expected` and the
# ratio of the quantity really produced and the quantity to produce.
ratio = production.qty_producing / production.product_qty
for workorder in production.workorder_ids:
workorder.duration_expected = workorder.duration_expected * ratio
for workorder in backorder_mo.workorder_ids:
workorder.duration_expected = workorder.duration_expected * (1 - ratio)
# As we have split the moves before validating them, we need to 'remove' the excess reservation
if not close_mo:
raw_moves = self.move_raw_ids.filtered(lambda m: not m.additional)
raw_moves._do_unreserve()
for sml in raw_moves.move_line_ids:
try:
q = self.env['stock.quant']._update_reserved_quantity(sml.product_id, sml.location_id, sml.qty_done,
lot_id=sml.lot_id, package_id=sml.package_id,
owner_id=sml.owner_id, strict=True)
reserved_qty = sum([x[1] for x in q])
reserved_qty = sml.product_id.uom_id._compute_quantity(reserved_qty, sml.product_uom_id)
except UserError:
reserved_qty = 0
sml.with_context(bypass_reservation_update=True).product_uom_qty = reserved_qty
raw_moves._recompute_state()
backorders.action_confirm()
bo_to_assign.action_assign()
# Remove the serial move line without reserved quantity. Post inventory will assigned all the non done moves
# So those move lines are duplicated.
backorders.move_raw_ids.move_line_ids.filtered(lambda ml: ml.product_id.tracking == 'serial' and ml.product_qty == 0).unlink()
wo_to_cancel = self.env['mrp.workorder']
wo_to_update = self.env['mrp.workorder']
for old_wo, wo in zip(self.workorder_ids, backorders.workorder_ids):
if old_wo.qty_remaining == 0:
wo_to_cancel += wo
continue
if not wo_to_update or wo_to_update[-1].production_id != wo.production_id:
wo_to_update += wo
wo.qty_produced = max(old_wo.qty_produced - old_wo.qty_producing, 0)
if wo.product_tracking == 'serial':
wo.qty_producing = 1
else:
wo.qty_producing = wo.qty_remaining
wo_to_cancel.action_cancel()
for wo in wo_to_update:
wo.state = 'ready' if wo.next_work_order_id.production_availability == 'assigned' else 'waiting'
return backorders
def _split_productions(self, amounts=False, cancel_remaning_qty=False, set_consumed_qty=False):
""" Splits productions into productions smaller quantities to produce, i.e. creates
its backorders.
:param dict amounts: a dict with a production as key and a list value containing
the amounts each production split should produce including the original production,
e.g. {mrp.production(1,): [3, 2]} will result in mrp.production(1,) having a product_qty=3
and a new backorder with product_qty=2.
:return: mrp.production records in order of [orig_prod_1, backorder_prod_1,
backorder_prod_2, orig_prod_2, backorder_prod_2, etc.]
"""
def _default_amounts(production):
return [production.qty_producing, production._get_quantity_to_backorder()]
if not amounts:
amounts = {}
for production in self:
mo_amounts = amounts.get(production)
if not mo_amounts:
amounts[production] = _default_amounts(production)
continue
total_amount = sum(mo_amounts)
diff = float_compare(production.product_qty, total_amount, precision_rounding=production.product_uom_id.rounding)
if diff > 0 and not cancel_remaning_qty:
amounts[production].append(production.product_qty - total_amount)
elif diff < 0 or production.state in ['done', 'cancel']:
raise UserError(_("Unable to split with more than the quantity to produce."))
backorder_vals_list = []
initial_qty_by_production = {}
# Create the backorders.
for production in self:
initial_qty_by_production[production] = production.product_qty
if production.backorder_sequence == 0: # Activate backorder naming
production.backorder_sequence = 1
production.name = self._get_name_backorder(production.name, production.backorder_sequence)
production.product_qty = amounts[production][0]
backorder_vals = production.copy_data(default=production._get_backorder_mo_vals())[0]
backorder_qtys = amounts[production][1:]
next_seq = max(production.procurement_group_id.mrp_production_ids.mapped("backorder_sequence"), default=1)
for qty_to_backorder in backorder_qtys:
next_seq += 1
backorder_vals_list.append(dict(
backorder_vals,
product_qty=qty_to_backorder,
name=production._get_name_backorder(production.name, next_seq),
backorder_sequence=next_seq,
state='confirmed'
))
backorders = self.env['mrp.production'].with_context(skip_confirm=True).create(backorder_vals_list)
index = 0
production_to_backorders = {}
production_ids = OrderedSet()
for production in self:
number_of_backorder_created = len(amounts.get(production, _default_amounts(production))) - 1
production_backorders = backorders[index:index + number_of_backorder_created]
production_to_backorders[production] = production_backorders
production_ids.update(production.ids)
production_ids.update(production_backorders.ids)
index += number_of_backorder_created
# Split the `stock.move` among new backorders.
new_moves_vals = []
moves = []
for production in self:
for move in production.move_raw_ids | production.move_finished_ids:
if move.additional:
continue
unit_factor = move.product_uom_qty / initial_qty_by_production[production]
initial_move_vals = move.copy_data(move._get_backorder_move_vals())[0]
move.with_context(do_not_unreserve=True).product_uom_qty = production.product_qty * unit_factor
for backorder in production_to_backorders[production]:
move_vals = dict(
initial_move_vals,
product_uom_qty=backorder.product_qty * unit_factor
)
if move.raw_material_production_id:
move_vals['raw_material_production_id'] = backorder.id
else:
move_vals['production_id'] = backorder.id
new_moves_vals.append(move_vals)
moves.append(move)
backorder_moves = self.env['stock.move'].create(new_moves_vals)
# Split `stock.move.line`s. 2 options for this:
# - do_unreserve -> action_assign
# - Split the reserved amounts manually
# The first option would be easier to maintain since it's less code
# However it could be slower (due to `stock.quant` update) and could
# create inconsistencies in mass production if a new lot higher in a
# FIFO strategy arrives between the reservation and the backorder creation
move_to_backorder_moves = defaultdict(lambda: self.env['stock.move'])
for move, backorder_move in zip(moves, backorder_moves):
move_to_backorder_moves[move] |= backorder_move
move_lines_vals = []
assigned_moves = set()
partially_assigned_moves = set()
move_lines_to_unlink = set()
for initial_move, backorder_moves in move_to_backorder_moves.items():
ml_by_move = []
product_uom = initial_move.product_id.uom_id
for move_line in initial_move.move_line_ids:
available_qty = move_line.product_uom_id._compute_quantity(move_line.product_uom_qty, product_uom)
if float_compare(available_qty, 0, precision_rounding=move_line.product_uom_id.rounding) <= 0:
continue
ml_by_move.append((available_qty, move_line, move_line.copy_data()[0]))
initial_move.move_line_ids.with_context(bypass_reservation_update=True).write({'product_uom_qty': 0})
moves = list(initial_move | backorder_moves)
move = moves and moves.pop(0)
move_qty_to_reserve = move.product_qty
for quantity, move_line, ml_vals in ml_by_move:
while float_compare(quantity, 0, precision_rounding=product_uom.rounding) > 0 and move:
# Do not create `stock.move.line` if there is no initial demand on `stock.move`
taken_qty = min(move_qty_to_reserve, quantity)
taken_qty_uom = product_uom._compute_quantity(taken_qty, move_line.product_uom_id)
if move == initial_move:
move_line.with_context(bypass_reservation_update=True).product_uom_qty = taken_qty_uom
if set_consumed_qty:
move_line.qty_done = taken_qty_uom
elif not float_is_zero(taken_qty_uom, precision_rounding=move_line.product_uom_id.rounding):
new_ml_vals = dict(
ml_vals,
product_uom_qty=taken_qty_uom,
move_id=move.id
)
if set_consumed_qty:
new_ml_vals['qty_done'] = taken_qty_uom
move_lines_vals.append(new_ml_vals)
quantity -= taken_qty
move_qty_to_reserve -= taken_qty
if float_compare(move_qty_to_reserve, 0, precision_rounding=move.product_uom.rounding) <= 0:
assigned_moves.add(move.id)
move = moves and moves.pop(0)
move_qty_to_reserve = move and move.product_qty or 0
# Unreserve the quantity removed from initial `stock.move.line` and
# not assigned to a move anymore. In case of a split smaller than initial
# quantity and fully reserved
if quantity:
self.env['stock.quant']._update_reserved_quantity(
move_line.product_id, move_line.location_id, -quantity,
lot_id=move_line.lot_id, package_id=move_line.package_id,
owner_id=move_line.owner_id, strict=True)
if move and move_qty_to_reserve != move.product_qty:
partially_assigned_moves.add(move.id)
move_lines_to_unlink.update(initial_move.move_line_ids.filtered(
lambda ml: not ml.product_uom_qty and not ml.qty_done).ids)
self.env['stock.move'].browse(assigned_moves).write({'state': 'assigned'})
self.env['stock.move'].browse(partially_assigned_moves).write({'state': 'partially_available'})
# Avoid triggering a useless _recompute_state
self.env['stock.move.line'].browse(move_lines_to_unlink).write({'move_id': False})
self.env['stock.move.line'].browse(move_lines_to_unlink).unlink()
self.env['stock.move.line'].create(move_lines_vals)
# We need to adapt `duration_expected` on both the original workorders and their
# backordered workorders. To do that, we use the original `duration_expected` and the
# ratio of the quantity produced and the quantity to produce.
for production in self:
initial_qty = initial_qty_by_production[production]
initial_workorder_remaining_qty = []
bo = production_to_backorders[production]
# Adapt duration
for workorder in (production | bo).workorder_ids:
workorder.duration_expected = workorder.duration_expected * workorder.production_id.product_qty / initial_qty
# Adapt quantities produced
for workorder in production.workorder_ids:
initial_workorder_remaining_qty.append(max(workorder.qty_produced - workorder.qty_production, 0))
workorder.qty_produced = min(workorder.qty_produced, workorder.qty_production)
workorders_len = len(bo.workorder_ids)
for index, workorder in enumerate(bo.workorder_ids):
remaining_qty = initial_workorder_remaining_qty[index // workorders_len]
if remaining_qty:
workorder.qty_produced = max(workorder.qty_production, remaining_qty)
initial_workorder_remaining_qty[index % workorders_len] = max(remaining_qty - workorder.qty_produced, 0)
backorders._action_confirm_mo_backorders()
return self.env['mrp.production'].browse(production_ids)
def _action_confirm_mo_backorders(self):
self.workorder_ids._action_confirm()
def button_mark_done(self):
self._button_mark_done_sanity_checks()
if not self.env.context.get('button_mark_done_production_ids'):
self = self.with_context(button_mark_done_production_ids=self.ids)
res = self._pre_button_mark_done()
if res is not True:
return res
if self.env.context.get('mo_ids_to_backorder'):
productions_to_backorder = self.browse(self.env.context['mo_ids_to_backorder'])
productions_not_to_backorder = self - productions_to_backorder
close_mo = False
else:
productions_not_to_backorder = self
productions_to_backorder = self.env['mrp.production']
close_mo = True
self.workorder_ids.button_finish()
backorders = productions_to_backorder._generate_backorder_productions(close_mo=close_mo)
productions_not_to_backorder._post_inventory(cancel_backorder=True)
productions_to_backorder._post_inventory(cancel_backorder=True)
# if completed products make other confirmed/partially_available moves available, assign them
done_move_finished_ids = (productions_to_backorder.move_finished_ids | productions_not_to_backorder.move_finished_ids).filtered(lambda m: m.state == 'done')
done_move_finished_ids._trigger_assign()
# Moves without quantity done are not posted => set them as done instead of canceling. In
# case the user edits the MO later on and sets some consumed quantity on those, we do not
# want the move lines to be canceled.
(productions_not_to_backorder.move_raw_ids | productions_not_to_backorder.move_finished_ids).filtered(lambda x: x.state not in ('done', 'cancel')).write({
'state': 'done',
'product_uom_qty': 0.0,
})
for production in self:
production.write({
'date_finished': fields.Datetime.now(),
'product_qty': production.qty_produced,
'priority': '0',
'is_locked': True,
'state': 'done',
})
for workorder in self.workorder_ids.filtered(lambda w: w.state not in ('done', 'cancel')):
workorder.duration_expected = workorder._get_duration_expected()
if not backorders:
if self.env.context.get('from_workorder'):
return {
'type': 'ir.actions.act_window',
'res_model': 'mrp.production',
'views': [[self.env.ref('mrp.mrp_production_form_view').id, 'form']],
'res_id': self.id,
'target': 'main',
}
return True
context = self.env.context.copy()
context = {k: v for k, v in context.items() if not k.startswith('default_')}
for k, v in context.items():
if k.startswith('skip_'):
context[k] = False
action = {
'res_model': 'mrp.production',
'type': 'ir.actions.act_window',
'context': dict(context, mo_ids_to_backorder=None, button_mark_done_production_ids=None)
}
if len(backorders) == 1:
action.update({
'view_mode': 'form',
'res_id': backorders[0].id,
})
else:
action.update({
'name': _("Backorder MO"),
'domain': [('id', 'in', backorders.ids)],
'view_mode': 'tree,form',
})
return action
def _pre_button_mark_done(self):
productions_to_immediate = self._check_immediate()
if productions_to_immediate:
return productions_to_immediate._action_generate_immediate_wizard()
for production in self:
if float_is_zero(production.qty_producing, precision_rounding=production.product_uom_id.rounding):
raise UserError(_('The quantity to produce must be positive!'))
if production.move_raw_ids and not any(production.move_raw_ids.mapped('quantity_done')):
raise UserError(_("You must indicate a non-zero amount consumed for at least one of your components"))
consumption_issues = self._get_consumption_issues()
if consumption_issues:
return self._action_generate_consumption_wizard(consumption_issues)
quantity_issues = self._get_quantity_produced_issues()
if quantity_issues:
return self._action_generate_backorder_wizard(quantity_issues)
return True
def _button_mark_done_sanity_checks(self):
self._check_company()
for order in self:
order._check_sn_uniqueness()
def do_unreserve(self):
self.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel'))._do_unreserve()
def button_scrap(self):
self.ensure_one()
return {
'name': _('Scrap'),
'view_mode': 'form',
'res_model': 'stock.scrap',
'view_id': self.env.ref('stock.stock_scrap_form_view2').id,
'type': 'ir.actions.act_window',
'context': {'default_production_id': self.id,
'product_ids': (self.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel')) | self.move_finished_ids.filtered(lambda x: x.state == 'done')).mapped('product_id').ids,
'default_company_id': self.company_id.id
},
'target': 'new',
}
def action_see_move_scrap(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_stock_scrap")
action['domain'] = [('production_id', '=', self.id)]
action['context'] = dict(self._context, default_origin=self.name)
return action
@api.model
def get_empty_list_help(self, help):
self = self.with_context(
empty_list_help_document_name=_("manufacturing order"),
)
return super(MrpProduction, self).get_empty_list_help(help)
def _log_downside_manufactured_quantity(self, moves_modification, cancel=False):
def _keys_in_sorted(move):
""" sort by picking and the responsible for the product the
move.
"""
return (move.picking_id.id, move.product_id.responsible_id.id)
def _keys_in_groupby(move):
""" group by picking and the responsible for the product the
move.
"""
return (move.picking_id, move.product_id.responsible_id)
def _render_note_exception_quantity_mo(rendering_context):
values = {
'production_order': self,
'order_exceptions': rendering_context,
'impacted_pickings': False,
'cancel': cancel
}
return self.env.ref('mrp.exception_on_mo')._render(values=values)
documents = self.env['stock.picking']._log_activity_get_documents(moves_modification, 'move_dest_ids', 'DOWN', _keys_in_sorted, _keys_in_groupby)
documents = self.env['stock.picking']._less_quantities_than_expected_add_documents(moves_modification, documents)
self.env['stock.picking']._log_activity(_render_note_exception_quantity_mo, documents)
def _log_manufacture_exception(self, documents, cancel=False):
def _render_note_exception_quantity_mo(rendering_context):
visited_objects = []
order_exceptions = {}
for exception in rendering_context:
order_exception, visited = exception
order_exceptions.update(order_exception)
visited_objects += visited
visited_objects = [sm for sm in visited_objects if sm._name == 'stock.move']
impacted_object = []
if visited_objects:
visited_objects = self.env[visited_objects[0]._name].concat(*visited_objects)
visited_objects |= visited_objects.mapped('move_orig_ids')
impacted_object = visited_objects.filtered(lambda m: m.state not in ('done', 'cancel')).mapped('picking_id')
values = {
'production_order': self,
'order_exceptions': order_exceptions,
'impacted_object': impacted_object,
'cancel': cancel
}
return self.env.ref('mrp.exception_on_mo')._render(values=values)
self.env['stock.picking']._log_activity(_render_note_exception_quantity_mo, documents)
def button_unbuild(self):
self.ensure_one()
return {
'name': _('Unbuild: %s', self.product_id.display_name),
'view_mode': 'form',
'res_model': 'mrp.unbuild',
'view_id': self.env.ref('mrp.mrp_unbuild_form_view_simplified').id,
'type': 'ir.actions.act_window',
'context': {'default_product_id': self.product_id.id,
'default_mo_id': self.id,
'default_company_id': self.company_id.id,
'default_location_id': self.location_dest_id.id,
'default_location_dest_id': self.location_src_id.id,
'create': False, 'edit': False},
'target': 'new',
}
def action_serial_mass_produce_wizard(self):
self.ensure_one()
self._check_company()
if self.state != 'confirmed':
return
if self.product_id.tracking != 'serial':
return
dummy, dummy, missing_components, multiple_lot_components = self._check_serial_mass_produce_components()
message = ""
if missing_components:
message += _("Make sure enough quantities of these components are reserved to carry on production:\n")
message += "\n".join(component.name for component in missing_components)
if multiple_lot_components:
if message:
message += "\n"
message += _("Component Lots must be unique for mass production. Please review reservation for:\n")
message += "\n".join(component.name for component in multiple_lot_components)
if message:
raise UserError(message)
next_serial = self.env['stock.production.lot']._get_next_serial(self.company_id, self.product_id)
action = self.env["ir.actions.actions"]._for_xml_id("mrp.act_assign_serial_numbers_production")
action['context'] = {
'default_production_id': self.id,
'default_expected_qty': self.product_qty,
'default_next_serial_number': next_serial,
'default_next_serial_count': self.product_qty - self.qty_produced,
}
return action
@api.model
def _prepare_procurement_group_vals(self, values):
return {'name': values['name']}
def _get_quantity_to_backorder(self):
self.ensure_one()
return max(self.product_qty - self.qty_producing, 0)
def _check_sn_uniqueness(self):
""" Alert the user if the serial number as already been consumed/produced """
if self.product_tracking == 'serial' and self.lot_producing_id:
if self._is_finished_sn_already_produced(self.lot_producing_id):
raise UserError(_('This serial number for product %s has already been produced', self.product_id.name))
for move in self.move_finished_ids:
if move.has_tracking != 'serial' or move.product_id == self.product_id:
continue
for move_line in move.move_line_ids:
if self._is_finished_sn_already_produced(move_line.lot_id, excluded_sml=move_line):
raise UserError(_('The serial number %(number)s used for byproduct %(product_name)s has already been produced',
number=move_line.lot_id.name, product_name=move_line.product_id.name))
for move in self.move_raw_ids:
if move.has_tracking != 'serial':
continue
for move_line in move.move_line_ids:
if float_is_zero(move_line.qty_done, precision_rounding=move_line.product_uom_id.rounding):
continue
message = _('The serial number %(number)s used for component %(component)s has already been consumed',
number=move_line.lot_id.name,
component=move_line.product_id.name)
co_prod_move_lines = self.move_raw_ids.move_line_ids
# Check presence of same sn in previous productions
duplicates = self.env['stock.move.line'].search_count([
('lot_id', '=', move_line.lot_id.id),
('qty_done', '=', 1),
('state', '=', 'done'),
('location_dest_id.usage', '=', 'production'),
('production_id', '!=', False),
])
if duplicates:
# Maybe some move lines have been compensated by unbuild
duplicates_returned = move.product_id._count_returned_sn_products(move_line.lot_id)
removed = self.env['stock.move.line'].search_count([
('lot_id', '=', move_line.lot_id.id),
('state', '=', 'done'),
('location_dest_id.scrap_location', '=', True)
])
unremoved = self.env['stock.move.line'].search_count([
('lot_id', '=', move_line.lot_id.id),
('state', '=', 'done'),
('location_id.scrap_location', '=', True),
('location_dest_id.scrap_location', '=', False),
])
# Either removed or unbuild
if not ((duplicates_returned or removed) and duplicates - duplicates_returned - removed + unremoved == 0):
raise UserError(message)
# Check presence of same sn in current production
duplicates = co_prod_move_lines.filtered(lambda ml: ml.qty_done and ml.lot_id == move_line.lot_id) - move_line
if duplicates:
raise UserError(message)
def _is_finished_sn_already_produced(self, lot, excluded_sml=None):
excluded_sml = excluded_sml or self.env['stock.move.line']
domain = [
('lot_id', '=', lot.id),
('qty_done', '=', 1),
('state', '=', 'done')
]
co_prod_move_lines = self.move_finished_ids.move_line_ids - excluded_sml
domain_unbuild = domain + [
('production_id', '=', False),
('location_dest_id.usage', '=', 'production')
]
# Check presence of same sn in previous productions
duplicates = self.env['stock.move.line'].search_count(domain + [
('location_id.usage', '=', 'production')
])
if duplicates:
# Maybe some move lines have been compensated by unbuild
duplicates_unbuild = self.env['stock.move.line'].search_count(domain_unbuild + [
('move_id.unbuild_id', '!=', False)
])
removed = self.env['stock.move.line'].search_count([
('lot_id', '=', lot.id),
('state', '=', 'done'),
('location_dest_id.scrap_location', '=', True)
])
# Either removed or unbuild
if not ((duplicates_unbuild or removed) and duplicates - duplicates_unbuild - removed == 0):
return True
# Check presence of same sn in current production
duplicates = co_prod_move_lines.filtered(lambda ml: ml.qty_done and ml.lot_id == lot)
return bool(duplicates)
def _check_immediate(self):
immediate_productions = self.browse()
if self.env.context.get('skip_immediate'):
return immediate_productions
pd = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for production in self:
if all(float_is_zero(ml.qty_done, precision_digits=pd) for
ml in production.move_raw_ids.move_line_ids.filtered(lambda m: m.state not in ('done', 'cancel'))
) and float_is_zero(production.qty_producing, precision_digits=pd):
immediate_productions |= production
return immediate_productions
def _check_serial_mass_produce_components(self):
have_serial_components = False
have_lot_components = False
missing_components = set()
multiple_lot_components = set()
for production in self:
have_serial_components |= any(move.product_id.tracking == 'serial' for move in production.move_raw_ids)
have_lot_components |= any(move.product_id.tracking == 'lot' for move in production.move_raw_ids)
missing_components.update([move.product_id for move in production.move_raw_ids if float_compare(move.reserved_availability, move.product_uom_qty, precision_rounding=move.product_uom.rounding) < 0])
components = {}
for move in production.move_raw_ids:
if move.product_id.tracking != 'lot':
continue
lot_ids = move.mapped('move_line_ids.lot_id.id')
if not lot_ids:
continue
components.setdefault(move.product_id, set()).update(lot_ids)
multiple_lot_components.update([p for p, l in components.items() if len(l) != 1])
return (have_serial_components, have_lot_components, missing_components, multiple_lot_components)
def _generate_backorder_productions_multi(self, serial_numbers, cancel_remaining_quantities=False):
warnings.warn("Method '_generate_backorder_productions_multi()' is deprecated, use _split_productions() instead.", DeprecationWarning)
self._split_productions({self: [1] * len(serial_numbers)}, cancel_remaining_quantities)
| 53.603687 | 116,320 |
45,858 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from collections import defaultdict
import json
from odoo import api, fields, models, _, SUPERUSER_ID
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_round, format_datetime
class MrpWorkorder(models.Model):
_name = 'mrp.workorder'
_description = 'Work Order'
def _read_group_workcenter_id(self, workcenters, domain, order):
workcenter_ids = self.env.context.get('default_workcenter_id')
if not workcenter_ids:
workcenter_ids = workcenters._search([], order=order, access_rights_uid=SUPERUSER_ID)
return workcenters.browse(workcenter_ids)
name = fields.Char(
'Work Order', required=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]})
workcenter_id = fields.Many2one(
'mrp.workcenter', 'Work Center', required=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)], 'progress': [('readonly', True)]},
group_expand='_read_group_workcenter_id', check_company=True)
working_state = fields.Selection(
string='Workcenter Status', related='workcenter_id.working_state',
help='Technical: used in views only')
product_id = fields.Many2one(related='production_id.product_id', readonly=True, store=True, check_company=True)
product_tracking = fields.Selection(related="product_id.tracking")
product_uom_id = fields.Many2one('uom.uom', 'Unit of Measure', required=True, readonly=True)
production_id = fields.Many2one('mrp.production', 'Manufacturing Order', required=True, check_company=True, readonly=True)
production_availability = fields.Selection(
string='Stock Availability', readonly=True,
related='production_id.reservation_state', store=True,
help='Technical: used in views and domains only.')
production_state = fields.Selection(
string='Production State', readonly=True,
related='production_id.state',
help='Technical: used in views only.')
production_bom_id = fields.Many2one('mrp.bom', related='production_id.bom_id')
qty_production = fields.Float('Original Production Quantity', readonly=True, related='production_id.product_qty')
company_id = fields.Many2one(related='production_id.company_id')
qty_producing = fields.Float(
compute='_compute_qty_producing', inverse='_set_qty_producing',
string='Currently Produced Quantity', digits='Product Unit of Measure')
qty_remaining = fields.Float('Quantity To Be Produced', compute='_compute_qty_remaining', digits='Product Unit of Measure')
qty_produced = fields.Float(
'Quantity', default=0.0,
readonly=True,
digits='Product Unit of Measure',
copy=False,
help="The number of products already handled by this work order")
is_produced = fields.Boolean(string="Has Been Produced",
compute='_compute_is_produced')
state = fields.Selection([
('pending', 'Waiting for another WO'),
('waiting', 'Waiting for components'),
('ready', 'Ready'),
('progress', 'In Progress'),
('done', 'Finished'),
('cancel', 'Cancelled')], string='Status',
compute='_compute_state', store=True,
default='pending', copy=False, readonly=True, index=True)
leave_id = fields.Many2one(
'resource.calendar.leaves',
help='Slot into workcenter calendar once planned',
check_company=True, copy=False)
date_planned_start = fields.Datetime(
'Scheduled Start Date',
compute='_compute_dates_planned',
inverse='_set_dates_planned',
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
store=True, copy=False)
date_planned_finished = fields.Datetime(
'Scheduled End Date',
compute='_compute_dates_planned',
inverse='_set_dates_planned',
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
store=True, copy=False)
date_start = fields.Datetime(
'Start Date', copy=False,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]})
date_finished = fields.Datetime(
'End Date', copy=False,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]})
duration_expected = fields.Float(
'Expected Duration', digits=(16, 2), default=60.0,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="Expected duration (in minutes)")
duration = fields.Float(
'Real Duration', compute='_compute_duration', inverse='_set_duration',
readonly=False, store=True, copy=False)
duration_unit = fields.Float(
'Duration Per Unit', compute='_compute_duration',
group_operator="avg", readonly=True, store=True)
duration_percent = fields.Integer(
'Duration Deviation (%)', compute='_compute_duration',
group_operator="avg", readonly=True, store=True)
progress = fields.Float('Progress Done (%)', digits=(16, 2), compute='_compute_progress')
operation_id = fields.Many2one(
'mrp.routing.workcenter', 'Operation', check_company=True)
# Should be used differently as BoM can change in the meantime
worksheet = fields.Binary(
'Worksheet', related='operation_id.worksheet', readonly=True)
worksheet_type = fields.Selection(
string='Worksheet Type', related='operation_id.worksheet_type', readonly=True)
worksheet_google_slide = fields.Char(
'Worksheet URL', related='operation_id.worksheet_google_slide', readonly=True)
operation_note = fields.Html("Description", related='operation_id.note', readonly=True)
move_raw_ids = fields.One2many(
'stock.move', 'workorder_id', 'Raw Moves',
domain=[('raw_material_production_id', '!=', False), ('production_id', '=', False)])
move_finished_ids = fields.One2many(
'stock.move', 'workorder_id', 'Finished Moves',
domain=[('raw_material_production_id', '=', False), ('production_id', '!=', False)])
move_line_ids = fields.One2many(
'stock.move.line', 'workorder_id', 'Moves to Track',
help="Inventory moves for which you must scan a lot number at this work order")
finished_lot_id = fields.Many2one(
'stock.production.lot', string='Lot/Serial Number', compute='_compute_finished_lot_id',
inverse='_set_finished_lot_id', domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]",
check_company=True, search='_search_finished_lot_id')
time_ids = fields.One2many(
'mrp.workcenter.productivity', 'workorder_id', copy=False)
is_user_working = fields.Boolean(
'Is the Current User Working', compute='_compute_working_users',
help="Technical field indicating whether the current user is working. ")
working_user_ids = fields.One2many('res.users', string='Working user on this work order.', compute='_compute_working_users')
last_working_user_id = fields.One2many('res.users', string='Last user that worked on this work order.', compute='_compute_working_users')
costs_hour = fields.Float(
string='Cost per hour',
help='Technical field to store the hourly cost of workcenter at time of work order completion (i.e. to keep a consistent cost).',
default=0.0, group_operator="avg")
next_work_order_id = fields.Many2one('mrp.workorder', "Next Work Order", check_company=True)
scrap_ids = fields.One2many('stock.scrap', 'workorder_id')
scrap_count = fields.Integer(compute='_compute_scrap_move_count', string='Scrap Move')
production_date = fields.Datetime('Production Date', related='production_id.date_planned_start', store=True)
json_popover = fields.Char('Popover Data JSON', compute='_compute_json_popover')
show_json_popover = fields.Boolean('Show Popover?', compute='_compute_json_popover')
consumption = fields.Selection(related='production_id.consumption')
@api.depends('production_availability')
def _compute_state(self):
# Force the flush of the production_availability, the wo state is modify in the _compute_reservation_state
# It is a trick to force that the state of workorder is computed as the end of the
# cyclic depends with the mo.state, mo.reservation_state and wo.state
for workorder in self:
if workorder.state not in ('waiting', 'ready'):
continue
if workorder.production_id.reservation_state not in ('waiting', 'confirmed', 'assigned'):
continue
if workorder.production_id.reservation_state == 'assigned' and workorder.state == 'waiting':
workorder.state = 'ready'
elif workorder.production_id.reservation_state != 'assigned' and workorder.state == 'ready':
workorder.state = 'waiting'
@api.depends('production_state', 'date_planned_start', 'date_planned_finished')
def _compute_json_popover(self):
previous_wo_data = self.env['mrp.workorder'].read_group(
[('next_work_order_id', 'in', self.ids)],
['ids:array_agg(id)', 'date_planned_start:max', 'date_planned_finished:max'],
['next_work_order_id'])
previous_wo_dict = dict([(x['next_work_order_id'][0], {
'id': x['ids'][0],
'date_planned_start': x['date_planned_start'],
'date_planned_finished': x['date_planned_finished']})
for x in previous_wo_data])
if self.ids:
conflicted_dict = self._get_conflicted_workorder_ids()
for wo in self:
infos = []
if not wo.date_planned_start or not wo.date_planned_finished or not wo.ids:
wo.show_json_popover = False
wo.json_popover = False
continue
if wo.state in ('pending', 'waiting', 'ready'):
previous_wo = previous_wo_dict.get(wo.id)
prev_start = previous_wo and previous_wo['date_planned_start'] or False
prev_finished = previous_wo and previous_wo['date_planned_finished'] or False
if wo.state == 'pending' and prev_start and not (prev_start > wo.date_planned_start):
infos.append({
'color': 'text-primary',
'msg': _("Waiting the previous work order, planned from %(start)s to %(end)s",
start=format_datetime(self.env, prev_start, dt_format=False),
end=format_datetime(self.env, prev_finished, dt_format=False))
})
if wo.date_planned_finished < fields.Datetime.now():
infos.append({
'color': 'text-warning',
'msg': _("The work order should have already been processed.")
})
if prev_start and prev_start > wo.date_planned_start:
infos.append({
'color': 'text-danger',
'msg': _("Scheduled before the previous work order, planned from %(start)s to %(end)s",
start=format_datetime(self.env, prev_start, dt_format=False),
end=format_datetime(self.env, prev_finished, dt_format=False))
})
if conflicted_dict.get(wo.id):
infos.append({
'color': 'text-danger',
'msg': _("Planned at the same time as other workorder(s) at %s", wo.workcenter_id.display_name)
})
color_icon = infos and infos[-1]['color'] or False
wo.show_json_popover = bool(color_icon)
wo.json_popover = json.dumps({
'infos': infos,
'color': color_icon,
'icon': 'fa-exclamation-triangle' if color_icon in ['text-warning', 'text-danger'] else 'fa-info-circle',
'replan': color_icon not in [False, 'text-primary']
})
@api.depends('production_id.lot_producing_id')
def _compute_finished_lot_id(self):
for workorder in self:
workorder.finished_lot_id = workorder.production_id.lot_producing_id
def _search_finished_lot_id(self, operator, value):
return [('production_id.lot_producing_id', operator, value)]
def _set_finished_lot_id(self):
for workorder in self:
workorder.production_id.lot_producing_id = workorder.finished_lot_id
@api.depends('production_id.qty_producing')
def _compute_qty_producing(self):
for workorder in self:
workorder.qty_producing = workorder.production_id.qty_producing
def _set_qty_producing(self):
for workorder in self:
if workorder.qty_producing != 0 and workorder.production_id.qty_producing != workorder.qty_producing:
workorder.production_id.qty_producing = workorder.qty_producing
workorder.production_id._set_qty_producing()
# Both `date_planned_start` and `date_planned_finished` are related fields on `leave_id`. Let's say
# we slide a workorder on a gantt view, a single call to write is made with both
# fields Changes. As the ORM doesn't batch the write on related fields and instead
# makes multiple call, the constraint check_dates() is raised.
# That's why the compute and set methods are needed. to ensure the dates are updated
# in the same time.
@api.depends('leave_id')
def _compute_dates_planned(self):
for workorder in self:
workorder.date_planned_start = workorder.leave_id.date_from
workorder.date_planned_finished = workorder.leave_id.date_to
def _set_dates_planned(self):
if not self[0].date_planned_start or not self[0].date_planned_finished:
if not self.leave_id:
return
raise UserError(_("It is not possible to unplan one single Work Order. "
"You should unplan the Manufacturing Order instead in order to unplan all the linked operations."))
date_from = self[0].date_planned_start
date_to = self[0].date_planned_finished
to_write = self.env['mrp.workorder']
for wo in self.sudo():
if wo.leave_id:
to_write |= wo
else:
wo.leave_id = wo.env['resource.calendar.leaves'].create({
'name': wo.display_name,
'calendar_id': wo.workcenter_id.resource_calendar_id.id,
'date_from': date_from,
'date_to': date_to,
'resource_id': wo.workcenter_id.resource_id.id,
'time_type': 'other',
})
to_write.leave_id.write({
'date_from': date_from,
'date_to': date_to,
})
def name_get(self):
res = []
for wo in self:
if len(wo.production_id.workorder_ids) == 1:
res.append((wo.id, "%s - %s - %s" % (wo.production_id.name, wo.product_id.name, wo.name)))
else:
res.append((wo.id, "%s - %s - %s - %s" % (wo.production_id.workorder_ids.ids.index(wo._origin.id) + 1, wo.production_id.name, wo.product_id.name, wo.name)))
return res
def unlink(self):
# Removes references to workorder to avoid Validation Error
(self.mapped('move_raw_ids') | self.mapped('move_finished_ids')).write({'workorder_id': False})
self.mapped('leave_id').unlink()
mo_dirty = self.production_id.filtered(lambda mo: mo.state in ("confirmed", "progress", "to_close"))
previous_wos = self.env['mrp.workorder'].search([
('next_work_order_id', 'in', self.ids),
('id', 'not in', self.ids)
])
for pw in previous_wos:
while pw.next_work_order_id and pw.next_work_order_id in self:
pw.next_work_order_id = pw.next_work_order_id.next_work_order_id
res = super().unlink()
# We need to go through `_action_confirm` for all workorders of the current productions to
# make sure the links between them are correct (`next_work_order_id` could be obsolete now).
mo_dirty.workorder_ids._action_confirm()
return res
@api.depends('production_id.product_qty', 'qty_produced', 'production_id.product_uom_id')
def _compute_is_produced(self):
self.is_produced = False
for order in self.filtered(lambda p: p.production_id and p.production_id.product_uom_id):
rounding = order.production_id.product_uom_id.rounding
order.is_produced = float_compare(order.qty_produced, order.production_id.product_qty, precision_rounding=rounding) >= 0
@api.depends('time_ids.duration', 'qty_produced')
def _compute_duration(self):
for order in self:
order.duration = sum(order.time_ids.mapped('duration'))
order.duration_unit = round(order.duration / max(order.qty_produced, 1), 2) # rounding 2 because it is a time
if order.duration_expected:
order.duration_percent = max(-2147483648, min(2147483647, 100 * (order.duration_expected - order.duration) / order.duration_expected))
else:
order.duration_percent = 0
def _set_duration(self):
def _float_duration_to_second(duration):
minutes = duration // 1
seconds = (duration % 1) * 60
return minutes * 60 + seconds
for order in self:
old_order_duation = sum(order.time_ids.mapped('duration'))
new_order_duration = order.duration
if new_order_duration == old_order_duation:
continue
delta_duration = new_order_duration - old_order_duation
if delta_duration > 0:
date_start = datetime.now() - timedelta(seconds=_float_duration_to_second(delta_duration))
self.env['mrp.workcenter.productivity'].create(
order._prepare_timeline_vals(delta_duration, date_start, datetime.now())
)
else:
duration_to_remove = abs(delta_duration)
timelines = order.time_ids.sorted(lambda t: t.date_start)
timelines_to_unlink = self.env['mrp.workcenter.productivity']
for timeline in timelines:
if duration_to_remove <= 0.0:
break
if timeline.duration <= duration_to_remove:
duration_to_remove -= timeline.duration
timelines_to_unlink |= timeline
else:
new_time_line_duration = timeline.duration - duration_to_remove
timeline.date_start = timeline.date_end - timedelta(seconds=_float_duration_to_second(new_time_line_duration))
break
timelines_to_unlink.unlink()
@api.depends('duration', 'duration_expected', 'state')
def _compute_progress(self):
for order in self:
if order.state == 'done':
order.progress = 100
elif order.duration_expected:
order.progress = order.duration * 100 / order.duration_expected
else:
order.progress = 0
def _compute_working_users(self):
""" Checks whether the current user is working, all the users currently working and the last user that worked. """
for order in self:
order.working_user_ids = [(4, order.id) for order in order.time_ids.filtered(lambda time: not time.date_end).sorted('date_start').mapped('user_id')]
if order.working_user_ids:
order.last_working_user_id = order.working_user_ids[-1]
elif order.time_ids:
order.last_working_user_id = order.time_ids.filtered('date_end').sorted('date_end')[-1].user_id if order.time_ids.filtered('date_end') else order.time_ids[-1].user_id
else:
order.last_working_user_id = False
if order.time_ids.filtered(lambda x: (x.user_id.id == self.env.user.id) and (not x.date_end) and (x.loss_type in ('productive', 'performance'))):
order.is_user_working = True
else:
order.is_user_working = False
def _compute_scrap_move_count(self):
data = self.env['stock.scrap'].read_group([('workorder_id', 'in', self.ids)], ['workorder_id'], ['workorder_id'])
count_data = dict((item['workorder_id'][0], item['workorder_id_count']) for item in data)
for workorder in self:
workorder.scrap_count = count_data.get(workorder.id, 0)
@api.onchange('operation_id')
def _onchange_operation_id(self):
if self.operation_id:
self.name = self.operation_id.name
self.workcenter_id = self.operation_id.workcenter_id.id
@api.onchange('date_planned_start', 'duration_expected', 'workcenter_id')
def _onchange_date_planned_start(self):
if self.date_planned_start and self.duration_expected and self.workcenter_id:
self.date_planned_finished = self._calculate_date_planned_finished()
def _calculate_date_planned_finished(self, date_planned_start=False):
return self.workcenter_id.resource_calendar_id.plan_hours(
self.duration_expected / 60.0, date_planned_start or self.date_planned_start,
compute_leaves=True, domain=[('time_type', 'in', ['leave', 'other'])]
)
@api.onchange('date_planned_finished')
def _onchange_date_planned_finished(self):
if self.date_planned_start and self.date_planned_finished:
self.duration_expected = self._calculate_duration_expected()
def _calculate_duration_expected(self, date_planned_start=False, date_planned_finished=False):
interval = self.workcenter_id.resource_calendar_id.get_work_duration_data(
date_planned_start or self.date_planned_start, date_planned_finished or self.date_planned_finished,
domain=[('time_type', 'in', ['leave', 'other'])]
)
return interval['hours'] * 60
@api.onchange('operation_id', 'workcenter_id', 'qty_production')
def _onchange_expected_duration(self):
self.duration_expected = self._get_duration_expected()
@api.onchange('finished_lot_id')
def _onchange_finished_lot_id(self):
res = self.production_id._can_produce_serial_number(sn=self.finished_lot_id)
if res is not True:
return res
def write(self, values):
if 'production_id' in values:
raise UserError(_('You cannot link this work order to another manufacturing order.'))
if 'workcenter_id' in values:
for workorder in self:
if workorder.workcenter_id.id != values['workcenter_id']:
if workorder.state in ('progress', 'done', 'cancel'):
raise UserError(_('You cannot change the workcenter of a work order that is in progress or done.'))
workorder.leave_id.resource_id = self.env['mrp.workcenter'].browse(values['workcenter_id']).resource_id
if 'date_planned_start' in values or 'date_planned_finished' in values:
for workorder in self:
start_date = fields.Datetime.to_datetime(values.get('date_planned_start', workorder.date_planned_start))
end_date = fields.Datetime.to_datetime(values.get('date_planned_finished', workorder.date_planned_finished))
if start_date and end_date and start_date > end_date:
raise UserError(_('The planned end date of the work order cannot be prior to the planned start date, please correct this to save the work order.'))
if 'duration_expected' not in values and not self.env.context.get('bypass_duration_calculation'):
if values.get('date_planned_start') and values.get('date_planned_finished'):
computed_finished_time = workorder._calculate_date_planned_finished(start_date)
values['date_planned_finished'] = computed_finished_time
elif start_date and end_date:
computed_duration = workorder._calculate_duration_expected(date_planned_start=start_date, date_planned_finished=end_date)
values['duration_expected'] = computed_duration
# Update MO dates if the start date of the first WO or the
# finished date of the last WO is update.
if workorder == workorder.production_id.workorder_ids[0] and 'date_planned_start' in values:
if values['date_planned_start']:
workorder.production_id.with_context(force_date=True).write({
'date_planned_start': fields.Datetime.to_datetime(values['date_planned_start'])
})
if workorder == workorder.production_id.workorder_ids[-1] and 'date_planned_finished' in values:
if values['date_planned_finished']:
workorder.production_id.with_context(force_date=True).write({
'date_planned_finished': fields.Datetime.to_datetime(values['date_planned_finished'])
})
return super(MrpWorkorder, self).write(values)
@api.model_create_multi
def create(self, values):
res = super().create(values)
# Auto-confirm manually added workorders.
# We need to go through `_action_confirm` for all workorders of the current productions to
# make sure the links between them are correct.
if self.env.context.get('skip_confirm'):
return res
to_confirm = res.filtered(lambda wo: wo.production_id.state in ("confirmed", "progress", "to_close"))
to_confirm = to_confirm.production_id.workorder_ids
to_confirm._action_confirm()
return res
def _action_confirm(self):
workorders_by_production = defaultdict(lambda: self.env['mrp.workorder'])
for workorder in self:
workorders_by_production[workorder.production_id] |= workorder
for production, workorders in workorders_by_production.items():
workorders_by_bom = defaultdict(lambda: self.env['mrp.workorder'])
bom = self.env['mrp.bom']
moves = production.move_raw_ids | production.move_finished_ids
for workorder in workorders:
bom = workorder.operation_id.bom_id or workorder.production_id.bom_id
previous_workorder = workorders_by_bom[bom][-1:]
previous_workorder.next_work_order_id = workorder.id
workorders_by_bom[bom] |= workorder
moves.filtered(lambda m: m.operation_id == workorder.operation_id).write({
'workorder_id': workorder.id
})
exploded_boms, dummy = production.bom_id.explode(production.product_id, 1, picking_type=production.bom_id.picking_type_id)
exploded_boms = {b[0]: b[1] for b in exploded_boms}
for move in moves:
if move.workorder_id:
continue
bom = move.bom_line_id.bom_id
while bom and bom not in workorders_by_bom:
bom_data = exploded_boms.get(bom, {})
bom = bom_data.get('parent_line') and bom_data['parent_line'].bom_id or False
if bom in workorders_by_bom:
move.write({
'workorder_id': workorders_by_bom[bom][-1:].id
})
else:
move.write({
'workorder_id': workorders_by_bom[production.bom_id][-1:].id
})
for workorders in workorders_by_bom.values():
if not workorders:
continue
if workorders[0].state == 'pending':
workorders[0].state = 'ready' if workorders[0].production_availability == 'assigned' else 'waiting'
for workorder in workorders:
workorder._start_nextworkorder()
def _get_byproduct_move_to_update(self):
return self.production_id.move_finished_ids.filtered(lambda x: (x.product_id.id != self.production_id.product_id.id) and (x.state not in ('done', 'cancel')))
def _start_nextworkorder(self):
if self.state == 'done':
next_order = self.next_work_order_id
while next_order and next_order.state == 'cancel':
next_order = next_order.next_work_order_id
if next_order.state == 'pending':
next_order.state = 'ready' if next_order.production_availability == 'assigned' else 'waiting'
@api.model
def gantt_unavailability(self, start_date, end_date, scale, group_bys=None, rows=None):
"""Get unavailabilities data to display in the Gantt view."""
workcenter_ids = set()
def traverse_inplace(func, row, **kargs):
res = func(row, **kargs)
if res:
kargs.update(res)
for row in row.get('rows'):
traverse_inplace(func, row, **kargs)
def search_workcenter_ids(row):
if row.get('groupedBy') and row.get('groupedBy')[0] == 'workcenter_id' and row.get('resId'):
workcenter_ids.add(row.get('resId'))
for row in rows:
traverse_inplace(search_workcenter_ids, row)
start_datetime = fields.Datetime.to_datetime(start_date)
end_datetime = fields.Datetime.to_datetime(end_date)
workcenters = self.env['mrp.workcenter'].browse(workcenter_ids)
unavailability_mapping = workcenters._get_unavailability_intervals(start_datetime, end_datetime)
# Only notable interval (more than one case) is send to the front-end (avoid sending useless information)
cell_dt = (scale in ['day', 'week'] and timedelta(hours=1)) or (scale == 'month' and timedelta(days=1)) or timedelta(days=28)
def add_unavailability(row, workcenter_id=None):
if row.get('groupedBy') and row.get('groupedBy')[0] == 'workcenter_id' and row.get('resId'):
workcenter_id = row.get('resId')
if workcenter_id:
notable_intervals = filter(lambda interval: interval[1] - interval[0] >= cell_dt, unavailability_mapping[workcenter_id])
row['unavailabilities'] = [{'start': interval[0], 'stop': interval[1]} for interval in notable_intervals]
return {'workcenter_id': workcenter_id}
for row in rows:
traverse_inplace(add_unavailability, row)
return rows
def button_start(self):
self.ensure_one()
if any(not time.date_end for time in self.time_ids.filtered(lambda t: t.user_id.id == self.env.user.id)):
return True
# As button_start is automatically called in the new view
if self.state in ('done', 'cancel'):
return True
if self.product_tracking == 'serial':
self.qty_producing = 1.0
elif self.qty_producing == 0:
self.qty_producing = self.qty_remaining
self.env['mrp.workcenter.productivity'].create(
self._prepare_timeline_vals(self.duration, datetime.now())
)
if self.production_id.state != 'progress':
self.production_id.write({
'date_start': datetime.now(),
})
if self.state == 'progress':
return True
start_date = datetime.now()
vals = {
'state': 'progress',
'date_start': start_date,
}
if not self.leave_id:
leave = self.env['resource.calendar.leaves'].create({
'name': self.display_name,
'calendar_id': self.workcenter_id.resource_calendar_id.id,
'date_from': start_date,
'date_to': start_date + relativedelta(minutes=self.duration_expected),
'resource_id': self.workcenter_id.resource_id.id,
'time_type': 'other'
})
vals['leave_id'] = leave.id
return self.write(vals)
else:
if not self.date_planned_start or self.date_planned_start > start_date:
vals['date_planned_start'] = start_date
vals['date_planned_finished'] = self._calculate_date_planned_finished(start_date)
if self.date_planned_finished and self.date_planned_finished < start_date:
vals['date_planned_finished'] = start_date
return self.with_context(bypass_duration_calculation=True).write(vals)
def button_finish(self):
end_date = datetime.now()
for workorder in self:
if workorder.state in ('done', 'cancel'):
continue
workorder.end_all()
vals = {
'qty_produced': workorder.qty_produced or workorder.qty_producing or workorder.qty_production,
'state': 'done',
'date_finished': end_date,
'date_planned_finished': end_date,
'costs_hour': workorder.workcenter_id.costs_hour
}
if not workorder.date_start:
vals['date_start'] = end_date
if not workorder.date_planned_start or end_date < workorder.date_planned_start:
vals['date_planned_start'] = end_date
workorder.with_context(bypass_duration_calculation=True).write(vals)
workorder._start_nextworkorder()
return True
def end_previous(self, doall=False):
"""
@param: doall: This will close all open time lines on the open work orders when doall = True, otherwise
only the one of the current user
"""
# TDE CLEANME
timeline_obj = self.env['mrp.workcenter.productivity']
domain = [('workorder_id', 'in', self.ids), ('date_end', '=', False)]
if not doall:
domain.append(('user_id', '=', self.env.user.id))
not_productive_timelines = timeline_obj.browse()
for timeline in timeline_obj.search(domain, limit=None if doall else 1):
wo = timeline.workorder_id
if wo.duration_expected <= wo.duration:
if timeline.loss_type == 'productive':
not_productive_timelines += timeline
timeline.write({'date_end': fields.Datetime.now()})
else:
maxdate = fields.Datetime.from_string(timeline.date_start) + relativedelta(minutes=wo.duration_expected - wo.duration)
enddate = datetime.now()
if maxdate > enddate:
timeline.write({'date_end': enddate})
else:
timeline.write({'date_end': maxdate})
not_productive_timelines += timeline.copy({'date_start': maxdate, 'date_end': enddate})
if not_productive_timelines:
loss_id = self.env['mrp.workcenter.productivity.loss'].search([('loss_type', '=', 'performance')], limit=1)
if not len(loss_id):
raise UserError(_("You need to define at least one unactive productivity loss in the category 'Performance'. Create one from the Manufacturing app, menu: Configuration / Productivity Losses."))
not_productive_timelines.write({'loss_id': loss_id.id})
return True
def end_all(self):
return self.end_previous(doall=True)
def button_pending(self):
self.end_previous()
return True
def button_unblock(self):
for order in self:
order.workcenter_id.unblock()
return True
def action_cancel(self):
self.leave_id.unlink()
self.end_all()
return self.write({'state': 'cancel'})
def action_replan(self):
"""Replan a work order.
It actually replans every "ready" or "pending"
work orders of the linked manufacturing orders.
"""
for production in self.production_id:
production._plan_workorders(replan=True)
return True
def button_done(self):
if any(x.state in ('done', 'cancel') for x in self):
raise UserError(_('A Manufacturing Order is already done or cancelled.'))
self.end_all()
end_date = datetime.now()
return self.write({
'state': 'done',
'date_finished': end_date,
'date_planned_finished': end_date,
'costs_hour': self.workcenter_id.costs_hour
})
def button_scrap(self):
self.ensure_one()
return {
'name': _('Scrap'),
'view_mode': 'form',
'res_model': 'stock.scrap',
'view_id': self.env.ref('stock.stock_scrap_form_view2').id,
'type': 'ir.actions.act_window',
'context': {'default_company_id': self.production_id.company_id.id,
'default_workorder_id': self.id,
'default_production_id': self.production_id.id,
'product_ids': (self.production_id.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel')) | self.production_id.move_finished_ids.filtered(lambda x: x.state == 'done')).mapped('product_id').ids},
'target': 'new',
}
def action_see_move_scrap(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_stock_scrap")
action['domain'] = [('workorder_id', '=', self.id)]
return action
def action_open_wizard(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_workorder_mrp_production_form")
action['res_id'] = self.id
return action
@api.depends('qty_production', 'qty_produced')
def _compute_qty_remaining(self):
for wo in self:
wo.qty_remaining = float_round(wo.qty_production - wo.qty_produced, precision_rounding=wo.production_id.product_uom_id.rounding)
def _get_duration_expected(self, alternative_workcenter=False, ratio=1):
self.ensure_one()
if not self.workcenter_id:
return self.duration_expected
if not self.operation_id:
duration_expected_working = (self.duration_expected - self.workcenter_id.time_start - self.workcenter_id.time_stop) * self.workcenter_id.time_efficiency / 100.0
if duration_expected_working < 0:
duration_expected_working = 0
return self.workcenter_id.time_start + self.workcenter_id.time_stop + duration_expected_working * ratio * 100.0 / self.workcenter_id.time_efficiency
qty_production = self.production_id.product_uom_id._compute_quantity(self.qty_production, self.production_id.product_id.uom_id)
cycle_number = float_round(qty_production / self.workcenter_id.capacity, precision_digits=0, rounding_method='UP')
if alternative_workcenter:
# TODO : find a better alternative : the settings of workcenter can change
duration_expected_working = (self.duration_expected - self.workcenter_id.time_start - self.workcenter_id.time_stop) * self.workcenter_id.time_efficiency / (100.0 * cycle_number)
if duration_expected_working < 0:
duration_expected_working = 0
alternative_wc_cycle_nb = float_round(qty_production / alternative_workcenter.capacity, precision_digits=0, rounding_method='UP')
return alternative_workcenter.time_start + alternative_workcenter.time_stop + alternative_wc_cycle_nb * duration_expected_working * 100.0 / alternative_workcenter.time_efficiency
time_cycle = self.operation_id.time_cycle
return self.workcenter_id.time_start + self.workcenter_id.time_stop + cycle_number * time_cycle * 100.0 / self.workcenter_id.time_efficiency
def _get_conflicted_workorder_ids(self):
"""Get conlicted workorder(s) with self.
Conflict means having two workorders in the same time in the same workcenter.
:return: defaultdict with key as workorder id of self and value as related conflicted workorder
"""
self.flush(['state', 'date_planned_start', 'date_planned_finished', 'workcenter_id'])
sql = """
SELECT wo1.id, wo2.id
FROM mrp_workorder wo1, mrp_workorder wo2
WHERE
wo1.id IN %s
AND wo1.state IN ('pending', 'waiting', 'ready')
AND wo2.state IN ('pending', 'waiting', 'ready')
AND wo1.id != wo2.id
AND wo1.workcenter_id = wo2.workcenter_id
AND (DATE_TRUNC('second', wo2.date_planned_start), DATE_TRUNC('second', wo2.date_planned_finished))
OVERLAPS (DATE_TRUNC('second', wo1.date_planned_start), DATE_TRUNC('second', wo1.date_planned_finished))
"""
self.env.cr.execute(sql, [tuple(self.ids)])
res = defaultdict(list)
for wo1, wo2 in self.env.cr.fetchall():
res[wo1].append(wo2)
return res
@api.model
def _prepare_component_quantity(self, move, qty_producing):
""" helper that computes quantity to consume (or to create in case of byproduct)
depending on the quantity producing and the move's unit factor"""
if move.product_id.tracking == 'serial':
uom = move.product_id.uom_id
else:
uom = move.product_uom
return move.product_uom._compute_quantity(
qty_producing * move.unit_factor,
uom,
round=False
)
def _prepare_timeline_vals(self, duration, date_start, date_end=False):
# Need a loss in case of the real time exceeding the expected
if not self.duration_expected or duration < self.duration_expected:
loss_id = self.env['mrp.workcenter.productivity.loss'].search([('loss_type', '=', 'productive')], limit=1)
if not len(loss_id):
raise UserError(_("You need to define at least one productivity loss in the category 'Productivity'. Create one from the Manufacturing app, menu: Configuration / Productivity Losses."))
else:
loss_id = self.env['mrp.workcenter.productivity.loss'].search([('loss_type', '=', 'performance')], limit=1)
if not len(loss_id):
raise UserError(_("You need to define at least one productivity loss in the category 'Performance'. Create one from the Manufacturing app, menu: Configuration / Productivity Losses."))
return {
'workorder_id': self.id,
'workcenter_id': self.workcenter_id.id,
'description': _('Time Tracking: %(user)s', user=self.env.user.name),
'loss_id': loss_id[0].id,
'date_start': date_start,
'date_end': date_end,
'user_id': self.env.user.id, # FIXME sle: can be inconsistent with company_id
'company_id': self.company_id.id,
}
def _update_finished_move(self):
""" Update the finished move & move lines in order to set the finished
product lot on it as well as the produced quantity. This method get the
information either from the last workorder or from the Produce wizard."""
production_move = self.production_id.move_finished_ids.filtered(
lambda move: move.product_id == self.product_id and
move.state not in ('done', 'cancel')
)
if not production_move:
return
if production_move.product_id.tracking != 'none':
if not self.finished_lot_id:
raise UserError(_('You need to provide a lot for the finished product.'))
move_line = production_move.move_line_ids.filtered(
lambda line: line.lot_id.id == self.finished_lot_id.id
)
if move_line:
if self.product_id.tracking == 'serial':
raise UserError(_('You cannot produce the same serial number twice.'))
move_line.product_uom_qty += self.qty_producing
move_line.qty_done += self.qty_producing
else:
quantity = self.product_uom_id._compute_quantity(self.qty_producing, self.product_id.uom_id, rounding_method='HALF-UP')
putaway_location = production_move.location_dest_id._get_putaway_strategy(self.product_id, quantity)
move_line.create({
'move_id': production_move.id,
'product_id': production_move.product_id.id,
'lot_id': self.finished_lot_id.id,
'product_uom_qty': self.qty_producing,
'product_uom_id': self.product_uom_id.id,
'qty_done': self.qty_producing,
'location_id': production_move.location_id.id,
'location_dest_id': putaway_location.id,
})
else:
rounding = production_move.product_uom.rounding
production_move._set_quantity_done(
float_round(self.qty_producing, precision_rounding=rounding)
)
def _check_sn_uniqueness(self):
# todo master: remove
pass
def _update_qty_producing(self, quantity):
self.ensure_one()
if self.qty_producing:
self.qty_producing = quantity
| 52.230068 | 45,858 |
28,180 |
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, ValidationError
from odoo.osv.expression import AND, NEGATIVE_TERM_OPERATORS
from odoo.tools import float_round
from collections import defaultdict
class MrpBom(models.Model):
""" Defines bills of material for a product or a product template """
_name = 'mrp.bom'
_description = 'Bill of Material'
_inherit = ['mail.thread']
_rec_name = 'product_tmpl_id'
_order = "sequence, id"
_check_company_auto = True
def _get_default_product_uom_id(self):
return self.env['uom.uom'].search([], limit=1, order='id').id
code = fields.Char('Reference')
active = fields.Boolean(
'Active', default=True,
help="If the active field is set to False, it will allow you to hide the bills of material without removing it.")
type = fields.Selection([
('normal', 'Manufacture this product'),
('phantom', 'Kit')], 'BoM Type',
default='normal', required=True)
product_tmpl_id = fields.Many2one(
'product.template', 'Product',
check_company=True, index=True,
domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", required=True)
product_id = fields.Many2one(
'product.product', 'Product Variant',
check_company=True, index=True,
domain="['&', ('product_tmpl_id', '=', product_tmpl_id), ('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
help="If a product variant is defined the BOM is available only for this product.")
bom_line_ids = fields.One2many('mrp.bom.line', 'bom_id', 'BoM Lines', copy=True)
byproduct_ids = fields.One2many('mrp.bom.byproduct', 'bom_id', 'By-products', copy=True)
product_qty = fields.Float(
'Quantity', default=1.0,
digits='Unit of Measure', required=True,
help="This should be the smallest quantity that this product can be produced in. If the BOM contains operations, make sure the work center capacity is accurate.")
product_uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
default=_get_default_product_uom_id, required=True,
help="Unit of Measure (Unit of Measure) is the unit of measurement for the inventory control", domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_tmpl_id.uom_id.category_id')
sequence = fields.Integer('Sequence', help="Gives the sequence order when displaying a list of bills of material.")
operation_ids = fields.One2many('mrp.routing.workcenter', 'bom_id', 'Operations', copy=True)
ready_to_produce = fields.Selection([
('all_available', ' When all components are available'),
('asap', 'When components for 1st operation are available')], string='Manufacturing Readiness',
default='all_available', help="Defines when a Manufacturing Order is considered as ready to be started", required=True)
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type', domain="[('code', '=', 'mrp_operation'), ('company_id', '=', company_id)]",
check_company=True,
help=u"When a procurement has a ‘produce’ route with a operation type set, it will try to create "
"a Manufacturing Order for that product using a BoM of the same operation type. That allows "
"to define stock rules which trigger different manufacturing orders with different BoMs.")
company_id = fields.Many2one(
'res.company', 'Company', index=True,
default=lambda self: self.env.company)
consumption = fields.Selection([
('flexible', 'Allowed'),
('warning', 'Allowed with warning'),
('strict', 'Blocked')],
help="Defines if you can consume more or less components than the quantity defined on the BoM:\n"
" * Allowed: allowed for all manufacturing users.\n"
" * Allowed with warning: allowed for all manufacturing users with summary of consumption differences when closing the manufacturing order.\n"
" * Blocked: only a manager can close a manufacturing order when the BoM consumption is not respected.",
default='warning',
string='Flexible Consumption',
required=True
)
possible_product_template_attribute_value_ids = fields.Many2many(
'product.template.attribute.value',
compute='_compute_possible_product_template_attribute_value_ids')
_sql_constraints = [
('qty_positive', 'check (product_qty > 0)', 'The quantity to produce must be positive!'),
]
@api.depends(
'product_tmpl_id.attribute_line_ids.value_ids',
'product_tmpl_id.attribute_line_ids.attribute_id.create_variant',
'product_tmpl_id.attribute_line_ids.product_template_value_ids.ptav_active',
)
def _compute_possible_product_template_attribute_value_ids(self):
for bom in self:
bom.possible_product_template_attribute_value_ids = bom.product_tmpl_id.valid_product_template_attribute_line_ids._without_no_variant_attributes().product_template_value_ids._only_active()
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
self.bom_line_ids.bom_product_template_attribute_value_ids = False
self.operation_ids.bom_product_template_attribute_value_ids = False
self.byproduct_ids.bom_product_template_attribute_value_ids = False
@api.constrains('product_id', 'product_tmpl_id', 'bom_line_ids', 'byproduct_ids', 'operation_ids')
def _check_bom_lines(self):
for bom in self:
for bom_line in bom.bom_line_ids:
if bom.product_id:
same_product = bom.product_id == bom_line.product_id
else:
same_product = bom.product_tmpl_id == bom_line.product_id.product_tmpl_id
if same_product:
raise ValidationError(_("BoM line product %s should not be the same as BoM product.") % bom.display_name)
apply_variants = bom.bom_line_ids.bom_product_template_attribute_value_ids | bom.operation_ids.bom_product_template_attribute_value_ids | bom.byproduct_ids.bom_product_template_attribute_value_ids
if bom.product_id and apply_variants:
raise ValidationError(_("You cannot use the 'Apply on Variant' functionality and simultaneously create a BoM for a specific variant."))
for ptav in apply_variants:
if ptav.product_tmpl_id != bom.product_tmpl_id:
raise ValidationError(_(
"The attribute value %(attribute)s set on product %(product)s does not match the BoM product %(bom_product)s.",
attribute=ptav.display_name,
product=ptav.product_tmpl_id.display_name,
bom_product=bom_line.parent_product_tmpl_id.display_name
))
for byproduct in bom.byproduct_ids:
if bom.product_id:
same_product = bom.product_id == byproduct.product_id
else:
same_product = bom.product_tmpl_id == byproduct.product_id.product_tmpl_id
if same_product:
raise ValidationError(_("By-product %s should not be the same as BoM product.") % bom.display_name)
if byproduct.cost_share < 0:
raise ValidationError(_("By-products cost shares must be positive."))
if sum(bom.byproduct_ids.mapped('cost_share')) > 100:
raise ValidationError(_("The total cost share for a BoM's by-products cannot exceed 100."))
@api.onchange('bom_line_ids', 'product_qty')
def onchange_bom_structure(self):
if self.type == 'phantom' and self._origin and self.env['stock.move'].search([('bom_line_id', 'in', self._origin.bom_line_ids.ids)], limit=1):
return {
'warning': {
'title': _('Warning'),
'message': _(
'The product has already been used at least once, editing its structure may lead to undesirable behaviours. '
'You should rather archive the product and create a new one with a new bill of materials.'),
}
}
@api.onchange('product_uom_id')
def onchange_product_uom_id(self):
res = {}
if not self.product_uom_id or not self.product_tmpl_id:
return
if self.product_uom_id.category_id.id != self.product_tmpl_id.uom_id.category_id.id:
self.product_uom_id = self.product_tmpl_id.uom_id.id
res['warning'] = {'title': _('Warning'), 'message': _('The Product Unit of Measure you chose has a different category than in the product form.')}
return res
@api.onchange('product_tmpl_id')
def onchange_product_tmpl_id(self):
if self.product_tmpl_id:
self.product_uom_id = self.product_tmpl_id.uom_id.id
if self.product_id.product_tmpl_id != self.product_tmpl_id:
self.product_id = False
self.bom_line_ids.bom_product_template_attribute_value_ids = False
self.operation_ids.bom_product_template_attribute_value_ids = False
self.byproduct_ids.bom_product_template_attribute_value_ids = False
domain = [('product_tmpl_id', '=', self.product_tmpl_id.id)]
if self.id.origin:
domain.append(('id', '!=', self.id.origin))
number_of_bom_of_this_product = self.env['mrp.bom'].search_count(domain)
if number_of_bom_of_this_product: # add a reference to the bom if there is already a bom for this product
self.code = _("%s (new) %s", self.product_tmpl_id.name, number_of_bom_of_this_product)
else:
self.code = False
def copy(self, default=None):
res = super().copy(default)
for bom_line in res.bom_line_ids:
if bom_line.operation_id:
operation = res.operation_ids.filtered(lambda op: op._get_comparison_values() == bom_line.operation_id._get_comparison_values())
# Two operations could have the same values so we take the first one
bom_line.operation_id = operation[:1]
return res
@api.model
def name_create(self, name):
# prevent to use string as product_tmpl_id
if isinstance(name, str):
raise UserError(_("You cannot create a new Bill of Material from here."))
return super(MrpBom, self).name_create(name)
def toggle_active(self):
self.with_context({'active_test': False}).operation_ids.toggle_active()
return super().toggle_active()
def name_get(self):
return [(bom.id, '%s%s' % (bom.code and '%s: ' % bom.code or '', bom.product_tmpl_id.display_name)) for bom in self]
@api.constrains('product_tmpl_id', 'product_id', 'type')
def check_kit_has_not_orderpoint(self):
product_ids = [pid for bom in self.filtered(lambda bom: bom.type == "phantom")
for pid in (bom.product_id.ids or bom.product_tmpl_id.product_variant_ids.ids)]
if self.env['stock.warehouse.orderpoint'].search([('product_id', 'in', product_ids)], count=True):
raise ValidationError(_("You can not create a kit-type bill of materials for products that have at least one reordering rule."))
@api.ondelete(at_uninstall=False)
def _unlink_except_running_mo(self):
if self.env['mrp.production'].search([('bom_id', 'in', self.ids), ('state', 'not in', ['done', 'cancel'])], limit=1):
raise UserError(_('You can not delete a Bill of Material with running manufacturing orders.\nPlease close or cancel it first.'))
@api.model
def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
domain = []
if (name or '').strip():
domain = ['|', (self._rec_name, operator, name), ('code', operator, name)]
if operator in NEGATIVE_TERM_OPERATORS:
domain = domain[1:]
return self._search(AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
@api.model
def _bom_find_domain(self, products, picking_type=None, company_id=False, bom_type=False):
domain = ['&', '|', ('product_id', 'in', products.ids), '&', ('product_id', '=', False), ('product_tmpl_id', 'in', products.product_tmpl_id.ids), ('active', '=', True)]
if company_id or self.env.context.get('company_id'):
domain = AND([domain, ['|', ('company_id', '=', False), ('company_id', '=', company_id or self.env.context.get('company_id'))]])
if picking_type:
domain = AND([domain, ['|', ('picking_type_id', '=', picking_type.id), ('picking_type_id', '=', False)]])
if bom_type:
domain = AND([domain, [('type', '=', bom_type)]])
return domain
@api.model
def _bom_find(self, products, picking_type=None, company_id=False, bom_type=False):
""" Find the first BoM for each products
:param products: `product.product` recordset
:return: One bom (or empty recordset `mrp.bom` if none find) by product (`product.product` record)
:rtype: defaultdict(`lambda: self.env['mrp.bom']`)
"""
bom_by_product = defaultdict(lambda: self.env['mrp.bom'])
products = products.filtered(lambda p: p.type != 'service')
if not products:
return bom_by_product
domain = self._bom_find_domain(products, picking_type=picking_type, company_id=company_id, bom_type=bom_type)
# Performance optimization, allow usage of limit and avoid the for loop `bom.product_tmpl_id.product_variant_ids`
if len(products) == 1:
bom = self.search(domain, order='sequence, product_id, id', limit=1)
if bom:
bom_by_product[products] = bom
return bom_by_product
boms = self.search(domain, order='sequence, product_id, id')
products_ids = set(products.ids)
for bom in boms:
products_implies = bom.product_id or bom.product_tmpl_id.product_variant_ids
for product in products_implies:
if product.id in products_ids and product not in bom_by_product:
bom_by_product[product] = bom
return bom_by_product
def explode(self, product, quantity, picking_type=False):
"""
Explodes the BoM and creates two lists with all the information you need: bom_done and line_done
Quantity describes the number of times you need the BoM: so the quantity divided by the number created by the BoM
and converted into its UoM
"""
from collections import defaultdict
graph = defaultdict(list)
V = set()
def check_cycle(v, visited, recStack, graph):
visited[v] = True
recStack[v] = True
for neighbour in graph[v]:
if visited[neighbour] == False:
if check_cycle(neighbour, visited, recStack, graph) == True:
return True
elif recStack[neighbour] == True:
return True
recStack[v] = False
return False
product_ids = set()
product_boms = {}
def update_product_boms():
products = self.env['product.product'].browse(product_ids)
product_boms.update(self._bom_find(products, picking_type=picking_type or self.picking_type_id,
company_id=self.company_id.id, bom_type='phantom'))
# Set missing keys to default value
for product in products:
product_boms.setdefault(product, self.env['mrp.bom'])
boms_done = [(self, {'qty': quantity, 'product': product, 'original_qty': quantity, 'parent_line': False})]
lines_done = []
V |= set([product.product_tmpl_id.id])
bom_lines = []
for bom_line in self.bom_line_ids:
product_id = bom_line.product_id
V |= set([product_id.product_tmpl_id.id])
graph[product.product_tmpl_id.id].append(product_id.product_tmpl_id.id)
bom_lines.append((bom_line, product, quantity, False))
product_ids.add(product_id.id)
update_product_boms()
product_ids.clear()
while bom_lines:
current_line, current_product, current_qty, parent_line = bom_lines[0]
bom_lines = bom_lines[1:]
if current_line._skip_bom_line(current_product):
continue
line_quantity = current_qty * current_line.product_qty
if not current_line.product_id in product_boms:
update_product_boms()
product_ids.clear()
bom = product_boms.get(current_line.product_id)
if bom:
converted_line_quantity = current_line.product_uom_id._compute_quantity(line_quantity / bom.product_qty, bom.product_uom_id)
bom_lines += [(line, current_line.product_id, converted_line_quantity, current_line) for line in bom.bom_line_ids]
for bom_line in bom.bom_line_ids:
graph[current_line.product_id.product_tmpl_id.id].append(bom_line.product_id.product_tmpl_id.id)
if bom_line.product_id.product_tmpl_id.id in V and check_cycle(bom_line.product_id.product_tmpl_id.id, {key: False for key in V}, {key: False for key in V}, graph):
raise UserError(_('Recursion error! A product with a Bill of Material should not have itself in its BoM or child BoMs!'))
V |= set([bom_line.product_id.product_tmpl_id.id])
if not bom_line.product_id in product_boms:
product_ids.add(bom_line.product_id.id)
boms_done.append((bom, {'qty': converted_line_quantity, 'product': current_product, 'original_qty': quantity, 'parent_line': current_line}))
else:
# We round up here because the user expects that if he has to consume a little more, the whole UOM unit
# should be consumed.
rounding = current_line.product_uom_id.rounding
line_quantity = float_round(line_quantity, precision_rounding=rounding, rounding_method='UP')
lines_done.append((current_line, {'qty': line_quantity, 'product': current_product, 'original_qty': quantity, 'parent_line': parent_line}))
return boms_done, lines_done
@api.model
def get_import_templates(self):
return [{
'label': _('Import Template for Bills of Materials'),
'template': '/mrp/static/xls/mrp_bom.xls'
}]
class MrpBomLine(models.Model):
_name = 'mrp.bom.line'
_order = "sequence, id"
_rec_name = "product_id"
_description = 'Bill of Material Line'
_check_company_auto = True
def _get_default_product_uom_id(self):
return self.env['uom.uom'].search([], limit=1, order='id').id
product_id = fields.Many2one('product.product', 'Component', required=True, check_company=True)
product_tmpl_id = fields.Many2one('product.template', 'Product Template', related='product_id.product_tmpl_id', store=True, index=True)
company_id = fields.Many2one(
related='bom_id.company_id', store=True, index=True, readonly=True)
product_qty = fields.Float(
'Quantity', default=1.0,
digits='Product Unit of Measure', required=True)
product_uom_id = fields.Many2one(
'uom.uom', 'Product Unit of Measure',
default=_get_default_product_uom_id,
required=True,
help="Unit of Measure (Unit of Measure) is the unit of measurement for the inventory control", domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
sequence = fields.Integer(
'Sequence', default=1,
help="Gives the sequence order when displaying.")
bom_id = fields.Many2one(
'mrp.bom', 'Parent BoM',
index=True, ondelete='cascade', required=True)
parent_product_tmpl_id = fields.Many2one('product.template', 'Parent Product Template', related='bom_id.product_tmpl_id')
possible_bom_product_template_attribute_value_ids = fields.Many2many(related='bom_id.possible_product_template_attribute_value_ids')
bom_product_template_attribute_value_ids = fields.Many2many(
'product.template.attribute.value', string="Apply on Variants", ondelete='restrict',
domain="[('id', 'in', possible_bom_product_template_attribute_value_ids)]",
help="BOM Product Variants needed to apply this line.")
allowed_operation_ids = fields.One2many('mrp.routing.workcenter', related='bom_id.operation_ids')
operation_id = fields.Many2one(
'mrp.routing.workcenter', 'Consumed in Operation', check_company=True,
domain="[('id', 'in', allowed_operation_ids)]",
help="The operation where the components are consumed, or the finished products created.")
child_bom_id = fields.Many2one(
'mrp.bom', 'Sub BoM', compute='_compute_child_bom_id')
child_line_ids = fields.One2many(
'mrp.bom.line', string="BOM lines of the referred bom",
compute='_compute_child_line_ids')
attachments_count = fields.Integer('Attachments Count', compute='_compute_attachments_count')
_sql_constraints = [
('bom_qty_zero', 'CHECK (product_qty>=0)', 'All product quantities must be greater or equal to 0.\n'
'Lines with 0 quantities can be used as optional lines. \n'
'You should install the mrp_byproduct module if you want to manage extra products on BoMs !'),
]
@api.depends('product_id', 'bom_id')
def _compute_child_bom_id(self):
for line in self:
if not line.product_id:
line.child_bom_id = False
else:
line.child_bom_id = self.env['mrp.bom']._bom_find(line.product_id)[line.product_id]
@api.depends('product_id')
def _compute_attachments_count(self):
for line in self:
nbr_attach = self.env['mrp.document'].search_count([
'|',
'&', ('res_model', '=', 'product.product'), ('res_id', '=', line.product_id.id),
'&', ('res_model', '=', 'product.template'), ('res_id', '=', line.product_id.product_tmpl_id.id)])
line.attachments_count = nbr_attach
@api.depends('child_bom_id')
def _compute_child_line_ids(self):
""" If the BOM line refers to a BOM, return the ids of the child BOM lines """
for line in self:
line.child_line_ids = line.child_bom_id.bom_line_ids.ids or False
@api.onchange('product_uom_id')
def onchange_product_uom_id(self):
res = {}
if not self.product_uom_id or not self.product_id:
return res
if self.product_uom_id.category_id != self.product_id.uom_id.category_id:
self.product_uom_id = self.product_id.uom_id.id
res['warning'] = {'title': _('Warning'), 'message': _('The Product Unit of Measure you chose has a different category than in the product form.')}
return res
@api.onchange('product_id')
def onchange_product_id(self):
if self.product_id:
self.product_uom_id = self.product_id.uom_id.id
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if 'product_id' in values and 'product_uom_id' not in values:
values['product_uom_id'] = self.env['product.product'].browse(values['product_id']).uom_id.id
return super(MrpBomLine, self).create(vals_list)
def _skip_bom_line(self, product):
""" Control if a BoM line should be produced, can be inherited to add
custom control.
"""
self.ensure_one()
if product._name == 'product.template':
return False
return not product._match_all_variant_values(self.bom_product_template_attribute_value_ids)
def action_see_attachments(self):
domain = [
'|',
'&', ('res_model', '=', 'product.product'), ('res_id', '=', self.product_id.id),
'&', ('res_model', '=', 'product.template'), ('res_id', '=', self.product_id.product_tmpl_id.id)]
attachment_view = self.env.ref('mrp.view_document_file_kanban_mrp')
return {
'name': _('Attachments'),
'domain': domain,
'res_model': 'mrp.document',
'type': 'ir.actions.act_window',
'view_id': attachment_view.id,
'views': [(attachment_view.id, 'kanban'), (False, 'form')],
'view_mode': 'kanban,tree,form',
'help': _('''<p class="o_view_nocontent_smiling_face">
Upload files to your product
</p><p>
Use this feature to store any files, like drawings or specifications.
</p>'''),
'limit': 80,
'context': "{'default_res_model': '%s','default_res_id': %d, 'default_company_id': %s}" % ('product.product', self.product_id.id, self.company_id.id)
}
class MrpByProduct(models.Model):
_name = 'mrp.bom.byproduct'
_description = 'Byproduct'
_rec_name = "product_id"
_check_company_auto = True
_order = 'sequence, id'
product_id = fields.Many2one('product.product', 'By-product', required=True, check_company=True)
company_id = fields.Many2one(related='bom_id.company_id', store=True, index=True, readonly=True)
product_qty = fields.Float(
'Quantity',
default=1.0, digits='Product Unit of Measure', required=True)
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
product_uom_id = fields.Many2one('uom.uom', 'Unit of Measure', required=True,
domain="[('category_id', '=', product_uom_category_id)]")
bom_id = fields.Many2one('mrp.bom', 'BoM', ondelete='cascade', index=True)
allowed_operation_ids = fields.One2many('mrp.routing.workcenter', related='bom_id.operation_ids')
operation_id = fields.Many2one(
'mrp.routing.workcenter', 'Produced in Operation', check_company=True,
domain="[('id', 'in', allowed_operation_ids)]")
possible_bom_product_template_attribute_value_ids = fields.Many2many(related='bom_id.possible_product_template_attribute_value_ids')
bom_product_template_attribute_value_ids = fields.Many2many(
'product.template.attribute.value', string="Apply on Variants", ondelete='restrict',
domain="[('id', 'in', possible_bom_product_template_attribute_value_ids)]",
help="BOM Product Variants needed to apply this line.")
sequence = fields.Integer("Sequence")
cost_share = fields.Float(
"Cost Share (%)", digits=(5, 2), # decimal = 2 is important for rounding calculations!!
help="The percentage of the final production cost for this by-product line (divided between the quantity produced)."
"The total of all by-products' cost share must be less than or equal to 100.")
@api.onchange('product_id')
def _onchange_product_id(self):
""" Changes UoM if product_id changes. """
if self.product_id:
self.product_uom_id = self.product_id.uom_id.id
def _skip_byproduct_line(self, product):
""" Control if a byproduct line should be produced, can be inherited to add
custom control.
"""
self.ensure_one()
if product._name == 'product.template':
return False
return not product._match_all_variant_values(self.bom_product_template_attribute_value_ids)
| 53.56654 | 28,176 |
21,893 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil import relativedelta
from datetime import timedelta
from functools import partial
import datetime
from pytz import timezone
from random import randint
from odoo import api, exceptions, fields, models, _
from odoo.exceptions import ValidationError
from odoo.addons.resource.models.resource import make_aware, Intervals
from odoo.tools.float_utils import float_compare
class MrpWorkcenter(models.Model):
_name = 'mrp.workcenter'
_description = 'Work Center'
_order = "sequence, id"
_inherit = ['resource.mixin']
_check_company_auto = True
# resource
name = fields.Char('Work Center', related='resource_id.name', store=True, readonly=False)
time_efficiency = fields.Float('Time Efficiency', related='resource_id.time_efficiency', default=100, store=True, readonly=False)
active = fields.Boolean('Active', related='resource_id.active', default=True, store=True, readonly=False)
code = fields.Char('Code', copy=False)
note = fields.Html(
'Description',
help="Description of the Work Center.")
capacity = fields.Float(
'Capacity', default=1.0,
help="Number of pieces (in product UoM) that can be produced in parallel (at the same time) at this work center. For example: the capacity is 5 and you need to produce 10 units, then the operation time listed on the BOM will be multiplied by two. However, note that both time before and after production will only be counted once.")
sequence = fields.Integer(
'Sequence', default=1, required=True,
help="Gives the sequence order when displaying a list of work centers.")
color = fields.Integer('Color')
costs_hour = fields.Float(string='Cost per hour', help='Specify cost of work center per hour.', default=0.0)
time_start = fields.Float('Setup Time', help="Time in minutes for the setup.")
time_stop = fields.Float('Cleanup Time', help="Time in minutes for the cleaning.")
routing_line_ids = fields.One2many('mrp.routing.workcenter', 'workcenter_id', "Routing Lines")
order_ids = fields.One2many('mrp.workorder', 'workcenter_id', "Orders")
workorder_count = fields.Integer('# Work Orders', compute='_compute_workorder_count')
workorder_ready_count = fields.Integer('# Read Work Orders', compute='_compute_workorder_count')
workorder_progress_count = fields.Integer('Total Running Orders', compute='_compute_workorder_count')
workorder_pending_count = fields.Integer('Total Pending Orders', compute='_compute_workorder_count')
workorder_late_count = fields.Integer('Total Late Orders', compute='_compute_workorder_count')
time_ids = fields.One2many('mrp.workcenter.productivity', 'workcenter_id', 'Time Logs')
working_state = fields.Selection([
('normal', 'Normal'),
('blocked', 'Blocked'),
('done', 'In Progress')], 'Workcenter Status', compute="_compute_working_state", store=True)
blocked_time = fields.Float(
'Blocked Time', compute='_compute_blocked_time',
help='Blocked hours over the last month', digits=(16, 2))
productive_time = fields.Float(
'Productive Time', compute='_compute_productive_time',
help='Productive hours over the last month', digits=(16, 2))
oee = fields.Float(compute='_compute_oee', help='Overall Equipment Effectiveness, based on the last month')
oee_target = fields.Float(string='OEE Target', help="Overall Effective Efficiency Target in percentage", default=90)
performance = fields.Integer('Performance', compute='_compute_performance', help='Performance over the last month')
workcenter_load = fields.Float('Work Center Load', compute='_compute_workorder_count')
alternative_workcenter_ids = fields.Many2many(
'mrp.workcenter',
'mrp_workcenter_alternative_rel',
'workcenter_id',
'alternative_workcenter_id',
domain="[('id', '!=', id), '|', ('company_id', '=', company_id), ('company_id', '=', False)]",
string="Alternative Workcenters", check_company=True,
help="Alternative workcenters that can be substituted to this one in order to dispatch production"
)
tag_ids = fields.Many2many('mrp.workcenter.tag')
@api.constrains('alternative_workcenter_ids')
def _check_alternative_workcenter(self):
for workcenter in self:
if workcenter in workcenter.alternative_workcenter_ids:
raise ValidationError(_("Workcenter %s cannot be an alternative of itself.", workcenter.name))
@api.depends('order_ids.duration_expected', 'order_ids.workcenter_id', 'order_ids.state', 'order_ids.date_planned_start')
def _compute_workorder_count(self):
MrpWorkorder = self.env['mrp.workorder']
result = {wid: {} for wid in self._ids}
result_duration_expected = {wid: 0 for wid in self._ids}
# Count Late Workorder
data = MrpWorkorder.read_group(
[('workcenter_id', 'in', self.ids), ('state', 'in', ('pending', 'waiting', 'ready')), ('date_planned_start', '<', datetime.datetime.now().strftime('%Y-%m-%d'))],
['workcenter_id'], ['workcenter_id'])
count_data = dict((item['workcenter_id'][0], item['workcenter_id_count']) for item in data)
# Count All, Pending, Ready, Progress Workorder
res = MrpWorkorder.read_group(
[('workcenter_id', 'in', self.ids)],
['workcenter_id', 'state', 'duration_expected'], ['workcenter_id', 'state'],
lazy=False)
for res_group in res:
result[res_group['workcenter_id'][0]][res_group['state']] = res_group['__count']
if res_group['state'] in ('pending', 'waiting', 'ready', 'progress'):
result_duration_expected[res_group['workcenter_id'][0]] += res_group['duration_expected']
for workcenter in self:
workcenter.workorder_count = sum(count for state, count in result[workcenter.id].items() if state not in ('done', 'cancel'))
workcenter.workorder_pending_count = result[workcenter.id].get('pending', 0)
workcenter.workcenter_load = result_duration_expected[workcenter.id]
workcenter.workorder_ready_count = result[workcenter.id].get('ready', 0)
workcenter.workorder_progress_count = result[workcenter.id].get('progress', 0)
workcenter.workorder_late_count = count_data.get(workcenter.id, 0)
@api.depends('time_ids', 'time_ids.date_end', 'time_ids.loss_type')
def _compute_working_state(self):
for workcenter in self:
# We search for a productivity line associated to this workcenter having no `date_end`.
# If we do not find one, the workcenter is not currently being used. If we find one, according
# to its `type_loss`, the workcenter is either being used or blocked.
time_log = self.env['mrp.workcenter.productivity'].search([
('workcenter_id', '=', workcenter.id),
('date_end', '=', False)
], limit=1)
if not time_log:
# the workcenter is not being used
workcenter.working_state = 'normal'
elif time_log.loss_type in ('productive', 'performance'):
# the productivity line has a `loss_type` that means the workcenter is being used
workcenter.working_state = 'done'
else:
# the workcenter is blocked
workcenter.working_state = 'blocked'
def _compute_blocked_time(self):
# TDE FIXME: productivity loss type should be only losses, probably count other time logs differently ??
data = self.env['mrp.workcenter.productivity'].read_group([
('date_start', '>=', fields.Datetime.to_string(datetime.datetime.now() - relativedelta.relativedelta(months=1))),
('workcenter_id', 'in', self.ids),
('date_end', '!=', False),
('loss_type', '!=', 'productive')],
['duration', 'workcenter_id'], ['workcenter_id'], lazy=False)
count_data = dict((item['workcenter_id'][0], item['duration']) for item in data)
for workcenter in self:
workcenter.blocked_time = count_data.get(workcenter.id, 0.0) / 60.0
def _compute_productive_time(self):
# TDE FIXME: productivity loss type should be only losses, probably count other time logs differently
data = self.env['mrp.workcenter.productivity'].read_group([
('date_start', '>=', fields.Datetime.to_string(datetime.datetime.now() - relativedelta.relativedelta(months=1))),
('workcenter_id', 'in', self.ids),
('date_end', '!=', False),
('loss_type', '=', 'productive')],
['duration', 'workcenter_id'], ['workcenter_id'], lazy=False)
count_data = dict((item['workcenter_id'][0], item['duration']) for item in data)
for workcenter in self:
workcenter.productive_time = count_data.get(workcenter.id, 0.0) / 60.0
@api.depends('blocked_time', 'productive_time')
def _compute_oee(self):
for order in self:
if order.productive_time:
order.oee = round(order.productive_time * 100.0 / (order.productive_time + order.blocked_time), 2)
else:
order.oee = 0.0
def _compute_performance(self):
wo_data = self.env['mrp.workorder'].read_group([
('date_start', '>=', fields.Datetime.to_string(datetime.datetime.now() - relativedelta.relativedelta(months=1))),
('workcenter_id', 'in', self.ids),
('state', '=', 'done')], ['duration_expected', 'workcenter_id', 'duration'], ['workcenter_id'], lazy=False)
duration_expected = dict((data['workcenter_id'][0], data['duration_expected']) for data in wo_data)
duration = dict((data['workcenter_id'][0], data['duration']) for data in wo_data)
for workcenter in self:
if duration.get(workcenter.id):
workcenter.performance = 100 * duration_expected.get(workcenter.id, 0.0) / duration[workcenter.id]
else:
workcenter.performance = 0.0
@api.constrains('capacity')
def _check_capacity(self):
if any(workcenter.capacity <= 0.0 for workcenter in self):
raise exceptions.UserError(_('The capacity must be strictly positive.'))
def unblock(self):
self.ensure_one()
if self.working_state != 'blocked':
raise exceptions.UserError(_("It has already been unblocked."))
times = self.env['mrp.workcenter.productivity'].search([('workcenter_id', '=', self.id), ('date_end', '=', False)])
times.write({'date_end': fields.Datetime.now()})
return {'type': 'ir.actions.client', 'tag': 'reload'}
@api.model_create_multi
def create(self, vals_list):
# resource_type is 'human' by default. As we are not living in
# /r/latestagecapitalism, workcenters are 'material'
records = super(MrpWorkcenter, self.with_context(default_resource_type='material')).create(vals_list)
return records
def write(self, vals):
if 'company_id' in vals:
self.resource_id.company_id = vals['company_id']
return super(MrpWorkcenter, self).write(vals)
def action_show_operations(self):
self.ensure_one()
action = self.env['ir.actions.actions']._for_xml_id('mrp.mrp_routing_action')
action['domain'] = [('workcenter_id', '=', self.id)]
action['context'] = {
'default_workcenter_id': self.id,
}
return action
def action_work_order(self):
action = self.env["ir.actions.actions"]._for_xml_id("mrp.action_work_orders")
return action
def _get_unavailability_intervals(self, start_datetime, end_datetime):
"""Get the unavailabilities intervals for the workcenters in `self`.
Return the list of unavailabilities (a tuple of datetimes) indexed
by workcenter id.
:param start_datetime: filter unavailability with only slots after this start_datetime
:param end_datetime: filter unavailability with only slots before this end_datetime
:rtype: dict
"""
unavailability_ressources = self.resource_id._get_unavailable_intervals(start_datetime, end_datetime)
return {wc.id: unavailability_ressources.get(wc.resource_id.id, []) for wc in self}
def _get_first_available_slot(self, start_datetime, duration):
"""Get the first available interval for the workcenter in `self`.
The available interval is disjoinct with all other workorders planned on this workcenter, but
can overlap the time-off of the related calendar (inverse of the working hours).
Return the first available interval (start datetime, end datetime) or,
if there is none before 700 days, a tuple error (False, 'error message').
:param start_datetime: begin the search at this datetime
:param duration: minutes needed to make the workorder (float)
:rtype: tuple
"""
self.ensure_one()
start_datetime, revert = make_aware(start_datetime)
resource = self.resource_id
get_available_intervals = partial(self.resource_calendar_id._work_intervals_batch, domain=[('time_type', 'in', ['other', 'leave'])], resources=resource, tz=timezone(self.resource_calendar_id.tz))
get_workorder_intervals = partial(self.resource_calendar_id._leave_intervals_batch, domain=[('time_type', '=', 'other')], resources=resource, tz=timezone(self.resource_calendar_id.tz))
remaining = duration
start_interval = start_datetime
delta = timedelta(days=14)
for n in range(50): # 50 * 14 = 700 days in advance (hardcoded)
dt = start_datetime + delta * n
available_intervals = get_available_intervals(dt, dt + delta)[resource.id]
workorder_intervals = get_workorder_intervals(dt, dt + delta)[resource.id]
for start, stop, dummy in available_intervals:
# Shouldn't loop more than 2 times because the available_intervals contains the workorder_intervals
# And remaining == duration can only occur at the first loop and at the interval intersection (cannot happen several time because available_intervals > workorder_intervals
for i in range(2):
interval_minutes = (stop - start).total_seconds() / 60
# If the remaining minutes has never decrease update start_interval
if remaining == duration:
start_interval = start
# If there is a overlap between the possible available interval and a others WO
if Intervals([(start_interval, start + timedelta(minutes=min(remaining, interval_minutes)), dummy)]) & workorder_intervals:
remaining = duration
elif float_compare(interval_minutes, remaining, precision_digits=3) >= 0:
return revert(start_interval), revert(start + timedelta(minutes=remaining))
else:
# Decrease a part of the remaining duration
remaining -= interval_minutes
# Go to the next available interval because the possible current interval duration has been used
break
return False, 'Not available slot 700 days after the planned start'
def action_archive(self):
res = super().action_archive()
filtered_workcenters = ", ".join(workcenter.name for workcenter in self.filtered('routing_line_ids'))
if filtered_workcenters:
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _("Note that archived work center(s): '%s' is/are still linked to active Bill of Materials, which means that operations can still be planned on it/them. "
"To prevent this, deletion of the work center is recommended instead.", filtered_workcenters),
'type': 'warning',
'sticky': True, #True/False will display for few seconds if false
'next': {'type': 'ir.actions.act_window_close'},
},
}
return res
class WorkcenterTag(models.Model):
_name = 'mrp.workcenter.tag'
_description = 'Add tag for the workcenter'
_order = 'name'
def _get_default_color(self):
return randint(1, 11)
name = fields.Char("Tag Name", required=True)
color = fields.Integer("Color Index", default=_get_default_color)
_sql_constraints = [
('tag_name_unique', 'unique(name)',
'The tag name must be unique.'),
]
class MrpWorkcenterProductivityLossType(models.Model):
_name = "mrp.workcenter.productivity.loss.type"
_description = 'MRP Workorder productivity losses'
_rec_name = 'loss_type'
@api.depends('loss_type')
def name_get(self):
""" As 'category' field in form view is a Many2one, its value will be in
lower case. In order to display its value capitalized 'name_get' is
overrided.
"""
result = []
for rec in self:
result.append((rec.id, rec.loss_type.title()))
return result
loss_type = fields.Selection([
('availability', 'Availability'),
('performance', 'Performance'),
('quality', 'Quality'),
('productive', 'Productive')], string='Category', default='availability', required=True)
class MrpWorkcenterProductivityLoss(models.Model):
_name = "mrp.workcenter.productivity.loss"
_description = "Workcenter Productivity Losses"
_order = "sequence, id"
name = fields.Char('Blocking Reason', required=True)
sequence = fields.Integer('Sequence', default=1)
manual = fields.Boolean('Is a Blocking Reason', default=True)
loss_id = fields.Many2one('mrp.workcenter.productivity.loss.type', domain=([('loss_type', 'in', ['quality', 'availability'])]), string='Category')
loss_type = fields.Selection(string='Effectiveness Category', related='loss_id.loss_type', store=True, readonly=False)
class MrpWorkcenterProductivity(models.Model):
_name = "mrp.workcenter.productivity"
_description = "Workcenter Productivity Log"
_order = "id desc"
_rec_name = "loss_id"
_check_company_auto = True
def _get_default_company_id(self):
company_id = False
if self.env.context.get('default_company_id'):
company_id = self.env.context['default_company_id']
if not company_id and self.env.context.get('default_workorder_id'):
workorder = self.env['mrp.workorder'].browse(self.env.context['default_workorder_id'])
company_id = workorder.company_id
if not company_id and self.env.context.get('default_workcenter_id'):
workcenter = self.env['mrp.workcenter'].browse(self.env.context['default_workcenter_id'])
company_id = workcenter.company_id
if not company_id:
company_id = self.env.company
return company_id
production_id = fields.Many2one('mrp.production', string='Manufacturing Order', related='workorder_id.production_id', readonly=True)
workcenter_id = fields.Many2one('mrp.workcenter', "Work Center", required=True, check_company=True, index=True)
company_id = fields.Many2one(
'res.company', required=True, index=True,
default=lambda self: self._get_default_company_id())
workorder_id = fields.Many2one('mrp.workorder', 'Work Order', check_company=True, index=True)
user_id = fields.Many2one(
'res.users', "User",
default=lambda self: self.env.uid)
loss_id = fields.Many2one(
'mrp.workcenter.productivity.loss', "Loss Reason",
ondelete='restrict', required=True)
loss_type = fields.Selection(
string="Effectiveness", related='loss_id.loss_type', store=True, readonly=False)
description = fields.Text('Description')
date_start = fields.Datetime('Start Date', default=fields.Datetime.now, required=True)
date_end = fields.Datetime('End Date')
duration = fields.Float('Duration', compute='_compute_duration', store=True)
@api.depends('date_end', 'date_start')
def _compute_duration(self):
for blocktime in self:
if blocktime.date_start and blocktime.date_end:
d1 = fields.Datetime.from_string(blocktime.date_start)
d2 = fields.Datetime.from_string(blocktime.date_end)
diff = d2 - d1
if (blocktime.loss_type not in ('productive', 'performance')) and blocktime.workcenter_id.resource_calendar_id:
r = blocktime.workcenter_id._get_work_days_data_batch(d1, d2)[blocktime.workcenter_id.id]['hours']
blocktime.duration = round(r * 60, 2)
else:
blocktime.duration = round(diff.total_seconds() / 60.0, 2)
else:
blocktime.duration = 0.0
@api.constrains('workorder_id')
def _check_open_time_ids(self):
for workorder in self.workorder_id:
open_time_ids_by_user = self.env["mrp.workcenter.productivity"].read_group([("id", "in", workorder.time_ids.ids), ("date_end", "=", False)], ["user_id", "open_time_ids_count:count(id)"], ["user_id"])
if any(data["open_time_ids_count"] > 1 for data in open_time_ids_by_user):
raise ValidationError(_('The Workorder (%s) cannot be started twice!', workorder.display_name))
def button_block(self):
self.ensure_one()
self.workcenter_id.order_ids.end_all()
| 53.791155 | 21,893 |
1,178 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import json
import logging
from odoo import http
from odoo.http import request
from odoo.tools.translate import _
logger = logging.getLogger(__name__)
class MrpDocumentRoute(http.Controller):
@http.route('/mrp/upload_attachment', type='http', methods=['POST'], auth="user")
def upload_document(self, ufile, **kwargs):
files = request.httprequest.files.getlist('ufile')
result = {'success': _("All files uploaded")}
for ufile in files:
try:
mimetype = ufile.content_type
request.env['mrp.document'].create({
'name': ufile.filename,
'res_model': kwargs.get('res_model'),
'res_id': int(kwargs.get('res_id')),
'mimetype': mimetype,
'datas': base64.encodebytes(ufile.read()),
})
except Exception as e:
logger.exception("Fail to upload document %s" % ufile.filename)
result = {'error': str(e)}
return json.dumps(result)
| 33.657143 | 1,178 |
599 |
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 ReportStockRule(models.AbstractModel):
_inherit = 'report.stock.report_stock_rule'
@api.model
def _get_rule_loc(self, rule, product_id):
""" We override this method to handle manufacture rule which do not have a location_src_id.
"""
res = super(ReportStockRule, self)._get_rule_loc(rule, product_id)
if rule.action == 'manufacture':
res['source'] = product_id.property_stock_production
return res
| 35.235294 | 599 |
481 |
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 format_date
class ReceptionReport(models.AbstractModel):
_inherit = 'report.stock.report_reception'
def _get_formatted_scheduled_date(self, source):
if source._name == 'mrp.production':
return format_date(self.env, source.date_planned_start)
return super()._get_formatted_scheduled_date(source)
| 34.357143 | 481 |
1,841 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ReplenishmentReport(models.AbstractModel):
_inherit = 'report.stock.report_product_product_replenishment'
def _move_draft_domain(self, product_template_ids, product_variant_ids, wh_location_ids):
in_domain, out_domain = super()._move_draft_domain(product_template_ids, product_variant_ids, wh_location_ids)
in_domain += [('production_id', '=', False)]
out_domain += [('raw_material_production_id', '=', False)]
return in_domain, out_domain
def _compute_draft_quantity_count(self, product_template_ids, product_variant_ids, wh_location_ids):
res = super()._compute_draft_quantity_count(product_template_ids, product_variant_ids, wh_location_ids)
res['draft_production_qty'] = {}
domain = self._product_domain(product_template_ids, product_variant_ids)
domain += [('state', '=', 'draft')]
# Pending incoming quantity.
mo_domain = domain + [('location_dest_id', 'in', wh_location_ids)]
grouped_mo = self.env['mrp.production'].read_group(mo_domain, ['product_qty:sum'], 'product_id')
res['draft_production_qty']['in'] = sum(mo['product_qty'] for mo in grouped_mo)
# Pending outgoing quantity.
move_domain = domain + [
('raw_material_production_id', '!=', False),
('location_id', 'in', wh_location_ids),
]
grouped_moves = self.env['stock.move'].read_group(move_domain, ['product_qty:sum'], 'product_id')
res['draft_production_qty']['out'] = sum(move['product_qty'] for move in grouped_moves)
res['qty']['in'] += res['draft_production_qty']['in']
res['qty']['out'] += res['draft_production_qty']['out']
return res
| 49.756757 | 1,841 |
17,576 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import json
from odoo import api, models, _
from odoo.tools import float_round
class ReportBomStructure(models.AbstractModel):
_name = 'report.mrp.report_bom_structure'
_description = 'BOM Structure Report'
@api.model
def _get_report_values(self, docids, data=None):
docs = []
for bom_id in docids:
bom = self.env['mrp.bom'].browse(bom_id)
variant = data.get('variant')
candidates = variant and self.env['product.product'].browse(int(variant)) or bom.product_id or bom.product_tmpl_id.product_variant_ids
quantity = float(data.get('quantity', bom.product_qty))
for product_variant_id in candidates.ids:
if data and data.get('childs'):
doc = self._get_pdf_line(bom_id, product_id=product_variant_id, qty=quantity, child_bom_ids=set(json.loads(data.get('childs'))))
else:
doc = self._get_pdf_line(bom_id, product_id=product_variant_id, qty=quantity, unfolded=True)
doc['report_type'] = 'pdf'
doc['report_structure'] = data and data.get('report_type') or 'all'
docs.append(doc)
if not candidates:
if data and data.get('childs'):
doc = self._get_pdf_line(bom_id, qty=quantity, child_bom_ids=set(json.loads(data.get('childs'))))
else:
doc = self._get_pdf_line(bom_id, qty=quantity, unfolded=True)
doc['report_type'] = 'pdf'
doc['report_structure'] = data and data.get('report_type') or 'all'
docs.append(doc)
return {
'doc_ids': docids,
'doc_model': 'mrp.bom',
'docs': docs,
}
@api.model
def get_html(self, bom_id=False, searchQty=1, searchVariant=False):
res = self._get_report_data(bom_id=bom_id, searchQty=searchQty, searchVariant=searchVariant)
res['lines']['report_type'] = 'html'
res['lines']['report_structure'] = 'all'
res['lines']['has_attachments'] = res['lines']['attachments'] or any(component['attachments'] for component in res['lines']['components'])
res['lines'] = self.env.ref('mrp.report_mrp_bom')._render({'data': res['lines']})
return res
@api.model
def get_bom(self, bom_id=False, product_id=False, line_qty=False, line_id=False, level=False):
lines = self._get_bom(bom_id=bom_id, product_id=product_id, line_qty=line_qty, line_id=line_id, level=level)
return self.env.ref('mrp.report_mrp_bom_line')._render({'data': lines})
@api.model
def get_operations(self, product_id=False, bom_id=False, qty=0, level=0):
bom = self.env['mrp.bom'].browse(bom_id)
product = self.env['product.product'].browse(product_id)
lines = self._get_operation_line(product, bom, float_round(qty / bom.product_qty, precision_rounding=1, rounding_method='UP'), level)
values = {
'bom_id': bom_id,
'currency': self.env.company.currency_id,
'operations': lines,
'extra_column_count': self._get_extra_column_count()
}
return self.env.ref('mrp.report_mrp_operation_line')._render({'data': values})
@api.model
def get_byproducts(self, bom_id=False, qty=0, level=0, total=0):
bom = self.env['mrp.bom'].browse(bom_id)
lines, dummy = self._get_byproducts_lines(bom, qty, level, total)
values = {
'bom_id': bom_id,
'currency': self.env.company.currency_id,
'byproducts': lines,
'extra_column_count': self._get_extra_column_count(),
}
return self.env.ref('mrp.report_mrp_byproduct_line')._render({'data': values})
@api.model
def _get_report_data(self, bom_id, searchQty=0, searchVariant=False):
lines = {}
bom = self.env['mrp.bom'].browse(bom_id)
bom_quantity = searchQty or bom.product_qty or 1
bom_product_variants = {}
bom_uom_name = ''
if bom:
bom_uom_name = bom.product_uom_id.name
# Get variants used for search
if not bom.product_id:
for variant in bom.product_tmpl_id.product_variant_ids:
bom_product_variants[variant.id] = variant.display_name
lines = self._get_bom(bom_id, product_id=searchVariant, line_qty=bom_quantity, level=1)
return {
'lines': lines,
'variants': bom_product_variants,
'bom_uom_name': bom_uom_name,
'bom_qty': bom_quantity,
'is_variant_applied': self.env.user.user_has_groups('product.group_product_variant') and len(bom_product_variants) > 1,
'is_uom_applied': self.env.user.user_has_groups('uom.group_uom'),
'extra_column_count': self._get_extra_column_count()
}
def _get_bom(self, bom_id=False, product_id=False, line_qty=False, line_id=False, level=False):
bom = self.env['mrp.bom'].browse(bom_id)
company = bom.company_id or self.env.company
bom_quantity = line_qty
if line_id:
current_line = self.env['mrp.bom.line'].browse(int(line_id))
bom_quantity = current_line.product_uom_id._compute_quantity(line_qty, bom.product_uom_id) or 0
# Display bom components for current selected product variant
if product_id:
product = self.env['product.product'].browse(int(product_id))
else:
product = bom.product_id or bom.product_tmpl_id.product_variant_id
if product:
attachments = self.env['mrp.document'].search(['|', '&', ('res_model', '=', 'product.product'),
('res_id', '=', product.id), '&', ('res_model', '=', 'product.template'), ('res_id', '=', product.product_tmpl_id.id)])
else:
# Use the product template instead of the variant
product = bom.product_tmpl_id
attachments = self.env['mrp.document'].search([('res_model', '=', 'product.template'), ('res_id', '=', product.id)])
operations = self._get_operation_line(product, bom, float_round(bom_quantity, precision_rounding=1, rounding_method='UP'), 0)
lines = {
'bom': bom,
'bom_qty': bom_quantity,
'bom_prod_name': product.display_name,
'currency': company.currency_id,
'product': product,
'code': bom and bom.display_name or '',
'price': product.uom_id._compute_price(product.with_company(company).standard_price, bom.product_uom_id) * bom_quantity,
'total': sum([op['total'] for op in operations]),
'level': level or 0,
'operations': operations,
'operations_cost': sum([op['total'] for op in operations]),
'attachments': attachments,
'operations_time': sum([op['duration_expected'] for op in operations])
}
components, total = self._get_bom_lines(bom, bom_quantity, product, line_id, level)
lines['total'] += total
lines['components'] = components
byproducts, byproduct_cost_portion = self._get_byproducts_lines(bom, bom_quantity, level, lines['total'])
lines['byproducts'] = byproducts
lines['cost_share'] = float_round(1 - byproduct_cost_portion, precision_rounding=0.0001)
lines['bom_cost'] = lines['total'] * lines['cost_share']
lines['byproducts_cost'] = sum(byproduct['bom_cost'] for byproduct in byproducts)
lines['byproducts_total'] = sum(byproduct['product_qty'] for byproduct in byproducts)
lines['extra_column_count'] = self._get_extra_column_count()
return lines
def _get_bom_lines(self, bom, bom_quantity, product, line_id, level):
components = []
total = 0
for line in bom.bom_line_ids:
line_quantity = (bom_quantity / (bom.product_qty or 1.0)) * line.product_qty
if line._skip_bom_line(product):
continue
company = bom.company_id or self.env.company
price = line.product_id.uom_id._compute_price(line.product_id.with_company(company).standard_price, line.product_uom_id) * line_quantity
if line.child_bom_id:
factor = line.product_uom_id._compute_quantity(line_quantity, line.child_bom_id.product_uom_id)
sub_total = self._get_price(line.child_bom_id, factor, line.product_id)
byproduct_cost_share = sum(line.child_bom_id.byproduct_ids.mapped('cost_share'))
if byproduct_cost_share:
sub_total *= float_round(1 - byproduct_cost_share / 100, precision_rounding=0.0001)
else:
sub_total = price
sub_total = self.env.company.currency_id.round(sub_total)
components.append({
'prod_id': line.product_id.id,
'prod_name': line.product_id.display_name,
'code': line.child_bom_id and line.child_bom_id.display_name or '',
'prod_qty': line_quantity,
'prod_uom': line.product_uom_id.name,
'prod_cost': company.currency_id.round(price),
'parent_id': bom.id,
'line_id': line.id,
'level': level or 0,
'total': sub_total,
'child_bom': line.child_bom_id.id,
'phantom_bom': line.child_bom_id and line.child_bom_id.type == 'phantom' or False,
'attachments': self.env['mrp.document'].search(['|', '&',
('res_model', '=', 'product.product'), ('res_id', '=', line.product_id.id), '&', ('res_model', '=', 'product.template'), ('res_id', '=', line.product_id.product_tmpl_id.id)]),
})
total += sub_total
return components, total
def _get_byproducts_lines(self, bom, bom_quantity, level, total):
byproducts = []
byproduct_cost_portion = 0
company = bom.company_id or self.env.company
for byproduct in bom.byproduct_ids:
line_quantity = (bom_quantity / (bom.product_qty or 1.0)) * byproduct.product_qty
cost_share = byproduct.cost_share / 100
byproduct_cost_portion += cost_share
price = byproduct.product_id.uom_id._compute_price(byproduct.product_id.with_company(company).standard_price, byproduct.product_uom_id) * line_quantity
byproducts.append({
'product_id': byproduct.product_id,
'product_name': byproduct.product_id.display_name,
'product_qty': line_quantity,
'product_uom': byproduct.product_uom_id.name,
'product_cost': company.currency_id.round(price),
'parent_id': bom.id,
'level': level or 0,
'bom_cost': company.currency_id.round(total * cost_share),
'cost_share': cost_share,
})
return byproducts, byproduct_cost_portion
def _get_operation_line(self, product, bom, qty, level):
operations = []
total = 0.0
qty = bom.product_uom_id._compute_quantity(qty, bom.product_tmpl_id.uom_id)
for operation in bom.operation_ids:
if operation._skip_operation_line(product):
continue
operation_cycle = float_round(qty / operation.workcenter_id.capacity, precision_rounding=1, rounding_method='UP')
duration_expected = (operation_cycle * operation.time_cycle * 100.0 / operation.workcenter_id.time_efficiency) + (operation.workcenter_id.time_stop + operation.workcenter_id.time_start)
total = ((duration_expected / 60.0) * operation.workcenter_id.costs_hour)
operations.append({
'level': level or 0,
'operation': operation,
'name': operation.name + ' - ' + operation.workcenter_id.name,
'duration_expected': duration_expected,
'total': self.env.company.currency_id.round(total),
})
return operations
def _get_price(self, bom, factor, product):
price = 0
if bom.operation_ids:
# routing are defined on a BoM and don't have a concept of quantity.
# It means that the operation time are defined for the quantity on
# the BoM (the user produces a batch of products). E.g the user
# product a batch of 10 units with a 5 minutes operation, the time
# will be the 5 for a quantity between 1-10, then doubled for
# 11-20,...
operation_cycle = float_round(factor, precision_rounding=1, rounding_method='UP')
operations = self._get_operation_line(product, bom, operation_cycle, 0)
price += sum([op['total'] for op in operations])
for line in bom.bom_line_ids:
if line._skip_bom_line(product):
continue
if line.child_bom_id:
qty = line.product_uom_id._compute_quantity(line.product_qty * (factor / bom.product_qty), line.child_bom_id.product_uom_id)
sub_price = self._get_price(line.child_bom_id, qty, line.product_id)
byproduct_cost_share = sum(line.child_bom_id.byproduct_ids.mapped('cost_share'))
if byproduct_cost_share:
sub_price *= float_round(1 - byproduct_cost_share / 100, precision_rounding=0.0001)
price += sub_price
else:
prod_qty = line.product_qty * factor / bom.product_qty
company = bom.company_id or self.env.company
not_rounded_price = line.product_id.uom_id._compute_price(line.product_id.with_company(company).standard_price, line.product_uom_id) * prod_qty
price += company.currency_id.round(not_rounded_price)
return price
def _get_sub_lines(self, bom, product_id, line_qty, line_id, level, child_bom_ids, unfolded):
data = self._get_bom(bom_id=bom.id, product_id=product_id, line_qty=line_qty, line_id=line_id, level=level)
bom_lines = data['components']
lines = []
for bom_line in bom_lines:
lines.append({
'name': bom_line['prod_name'],
'type': 'bom',
'quantity': bom_line['prod_qty'],
'uom': bom_line['prod_uom'],
'prod_cost': bom_line['prod_cost'],
'bom_cost': bom_line['total'],
'level': bom_line['level'],
'code': bom_line['code'],
'child_bom': bom_line['child_bom'],
'prod_id': bom_line['prod_id']
})
if bom_line['child_bom'] and (unfolded or bom_line['child_bom'] in child_bom_ids):
line = self.env['mrp.bom.line'].browse(bom_line['line_id'])
lines += (self._get_sub_lines(line.child_bom_id, line.product_id.id, bom_line['prod_qty'], line, level + 1, child_bom_ids, unfolded))
if data['operations']:
lines.append({
'name': _('Operations'),
'type': 'operation',
'quantity': data['operations_time'],
'uom': _('minutes'),
'bom_cost': data['operations_cost'],
'level': level,
})
for operation in data['operations']:
if unfolded or 'operation-' + str(bom.id) in child_bom_ids:
lines.append({
'name': operation['name'],
'type': 'operation',
'quantity': operation['duration_expected'],
'uom': _('minutes'),
'bom_cost': operation['total'],
'level': level + 1,
})
if data['byproducts']:
lines.append({
'name': _('Byproducts'),
'type': 'byproduct',
'uom': False,
'quantity': data['byproducts_total'],
'bom_cost': data['byproducts_cost'],
'level': level,
})
for byproduct in data['byproducts']:
if unfolded or 'byproduct-' + str(bom.id) in child_bom_ids:
lines.append({
'name': byproduct['product_name'],
'type': 'byproduct',
'quantity': byproduct['product_qty'],
'uom': byproduct['product_uom'],
'prod_cost': byproduct['product_cost'],
'bom_cost': byproduct['bom_cost'],
'level': level + 1,
})
return lines
def _get_pdf_line(self, bom_id, product_id=False, qty=1, child_bom_ids=None, unfolded=False):
if child_bom_ids is None:
child_bom_ids = set()
bom = self.env['mrp.bom'].browse(bom_id)
product_id = product_id or bom.product_id.id or bom.product_tmpl_id.product_variant_id.id
data = self._get_bom(bom_id=bom_id, product_id=product_id, line_qty=qty, )
pdf_lines = self._get_sub_lines(bom, product_id, qty, False, 1, child_bom_ids, unfolded)
data['components'] = []
data['lines'] = pdf_lines
data['extra_column_count'] = self._get_extra_column_count()
return data
def _get_extra_column_count(self):
return 0
| 51.846608 | 17,576 |
2,616 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# SKR04
# =====
# Dieses Modul bietet Ihnen einen deutschen Kontenplan basierend auf dem SKR03.
# Gemäss der aktuellen Einstellungen ist ein neues Unternehmen in Odoo
# Umsatzsteuerpflichtig. Zahlreiche Erlös- und Aufwandskonten enthalten
# bereits eine zugeordnete Steuer. Hierdurch wird für diese Konten bereits
# die richtige Vorsteuer (Eingangsrechnungen) bzw. Umsatzsteuer
# (Ausgangsrechnungen) automatisch ausgewählt.
#
# Die Zuordnung von Steuerkonten zu Produkten und / oder Sachkonten kann
# für den jeweiligen betrieblichen Anwendungszweck überarbeitet oder
# auch erweitert werden.
# Die mit diesem Kontenrahmen installierten Steuerschlüssel (z.B. 19%, 7%,
# steuerfrei) können hierzu bei den Produktstammdaten hinterlegt werden
# (in Abhängigkeit der Steuervorschriften). Die Zuordnung erfolgt auf
# dem Aktenreiter Finanzbuchhaltung (Kategorie: Umsatzsteuer / Vorsteuer).
# Die Zuordnung der Steuern für Ein- und Ausfuhren aus EU Ländern, sowie auch
# für den Ein- und Verkauf aus und in Drittländer sollten beim Partner
# (Lieferant / Kunde) hinterlegt werden (in Anhängigkeit vom Herkunftsland
# des Lieferanten/Kunden). Diese Zuordnung ist 'höherwertig' als
# die Zuordnung bei Produkten und überschreibt diese im Einzelfall.
#
# Zur Vereinfachung der Steuerausweise und Buchung bei Auslandsgeschäften
# erlaubt Odoo ein generelles Mapping von Steuerausweis und Steuerkonten
# (z.B. Zuordnung 'Umsatzsteuer 19%' zu 'steuerfreie Einfuhren aus der EU')
# zwecks Zuordnung dieses Mappings zum ausländischen Partner (Kunde/Lieferant).
{
'name': 'Germany SKR04 - Accounting',
'icon': '/l10n_de/static/description/icon.png',
'version': '3.1',
'author': 'openbig.org',
'website': 'http://www.openbig.org',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Dieses Modul beinhaltet einen deutschen Kontenrahmen basierend auf dem SKR04.
==============================================================================
German accounting chart and localization.
""",
'depends': ['l10n_de'],
'data': [
'data/l10n_de_skr04_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_de_skr04_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_fiscal_position_data.xml',
'data/account_reconcile_model_template.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 43.3 | 2,598 |
258 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
update_taxes_from_templates(cr, 'l10n_de_skr04.l10n_chart_de_skr04')
| 43 | 258 |
271 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import odoo
def migrate(cr, version):
registry = odoo.registry(cr.dbname)
from odoo.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable
migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_de_skr04')
| 33.875 | 271 |
476 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import sys
class ExceptionLogger:
"""
Redirect Exceptions to the logger to keep track of them in the log file.
"""
def __init__(self):
self.logger = logging.getLogger()
def write(self, message):
if message != '\n':
self.logger.error(message)
def flush(self):
pass
sys.stderr = ExceptionLogger()
| 20.695652 | 476 |
3,092 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from threading import Thread
import time
from odoo.addons.hw_drivers.main import drivers, interfaces, iot_devices
_logger = logging.getLogger(__name__)
class InterfaceMetaClass(type):
def __new__(cls, clsname, bases, attrs):
new_interface = super(InterfaceMetaClass, cls).__new__(cls, clsname, bases, attrs)
interfaces[clsname] = new_interface
return new_interface
class Interface(Thread, metaclass=InterfaceMetaClass):
_loop_delay = 3 # Delay (in seconds) between calls to get_devices or 0 if it should be called only once
_detected_devices = {}
connection_type = ''
def __init__(self):
super(Interface, self).__init__()
self.drivers = sorted([d for d in drivers if d.connection_type == self.connection_type], key=lambda d: d.priority, reverse=True)
def run(self):
while self.connection_type and self.drivers:
self.update_iot_devices(self.get_devices())
if not self._loop_delay:
break
time.sleep(self._loop_delay)
def update_iot_devices(self, devices={}):
added = devices.keys() - self._detected_devices
removed = self._detected_devices - devices.keys()
# keys() returns a dict_keys, and the values of that stay in sync with the
# original dictionary if it changes. This means that get_devices needs to return
# a newly created dictionary every time. If it doesn't do that and reuses the
# same dictionary, this logic won't detect any changes that are made. Could be
# avoided by converting the dict_keys into a regular dict. The current logic
# also can't detect if a device is replaced by a different one with the same
# key. Also, _detected_devices starts out as a class variable but gets turned
# into an instance variable here. It would be better if it was an instance
# variable from the start to avoid confusion.
self._detected_devices = devices.keys()
for identifier in removed:
if identifier in iot_devices:
iot_devices[identifier].disconnect()
_logger.info('Device %s is now disconnected', identifier)
for identifier in added:
for driver in self.drivers:
if driver.supported(devices[identifier]):
_logger.info('Device %s is now connected', identifier)
d = driver(identifier, devices[identifier])
d.daemon = True
iot_devices[identifier] = d
# Start the thread after creating the iot_devices entry so the
# thread can assume the iot_devices entry will exist while it's
# running, at least until the `disconnect` above gets triggered
# when `removed` is not empty.
d.start()
break
def get_devices(self):
raise NotImplementedError()
| 44.171429 | 3,092 |
618 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Hardware Proxy',
'category': 'Hidden',
'sequence': 6,
'summary': 'Connect the Web Client to Hardware Peripherals',
'website': 'https://www.odoo.com/app/iot',
'description': """
Hardware Poxy
=============
This module allows you to remotely use peripherals connected to this server.
This modules only contains the enabling framework. The actual devices drivers
are found in other modules that must be installed separately.
""",
'installable': False,
'license': 'LGPL-3',
}
| 28.090909 | 618 |
3,029 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
import logging
import subprocess
import requests
from threading import Thread
import time
import urllib3
from odoo.modules.module import get_resource_path
from odoo.addons.hw_drivers.main import iot_devices, manager
from odoo.addons.hw_drivers.tools import helpers
_logger = logging.getLogger(__name__)
class ConnectionManager(Thread):
def __init__(self):
super(ConnectionManager, self).__init__()
self.pairing_code = False
self.pairing_uuid = False
def run(self):
if not helpers.get_odoo_server_url() and not helpers.access_point():
end_time = datetime.now() + timedelta(minutes=5)
while (datetime.now() < end_time):
self._connect_box()
time.sleep(10)
self.pairing_code = False
self.pairing_uuid = False
self._refresh_displays()
def _connect_box(self):
data = {
'jsonrpc': 2.0,
'params': {
'pairing_code': self.pairing_code,
'pairing_uuid': self.pairing_uuid,
}
}
try:
urllib3.disable_warnings()
req = requests.post('https://iot-proxy.odoo.com/odoo-enterprise/iot/connect-box', json=data, verify=False)
result = req.json().get('result', {})
if all(key in result for key in ['pairing_code', 'pairing_uuid']):
self.pairing_code = result['pairing_code']
self.pairing_uuid = result['pairing_uuid']
elif all(key in result for key in ['url', 'token', 'db_uuid', 'enterprise_code']):
self._connect_to_server(result['url'], result['token'], result['db_uuid'], result['enterprise_code'])
except Exception as e:
_logger.error('Could not reach iot-proxy.odoo.com')
_logger.error('A error encountered : %s ' % e)
def _connect_to_server(self, url, token, db_uuid, enterprise_code):
if db_uuid and enterprise_code:
helpers.add_credential(db_uuid, enterprise_code)
# Save DB URL and token
subprocess.check_call([get_resource_path('point_of_sale', 'tools/posbox/configuration/connect_to_server.sh'), url, '', token, 'noreboot'])
# Notify the DB, so that the kanban view already shows the IoT Box
manager.send_alldevices()
# Restart to checkout the git branch, get a certificate, load the IoT handlers...
subprocess.check_call(["sudo", "service", "odoo", "restart"])
def _refresh_displays(self):
"""Refresh all displays to hide the pairing code"""
for d in iot_devices:
if iot_devices[d].device_type == 'display':
iot_devices[d].action({
'action': 'display_refresh'
})
connection_manager = ConnectionManager()
connection_manager.daemon = True
connection_manager.start()
| 39.337662 | 3,029 |
1,429 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
class IoTBoxHttpRequest(http.HttpRequest):
def dispatch(self):
if self._is_cors_preflight(http.request.endpoint):
# Using the PoS in debug mode in v12, the call to '/hw_proxy/handshake' contains the
# 'X-Debug-Mode' header, which was removed from 'Access-Control-Allow-Headers' in v13.
# When the code of http.py is not checked out to v12 (i.e. in Community), the connection
# fails as the header is rejected and none of the devices can be used.
headers = {
'Access-Control-Max-Age': 60 * 60 * 24,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Debug-Mode'
}
return http.Response(status=200, headers=headers)
return super(IoTBoxHttpRequest, self).dispatch()
class IoTBoxRoot(http.Root):
def setup_db(self, httprequest):
# No database on the IoT Box
pass
def get_request(self, httprequest):
# Override HttpRequestwith IoTBoxHttpRequest
if httprequest.mimetype not in ("application/json", "application/json-rpc"):
return IoTBoxHttpRequest(httprequest)
return super(IoTBoxRoot, self).get_request(httprequest)
http.Root = IoTBoxRoot
http.root = IoTBoxRoot()
| 42.029412 | 1,429 |
3,994 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from traceback import format_exc
from dbus.mainloop.glib import DBusGMainLoop
import json
import logging
import socket
from threading import Thread
import time
import urllib3
from odoo.addons.hw_drivers.tools import helpers
_logger = logging.getLogger(__name__)
drivers = []
interfaces = {}
iot_devices = {}
class Manager(Thread):
def send_alldevices(self):
"""
This method send IoT Box and devices informations to Odoo database
"""
server = helpers.get_odoo_server_url()
if server:
subject = helpers.read_file_first_line('odoo-subject.conf')
if subject:
domain = helpers.get_ip().replace('.', '-') + subject.strip('*')
else:
domain = helpers.get_ip()
iot_box = {
'name': socket.gethostname(),
'identifier': helpers.get_mac_address(),
'ip': domain,
'token': helpers.get_token(),
'version': helpers.get_version(),
}
devices_list = {}
for device in iot_devices:
identifier = iot_devices[device].device_identifier
devices_list[identifier] = {
'name': iot_devices[device].device_name,
'type': iot_devices[device].device_type,
'manufacturer': iot_devices[device].device_manufacturer,
'connection': iot_devices[device].device_connection,
}
data = {'params': {'iot_box': iot_box, 'devices': devices_list,}}
# disable certifiacte verification
urllib3.disable_warnings()
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
try:
http.request(
'POST',
server + "/iot/setup",
body=json.dumps(data).encode('utf8'),
headers={
'Content-type': 'application/json',
'Accept': 'text/plain',
},
)
except Exception as e:
_logger.error('Could not reach configured server')
_logger.error('A error encountered : %s ' % e)
else:
_logger.warning('Odoo server not set')
def run(self):
"""
Thread that will load interfaces and drivers and contact the odoo server with the updates
"""
helpers.check_git_branch()
is_certificate_ok, certificate_details = helpers.get_certificate_status()
if not is_certificate_ok:
_logger.warning("An error happened when trying to get the HTTPS certificate: %s",
certificate_details)
# We first add the IoT Box to the connected DB because IoT handlers cannot be downloaded if
# the identifier of the Box is not found in the DB. So add the Box to the DB.
self.send_alldevices()
helpers.download_iot_handlers()
helpers.load_iot_handlers()
# Start the interfaces
for interface in interfaces.values():
i = interface()
i.daemon = True
i.start()
# Check every 3 secondes if the list of connected devices has changed and send the updated
# list to the connected DB.
self.previous_iot_devices = []
while 1:
try:
if iot_devices != self.previous_iot_devices:
self.send_alldevices()
self.previous_iot_devices = iot_devices.copy()
time.sleep(3)
except:
# No matter what goes wrong, the Manager loop needs to keep running
_logger.error(format_exc())
# Must be started from main thread
DBusGMainLoop(set_as_default=True)
manager = Manager()
manager.daemon = True
manager.start()
| 35.660714 | 3,994 |
2,554 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from threading import Thread, Event
from odoo.addons.hw_drivers.main import drivers, iot_devices
from odoo.tools.lru import LRU
class DriverMetaClass(type):
def __new__(cls, clsname, bases, attrs):
newclass = super(DriverMetaClass, cls).__new__(cls, clsname, bases, attrs)
if hasattr(newclass, 'priority'):
newclass.priority += 1
else:
newclass.priority = 0
drivers.append(newclass)
return newclass
class Driver(Thread, metaclass=DriverMetaClass):
"""
Hook to register the driver into the drivers list
"""
connection_type = ''
def __init__(self, identifier, device):
super(Driver, self).__init__()
self.dev = device
self.device_identifier = identifier
self.device_name = ''
self.device_connection = ''
self.device_type = ''
self.device_manufacturer = ''
self.data = {'value': ''}
self._actions = {}
self._stopped = Event()
# Least Recently Used (LRU) Cache that will store the idempotent keys already seen.
self._iot_idempotent_ids_cache = LRU(500)
@classmethod
def supported(cls, device):
"""
On specific driver override this method to check if device is supported or not
return True or False
"""
return False
def action(self, data):
"""Helper function that calls a specific action method on the device.
:param data: the `_actions` key mapped to the action method we want to call
:type data: string
"""
self._actions[data.get('action', '')](data)
def disconnect(self):
self._stopped.set()
del iot_devices[self.device_identifier]
def _check_idempotency(self, iot_idempotent_id, session_id):
"""
Some IoT requests for the same action might be received several times.
To avoid duplicating the resulting actions, we check if the action was "recently" executed.
If this is the case, we will simply ignore the action
:return: the `session_id` of the same `iot_idempotent_id` if any. False otherwise,
which means that it is the first time that the IoT box received the request with this ID
"""
cache = self._iot_idempotent_ids_cache
if iot_idempotent_id in cache:
return cache[iot_idempotent_id]
cache[iot_idempotent_id] = session_id
return False
| 34.053333 | 2,554 |
1,832 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from threading import Event
import time
from odoo.http import request
class EventManager(object):
def __init__(self):
self.events = []
self.sessions = {}
def _delete_expired_sessions(self, max_time=70):
'''
Clears sessions that are no longer called.
:param max_time: time a session can stay unused before being deleted
'''
now = time.time()
expired_sessions = [
session
for session in self.sessions
if now - self.sessions[session]['time_request'] > max_time
]
for session in expired_sessions:
del self.sessions[session]
def add_request(self, listener):
self.session = {
'session_id': listener['session_id'],
'devices': listener['devices'],
'event': Event(),
'result': {},
'time_request': time.time(),
}
self._delete_expired_sessions()
self.sessions[listener['session_id']] = self.session
return self.sessions[listener['session_id']]
def device_changed(self, device):
event = {
**device.data,
'device_identifier': device.device_identifier,
'time': time.time(),
'request_data': json.loads(request.params['data']) if request and 'data' in request.params else None,
}
self.events.append(event)
for session in self.sessions:
if device.device_identifier in self.sessions[session]['devices'] and not self.sessions[session]['event'].isSet():
self.sessions[session]['result'] = event
self.sessions[session]['event'].set()
event_manager = EventManager()
| 32.714286 | 1,832 |
13,823 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from enum import Enum
from importlib import util
import io
import json
import logging
import netifaces
from OpenSSL import crypto
import os
from pathlib import Path
import subprocess
import urllib3
import zipfile
from threading import Thread
import time
from odoo import _, http
from odoo.modules.module import get_resource_path
_logger = logging.getLogger(__name__)
#----------------------------------------------------------
# Helper
#----------------------------------------------------------
class CertificateStatus(Enum):
OK = 1
NEED_REFRESH = 2
ERROR = 3
class IoTRestart(Thread):
"""
Thread to restart odoo server in IoT Box when we must return a answer before
"""
def __init__(self, delay):
Thread.__init__(self)
self.delay = delay
def run(self):
time.sleep(self.delay)
subprocess.check_call(["sudo", "service", "odoo", "restart"])
def access_point():
return get_ip() == '10.11.12.1'
def add_credential(db_uuid, enterprise_code):
write_file('odoo-db-uuid.conf', db_uuid)
write_file('odoo-enterprise-code.conf', enterprise_code)
def check_certificate():
"""
Check if the current certificate is up to date or not authenticated
:return CheckCertificateStatus
"""
server = get_odoo_server_url()
if not server:
return {"status": CertificateStatus.ERROR,
"error_code": "ERR_IOT_HTTPS_CHECK_NO_SERVER"}
path = Path('/etc/ssl/certs/nginx-cert.crt')
if not path.exists():
return {"status": CertificateStatus.NEED_REFRESH}
try:
with path.open('r') as f:
cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
except EnvironmentError:
_logger.exception("Unable to read certificate file")
return {"status": CertificateStatus.ERROR,
"error_code": "ERR_IOT_HTTPS_CHECK_CERT_READ_EXCEPTION"}
cert_end_date = datetime.datetime.strptime(cert.get_notAfter().decode('utf-8'), "%Y%m%d%H%M%SZ") - datetime.timedelta(days=10)
for key in cert.get_subject().get_components():
if key[0] == b'CN':
cn = key[1].decode('utf-8')
if cn == 'OdooTempIoTBoxCertificate' or datetime.datetime.now() > cert_end_date:
message = _('Your certificate %s must be updated') % (cn)
_logger.info(message)
return {"status": CertificateStatus.NEED_REFRESH}
else:
message = _('Your certificate %s is valid until %s') % (cn, cert_end_date)
_logger.info(message)
return {"status": CertificateStatus.OK, "message": message}
def check_git_branch():
"""
Check if the local branch is the same than the connected Odoo DB and
checkout to match it if needed.
"""
server = get_odoo_server_url()
if server:
urllib3.disable_warnings()
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
try:
response = http.request(
'POST',
server + "/web/webclient/version_info",
body = '{}',
headers = {'Content-type': 'application/json'}
)
if response.status == 200:
git = ['git', '--work-tree=/home/pi/odoo/', '--git-dir=/home/pi/odoo/.git']
db_branch = json.loads(response.data)['result']['server_serie'].replace('~', '-')
if not subprocess.check_output(git + ['ls-remote', 'origin', db_branch]):
db_branch = 'master'
local_branch = subprocess.check_output(git + ['symbolic-ref', '-q', '--short', 'HEAD']).decode('utf-8').rstrip()
if db_branch != local_branch:
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/"])
subprocess.check_call(["rm", "-rf", "/home/pi/odoo/addons/hw_drivers/iot_handlers/drivers/*"])
subprocess.check_call(["rm", "-rf", "/home/pi/odoo/addons/hw_drivers/iot_handlers/interfaces/*"])
subprocess.check_call(git + ['branch', '-m', db_branch])
subprocess.check_call(git + ['remote', 'set-branches', 'origin', db_branch])
os.system('/home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/posbox_update.sh')
subprocess.call(["sudo", "mount", "-o", "remount,ro", "/"])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups"])
except Exception as e:
_logger.error('Could not reach configured server')
_logger.error('A error encountered : %s ' % e)
def check_image():
"""
Check if the current image of IoT Box is up to date
"""
url = 'https://nightly.odoo.com/master/iotbox/SHA1SUMS.txt'
urllib3.disable_warnings()
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
response = http.request('GET', url)
checkFile = {}
valueActual = ''
for line in response.data.decode().split('\n'):
if line:
value, name = line.split(' ')
checkFile.update({value: name})
if name == 'iotbox-latest.zip':
valueLastest = value
elif name == get_img_name():
valueActual = value
if valueActual == valueLastest:
return False
version = checkFile.get(valueLastest, 'Error').replace('iotboxv', '').replace('.zip', '').split('_')
return {'major': version[0], 'minor': version[1]}
def get_certificate_status(is_first=True):
"""
Will get the HTTPS certificate details if present. Will load the certificate if missing.
:param is_first: Use to make sure that the recursion happens only once
:return: (bool, str)
"""
check_certificate_result = check_certificate()
certificateStatus = check_certificate_result["status"]
if certificateStatus == CertificateStatus.ERROR:
return False, check_certificate_result["error_code"]
if certificateStatus == CertificateStatus.NEED_REFRESH and is_first:
certificate_process = load_certificate()
if certificate_process is not True:
return False, certificate_process
return get_certificate_status(is_first=False) # recursive call to attempt certificate read
return True, check_certificate_result.get("message",
"The HTTPS certificate was generated correctly")
def get_img_name():
major, minor = get_version().split('.')
return 'iotboxv%s_%s.zip' % (major, minor)
def get_ip():
while True:
try:
return netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']
except KeyError:
pass
try:
return netifaces.ifaddresses('wlan0')[netifaces.AF_INET][0]['addr']
except KeyError:
pass
_logger.warning("Couldn't get IP, sleeping and retrying.")
time.sleep(5)
def get_mac_address():
while True:
try:
return netifaces.ifaddresses('eth0')[netifaces.AF_LINK][0]['addr']
except KeyError:
pass
try:
return netifaces.ifaddresses('wlan0')[netifaces.AF_LINK][0]['addr']
except KeyError:
pass
_logger.warning("Couldn't get MAC address, sleeping and retrying.")
time.sleep(5)
def get_ssid():
ap = subprocess.call(['systemctl', 'is-active', '--quiet', 'hostapd']) # if service is active return 0 else inactive
if not ap:
return subprocess.check_output(['grep', '-oP', '(?<=ssid=).*', '/etc/hostapd/hostapd.conf']).decode('utf-8').rstrip()
process_iwconfig = subprocess.Popen(['iwconfig'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process_grep = subprocess.Popen(['grep', 'ESSID:"'], stdin=process_iwconfig.stdout, stdout=subprocess.PIPE)
return subprocess.check_output(['sed', 's/.*"\\(.*\\)"/\\1/'], stdin=process_grep.stdout).decode('utf-8').rstrip()
def get_odoo_server_url():
ap = subprocess.call(['systemctl', 'is-active', '--quiet', 'hostapd']) # if service is active return 0 else inactive
if not ap:
return False
return read_file_first_line('odoo-remote-server.conf')
def get_token():
return read_file_first_line('token')
def get_version():
return subprocess.check_output(['cat', '/var/odoo/iotbox_version']).decode().rstrip()
def get_wifi_essid():
wifi_options = []
process_iwlist = subprocess.Popen(['sudo', 'iwlist', 'wlan0', 'scan'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process_grep = subprocess.Popen(['grep', 'ESSID:"'], stdin=process_iwlist.stdout, stdout=subprocess.PIPE).stdout.readlines()
for ssid in process_grep:
essid = ssid.decode('utf-8').split('"')[1]
if essid not in wifi_options:
wifi_options.append(essid)
return wifi_options
def load_certificate():
"""
Send a request to Odoo with customer db_uuid and enterprise_code to get a true certificate
"""
db_uuid = read_file_first_line('odoo-db-uuid.conf')
enterprise_code = read_file_first_line('odoo-enterprise-code.conf')
if not (db_uuid and enterprise_code):
return "ERR_IOT_HTTPS_LOAD_NO_CREDENTIAL"
url = 'https://www.odoo.com/odoo-enterprise/iot/x509'
data = {
'params': {
'db_uuid': db_uuid,
'enterprise_code': enterprise_code
}
}
urllib3.disable_warnings()
http = urllib3.PoolManager(cert_reqs='CERT_NONE', retries=urllib3.Retry(4))
try:
response = http.request(
'POST',
url,
body = json.dumps(data).encode('utf8'),
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
)
except Exception as e:
_logger.exception("An error occurred while trying to reach odoo.com servers.")
return "ERR_IOT_HTTPS_LOAD_REQUEST_EXCEPTION\n\n%s" % e
if response.status != 200:
return "ERR_IOT_HTTPS_LOAD_REQUEST_STATUS %s\n\n%s" % (response.status, response.reason)
result = json.loads(response.data.decode('utf8'))['result']
if not result:
return "ERR_IOT_HTTPS_LOAD_REQUEST_NO_RESULT"
write_file('odoo-subject.conf', result['subject_cn'])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/"])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/"])
Path('/etc/ssl/certs/nginx-cert.crt').write_text(result['x509_pem'])
Path('/root_bypass_ramdisks/etc/ssl/certs/nginx-cert.crt').write_text(result['x509_pem'])
Path('/etc/ssl/private/nginx-cert.key').write_text(result['private_key_pem'])
Path('/root_bypass_ramdisks/etc/ssl/private/nginx-cert.key').write_text(result['private_key_pem'])
subprocess.call(["sudo", "mount", "-o", "remount,ro", "/"])
subprocess.call(["sudo", "mount", "-o", "remount,ro", "/root_bypass_ramdisks/"])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups"])
subprocess.check_call(["sudo", "service", "nginx", "restart"])
return True
def download_iot_handlers(auto=True):
"""
Get the drivers from the configured Odoo server
"""
server = get_odoo_server_url()
if server:
urllib3.disable_warnings()
pm = urllib3.PoolManager(cert_reqs='CERT_NONE')
server = server + '/iot/get_handlers'
try:
resp = pm.request('POST', server, fields={'mac': get_mac_address(), 'auto': auto})
if resp.data:
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/"])
drivers_path = Path.home() / 'odoo/addons/hw_drivers/iot_handlers'
zip_file = zipfile.ZipFile(io.BytesIO(resp.data))
zip_file.extractall(drivers_path)
subprocess.call(["sudo", "mount", "-o", "remount,ro", "/"])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups"])
except Exception as e:
_logger.error('Could not reach configured server')
_logger.error('A error encountered : %s ' % e)
def load_iot_handlers():
"""
This method loads local files: 'odoo/addons/hw_drivers/iot_handlers/drivers' and
'odoo/addons/hw_drivers/iot_handlers/interfaces'
And execute these python drivers and interfaces
"""
for directory in ['interfaces', 'drivers']:
path = get_resource_path('hw_drivers', 'iot_handlers', directory)
filesList = os.listdir(path)
for file in filesList:
path_file = os.path.join(path, file)
spec = util.spec_from_file_location(file, path_file)
if spec:
module = util.module_from_spec(spec)
spec.loader.exec_module(module)
http.addons_manifest = {}
http.root = http.Root()
def odoo_restart(delay):
IR = IoTRestart(delay)
IR.start()
def read_file_first_line(filename):
path = Path.home() / filename
path = Path('/home/pi/' + filename)
if path.exists():
with path.open('r') as f:
return f.readline().strip('\n')
return ''
def unlink_file(filename):
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/"])
path = Path.home() / filename
if path.exists():
path.unlink()
subprocess.call(["sudo", "mount", "-o", "remount,ro", "/"])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups"])
def write_file(filename, text):
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/"])
path = Path.home() / filename
path.write_text(text)
subprocess.call(["sudo", "mount", "-o", "remount,ro", "/"])
subprocess.call(["sudo", "mount", "-o", "remount,rw", "/root_bypass_ramdisks/etc/cups"])
| 39.269886 | 13,823 |
5,114 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import namedtuple
from contextlib import contextmanager
import logging
import serial
from threading import Lock
import time
import traceback
from odoo import _
from odoo.addons.hw_drivers.event_manager import event_manager
from odoo.addons.hw_drivers.driver import Driver
_logger = logging.getLogger(__name__)
SerialProtocol = namedtuple(
'SerialProtocol',
"name baudrate bytesize stopbits parity timeout writeTimeout measureRegexp statusRegexp "
"commandTerminator commandDelay measureDelay newMeasureDelay "
"measureCommand emptyAnswerValid")
@contextmanager
def serial_connection(path, protocol, is_probing=False):
"""Opens a serial connection to a device and closes it automatically after use.
:param path: path to the device
:type path: string
:param protocol: an object containing the serial protocol to connect to a device
:type protocol: namedtuple
:param is_probing: a flag thet if set to `True` makes the timeouts longer, defaults to False
:type is_probing: bool, optional
"""
PROBING_TIMEOUT = 1
port_config = {
'baudrate': protocol.baudrate,
'bytesize': protocol.bytesize,
'stopbits': protocol.stopbits,
'parity': protocol.parity,
'timeout': PROBING_TIMEOUT if is_probing else protocol.timeout, # longer timeouts for probing
'writeTimeout': PROBING_TIMEOUT if is_probing else protocol.writeTimeout # longer timeouts for probing
}
connection = serial.Serial(path, **port_config)
yield connection
connection.close()
class SerialDriver(Driver):
"""Abstract base class for serial drivers."""
_protocol = None
connection_type = 'serial'
STATUS_CONNECTED = 'connected'
STATUS_ERROR = 'error'
STATUS_CONNECTING = 'connecting'
def __init__(self, identifier, device):
""" Attributes initialization method for `SerialDriver`.
:param device: path to the device
:type device: str
"""
super(SerialDriver, self).__init__(identifier, device)
self._actions.update({
'get_status': self._push_status,
})
self.device_connection = 'serial'
self._device_lock = Lock()
self._status = {'status': self.STATUS_CONNECTING, 'message_title': '', 'message_body': ''}
self._set_name()
def _get_raw_response(connection):
pass
def _push_status(self):
"""Updates the current status and pushes it to the frontend."""
self.data['status'] = self._status
event_manager.device_changed(self)
def _set_name(self):
"""Tries to build the device's name based on its type and protocol name but falls back on a default name if that doesn't work."""
try:
name = ('%s serial %s' % (self._protocol.name, self.device_type)).title()
except Exception:
name = 'Unknown Serial Device'
self.device_name = name
def _take_measure(self):
pass
def _do_action(self, data):
"""Helper function that calls a specific action method on the device.
:param data: the `_actions` key mapped to the action method we want to call
:type data: string
"""
try:
with self._device_lock:
self._actions[data['action']](data)
time.sleep(self._protocol.commandDelay)
except Exception:
msg = _('An error occurred while performing action %s on %s') % (data, self.device_name)
_logger.exception(msg)
self._status = {'status': self.STATUS_ERROR, 'message_title': msg, 'message_body': traceback.format_exc()}
self._push_status()
def action(self, data):
"""Establish a connection with the device if needed and have it perform a specific action.
:param data: the `_actions` key mapped to the action method we want to call
:type data: string
"""
if self._connection and self._connection.isOpen():
self._do_action(data)
else:
with serial_connection(self.device_identifier, self._protocol) as connection:
self._connection = connection
self._do_action(data)
def run(self):
"""Continuously gets new measures from the device."""
try:
with serial_connection(self.device_identifier, self._protocol) as connection:
self._connection = connection
self._status['status'] = self.STATUS_CONNECTED
self._push_status()
while not self._stopped.isSet():
self._take_measure()
time.sleep(self._protocol.newMeasureDelay)
except Exception:
msg = _('Error while reading %s', self.device_name)
_logger.exception(msg)
self._status = {'status': self.STATUS_ERROR, 'message_title': msg, 'message_body': traceback.format_exc()}
self._push_status()
| 35.513889 | 5,114 |
14,971 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ctypes
import evdev
import json
import logging
from lxml import etree
import os
from pathlib import Path
from queue import Queue, Empty
import re
import subprocess
from threading import Lock
import time
import urllib3
from usb import util
from odoo import http, _
from odoo.addons.hw_drivers.controllers.proxy import proxy_drivers
from odoo.addons.hw_drivers.driver import Driver
from odoo.addons.hw_drivers.event_manager import event_manager
from odoo.addons.hw_drivers.main import iot_devices
from odoo.addons.hw_drivers.tools import helpers
_logger = logging.getLogger(__name__)
xlib = ctypes.cdll.LoadLibrary('libX11.so.6')
class KeyboardUSBDriver(Driver):
connection_type = 'usb'
keyboard_layout_groups = []
available_layouts = []
def __init__(self, identifier, device):
if not hasattr(KeyboardUSBDriver, 'display'):
os.environ['XAUTHORITY'] = "/run/lightdm/pi/xauthority"
KeyboardUSBDriver.display = xlib.XOpenDisplay(bytes(":0.0", "utf-8"))
super(KeyboardUSBDriver, self).__init__(identifier, device)
self.device_connection = 'direct'
self.device_name = self._set_name()
self._actions.update({
'update_layout': self._update_layout,
'update_is_scanner': self._save_is_scanner,
'': self._action_default,
})
# from https://github.com/xkbcommon/libxkbcommon/blob/master/test/evdev-scancodes.h
self._scancode_to_modifier = {
42: 'left_shift',
54: 'right_shift',
58: 'caps_lock',
69: 'num_lock',
100: 'alt_gr', # right alt
}
self._tracked_modifiers = {modifier: False for modifier in self._scancode_to_modifier.values()}
if not KeyboardUSBDriver.available_layouts:
KeyboardUSBDriver.load_layouts_list()
KeyboardUSBDriver.send_layouts_list()
for evdev_device in [evdev.InputDevice(path) for path in evdev.list_devices()]:
if (device.idVendor == evdev_device.info.vendor) and (device.idProduct == evdev_device.info.product):
self.input_device = evdev_device
self._set_device_type('scanner') if self._is_scanner() else self._set_device_type()
@classmethod
def supported(cls, device):
for cfg in device:
for itf in cfg:
if itf.bInterfaceClass == 3 and itf.bInterfaceProtocol != 2:
device.interface_protocol = itf.bInterfaceProtocol
return True
return False
@classmethod
def get_status(self):
"""Allows `hw_proxy.Proxy` to retrieve the status of the scanners"""
status = 'connected' if any(iot_devices[d].device_type == "scanner" for d in iot_devices) else 'disconnected'
return {'status': status, 'messages': ''}
@classmethod
def send_layouts_list(cls):
server = helpers.get_odoo_server_url()
if server:
urllib3.disable_warnings()
pm = urllib3.PoolManager(cert_reqs='CERT_NONE')
server = server + '/iot/keyboard_layouts'
try:
pm.request('POST', server, fields={'available_layouts': json.dumps(cls.available_layouts)})
except Exception as e:
_logger.error('Could not reach configured server')
_logger.error('A error encountered : %s ' % e)
@classmethod
def load_layouts_list(cls):
tree = etree.parse("/usr/share/X11/xkb/rules/base.xml", etree.XMLParser(ns_clean=True, recover=True))
layouts = tree.xpath("//layout")
for layout in layouts:
layout_name = layout.xpath("./configItem/name")[0].text
layout_description = layout.xpath("./configItem/description")[0].text
KeyboardUSBDriver.available_layouts.append({
'name': layout_description,
'layout': layout_name,
})
for variant in layout.xpath("./variantList/variant"):
variant_name = variant.xpath("./configItem/name")[0].text
variant_description = variant.xpath("./configItem/description")[0].text
KeyboardUSBDriver.available_layouts.append({
'name': variant_description,
'layout': layout_name,
'variant': variant_name,
})
def _set_name(self):
try:
manufacturer = util.get_string(self.dev, self.dev.iManufacturer)
product = util.get_string(self.dev, self.dev.iProduct)
return re.sub(r"[^\w \-+/*&]", '', "%s - %s" % (manufacturer, product))
except ValueError as e:
_logger.warning(e)
return _('Unknown input device')
def run(self):
try:
for event in self.input_device.read_loop():
if self._stopped.isSet():
break
if event.type == evdev.ecodes.EV_KEY:
data = evdev.categorize(event)
modifier_name = self._scancode_to_modifier.get(data.scancode)
if modifier_name:
if modifier_name in ('caps_lock', 'num_lock'):
if data.keystate == 1:
self._tracked_modifiers[modifier_name] = not self._tracked_modifiers[modifier_name]
else:
self._tracked_modifiers[modifier_name] = bool(data.keystate) # 1 for keydown, 0 for keyup
elif data.keystate == 1:
self.key_input(data.scancode)
except Exception as err:
_logger.warning(err)
def _change_keyboard_layout(self, new_layout):
"""Change the layout of the current device to what is specified in
new_layout.
Args:
new_layout (dict): A dict containing two keys:
- layout (str): The layout code
- variant (str): An optional key to represent the variant of the
selected layout
"""
if hasattr(self, 'keyboard_layout'):
KeyboardUSBDriver.keyboard_layout_groups.remove(self.keyboard_layout)
if new_layout:
self.keyboard_layout = new_layout.get('layout') or 'us'
if new_layout.get('variant'):
self.keyboard_layout += "(%s)" % new_layout['variant']
else:
self.keyboard_layout = 'us'
KeyboardUSBDriver.keyboard_layout_groups.append(self.keyboard_layout)
subprocess.call(["setxkbmap", "-display", ":0.0", ",".join(KeyboardUSBDriver.keyboard_layout_groups)])
# Close then re-open display to refresh the mapping
xlib.XCloseDisplay(KeyboardUSBDriver.display)
KeyboardUSBDriver.display = xlib.XOpenDisplay(bytes(":0.0", "utf-8"))
def save_layout(self, layout):
"""Save the layout to a file on the box to read it when restarting it.
We need that in order to keep the selected layout after a reboot.
Args:
new_layout (dict): A dict containing two keys:
- layout (str): The layout code
- variant (str): An optional key to represent the variant of the
selected layout
"""
file_path = Path.home() / 'odoo-keyboard-layouts.conf'
if file_path.exists():
data = json.loads(file_path.read_text())
else:
data = {}
data[self.device_identifier] = layout
helpers.write_file('odoo-keyboard-layouts.conf', json.dumps(data))
def load_layout(self):
"""Read the layout from the saved filed and set it as current layout.
If no file or no layout is found we use 'us' by default.
"""
file_path = Path.home() / 'odoo-keyboard-layouts.conf'
if file_path.exists():
data = json.loads(file_path.read_text())
layout = data.get(self.device_identifier, {'layout': 'us'})
else:
layout = {'layout': 'us'}
self._change_keyboard_layout(layout)
def _action_default(self, data):
self.data['value'] = ''
event_manager.device_changed(self)
def _is_scanner(self):
"""Read the device type from the saved filed and set it as current type.
If no file or no device type is found we try to detect it automatically.
"""
device_name = self.device_name.lower()
scanner_name = ['barcode', 'scanner', 'reader']
is_scanner = any(x in device_name for x in scanner_name) or self.dev.interface_protocol == '0'
file_path = Path.home() / 'odoo-keyboard-is-scanner.conf'
if file_path.exists():
data = json.loads(file_path.read_text())
is_scanner = data.get(self.device_identifier, {}).get('is_scanner', is_scanner)
return is_scanner
def _keyboard_input(self, scancode):
"""Deal with a keyboard input. Send the character corresponding to the
pressed key represented by its scancode to the connected Odoo instance.
Args:
scancode (int): The scancode of the pressed key.
"""
self.data['value'] = self._scancode_to_char(scancode)
if self.data['value']:
event_manager.device_changed(self)
def _barcode_scanner_input(self, scancode):
"""Deal with a barcode scanner input. Add the new character scanned to
the current barcode or complete the barcode if "Return" is pressed.
When a barcode is completed, two tasks are performed:
- Send a device_changed update to the event manager to notify the
listeners that the value has changed (used in Enterprise).
- Add the barcode to the list barcodes that are being queried in
Community.
Args:
scancode (int): The scancode of the pressed key.
"""
if scancode == 28: # Return
self.data['value'] = self._current_barcode
event_manager.device_changed(self)
self._barcodes.put((time.time(), self._current_barcode))
self._current_barcode = ''
else:
self._current_barcode += self._scancode_to_char(scancode)
def _save_is_scanner(self, data):
"""Save the type of device.
We need that in order to keep the selected type of device after a reboot.
"""
is_scanner = {'is_scanner': data.get('is_scanner')}
file_path = Path.home() / 'odoo-keyboard-is-scanner.conf'
if file_path.exists():
data = json.loads(file_path.read_text())
else:
data = {}
data[self.device_identifier] = is_scanner
helpers.write_file('odoo-keyboard-is-scanner.conf', json.dumps(data))
self._set_device_type('scanner') if is_scanner.get('is_scanner') else self._set_device_type()
def _update_layout(self, data):
layout = {
'layout': data.get('layout'),
'variant': data.get('variant'),
}
self._change_keyboard_layout(layout)
self.save_layout(layout)
def _set_device_type(self, device_type='keyboard'):
"""Modify the device type between 'keyboard' and 'scanner'
Args:
type (string): Type wanted to switch
"""
if device_type == 'scanner':
self.device_type = 'scanner'
self.key_input = self._barcode_scanner_input
self._barcodes = Queue()
self._current_barcode = ''
self.input_device.grab()
self.read_barcode_lock = Lock()
else:
self.device_type = 'keyboard'
self.key_input = self._keyboard_input
self.load_layout()
def _scancode_to_char(self, scancode):
"""Translate a received scancode to a character depending on the
selected keyboard layout and the current state of the keyboard's
modifiers.
Args:
scancode (int): The scancode of the pressed key, to be translated to
a character
Returns:
str: The translated scancode.
"""
# Scancode -> Keysym : Depends on the keyboard layout
group = KeyboardUSBDriver.keyboard_layout_groups.index(self.keyboard_layout)
modifiers = self._get_active_modifiers(scancode)
keysym = ctypes.c_int(xlib.XkbKeycodeToKeysym(KeyboardUSBDriver.display, scancode + 8, group, modifiers))
# Translate Keysym to a character
key_pressed = ctypes.create_string_buffer(5)
xlib.XkbTranslateKeySym(KeyboardUSBDriver.display, ctypes.byref(keysym), 0, ctypes.byref(key_pressed), 5, ctypes.byref(ctypes.c_int()))
if key_pressed.value:
return key_pressed.value.decode('utf-8')
return ''
def _get_active_modifiers(self, scancode):
"""Get the state of currently active modifiers.
Args:
scancode (int): The scancode of the key being translated
Returns:
int: The current state of the modifiers:
0 -- Lowercase
1 -- Highercase or (NumLock + key pressed on keypad)
2 -- AltGr
3 -- Highercase + AltGr
"""
modifiers = 0
uppercase = (self._tracked_modifiers['right_shift'] or self._tracked_modifiers['left_shift']) ^ self._tracked_modifiers['caps_lock']
if uppercase or (scancode in [71, 72, 73, 75, 76, 77, 79, 80, 81, 82, 83] and self._tracked_modifiers['num_lock']):
modifiers += 1
if self._tracked_modifiers['alt_gr']:
modifiers += 2
return modifiers
def read_next_barcode(self):
"""Get the value of the last barcode that was scanned but not sent yet
and not older than 5 seconds. This function is used in Community, when
we don't have access to the IoTLongpolling.
Returns:
str: The next barcode to be read or an empty string.
"""
# Previous query still running, stop it by sending a fake barcode
if self.read_barcode_lock.locked():
self._barcodes.put((time.time(), ""))
with self.read_barcode_lock:
try:
timestamp, barcode = self._barcodes.get(True, 55)
if timestamp > time.time() - 5:
return barcode
except Empty:
return ''
proxy_drivers['scanner'] = KeyboardUSBDriver
class KeyboardUSBController(http.Controller):
@http.route('/hw_proxy/scanner', type='json', auth='none', cors='*')
def get_barcode(self):
scanners = [iot_devices[d] for d in iot_devices if iot_devices[d].device_type == "scanner"]
if scanners:
return scanners[0].read_next_barcode()
time.sleep(5)
return None
| 40.244624 | 14,971 |
9,271 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import jinja2
import json
import logging
import netifaces as ni
import os
import subprocess
import threading
import time
import urllib3
from odoo import http
from odoo.addons.hw_drivers.connection_manager import connection_manager
from odoo.addons.hw_drivers.driver import Driver
from odoo.addons.hw_drivers.event_manager import event_manager
from odoo.addons.hw_drivers.main import iot_devices
from odoo.addons.hw_drivers.tools import helpers
path = os.path.realpath(os.path.join(os.path.dirname(__file__), '../../views'))
loader = jinja2.FileSystemLoader(path)
jinja_env = jinja2.Environment(loader=loader, autoescape=True)
jinja_env.filters["json"] = json.dumps
pos_display_template = jinja_env.get_template('pos_display.html')
_logger = logging.getLogger(__name__)
class DisplayDriver(Driver):
connection_type = 'display'
def __init__(self, identifier, device):
super(DisplayDriver, self).__init__(identifier, device)
self.device_type = 'display'
self.device_connection = 'hdmi'
self.device_name = device['name']
self.event_data = threading.Event()
self.owner = False
self.rendered_html = ''
if self.device_identifier != 'distant_display':
self._x_screen = device.get('x_screen', '0')
self.load_url()
self._actions.update({
'update_url': self._action_update_url,
'display_refresh': self._action_display_refresh,
'take_control': self._action_take_control,
'customer_facing_display': self._action_customer_facing_display,
'get_owner': self._action_get_owner,
})
@classmethod
def supported(cls, device):
return True # All devices with connection_type == 'display' are supported
@classmethod
def get_default_display(cls):
displays = list(filter(lambda d: iot_devices[d].device_type == 'display', iot_devices))
return len(displays) and iot_devices[displays[0]]
def run(self):
while self.device_identifier != 'distant_display' and not self._stopped.isSet():
time.sleep(60)
if self.url != 'http://localhost:8069/point_of_sale/display/' + self.device_identifier:
# Refresh the page every minute
self.call_xdotools('F5')
def update_url(self, url=None):
os.environ['DISPLAY'] = ":0." + self._x_screen
os.environ['XAUTHORITY'] = '/run/lightdm/pi/xauthority'
firefox_env = os.environ.copy()
firefox_env['HOME'] = '/tmp/' + self._x_screen
self.url = url or 'http://localhost:8069/point_of_sale/display/' + self.device_identifier
new_window = subprocess.call(['xdotool', 'search', '--onlyvisible', '--screen', self._x_screen, '--class', 'Firefox'])
subprocess.Popen(['firefox', self.url], env=firefox_env)
if new_window:
self.call_xdotools('F11')
def load_url(self):
url = None
if helpers.get_odoo_server_url():
# disable certifiacte verification
urllib3.disable_warnings()
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
try:
response = http.request('GET', "%s/iot/box/%s/display_url" % (helpers.get_odoo_server_url(), helpers.get_mac_address()))
if response.status == 200:
data = json.loads(response.data.decode('utf8'))
url = data[self.device_identifier]
except json.decoder.JSONDecodeError:
url = response.data.decode('utf8')
except Exception:
pass
return self.update_url(url)
def call_xdotools(self, keystroke):
os.environ['DISPLAY'] = ":0." + self._x_screen
os.environ['XAUTHORITY'] = "/run/lightdm/pi/xauthority"
try:
subprocess.call(['xdotool', 'search', '--sync', '--onlyvisible', '--screen', self._x_screen, '--class', 'Firefox', 'key', keystroke])
return "xdotool succeeded in stroking " + keystroke
except:
return "xdotool threw an error, maybe it is not installed on the IoTBox"
def update_customer_facing_display(self, origin, html=None):
if origin == self.owner:
self.rendered_html = html
self.event_data.set()
def get_serialized_order(self):
# IMPLEMENTATION OF LONGPOLLING
# Times out 2 seconds before the JS request does
if self.event_data.wait(28):
self.event_data.clear()
return {'rendered_html': self.rendered_html}
return {'rendered_html': False}
def take_control(self, new_owner, html=None):
# ALLOW A CASHIER TO TAKE CONTROL OVER THE POSBOX, IN CASE OF MULTIPLE CASHIER PER DISPLAY
self.owner = new_owner
self.rendered_html = html
self.data = {
'value': '',
'owner': self.owner,
}
event_manager.device_changed(self)
self.event_data.set()
def _action_update_url(self, data):
if self.device_identifier != 'distant_display':
self.update_url(data.get('url'))
def _action_display_refresh(self, data):
if self.device_identifier != 'distant_display':
self.call_xdotools('F5')
def _action_take_control(self, data):
self.take_control(self.data.get('owner'), data.get('html'))
def _action_customer_facing_display(self, data):
self.update_customer_facing_display(self.data.get('owner'), data.get('html'))
def _action_get_owner(self, data):
self.data = {
'value': '',
'owner': self.owner,
}
event_manager.device_changed(self)
class DisplayController(http.Controller):
@http.route('/hw_proxy/display_refresh', type='json', auth='none', cors='*')
def display_refresh(self):
display = DisplayDriver.get_default_display()
if display and display.device_identifier != 'distant_display':
return display.call_xdotools('F5')
@http.route('/hw_proxy/customer_facing_display', type='json', auth='none', cors='*')
def customer_facing_display(self, html=None):
display = DisplayDriver.get_default_display()
if display:
display.update_customer_facing_display(http.request.httprequest.remote_addr, html)
return {'status': 'updated'}
return {'status': 'failed'}
@http.route('/hw_proxy/take_control', type='json', auth='none', cors='*')
def take_control(self, html=None):
display = DisplayDriver.get_default_display()
if display:
display.take_control(http.request.httprequest.remote_addr, html)
return {
'status': 'success',
'message': 'You now have access to the display',
}
@http.route('/hw_proxy/test_ownership', type='json', auth='none', cors='*')
def test_ownership(self):
display = DisplayDriver.get_default_display()
if display and display.owner == http.request.httprequest.remote_addr:
return {'status': 'OWNER'}
return {'status': 'NOWNER'}
@http.route(['/point_of_sale/get_serialized_order', '/point_of_sale/get_serialized_order/<string:display_identifier>'], type='json', auth='none')
def get_serialized_order(self, display_identifier=None):
if display_identifier:
display = iot_devices.get(display_identifier)
else:
display = DisplayDriver.get_default_display()
if display:
return display.get_serialized_order()
return {
'rendered_html': False,
'error': "No display found",
}
@http.route(['/point_of_sale/display', '/point_of_sale/display/<string:display_identifier>'], type='http', auth='none')
def display(self, display_identifier=None):
cust_js = None
interfaces = ni.interfaces()
with open(os.path.join(os.path.dirname(__file__), "../../static/src/js/worker.js")) as js:
cust_js = js.read()
display_ifaces = []
for iface_id in interfaces:
if 'wlan' in iface_id or 'eth' in iface_id:
iface_obj = ni.ifaddresses(iface_id)
ifconfigs = iface_obj.get(ni.AF_INET, [])
essid = helpers.get_ssid()
for conf in ifconfigs:
if conf.get('addr'):
display_ifaces.append({
'iface_id': iface_id,
'essid': essid,
'addr': conf.get('addr'),
'icon': 'sitemap' if 'eth' in iface_id else 'wifi',
})
if not display_identifier:
display_identifier = DisplayDriver.get_default_display().device_identifier
return pos_display_template.render({
'title': "Odoo -- Point of Sale",
'breadcrumb': 'POS Client display',
'cust_js': cust_js,
'display_ifaces': display_ifaces,
'display_identifier': display_identifier,
'pairing_code': connection_manager.pairing_code,
})
| 39.619658 | 9,271 |
12,066 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import namedtuple
import logging
import re
import serial
import threading
import time
from odoo import http
from odoo.addons.hw_drivers.controllers.proxy import proxy_drivers
from odoo.addons.hw_drivers.event_manager import event_manager
from odoo.addons.hw_drivers.iot_handlers.drivers.SerialBaseDriver import SerialDriver, SerialProtocol, serial_connection
_logger = logging.getLogger(__name__)
# Only needed to ensure compatibility with older versions of Odoo
ACTIVE_SCALE = None
new_weight_event = threading.Event()
ScaleProtocol = namedtuple('ScaleProtocol', SerialProtocol._fields + ('zeroCommand', 'tareCommand', 'clearCommand', 'autoResetWeight'))
# 8217 Mettler-Toledo (Weight-only) Protocol, as described in the scale's Service Manual.
# e.g. here: https://www.manualslib.com/manual/861274/Mettler-Toledo-Viva.html?page=51#manual
# Our recommended scale, the Mettler-Toledo "Ariva-S", supports this protocol on
# both the USB and RS232 ports, it can be configured in the setup menu as protocol option 3.
# We use the default serial protocol settings, the scale's settings can be configured in the
# scale's menu anyway.
Toledo8217Protocol = ScaleProtocol(
name='Toledo 8217',
baudrate=9600,
bytesize=serial.SEVENBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_EVEN,
timeout=1,
writeTimeout=1,
measureRegexp=b"\x02\\s*([0-9.]+)N?\\r",
statusRegexp=b"\x02\\s*(\\?.)\\r",
commandDelay=0.2,
measureDelay=0.5,
newMeasureDelay=0.2,
commandTerminator=b'',
measureCommand=b'W',
zeroCommand=b'Z',
tareCommand=b'T',
clearCommand=b'C',
emptyAnswerValid=False,
autoResetWeight=False,
)
# The ADAM scales have their own RS232 protocol, usually documented in the scale's manual
# e.g at https://www.adamequipment.com/media/docs/Print%20Publications/Manuals/PDF/AZEXTRA/AZEXTRA-UM.pdf
# https://www.manualslib.com/manual/879782/Adam-Equipment-Cbd-4.html?page=32#manual
# Only the baudrate and label format seem to be configurable in the AZExtra series.
ADAMEquipmentProtocol = ScaleProtocol(
name='Adam Equipment',
baudrate=4800,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE,
timeout=0.2,
writeTimeout=0.2,
measureRegexp=b"\s*([0-9.]+)kg", # LABEL format 3 + KG in the scale settings, but Label 1/2 should work
statusRegexp=None,
commandTerminator=b"\r\n",
commandDelay=0.2,
measureDelay=0.5,
# AZExtra beeps every time you ask for a weight that was previously returned!
# Adding an extra delay gives the operator a chance to remove the products
# before the scale starts beeping. Could not find a way to disable the beeps.
newMeasureDelay=5,
measureCommand=b'P',
zeroCommand=b'Z',
tareCommand=b'T',
clearCommand=None, # No clear command -> Tare again
emptyAnswerValid=True, # AZExtra does not answer unless a new non-zero weight has been detected
autoResetWeight=True, # AZExtra will not return 0 after removing products
)
# Ensures compatibility with older versions of Odoo
class ScaleReadOldRoute(http.Controller):
@http.route('/hw_proxy/scale_read', type='json', auth='none', cors='*')
def scale_read(self):
if ACTIVE_SCALE:
return {'weight': ACTIVE_SCALE._scale_read_old_route()}
return None
class ScaleDriver(SerialDriver):
"""Abstract base class for scale drivers."""
last_sent_value = None
def __init__(self, identifier, device):
super(ScaleDriver, self).__init__(identifier, device)
self.device_type = 'scale'
self._set_actions()
self._is_reading = True
# Ensures compatibility with older versions of Odoo
# Only the last scale connected is kept
global ACTIVE_SCALE
ACTIVE_SCALE = self
proxy_drivers['scale'] = ACTIVE_SCALE
# Ensures compatibility with older versions of Odoo
# and allows using the `ProxyDevice` in the point of sale to retrieve the status
def get_status(self):
"""Allows `hw_proxy.Proxy` to retrieve the status of the scales"""
status = self._status
return {'status': status['status'], 'messages': [status['message_title'], ]}
def _set_actions(self):
"""Initializes `self._actions`, a map of action keys sent by the frontend to backend action methods."""
self._actions.update({
'read_once': self._read_once_action,
'set_zero': self._set_zero_action,
'set_tare': self._set_tare_action,
'clear_tare': self._clear_tare_action,
'start_reading': self._start_reading_action,
'stop_reading': self._stop_reading_action,
})
def _start_reading_action(self, data):
"""Starts asking for the scale value."""
self._is_reading = True
def _stop_reading_action(self, data):
"""Stops asking for the scale value."""
self._is_reading = False
def _clear_tare_action(self, data):
"""Clears the scale current tare weight."""
# if the protocol has no clear tare command, we can just tare again
clearCommand = self._protocol.clearCommand or self._protocol.tareCommand
self._connection.write(clearCommand + self._protocol.commandTerminator)
def _read_once_action(self, data):
"""Reads the scale current weight value and pushes it to the frontend."""
self._read_weight()
self.last_sent_value = self.data['value']
event_manager.device_changed(self)
def _set_zero_action(self, data):
"""Makes the weight currently applied to the scale the new zero."""
self._connection.write(self._protocol.zeroCommand + self._protocol.commandTerminator)
def _set_tare_action(self, data):
"""Sets the scale's current weight value as tare weight."""
self._connection.write(self._protocol.tareCommand + self._protocol.commandTerminator)
@staticmethod
def _get_raw_response(connection):
"""Gets raw bytes containing the updated value of the device.
:param connection: a connection to the device's serial port
:type connection: pyserial.Serial
:return: the raw response to a weight request
:rtype: str
"""
answer = []
while True:
char = connection.read(1)
if not char:
break
else:
answer.append(bytes(char))
return b''.join(answer)
def _read_weight(self):
"""Asks for a new weight from the scale, checks if it is valid and, if it is, makes it the current value."""
protocol = self._protocol
self._connection.write(protocol.measureCommand + protocol.commandTerminator)
answer = self._get_raw_response(self._connection)
match = re.search(self._protocol.measureRegexp, answer)
if match:
self.data = {
'value': float(match.group(1)),
'status': self._status
}
# Ensures compatibility with older versions of Odoo
def _scale_read_old_route(self):
"""Used when the iot app is not installed"""
with self._device_lock:
self._read_weight()
return self.data['value']
def _take_measure(self):
"""Reads the device's weight value, and pushes that value to the frontend."""
with self._device_lock:
self._read_weight()
if self.data['value'] != self.last_sent_value or self._status['status'] == self.STATUS_ERROR:
self.last_sent_value = self.data['value']
event_manager.device_changed(self)
class Toledo8217Driver(ScaleDriver):
"""Driver for the Toldedo 8217 serial scale."""
_protocol = Toledo8217Protocol
def __init__(self, identifier, device):
super(Toledo8217Driver, self).__init__(identifier, device)
self.device_manufacturer = 'Toledo'
@classmethod
def supported(cls, device):
"""Checks whether the device, which port info is passed as argument, is supported by the driver.
:param device: path to the device
:type device: str
:return: whether the device is supported by the driver
:rtype: bool
"""
protocol = cls._protocol
try:
with serial_connection(device['identifier'], protocol, is_probing=True) as connection:
connection.write(b'Ehello' + protocol.commandTerminator)
time.sleep(protocol.commandDelay)
answer = connection.read(8)
if answer == b'\x02E\rhello':
connection.write(b'F' + protocol.commandTerminator)
return True
except serial.serialutil.SerialTimeoutException:
pass
except Exception:
_logger.exception('Error while probing %s with protocol %s' % (device, protocol.name))
return False
class AdamEquipmentDriver(ScaleDriver):
"""Driver for the Adam Equipment serial scale."""
_protocol = ADAMEquipmentProtocol
priority = 0 # Test the supported method of this driver last, after all other serial drivers
def __init__(self, identifier, device):
super(AdamEquipmentDriver, self).__init__(identifier, device)
self._is_reading = False
self._last_weight_time = 0
self.device_manufacturer = 'Adam'
def _check_last_weight_time(self):
"""The ADAM doesn't make the difference between a value of 0 and "the same value as last time":
in both cases it returns an empty string.
With this, unless the weight changes, we give the user `TIME_WEIGHT_KEPT` seconds to log the new weight,
then change it back to zero to avoid keeping it indefinetely, which could cause issues.
In any case the ADAM must always go back to zero before it can weight again.
"""
TIME_WEIGHT_KEPT = 10
if self.data['value'] is None:
if time.time() - self._last_weight_time > TIME_WEIGHT_KEPT:
self.data['value'] = 0
else:
self._last_weight_time = time.time()
def _take_measure(self):
"""Reads the device's weight value, and pushes that value to the frontend."""
if self._is_reading:
with self._device_lock:
self._read_weight()
self._check_last_weight_time()
if self.data['value'] != self.last_sent_value or self._status['status'] == self.STATUS_ERROR:
self.last_sent_value = self.data['value']
event_manager.device_changed(self)
else:
time.sleep(0.5)
# Ensures compatibility with older versions of Odoo
def _scale_read_old_route(self):
"""Used when the iot app is not installed"""
time.sleep(3)
with self._device_lock:
self._read_weight()
self._check_last_weight_time()
return self.data['value']
@classmethod
def supported(cls, device):
"""Checks whether the device at `device` is supported by the driver.
:param device: path to the device
:type device: str
:return: whether the device is supported by the driver
:rtype: bool
"""
protocol = cls._protocol
try:
with serial_connection(device['identifier'], protocol, is_probing=True) as connection:
connection.write(protocol.measureCommand + protocol.commandTerminator)
# Checking whether writing to the serial port using the Adam protocol raises a timeout exception is about the only thing we can do.
return True
except serial.serialutil.SerialTimeoutException:
pass
except Exception:
_logger.exception('Error while probing %s with protocol %s' % (device, protocol.name))
return False
| 38.183544 | 12,066 |
10,553 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from base64 import b64decode
from cups import IPPError, IPP_PRINTER_IDLE, IPP_PRINTER_PROCESSING, IPP_PRINTER_STOPPED
import dbus
import io
import logging
import netifaces as ni
import os
from PIL import Image, ImageOps
import re
import subprocess
import tempfile
from uuid import getnode as get_mac
from odoo import http
from odoo.addons.hw_drivers.connection_manager import connection_manager
from odoo.addons.hw_drivers.controllers.proxy import proxy_drivers
from odoo.addons.hw_drivers.driver import Driver
from odoo.addons.hw_drivers.event_manager import event_manager
from odoo.addons.hw_drivers.iot_handlers.interfaces.PrinterInterface import PPDs, conn, cups_lock
from odoo.addons.hw_drivers.main import iot_devices
from odoo.addons.hw_drivers.tools import helpers
_logger = logging.getLogger(__name__)
RECEIPT_PRINTER_COMMANDS = {
'star': {
'center': b'\x1b\x1d\x61\x01', # ESC GS a n
'cut': b'\x1b\x64\x02', # ESC d n
'title': b'\x1b\x69\x01\x01%s\x1b\x69\x00\x00', # ESC i n1 n2
'drawers': [b'\x07', b'\x1a'] # BEL & SUB
},
'escpos': {
'center': b'\x1b\x61\x01', # ESC a n
'cut': b'\x1d\x56\x41\n', # GS V m
'title': b'\x1b\x21\x30%s\x1b\x21\x00', # ESC ! n
'drawers': [b'\x1b\x3d\x01', b'\x1b\x70\x00\x19\x19', b'\x1b\x70\x01\x19\x19'] # ESC = n then ESC p m t1 t2
}
}
def cups_notification_handler(message, uri, device_identifier, state, reason, accepting_jobs):
if device_identifier in iot_devices:
reason = reason if reason != 'none' else None
state_value = {
IPP_PRINTER_IDLE: 'connected',
IPP_PRINTER_PROCESSING: 'processing',
IPP_PRINTER_STOPPED: 'stopped'
}
iot_devices[device_identifier].update_status(state_value[state], message, reason)
# Create a Cups subscription if it doesn't exist yet
try:
conn.getSubscriptions('/printers/')
except IPPError:
conn.createSubscription(
uri='/printers/',
recipient_uri='dbus://',
events=['printer-state-changed']
)
# Listen for notifications from Cups
bus = dbus.SystemBus()
bus.add_signal_receiver(cups_notification_handler, signal_name="PrinterStateChanged", dbus_interface="org.cups.cupsd.Notifier")
class PrinterDriver(Driver):
connection_type = 'printer'
def __init__(self, identifier, device):
super(PrinterDriver, self).__init__(identifier, device)
self.device_type = 'printer'
self.device_connection = device['device-class'].lower()
self.device_name = device['device-make-and-model']
self.state = {
'status': 'connecting',
'message': 'Connecting to printer',
'reason': None,
}
self.send_status()
self._actions.update({
'cashbox': self.open_cashbox,
'print_receipt': self.print_receipt,
'': self._action_default,
})
self.receipt_protocol = 'star' if 'STR_T' in device['device-id'] else 'escpos'
if 'direct' in self.device_connection and any(cmd in device['device-id'] for cmd in ['CMD:STAR;', 'CMD:ESC/POS;']):
self.print_status()
@classmethod
def supported(cls, device):
if device.get('supported', False):
return True
protocol = ['dnssd', 'lpd', 'socket']
if any(x in device['url'] for x in protocol) and device['device-make-and-model'] != 'Unknown' or 'direct' in device['device-class']:
model = cls.get_device_model(device)
ppdFile = ''
for ppd in PPDs:
if model and model in PPDs[ppd]['ppd-product']:
ppdFile = ppd
break
with cups_lock:
if ppdFile:
conn.addPrinter(name=device['identifier'], ppdname=ppdFile, device=device['url'])
else:
conn.addPrinter(name=device['identifier'], device=device['url'])
conn.setPrinterInfo(device['identifier'], device['device-make-and-model'])
conn.enablePrinter(device['identifier'])
conn.acceptJobs(device['identifier'])
conn.setPrinterUsersAllowed(device['identifier'], ['all'])
conn.addPrinterOptionDefault(device['identifier'], "usb-no-reattach", "true")
conn.addPrinterOptionDefault(device['identifier'], "usb-unidir", "true")
return True
return False
@classmethod
def get_device_model(cls, device):
device_model = ""
if device.get('device-id'):
for device_id in [device_lo for device_lo in device['device-id'].split(';')]:
if any(x in device_id for x in ['MDL', 'MODEL']):
device_model = device_id.split(':')[1]
break
elif device.get('device-make-and-model'):
device_model = device['device-make-and-model']
return re.sub("[\(].*?[\)]", "", device_model).strip()
@classmethod
def get_status(cls):
status = 'connected' if any(iot_devices[d].device_type == "printer" and iot_devices[d].device_connection == 'direct' for d in iot_devices) else 'disconnected'
return {'status': status, 'messages': ''}
def disconnect(self):
self.update_status('disconnected', 'Printer was disconnected')
super(PrinterDriver, self).disconnect()
def update_status(self, status, message, reason=None):
"""Updates the state of the current printer.
Args:
status (str): The new value of the status
message (str): A comprehensive message describing the status
reason (str): The reason fo the current status
"""
if self.state['status'] != status or self.state['reason'] != reason:
self.state = {
'status': status,
'message': message,
'reason': reason,
}
self.send_status()
def send_status(self):
""" Sends the current status of the printer to the connected Odoo instance.
"""
self.data = {
'value': '',
'state': self.state,
}
event_manager.device_changed(self)
def print_raw(self, data):
process = subprocess.Popen(["lp", "-d", self.device_identifier], stdin=subprocess.PIPE)
process.communicate(data)
def print_receipt(self, data):
receipt = b64decode(data['receipt'])
im = Image.open(io.BytesIO(receipt))
# Convert to greyscale then to black and white
im = im.convert("L")
im = ImageOps.invert(im)
im = im.convert("1")
print_command = getattr(self, 'format_%s' % self.receipt_protocol)(im)
self.print_raw(print_command)
def format_star(self, im):
width = int((im.width + 7) / 8)
raster_init = b'\x1b\x2a\x72\x41'
raster_page_length = b'\x1b\x2a\x72\x50\x30\x00'
raster_send = b'\x62'
raster_close = b'\x1b\x2a\x72\x42'
raster_data = b''
dots = im.tobytes()
while len(dots):
raster_data += raster_send + width.to_bytes(2, 'little') + dots[:width]
dots = dots[width:]
return raster_init + raster_page_length + raster_data + raster_close
def format_escpos(self, im):
width = int((im.width + 7) / 8)
raster_send = b'\x1d\x76\x30\x00'
max_slice_height = 255
raster_data = b''
dots = im.tobytes()
while len(dots):
im_slice = dots[:width*max_slice_height]
slice_height = int(len(im_slice) / width)
raster_data += raster_send + width.to_bytes(2, 'little') + slice_height.to_bytes(2, 'little') + im_slice
dots = dots[width*max_slice_height:]
return raster_data + RECEIPT_PRINTER_COMMANDS['escpos']['cut']
def print_status(self):
"""Prints the status ticket of the IoTBox on the current printer."""
wlan = ''
ip = ''
mac = ''
homepage = ''
pairing_code = ''
ssid = helpers.get_ssid()
wlan = '\nWireless network:\n%s\n\n' % ssid
interfaces = ni.interfaces()
ips = []
for iface_id in interfaces:
iface_obj = ni.ifaddresses(iface_id)
ifconfigs = iface_obj.get(ni.AF_INET, [])
for conf in ifconfigs:
if conf.get('addr') and conf.get('addr'):
ips.append(conf.get('addr'))
if len(ips) == 0:
ip = '\nERROR: Could not connect to LAN\n\nPlease check that the IoTBox is correc-\ntly connected with a network cable,\n that the LAN is setup with DHCP, and\nthat network addresses are available'
elif len(ips) == 1:
ip = '\nIP Address:\n%s\n' % ips[0]
else:
ip = '\nIP Addresses:\n%s\n' % '\n'.join(ips)
if len(ips) >= 1:
ips_filtered = [i for i in ips if i != '127.0.0.1']
main_ips = ips_filtered and ips_filtered[0] or '127.0.0.1'
mac = '\nMAC Address:\n%s\n' % helpers.get_mac_address()
homepage = '\nHomepage:\nhttp://%s:8069\n\n' % main_ips
code = connection_manager.pairing_code
if code:
pairing_code = '\nPairing Code:\n%s\n' % code
commands = RECEIPT_PRINTER_COMMANDS[self.receipt_protocol]
title = commands['title'] % b'IoTBox Status'
self.print_raw(commands['center'] + title + b'\n' + wlan.encode() + mac.encode() + ip.encode() + homepage.encode() + pairing_code.encode() + commands['cut'])
def open_cashbox(self, data):
"""Sends a signal to the current printer to open the connected cashbox."""
commands = RECEIPT_PRINTER_COMMANDS[self.receipt_protocol]
for drawer in commands['drawers']:
self.print_raw(drawer)
def _action_default(self, data):
self.print_raw(b64decode(data['document']))
class PrinterController(http.Controller):
@http.route('/hw_proxy/default_printer_action', type='json', auth='none', cors='*')
def default_printer_action(self, data):
printer = next((d for d in iot_devices if iot_devices[d].device_type == 'printer' and iot_devices[d].device_connection == 'direct'), None)
if printer:
iot_devices[printer].action(data)
return True
return False
proxy_drivers['printer'] = PrinterDriver
| 38.655678 | 10,553 |
2,736 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.interface import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_delay = 120
connection_type = 'printer'
printer_devices = {}
def get_devices(self):
discovered_devices = {}
with cups_lock:
printers = conn.getPrinters()
devices = conn.getDevices()
for printer_name, printer in printers.items():
path = printer.get('device-uri', False)
if printer_name != self.get_identifier(path):
printer.update({'supported': True}) # these printers are automatically supported
device_class = 'network'
if 'usb' in printer.get('device-uri'):
device_class = 'direct'
printer.update({'device-class': device_class})
printer.update({'device-make-and-model': printer_name}) # give name setted in Cups
printer.update({'device-id': ''})
devices.update({printer_name: printer})
for path, device in devices.items():
identifier = self.get_identifier(path)
device.update({'identifier': identifier})
device.update({'url': path})
device.update({'disconnect_counter': 0})
discovered_devices.update({identifier: device})
self.printer_devices.update(discovered_devices)
# Deal with devices which are on the list but were not found during this call of "get_devices"
# If they aren't detected 3 times consecutively, remove them from the list of available devices
for device in list(self.printer_devices):
if not discovered_devices.get(device):
disconnect_counter = self.printer_devices.get(device).get('disconnect_counter')
if disconnect_counter >= 2:
self.printer_devices.pop(device, None)
else:
self.printer_devices[device].update({'disconnect_counter': disconnect_counter + 1})
return dict(self.printer_devices)
def get_identifier(self, path):
if 'uuid=' in path:
identifier = sub('[^a-zA-Z0-9_]', '', path.split('uuid=')[1])
elif 'serial=' in path:
identifier = sub('[^a-zA-Z0-9_]', '', path.split('serial=')[1])
else:
identifier = sub('[^a-zA-Z0-9_]', '', path)
return identifier
| 45.6 | 2,736 |
1,045 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from usb import core
from odoo.addons.hw_drivers.interface import Interface
class USBInterface(Interface):
connection_type = 'usb'
def get_devices(self):
"""
USB devices are identified by a combination of their `idVendor` and
`idProduct`. We can't be sure this combination in unique per equipment.
To still allow connecting multiple similar equipments, we complete the
identifier by a counter. The drawbacks are we can't be sure the equipments
will get the same identifiers after a reboot or a disconnect/reconnect.
"""
usb_devices = {}
devs = core.find(find_all=True)
cpt = 2
for dev in devs:
identifier = "usb_%04x:%04x" % (dev.idVendor, dev.idProduct)
if identifier in usb_devices:
identifier += '_%s' % cpt
cpt += 1
usb_devices[identifier] = dev
return usb_devices
| 36.034483 | 1,045 |
1,448 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from re import sub, finditer
import subprocess
from odoo.addons.hw_drivers.interface import Interface
class DisplayInterface(Interface):
_loop_delay = 0
connection_type = 'display'
def get_devices(self):
display_devices = {}
displays = subprocess.check_output(['tvservice', '-l']).decode()
x_screen = 0
for match in finditer('Display Number (\d), type HDMI (\d)', displays):
display_id, hdmi_id = match.groups()
tvservice_output = subprocess.check_output(['tvservice', '-nv', display_id]).decode().strip()
if tvservice_output:
display_name = tvservice_output.split('=')[1]
display_identifier = sub('[^a-zA-Z0-9 ]+', '', display_name).replace(' ', '_') + "_" + str(hdmi_id)
iot_device = {
'identifier': display_identifier,
'name': display_name,
'x_screen': str(x_screen),
}
display_devices[display_identifier] = iot_device
x_screen += 1
if not len(display_devices):
# No display connected, create "fake" device to be accessed from another computer
display_devices['distant_display'] = {
'name': "Distant Display",
}
return display_devices
| 38.105263 | 1,448 |
486 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from glob import glob
from odoo.addons.hw_drivers.interface import Interface
class SerialInterface(Interface):
connection_type = 'serial'
def get_devices(self):
serial_devices = {}
for identifier in glob('/dev/serial/by-path/*'):
serial_devices[identifier] = {
'identifier': identifier
}
return serial_devices
| 27 | 486 |
672 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
proxy_drivers = {}
class ProxyController(http.Controller):
@http.route('/hw_proxy/hello', type='http', auth='none', cors='*')
def hello(self):
return "ping"
@http.route('/hw_proxy/handshake', type='json', auth='none', cors='*')
def handshake(self):
return True
@http.route('/hw_proxy/status_json', type='json', auth='none', cors='*')
def status_json(self):
statuses = {}
for driver in proxy_drivers:
statuses[driver] = proxy_drivers[driver].get_status()
return statuses
| 30.545455 | 672 |
5,049 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from base64 import b64decode
import json
import logging
import os
import subprocess
import time
from odoo import http, tools
from odoo.http import send_file
from odoo.modules.module import get_resource_path
from odoo.addons.hw_drivers.event_manager import event_manager
from odoo.addons.hw_drivers.main import iot_devices, manager
from odoo.addons.hw_drivers.tools import helpers
_logger = logging.getLogger(__name__)
class DriverController(http.Controller):
@http.route('/hw_drivers/action', type='json', auth='none', cors='*', csrf=False, save_session=False)
def action(self, session_id, device_identifier, data):
"""
This route is called when we want to make a action with device (take picture, printing,...)
We specify in data from which session_id that action is called
And call the action of specific device
"""
iot_device = iot_devices.get(device_identifier)
if iot_device:
iot_device.data['owner'] = session_id
data = json.loads(data)
# Skip the request if it was already executed (duplicated action calls)
iot_idempotent_id = data.get("iot_idempotent_id")
if iot_idempotent_id:
idempotent_session = iot_device._check_idempotency(iot_idempotent_id, session_id)
if idempotent_session:
_logger.info("Ignored request from %s as iot_idempotent_id %s already received from session %s",
session_id, iot_idempotent_id, idempotent_session)
return False
iot_device.action(data)
return True
return False
@http.route('/hw_drivers/check_certificate', type='http', auth='none', cors='*', csrf=False, save_session=False)
def check_certificate(self):
"""
This route is called when we want to check if certificate is up-to-date
Used in cron.daily
"""
helpers.get_certificate_status()
@http.route('/hw_drivers/event', type='json', auth='none', cors='*', csrf=False, save_session=False)
def event(self, listener):
"""
listener is a dict in witch there are a sessions_id and a dict of device_identifier to listen
"""
req = event_manager.add_request(listener)
# Search for previous events and remove events older than 5 seconds
oldest_time = time.time() - 5
for event in list(event_manager.events):
if event['time'] < oldest_time:
del event_manager.events[0]
continue
if event['device_identifier'] in listener['devices'] and event['time'] > listener['last_event']:
event['session_id'] = req['session_id']
return event
# Wait for new event
if req['event'].wait(50):
req['event'].clear()
req['result']['session_id'] = req['session_id']
return req['result']
@http.route('/hw_drivers/box/connect', type='http', auth='none', cors='*', csrf=False, save_session=False)
def connect_box(self, token):
"""
This route is called when we want that a IoT Box will be connected to a Odoo DB
token is a base 64 encoded string and have 2 argument separate by |
1 - url of odoo DB
2 - token. This token will be compared to the token of Odoo. He have 1 hour lifetime
"""
server = helpers.get_odoo_server_url()
image = get_resource_path('hw_drivers', 'static/img', 'False.jpg')
if not server:
credential = b64decode(token).decode('utf-8').split('|')
url = credential[0]
token = credential[1]
if len(credential) > 2:
# IoT Box send token with db_uuid and enterprise_code only since V13
db_uuid = credential[2]
enterprise_code = credential[3]
helpers.add_credential(db_uuid, enterprise_code)
try:
subprocess.check_call([get_resource_path('point_of_sale', 'tools/posbox/configuration/connect_to_server.sh'), url, '', token, 'noreboot'])
manager.send_alldevices()
image = get_resource_path('hw_drivers', 'static/img', 'True.jpg')
helpers.odoo_restart(3)
except subprocess.CalledProcessError as e:
_logger.error('A error encountered : %s ' % e.output)
if os.path.isfile(image):
with open(image, 'rb') as f:
return f.read()
@http.route('/hw_drivers/download_logs', type='http', auth='none', cors='*', csrf=False, save_session=False)
def download_logs(self):
"""
Downloads the log file
"""
if tools.config['logfile']:
res = send_file(tools.config['logfile'], mimetype="text/plain", as_attachment=True)
res.headers['Cache-Control'] = 'no-cache'
return res
| 43.525862 | 5,049 |
2,643 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# SKR03
# =====
# Dieses Modul bietet Ihnen einen deutschen Kontenplan basierend auf dem SKR03.
# Gemäss der aktuellen Einstellungen ist ein neues Unternehmen in Odoo
# Umsatzsteuerpflichtig. Zahlreiche Erlös- und Aufwandskonten enthalten
# bereits eine zugeordnete Steuer. Hierdurch wird für diese Konten bereits
# die richtige Vorsteuer (Eingangsrechnungen) bzw. Umsatzsteuer
# (Ausgangsrechnungen) automatisch ausgewählt.
#
# Die Zuordnung von Steuerkonten zu Produkten und / oder Sachkonten kann
# für den jeweiligen betrieblichen Anwendungszweck überarbeitet oder
# auch erweitert werden.
# Die mit diesem Kontenrahmen installierten Steuerschlüssel (z.B. 19%, 7%,
# steuerfrei) können hierzu bei den Produktstammdaten hinterlegt werden
# (in Abhängigkeit der Steuervorschriften). Die Zuordnung erfolgt auf
# dem Aktenreiter Finanzbuchhaltung (Kategorie: Umsatzsteuer / Vorsteuer).
# Die Zuordnung der Steuern für Ein- und Ausfuhren aus EU Ländern, sowie auch
# für den Ein- und Verkauf aus und in Drittländer sollten beim Partner
# (Lieferant / Kunde) hinterlegt werden (in Anhängigkeit vom Herkunftsland
# des Lieferanten/Kunden). Diese Zuordnung ist 'höherwertig' als
# die Zuordnung bei Produkten und überschreibt diese im Einzelfall.
#
# Zur Vereinfachung der Steuerausweise und Buchung bei Auslandsgeschäften
# erlaubt Odoo ein generelles Mapping von Steuerausweis und Steuerkonten
# (z.B. Zuordnung 'Umsatzsteuer 19%' zu 'steuerfreie Einfuhren aus der EU')
# zwecks Zuordnung dieses Mappings zum ausländischen Partner (Kunde/Lieferant).
{
'name': 'Germany SKR03 - Accounting',
'icon': '/l10n_de/static/description/icon.png',
'version': '3.1',
'author': 'openbig.org',
'website': 'http://www.openbig.org',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Dieses Modul beinhaltet einen deutschen Kontenrahmen basierend auf dem SKR03.
==============================================================================
German accounting chart and localization.
""",
'depends': ['l10n_de'],
'data': [
'data/l10n_de_skr03_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_de_skr03_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_fiscal_position_data.xml',
'data/account_reconcile_model_template.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 42.33871 | 2,625 |
261 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
update_taxes_from_templates(cr, 'l10n_de_skr03.l10n_de_chart_template')
| 43.5 | 261 |
271 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import odoo
def migrate(cr, version):
registry = odoo.registry(cr.dbname)
from odoo.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable
migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_de_skr03')
| 33.875 | 271 |
3,229 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'CRM',
'version': '1.6',
'category': 'Sales/CRM',
'sequence': 15,
'summary': 'Track leads and close opportunities',
'description': "",
'website': 'https://www.odoo.com/app/crm',
'depends': [
'base_setup',
'sales_team',
'mail',
'calendar',
'resource',
'fetchmail',
'utm',
'web_tour',
'web_kanban_gauge',
'contacts',
'digest',
'phone_validation',
],
'data': [
'security/crm_security.xml',
'security/ir.model.access.csv',
'data/crm_lead_prediction_data.xml',
'data/crm_lost_reason_data.xml',
'data/crm_stage_data.xml',
'data/crm_team_data.xml',
'data/digest_data.xml',
'data/ir_action_data.xml',
'data/ir_cron_data.xml',
'data/mail_data.xml',
'data/crm_recurring_plan_data.xml',
'wizard/crm_lead_lost_views.xml',
'wizard/crm_lead_to_opportunity_views.xml',
'wizard/crm_lead_to_opportunity_mass_views.xml',
'wizard/crm_merge_opportunities_views.xml',
'wizard/crm_lead_pls_update_views.xml',
'views/calendar_views.xml',
'views/crm_recurring_plan_views.xml',
'views/crm_lost_reason_views.xml',
'views/crm_stage_views.xml',
'views/crm_lead_views.xml',
'views/crm_team_member_views.xml',
'views/digest_views.xml',
'views/mail_activity_views.xml',
'views/res_config_settings_views.xml',
'views/res_partner_views.xml',
'views/utm_campaign_views.xml',
'report/crm_activity_report_views.xml',
'report/crm_opportunity_report_views.xml',
'views/crm_team_views.xml',
'views/crm_menu_views.xml',
'views/crm_helper_templates.xml',
],
'demo': [
'data/crm_team_demo.xml',
'data/mail_template_demo.xml',
'data/crm_team_member_demo.xml',
'data/mail_activity_demo.xml',
'data/crm_lead_demo.xml',
],
'css': ['static/src/css/crm.css'],
'installable': True,
'application': True,
'auto_install': False,
'assets': {
'web.assets_qweb': [
'crm/static/src/xml/forecast_kanban.xml',
],
'web.assets_backend': [
'crm/static/src/js/crm_form.js',
'crm/static/src/js/crm_kanban.js',
'crm/static/src/js/forecast/*',
'crm/static/src/js/systray_activity_menu.js',
'crm/static/src/js/tours/crm.js',
'crm/static/src/scss/crm.scss',
'crm/static/src/scss/crm_team_member_views.scss',
],
"web.assets_backend_legacy_lazy": [
'crm/static/src/js/*_legacy.js',
],
'web.assets_tests': [
'crm/static/tests/tours/**/*',
],
'web.qunit_suite_tests': [
'crm/static/tests/mock_server.js',
'crm/static/tests/forecast_kanban_tests.js',
'crm/static/tests/forecast_view_tests.js',
'crm/static/tests/crm_rainbowman_tests.js',
],
},
'license': 'LGPL-3',
}
| 31.656863 | 3,229 |
17,046 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.common import TestCrmCommon, INCOMING_EMAIL
from odoo.exceptions import AccessError, UserError
from odoo.tests import Form, tagged
from odoo.tests.common import users
@tagged('multi_company')
class TestCRMLeadMultiCompany(TestCrmCommon):
@classmethod
def setUpClass(cls):
super(TestCRMLeadMultiCompany, cls).setUpClass()
cls._activate_multi_company()
def test_initial_data(self):
""" Ensure global data for those tests to avoid unwanted side effects """
self.assertFalse(self.sales_team_1.company_id)
self.assertEqual(self.user_sales_manager_mc.company_id, self.company_2)
@users('user_sales_manager_mc')
def test_lead_mc_company_computation(self):
""" Test lead company computation depending on various parameters. Check
the company is set from the team_id or from the env if there is no team.
No responsible, no team, should not limit company. """
# Lead with falsy values are kept
lead_no_team = self.env['crm.lead'].create({
'name': 'L1',
'team_id': False,
'user_id': False,
})
self.assertFalse(lead_no_team.company_id)
self.assertFalse(lead_no_team.team_id)
self.assertFalse(lead_no_team.user_id)
# Lead with team with company sets company
lead_team_c2 = self.env['crm.lead'].create({
'name': 'L2',
'team_id': self.team_company2.id,
'user_id': False,
})
self.assertEqual(lead_team_c2.company_id, self.company_2)
self.assertFalse(lead_team_c2.user_id)
# Update team wo company: reset lead company also
lead_team_c2.team_id = self.sales_team_1
self.assertFalse(lead_team_c2.company_id)
# Lead with global team has no company
lead_team_no_company = self.env['crm.lead'].create({
'name': 'No company',
'team_id': self.sales_team_1.id,
'user_id': False,
})
self.assertFalse(lead_no_team.company_id)
# Update team w company updates company
lead_team_no_company.team_id = self.team_company2
self.assertEqual(lead_team_no_company.company_id, self.company_2)
self.assertEqual(lead_team_no_company.team_id, self.team_company2)
@users('user_sales_manager_mc')
def test_lead_mc_company_computation_env_team_norestrict(self):
""" Check that the computed company is the one coming from the team even
when it's not in self.env.companies. This may happen when running the
Lead Assignment task. """
LeadUnsyncCids = self.env['crm.lead'].with_context(allowed_company_ids=[self.company_main.id])
self.assertEqual(LeadUnsyncCids.env.company, self.company_main)
self.assertEqual(LeadUnsyncCids.env.companies, self.company_main)
self.assertEqual(LeadUnsyncCids.env.user.company_id, self.company_2)
# multicompany raises if trying to create manually
with self.assertRaises(AccessError):
lead = LeadUnsyncCids.create({
'name': 'My Lead MC',
'team_id': self.team_company2.id
})
# simulate auto-creation through sudo (assignment-like)
lead = LeadUnsyncCids.sudo().create({
'name': 'My Lead MC',
'team_id': self.team_company2.id,
})
self.assertEqual(lead.company_id, self.company_2)
self.assertEqual(lead.team_id, self.team_company2)
self.assertEqual(lead.user_id, self.user_sales_manager_mc)
@users('user_sales_manager_mc')
def test_lead_mc_company_computation_env_user_restrict(self):
""" Check that the computed company is allowed (aka in self.env.companies).
If the assigned team has a set company, the lead has the same one. Otherwise, use one
allowed by user, preferentially choose env current company, user's company otherwise."""
# User is logged in company_main even their default company is company_2
LeadUnsyncCids = self.env['crm.lead'].with_context(allowed_company_ids=[self.company_main.id])
self.assertEqual(LeadUnsyncCids.env.company, self.company_main)
self.assertEqual(LeadUnsyncCids.env.companies, self.company_main)
self.assertEqual(LeadUnsyncCids.env.user.company_id, self.company_2)
# simulate auto-creation through sudo (assignment-like)
lead_1_auto = LeadUnsyncCids.sudo().create({
'name': 'My Lead MC 1 Auto',
})
self.assertEqual(lead_1_auto.team_id, self.sales_team_1,
'[Auto/1] First available team in current company should have been assigned (fallback as user in no team in Main Company).')
self.assertEqual(lead_1_auto.company_id, self.company_main,
'[Auto/1] Current company should be set on the lead as no company was assigned given by team and company is allowed for user.')
self.assertEqual(lead_1_auto.user_id, self.user_sales_manager_mc, '[Auto/1] Current user should have been assigned.')
# manual creation
lead_1_manual = LeadUnsyncCids.create({
'name': 'My Lead MC',
})
self.assertEqual(lead_1_manual.team_id, self.sales_team_1,
'[Auto/1] First available team in current company should have been assigned (fallback as user in no team in Main Company).')
self.assertEqual(lead_1_manual.company_id, self.company_main,
'[Auto/1] Current company should be set on the lead as no company was given by team and company is allowed for user.')
self.assertEqual(lead_1_manual.user_id, self.user_sales_manager_mc, '[Manual/1] Current user should have been assigned.')
# Logged on other company will use that one for the lead company with sales_team_2 as is assigned to company_2
LeadUnsyncCids = self.env['crm.lead'].with_context(allowed_company_ids=[self.company_main.id, self.company_2.id])
LeadUnsyncCids = LeadUnsyncCids.with_company(self.company_2)
self.assertEqual(LeadUnsyncCids.env.company, self.company_2)
lead_2_auto = LeadUnsyncCids.sudo().create({
'name': 'My Lead MC 2 Auto',
})
self.assertEqual(lead_2_auto.team_id, self.team_company2,
'[Auto/2] First available team user is a member of, in current company, should have been assigned.')
self.assertEqual(lead_2_auto.company_id, self.company_2,
'[Auto/2] Current company should be set on the lead as company was assigned on team.')
self.assertEqual(lead_2_auto.user_id, self.user_sales_manager_mc, '[Auto/2] Current user should have been assigned.')
lead_2_manual = LeadUnsyncCids.create({
'name': 'My Lead MC 2 Manual',
})
self.assertEqual(lead_2_manual.team_id, self.team_company2,
'[Manual/2] First available team user is a member of, in current company, should have been assigned.')
self.assertEqual(lead_2_manual.company_id, self.company_2,
'[Manual/2] Current company should be set on the lead as company was assigned on team.')
self.assertEqual(lead_2_manual.user_id, self.user_sales_manager_mc, '[Manual/2] Current user should have been assigned.')
# If assigned team has no company, use company
self.team_company2.write({'company_id': False})
lead_3_auto = LeadUnsyncCids.sudo().create({
'name': 'My Lead MC 3 Auto',
})
self.assertEqual(lead_3_auto.team_id, self.team_company2,
'[Auto/3] First available team user is a member of should have been assigned (fallback as no team with same company defined).')
self.assertEqual(lead_3_auto.company_id, self.company_2,
'[Auto/3] Current company should be set on the lead as no company was given by team and company is allowed for user.')
self.assertEqual(lead_3_auto.user_id, self.user_sales_manager_mc, '[Auto/3] Current user should have been assigned.')
lead_3_manual = LeadUnsyncCids.create({
'name': 'My Lead MC 3 Manual',
})
self.assertEqual(lead_3_manual.company_id, self.company_2,
'[Auto/3] First available team user is a member of should have been assigned (fallback as no team with same company defined).')
self.assertEqual(lead_3_manual.team_id, self.team_company2,
'[Auto/3] Current company should be set on the lead as no company was given by team and company is allowed for user.')
self.assertEqual(lead_3_manual.user_id, self.user_sales_manager_mc, '[Manual/3] Current user should have been assigned.')
# If all teams have no company and don't have user as member, the first sales team is used.
self.team_company2.write({'member_ids': [(3, self.user_sales_manager_mc.id)]})
lead_4_auto = LeadUnsyncCids.sudo().create({
'name': 'My Lead MC 4 Auto',
})
self.assertEqual(lead_4_auto.team_id, self.sales_team_1,
'[Auto/4] As no team has current user as member nor current company as company_id, first available team should have been assigned.')
self.assertEqual(lead_4_auto.company_id, self.company_2,
'[Auto/4] Current company should be set on the lead as no company was given by team and company is allowed for user.')
self.assertEqual(lead_4_auto.user_id, self.user_sales_manager_mc, '[Auto/4] Current user should have been assigned.')
lead_4_manual = LeadUnsyncCids.create({
'name': 'My Lead MC 4 Manual',
})
self.assertEqual(lead_4_manual.company_id, self.company_2,
'[Manual/4] As no team has current user as member nor current company as company_id, first available team should have been assigned.')
self.assertEqual(lead_4_manual.team_id, self.sales_team_1,
'[Manual/4] Current company should be set on the lead as no company was given by team and company is allowed for user.')
self.assertEqual(lead_4_manual.user_id, self.user_sales_manager_mc,
'[Manual/4] Current user should have been assigned.')
@users('user_sales_manager_mc')
def test_lead_mc_company_computation_partner_restrict(self):
""" Check company on partner limits the company on lead. As contacts may
be separated by company, lead with a partner should be limited to that
company. """
partner_c2 = self.partner_c2.with_env(self.env)
self.assertEqual(partner_c2.company_id, self.company_2)
lead = self.env['crm.lead'].create({
'partner_id': partner_c2.id,
'name': 'MC Partner, no company lead',
'user_id': False,
'team_id': False,
})
self.assertEqual(lead.company_id, self.company_2)
partner_main = self.env['res.partner'].create({
'company_id': self.company_main.id,
'email': '[email protected]',
'name': 'Customer for Main',
})
lead.write({'partner_id': partner_main})
self.assertEqual(lead.company_id, self.company_main)
# writing current user on lead would imply putting its team and team's company
# on lead (aka self.company_2), and this clashes with company restriction on
# customer
with self.assertRaises(UserError):
lead.write({
'user_id': self.env.user,
})
@users('user_sales_manager_mc')
def test_lead_mc_company_form(self):
""" Test lead company computation using form view """
crm_lead_form = Form(self.env['crm.lead'])
crm_lead_form.name = "Test Lead"
# default values: current user, its team and therefore its company
self.assertEqual(crm_lead_form.company_id, self.company_2)
self.assertEqual(crm_lead_form.user_id, self.user_sales_manager_mc)
self.assertEqual(crm_lead_form.team_id, self.team_company2)
# remove user, team only
crm_lead_form.user_id = self.env['res.users']
self.assertEqual(crm_lead_form.company_id, self.company_2)
self.assertEqual(crm_lead_form.user_id, self.env['res.users'])
self.assertEqual(crm_lead_form.team_id, self.team_company2)
# remove team, user only
crm_lead_form.user_id = self.user_sales_manager_mc
crm_lead_form.team_id = self.env['crm.team']
self.assertEqual(crm_lead_form.company_id, self.company_2)
self.assertEqual(crm_lead_form.user_id, self.user_sales_manager_mc)
self.assertEqual(crm_lead_form.team_id, self.env['crm.team'])
# remove both: void company to ease assignment
crm_lead_form.user_id = self.env['res.users']
self.assertEqual(crm_lead_form.company_id, self.env['res.company'])
self.assertEqual(crm_lead_form.user_id, self.env['res.users'])
self.assertEqual(crm_lead_form.team_id, self.env['crm.team'])
# force company manually
crm_lead_form.company_id = self.company_2
lead = crm_lead_form.save()
# user_sales_manager cannot read it due to MC rules
with self.assertRaises(AccessError):
lead.with_user(self.user_sales_manager).read(['name'])
@users('user_sales_manager_mc')
def test_lead_mc_company_form_progressives_setup(self):
""" Specific bug reported at Task-2520276. Flow
0) The sales team have no company set
1) Create a lead without a user_id and a team_id
2) Assign a team to the lead
3) Assign a user_id
Goal: if no company is set on the sales team the lead at step 2 should
not have any company_id set. Previous behavior
1) set the company of the env.user
2) Keep the company of the lead
3) set the user company if the current company is not one of the allowed company of the user
Wanted behavior
1) leave the company empty
2) set the company of the team even if it's False (so erase the company if the team has no company set)
3) set the user company if the current company is not one of the allowed company of the user
"""
lead = self.env['crm.lead'].create({
'name': 'Test Progressive Setup',
'user_id': False,
'team_id': False,
})
crm_lead_form = Form(lead)
self.assertEqual(crm_lead_form.company_id, self.env['res.company'])
crm_lead_form.team_id = self.sales_team_1
self.assertEqual(crm_lead_form.company_id, self.env['res.company'])
crm_lead_form.user_id = self.env.user
# self.assertEqual(crm_lead_form.company_id, self.env['res.company']) # FIXME
self.assertEqual(crm_lead_form.company_id, self.company_2)
@users('user_sales_manager_mc')
def test_lead_mc_company_form_w_partner_id(self):
""" Test lead company computation with partner having a company. """
partner_c2 = self.partner_c2.with_env(self.env)
crm_lead_form = Form(self.env['crm.lead'])
crm_lead_form.name = "Test Lead"
crm_lead_form.user_id = self.user_sales_manager_mc
crm_lead_form.partner_id = partner_c2
self.assertEqual(crm_lead_form.company_id, self.company_2, 'Crm: company comes from sales')
self.assertEqual(crm_lead_form.team_id, self.team_company2, 'Crm: team comes from sales')
# reset sales: should not reset company, as partner constrains it
crm_lead_form.team_id = self.env['crm.team']
crm_lead_form.user_id = self.env['res.users']
# ensuring that company_id is not overwritten when the salesperson becomes empty (w\o any team_id)
self.assertEqual(crm_lead_form.company_id, self.company_2, 'Crm: company comes from partner')
def test_gateway_incompatible_company_error_on_incoming_email(self):
self.assertTrue(self.sales_team_1.alias_name)
self.assertFalse(self.sales_team_1.company_id)
customer_company = self.env['res.partner'].create({
'company_id': self.company_2.id,
'email': '[email protected]',
'mobile': '+32455000000',
'name': 'InCompany Customer',
})
new_lead = self.format_and_process(
INCOMING_EMAIL,
customer_company.email,
'%s@%s' % (self.sales_team_1.alias_name, self.alias_domain),
subject='Team having partner in company',
target_model='crm.lead',
)
self.assertEqual(new_lead.company_id, self.company_2)
self.assertEqual(new_lead.email_from, customer_company.email)
self.assertEqual(new_lead.partner_id, customer_company)
| 52.937888 | 17,046 |
26,368 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
from datetime import datetime
from dateutil.relativedelta import relativedelta
from unittest.mock import patch
from odoo import fields
from odoo.addons.crm.tests.common import TestLeadConvertCommon
from odoo.tests.common import tagged
from odoo.tools import mute_logger
@tagged('lead_assign')
class TestLeadAssignCommon(TestLeadConvertCommon):
@classmethod
def setUpClass(cls):
super(TestLeadAssignCommon, cls).setUpClass()
cls._switch_to_multi_membership()
cls._switch_to_auto_assign()
# don't mess with existing teams, deactivate them to make tests repeatable
cls.sales_teams = cls.sales_team_1 + cls.sales_team_convert
cls.members = cls.sales_team_1_m1 + cls.sales_team_1_m2 + cls.sales_team_1_m3 + cls.sales_team_convert_m1 + cls.sales_team_convert_m2
cls.env['crm.team'].search([('id', 'not in', cls.sales_teams.ids)]).write({'active': False})
# don't mess with existing leads, unlink those assigned to users used here to make tests
# repeatable (archive is not sufficient because of lost leads)
cls.env['crm.lead'].with_context(active_test=False).search(['|', ('team_id', '=', False), ('user_id', 'in', cls.sales_teams.member_ids.ids)]).unlink()
cls.bundle_size = 50
cls.env['ir.config_parameter'].set_param('crm.assignment.commit.bundle', '%s' % cls.bundle_size)
cls.env['ir.config_parameter'].set_param('crm.assignment.delay', '0')
def assertInitialData(self):
self.assertEqual(self.sales_team_1.assignment_max, 75)
self.assertEqual(self.sales_team_convert.assignment_max, 90)
# ensure domains
self.assertEqual(self.sales_team_1.assignment_domain, False)
self.assertEqual(self.sales_team_1_m1.assignment_domain, False)
self.assertEqual(self.sales_team_1_m2.assignment_domain, "[('probability', '>=', 10)]")
self.assertEqual(self.sales_team_1_m3.assignment_domain, "[('probability', '>=', 20)]")
self.assertEqual(self.sales_team_convert.assignment_domain, "[('priority', 'in', ['1', '2', '3'])]")
self.assertEqual(self.sales_team_convert_m1.assignment_domain, "[('probability', '>=', 20)]")
self.assertEqual(self.sales_team_convert_m2.assignment_domain, False)
# start afresh
self.assertEqual(self.sales_team_1_m1.lead_month_count, 0)
self.assertEqual(self.sales_team_1_m2.lead_month_count, 0)
self.assertEqual(self.sales_team_1_m3.lead_month_count, 0)
self.assertEqual(self.sales_team_convert_m1.lead_month_count, 0)
self.assertEqual(self.sales_team_convert_m2.lead_month_count, 0)
@tagged('lead_assign')
class TestLeadAssign(TestLeadAssignCommon):
""" Test lead assignment feature added in saas-14.2 """
def test_assign_configuration(self):
now_patch = datetime(2020, 11, 2, 10, 0, 0)
with patch.object(fields.Datetime, 'now', return_value=now_patch):
config = self.env['res.config.settings'].create({
'crm_use_auto_assignment': True,
'crm_auto_assignment_action': 'auto',
'crm_auto_assignment_interval_number': 19,
'crm_auto_assignment_interval_type': 'hours'
})
config._onchange_crm_auto_assignment_run_datetime()
config.execute()
self.assertTrue(self.assign_cron.active)
self.assertEqual(self.assign_cron.nextcall, datetime(2020, 11, 2, 10, 0, 0) + relativedelta(hours=19))
config.write({
'crm_auto_assignment_interval_number': 2,
'crm_auto_assignment_interval_type': 'days'
})
config._onchange_crm_auto_assignment_run_datetime()
config.execute()
self.assertTrue(self.assign_cron.active)
self.assertEqual(self.assign_cron.nextcall, datetime(2020, 11, 2, 10, 0, 0) + relativedelta(days=2))
config.write({
'crm_auto_assignment_run_datetime': fields.Datetime.to_string(datetime(2020, 11, 1, 10, 0, 0)),
})
config.execute()
self.assertTrue(self.assign_cron.active)
self.assertEqual(self.assign_cron.nextcall, datetime(2020, 11, 1, 10, 0, 0))
config.write({
'crm_auto_assignment_action': 'manual',
})
config.execute()
self.assertFalse(self.assign_cron.active)
self.assertEqual(self.assign_cron.nextcall, datetime(2020, 11, 1, 10, 0, 0))
config.write({
'crm_use_auto_assignment': False,
'crm_auto_assignment_action': 'auto',
})
config.execute()
self.assertFalse(self.assign_cron.active)
self.assertEqual(self.assign_cron.nextcall, datetime(2020, 11, 1, 10, 0, 0))
def test_assign_count(self):
""" Test number of assigned leads when dealing with some existing data (leads
or opportunities) as well as with opt-out management. """
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_ids=[False, False, False, self.contact_1.id],
probabilities=[30],
count=8,
suffix='Initial',
)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# archived members should not be taken into account
self.sales_team_1_m1.action_archive()
# assignment_max = 0 means opt_out
self.sales_team_1_m2.assignment_max = 0
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx, lead in enumerate(leads):
lead.probability = idx * 10
# commit probability and related fields
leads.flush()
self.assertEqual(leads[0].probability, 0)
# create exiting leads for user_sales_salesman (sales_team_1_m3, sales_team_convert_m1)
existing_leads = self._create_leads_batch(
lead_type='lead', user_ids=[self.user_sales_salesman.id],
probabilities=[10],
count=14,
suffix='Existing')
self.assertEqual(existing_leads.team_id, self.sales_team_1, "Team should have lower sequence")
existing_leads[0].active = False # lost
existing_leads[1].probability = 100 # not won
existing_leads[2].probability = 0 # not lost
existing_leads.flush()
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertEqual(self.sales_team_1_m3.lead_month_count, 14)
self.assertEqual(self.sales_team_convert_m1.lead_month_count, 0)
# re-assign existing leads, check monthly count is updated
existing_leads[-2:]._handle_salesmen_assignment(user_ids=self.user_sales_manager.ids)
# commit probability and related fields
leads.flush()
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertEqual(self.sales_team_1_m3.lead_month_count, 12)
# sales_team_1_m2 is opt-out (new field in 14.3) -> even with max, no lead assigned
self.sales_team_1_m2.update({'assignment_max': 45, 'assignment_optout': True})
with self.with_user('user_sales_manager'):
teams_data, members_data = self.sales_team_1._action_assign_leads(work_days=4)
Leads = self.env['crm.lead']
self.assertEqual(
sorted(Leads.browse(teams_data[self.sales_team_1]['assigned']).mapped('name')),
['TestLeadInitial_0000', 'TestLeadInitial_0001', 'TestLeadInitial_0002',
'TestLeadInitial_0004', 'TestLeadInitial_0005', 'TestLeadInitial_0006']
)
self.assertEqual(
Leads.browse(teams_data[self.sales_team_1]['merged']).mapped('name'),
['TestLeadInitial_0003']
)
self.assertEqual(len(teams_data[self.sales_team_1]['duplicates']), 1)
self.assertEqual(
sorted(members_data[self.sales_team_1_m3]['assigned'].mapped('name')),
['TestLeadInitial_0000', 'TestLeadInitial_0005']
)
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertEqual(self.sales_team_1_m1.lead_month_count, 0) # archived do not get leads
self.assertEqual(self.sales_team_1_m2.lead_month_count, 0) # opt-out through assignment_max = 0
self.assertEqual(self.sales_team_1_m3.lead_month_count, 14) # 15 max on 4 days (2) + existing 12
with self.with_user('user_sales_manager'):
self.env['crm.team'].browse(self.sales_team_1.ids)._action_assign_leads(work_days=4)
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertEqual(self.sales_team_1_m1.lead_month_count, 0) # archived do not get leads
self.assertEqual(self.sales_team_1_m2.lead_month_count, 0) # opt-out through assignment_max = 0
self.assertEqual(self.sales_team_1_m3.lead_month_count, 16) # 15 max on 4 days (2) + existing 14 and not capped anymore
@mute_logger('odoo.models.unlink')
def test_assign_duplicates(self):
""" Test assign process with duplicates on partner. Allow to ensure notably
that de duplication is effectively performed. """
# fix the seed and avoid randomness
random.seed(1940)
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_ids=[self.contact_1.id, self.contact_2.id, False, False, False],
count=200
)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx in range(0, 5):
sliced_leads = leads[idx:len(leads):5]
for lead in sliced_leads:
lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2)
# commit probability and related fields
leads.flush()
with self.with_user('user_sales_manager'):
self.env['crm.team'].browse(self.sales_teams.ids)._action_assign_leads(work_days=2)
# teams assign
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
self.assertEqual(len(leads), 122)
leads_st1 = leads.filtered_domain([('team_id', '=', self.sales_team_1.id)])
leads_stc = leads.filtered_domain([('team_id', '=', self.sales_team_convert.id)])
# check random globally assigned enough leads to team
self.assertEqual(len(leads_st1), 76)
self.assertEqual(len(leads_stc), 46)
self.assertEqual(len(leads_st1) + len(leads_stc), len(leads)) # Make sure all lead are assigned
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4)
self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_convert_m1, 8) # 30 max on 15 (2) + compensation (5.6)
self.assertMemberAssign(self.sales_team_convert_m2, 15) # 60 max on 15 (4) + compsantion (11.2)
# teams assign: everything should be done due to duplicates
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
self.assertEqual(len(leads.filtered_domain([('team_id', '=', False)])), 0)
# deduplicate should have removed all duplicated linked to contact_1 and contact_2
new_assigned_leads_wpartner = self.env['crm.lead'].search([
('partner_id', 'in', (self.contact_1 | self.contact_2).ids),
('id', 'in', leads.ids)
])
self.assertEqual(len(new_assigned_leads_wpartner), 2)
@mute_logger('odoo.models.unlink')
def test_assign_no_duplicates(self):
# fix the seed and avoid randomness
random.seed(1945)
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_ids=[False],
count=150
)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx in range(0, 5):
sliced_leads = leads[idx:len(leads):5]
for lead in sliced_leads:
lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2)
# commit probability and related fields
leads.flush()
with self.with_user('user_sales_manager'):
self.env['crm.team'].browse(self.sales_teams.ids)._action_assign_leads(work_days=2)
# teams assign
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
leads_st1 = leads.filtered_domain([('team_id', '=', self.sales_team_1.id)])
leads_stc = leads.filtered_domain([('team_id', '=', self.sales_team_convert.id)])
self.assertEqual(len(leads), 150)
# check random globally assigned enough leads to team
self.assertEqual(len(leads_st1), 104)
self.assertEqual(len(leads_stc), 46)
self.assertEqual(len(leads_st1) + len(leads_stc), len(leads)) # Make sure all lead are assigned
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4)
self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_convert_m1, 8) # 30 max on 15 (2) + compensation (5.6)
self.assertMemberAssign(self.sales_team_convert_m2, 15) # 60 max on 15 (4) + compensation (11.2)
@mute_logger('odoo.models.unlink')
def test_assign_populated(self):
""" Test assignment on a more high volume oriented test set in order to
test more real life use cases. """
# fix the seed and avoid randomness (funny: try 1870)
random.seed(1871)
# create leads enough to assign one month of work
_lead_count, _email_dup_count, _partner_count = 600, 50, 150
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_count=_partner_count,
country_ids=[self.env.ref('base.be').id, self.env.ref('base.fr').id, False],
count=_lead_count,
email_dup_count=_email_dup_count)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# assign for one month, aka a lot
self.env.ref('crm.ir_cron_crm_lead_assign').write({'interval_type': 'days', 'interval_number': 30})
# create a third team
sales_team_3 = self.env['crm.team'].create({
'name': 'Sales Team 3',
'sequence': 15,
'alias_name': False,
'use_leads': True,
'use_opportunities': True,
'company_id': False,
'user_id': False,
'assignment_domain': [('country_id', '!=', False)],
})
sales_team_3_m1 = self.env['crm.team.member'].create({
'user_id': self.user_sales_manager.id,
'crm_team_id': sales_team_3.id,
'assignment_max': 60,
'assignment_domain': False,
})
sales_team_3_m2 = self.env['crm.team.member'].create({
'user_id': self.user_sales_leads.id,
'crm_team_id': sales_team_3.id,
'assignment_max': 60,
'assignment_domain': False,
})
sales_team_3_m3 = self.env['crm.team.member'].create({
'user_id': self.user_sales_salesman.id,
'crm_team_id': sales_team_3.id,
'assignment_max': 15,
'assignment_domain': [('probability', '>=', 10)],
})
sales_teams = self.sales_teams + sales_team_3
self.assertEqual(sum(team.assignment_max for team in sales_teams), 300)
self.assertEqual(len(leads), 650)
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx in range(0, 5):
sliced_leads = leads[idx:len(leads):5]
for lead in sliced_leads:
lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2)
# commit probability and related fields
leads.flush()
with self.with_user('user_sales_manager'):
self.env['crm.team'].browse(sales_teams.ids)._action_assign_leads(work_days=30)
# teams assign
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)])
self.assertEqual(leads.team_id, sales_teams)
self.assertEqual(leads.user_id, sales_teams.member_ids)
self.assertEqual(len(leads), 600)
# check random globally assigned enough leads to team
leads_st1 = leads.filtered_domain([('team_id', '=', self.sales_team_1.id)])
leads_st2 = leads.filtered_domain([('team_id', '=', self.sales_team_convert.id)])
leads_st3 = leads.filtered_domain([('team_id', '=', sales_team_3.id)])
self.assertLessEqual(len(leads_st1), 225) # 75 * 600 / 300 * 1.5 (because random)
self.assertLessEqual(len(leads_st2), 270) # 90 * 600 / 300 * 1.5 (because random)
self.assertLessEqual(len(leads_st3), 405) # 135 * 600 / 300 * 1.5 (because random)
self.assertGreaterEqual(len(leads_st1), 75) # 75 * 600 / 300 * 0.5 (because random)
self.assertGreaterEqual(len(leads_st2), 90) # 90 * 600 / 300 * 0.5 (because random)
self.assertGreaterEqual(len(leads_st3), 135) # 135 * 600 / 300 * 0.5 (because random)
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertMemberAssign(self.sales_team_1_m1, 45) # 45 max on one month
self.assertMemberAssign(self.sales_team_1_m2, 15) # 15 max on one month
self.assertMemberAssign(self.sales_team_1_m3, 15) # 15 max on one month
self.assertMemberAssign(self.sales_team_convert_m1, 30) # 30 max on one month
self.assertMemberAssign(self.sales_team_convert_m2, 60) # 60 max on one month
self.assertMemberAssign(sales_team_3_m1, 60) # 60 max on one month
self.assertMemberAssign(sales_team_3_m2, 60) # 60 max on one month
self.assertMemberAssign(sales_team_3_m3, 15) # 15 max on one month
def test_assign_quota(self):
""" Test quota computation """
self.assertInitialData()
# quota computation without existing leads
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=1),
10,
"Assignment quota: 45 max on 1 days -> 1.5, compensation (45-1.5)/5 -> 8.7"
)
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=2),
11,
"Assignment quota: 45 max on 2 days -> 3, compensation (45-3)/5 -> 8.4"
)
# quota should not exceed maximum
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=30),
45,
"Assignment quota: no compensation as exceeding monthly count"
)
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=60),
90,
"Assignment quota: no compensation and no limit anymore (do as asked)"
)
# create exiting leads for user_sales_leads (sales_team_1_m1)
existing_leads = self._create_leads_batch(
lead_type='lead', user_ids=[self.user_sales_leads.id],
probabilities=[10],
count=30)
self.assertEqual(existing_leads.team_id, self.sales_team_1, "Team should have lower sequence")
existing_leads.flush()
self.sales_team_1_m1.invalidate_cache(fnames=['lead_month_count'])
self.assertEqual(self.sales_team_1_m1.lead_month_count, 30)
# quota computation with existing leads
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=1),
4,
"Assignment quota: 45 max on 1 days -> 1.5, compensation (45-30-1.5)/5 -> 2.7"
)
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=2),
5,
"Assignment quota: 45 max on 2 days -> 3, compensation (45-30-3)/5 -> 2.4"
)
# quota should not exceed maximum
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=30),
45,
"Assignment quota: no compensation and no limit anymore (do as asked even with 30 already assigned)"
)
self.assertEqual(
self.sales_team_1_m1._get_assignment_quota(work_days=60),
90,
"Assignment quota: no compensation and no limit anymore (do as asked even with 30 already assigned)"
)
def test_assign_specific_won_lost(self):
""" Test leads taken into account in assign process: won, lost, stage
configuration. """
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_ids=[False, False, False, self.contact_1.id],
probabilities=[30],
count=6
)
leads[0].stage_id = self.stage_gen_won.id # is won -> should not be taken into account
leads[1].stage_id = False
leads[2].update({'stage_id': False, 'probability': 0})
leads[3].update({'stage_id': False, 'probability': False})
leads[4].active = False # is lost -> should not be taken into account
leads[5].update({'team_id': self.sales_team_convert.id, 'user_id': self.user_sales_manager.id}) # assigned lead should not be re-assigned
# commit probability and related fields
leads.flush()
with self.with_user('user_sales_manager'):
self.env['crm.team'].browse(self.sales_team_1.ids)._action_assign_leads(work_days=4)
self.assertEqual(leads[0].team_id, self.env['crm.team'], 'Won lead should not be assigned')
self.assertEqual(leads[0].user_id, self.env['res.users'], 'Won lead should not be assigned')
for lead in leads[1:4]:
self.assertIn(lead.user_id, self.sales_team_1.member_ids)
self.assertEqual(lead.team_id, self.sales_team_1)
self.assertEqual(leads[4].team_id, self.env['crm.team'], 'Lost lead should not be assigned')
self.assertEqual(leads[4].user_id, self.env['res.users'], 'Lost lead should not be assigned')
self.assertEqual(leads[5].team_id, self.sales_team_convert, 'Assigned lead should not be reassigned')
self.assertEqual(leads[5].user_id, self.user_sales_manager, 'Assigned lead should not be reassigned')
@mute_logger('odoo.models.unlink')
def test_merge_assign_keep_master_team(self):
""" Check existing opportunity keep its team and salesman when merged with a new lead """
sales_team_dupe = self.env['crm.team'].create({
'name': 'Sales Team Dupe',
'sequence': 15,
'alias_name': False,
'use_leads': True,
'use_opportunities': True,
'company_id': False,
'user_id': False,
'assignment_domain': "[]",
})
self.env['crm.team.member'].create({
'user_id': self.user_sales_salesman.id,
'crm_team_id': sales_team_dupe.id,
'assignment_max': 10,
'assignment_domain': "[]",
})
master_opp = self.env['crm.lead'].create({
'name': 'Master',
'type': 'opportunity',
'probability': 50,
'partner_id': self.contact_1.id,
'team_id': self.sales_team_1.id,
'user_id': self.user_sales_manager.id,
})
dupe_lead = self.env['crm.lead'].create({
'name': 'Dupe',
'type': 'lead',
'email_from': 'Duplicate Email <%s>' % master_opp.email_normalized,
'probability': 10,
'team_id': False,
'user_id': False,
})
sales_team_dupe._action_assign_leads(work_days=2)
self.assertFalse(dupe_lead.exists())
self.assertEqual(master_opp.team_id, self.sales_team_1, 'Opportunity: should keep its sales team')
self.assertEqual(master_opp.user_id, self.user_sales_manager, 'Opportunity: should keep its salesman')
def test_no_assign_if_exceed_max_assign(self):
""" Test no leads being assigned to any team member if weights list sums to 0"""
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
count=1
)
sales_team_4 = self.env['crm.team'].create({
'name': 'Sales Team 4',
'sequence': 15,
'use_leads': True,
})
sales_team_4_m1 = self.env['crm.team.member'].create({
'user_id': self.user_sales_salesman.id,
'crm_team_id': sales_team_4.id,
'assignment_max': 30,
})
sales_team_4_m1.lead_month_count = 50
leads.team_id = sales_team_4.id
members_data = sales_team_4_m1._assign_and_convert_leads(work_days=0.2)
self.assertEqual(
len(members_data[sales_team_4_m1]['assigned']),
0,
"If team member has lead count greater than max assign,then do not assign any more")
| 46.751773 | 26,368 |
32,753 |
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 tools
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.fields import Date
from odoo.tests import Form, tagged, users
from odoo.tests.common import TransactionCase
@tagged('crm_lead_pls')
class TestCRMPLS(TransactionCase):
@classmethod
def setUpClass(cls):
""" Keep a limited setup to ensure tests are not impacted by other
records created in CRM common. """
super(TestCRMPLS, cls).setUpClass()
cls.company_main = cls.env.user.company_id
cls.user_sales_manager = mail_new_test_user(
cls.env, login='user_sales_manager',
name='Martin PLS Sales Manager', email='[email protected]',
company_id=cls.company_main.id,
notification_type='inbox',
groups='sales_team.group_sale_manager,base.group_partner_manager',
)
cls.pls_team = cls.env['crm.team'].create({
'name': 'PLS Team',
})
def _get_lead_values(self, team_id, name_suffix, country_id, state_id, email_state, phone_state, source_id, stage_id):
return {
'name': 'lead_' + name_suffix,
'type': 'opportunity',
'state_id': state_id,
'email_state': email_state,
'phone_state': phone_state,
'source_id': source_id,
'stage_id': stage_id,
'country_id': country_id,
'team_id': team_id
}
def generate_leads_with_tags(self, tag_ids):
Lead = self.env['crm.lead']
team_id = self.env['crm.team'].create({
'name': 'blup',
}).id
leads_to_create = []
for i in range(150):
if i < 50: # tag 1
leads_to_create.append({
'name': 'lead_tag_%s' % str(i),
'tag_ids': [(4, tag_ids[0])],
'team_id': team_id
})
elif i < 100: # tag 2
leads_to_create.append({
'name': 'lead_tag_%s' % str(i),
'tag_ids': [(4, tag_ids[1])],
'team_id': team_id
})
else: # tag 1 and 2
leads_to_create.append({
'name': 'lead_tag_%s' % str(i),
'tag_ids': [(6, 0, tag_ids)],
'team_id': team_id
})
leads_with_tags = Lead.create(leads_to_create)
return leads_with_tags
def test_crm_lead_pls_update(self):
""" We test here that the wizard for updating probabilities from settings
is getting correct value from config params and after updating values
from the wizard, the config params are correctly updated
"""
# Set the PLS config
frequency_fields = self.env['crm.lead.scoring.frequency.field'].search([])
pls_fields_str = ','.join(frequency_fields.mapped('field_id.name'))
pls_start_date_str = "2021-01-01"
IrConfigSudo = self.env['ir.config_parameter'].sudo()
IrConfigSudo.set_param("crm.pls_start_date", pls_start_date_str)
IrConfigSudo.set_param("crm.pls_fields", pls_fields_str)
date_to_update = "2021-02-02"
fields_to_remove = frequency_fields.filtered(lambda f: f.field_id.name in ['source_id', 'lang_id'])
fields_after_updation_str = ','.join((frequency_fields - fields_to_remove).mapped('field_id.name'))
# Check that wizard to update lead probabilities has correct value set by default
pls_update_wizard = Form(self.env['crm.lead.pls.update'])
with pls_update_wizard:
self.assertEqual(Date.to_string(pls_update_wizard.pls_start_date), pls_start_date_str, 'Correct date is taken from config')
self.assertEqual(','.join([f.field_id.name for f in pls_update_wizard.pls_fields]), pls_fields_str, 'Correct fields are taken from config')
# Update the wizard values and check that config values and probabilities are updated accordingly
pls_update_wizard.pls_start_date = date_to_update
for field in fields_to_remove:
pls_update_wizard.pls_fields.remove(field.id)
pls_update_wizard0 = pls_update_wizard.save()
pls_update_wizard0.action_update_crm_lead_probabilities()
# Config params should have been updated
self.assertEqual(IrConfigSudo.get_param("crm.pls_start_date"), date_to_update, 'Correct date is updated in config')
self.assertEqual(IrConfigSudo.get_param("crm.pls_fields"), fields_after_updation_str, 'Correct fields are updated in config')
def test_predictive_lead_scoring(self):
""" We test here computation of lead probability based on PLS Bayes.
We will use 3 different values for each possible variables:
country_id : 1,2,3
state_id: 1,2,3
email_state: correct, incorrect, None
phone_state: correct, incorrect, None
source_id: 1,2,3
stage_id: 1,2,3 + the won stage
And we will compute all of this for 2 different team_id
Note : We assume here that original bayes computation is correct
as we don't compute manually the probabilities."""
Lead = self.env['crm.lead']
LeadScoringFrequency = self.env['crm.lead.scoring.frequency']
state_values = ['correct', 'incorrect', None]
source_ids = self.env['utm.source'].search([], limit=3).ids
state_ids = self.env['res.country.state'].search([], limit=3).ids
country_ids = self.env['res.country'].search([], limit=3).ids
stage_ids = self.env['crm.stage'].search([], limit=3).ids
won_stage_id = self.env['crm.stage'].search([('is_won', '=', True)], limit=1).id
team_ids = self.env['crm.team'].create([{'name': 'Team Test 1'}, {'name': 'Team Test 2'}, {'name': 'Team Test 3'}]).ids
# create bunch of lost and won crm_lead
leads_to_create = []
# for team 1
for i in range(3):
leads_to_create.append(
self._get_lead_values(team_ids[0], 'team_1_%s' % str(i), country_ids[i], state_ids[i], state_values[i], state_values[i], source_ids[i], stage_ids[i]))
leads_to_create.append(
self._get_lead_values(team_ids[0], 'team_1_%s' % str(3), country_ids[0], state_ids[1], state_values[2], state_values[0], source_ids[2], stage_ids[1]))
leads_to_create.append(
self._get_lead_values(team_ids[0], 'team_1_%s' % str(4), country_ids[1], state_ids[1], state_values[1], state_values[0], source_ids[1], stage_ids[0]))
# for team 2
leads_to_create.append(
self._get_lead_values(team_ids[1], 'team_2_%s' % str(5), country_ids[0], state_ids[1], state_values[2], state_values[0], source_ids[1], stage_ids[2]))
leads_to_create.append(
self._get_lead_values(team_ids[1], 'team_2_%s' % str(6), country_ids[0], state_ids[1], state_values[0], state_values[1], source_ids[2], stage_ids[1]))
leads_to_create.append(
self._get_lead_values(team_ids[1], 'team_2_%s' % str(7), country_ids[0], state_ids[2], state_values[0], state_values[1], source_ids[2], stage_ids[0]))
leads_to_create.append(
self._get_lead_values(team_ids[1], 'team_2_%s' % str(8), country_ids[0], state_ids[1], state_values[2], state_values[0], source_ids[2], stage_ids[1]))
leads_to_create.append(
self._get_lead_values(team_ids[1], 'team_2_%s' % str(9), country_ids[1], state_ids[0], state_values[1], state_values[0], source_ids[1], stage_ids[1]))
# for leads with no team
leads_to_create.append(
self._get_lead_values(False, 'no_team_%s' % str(10), country_ids[1], state_ids[1], state_values[2], state_values[0], source_ids[1], stage_ids[2]))
leads_to_create.append(
self._get_lead_values(False, 'no_team_%s' % str(11), country_ids[0], state_ids[1], state_values[1], state_values[1], source_ids[0], stage_ids[0]))
leads_to_create.append(
self._get_lead_values(False, 'no_team_%s' % str(12), country_ids[1], state_ids[2], state_values[0], state_values[1], source_ids[2], stage_ids[0]))
leads_to_create.append(
self._get_lead_values(False, 'no_team_%s' % str(13), country_ids[0], state_ids[1], state_values[2], state_values[0], source_ids[2], stage_ids[1]))
leads = Lead.create(leads_to_create)
# assign team 3 to all leads with no teams (also take data into account).
leads_with_no_team = self.env['crm.lead'].sudo().search([('team_id', '=', False)])
leads_with_no_team.write({'team_id': team_ids[2]})
# Set the PLS config
self.env['ir.config_parameter'].sudo().set_param("crm.pls_start_date", "2000-01-01")
self.env['ir.config_parameter'].sudo().set_param("crm.pls_fields", "country_id,state_id,email_state,phone_state,source_id,tag_ids")
# set leads as won and lost
# for Team 1
leads[0].action_set_lost()
leads[1].action_set_lost()
leads[2].action_set_won()
# for Team 2
leads[5].action_set_lost()
leads[6].action_set_lost()
leads[7].action_set_won()
# Leads with no team
leads[10].action_set_won()
leads[11].action_set_lost()
leads[12].action_set_lost()
# A. Test Full Rebuild
# rebuild frequencies table and recompute automated_probability for all leads.
Lead._cron_update_automated_probabilities()
# As the cron is computing and writing in SQL queries, we need to invalidate the cache
leads.invalidate_cache()
self.assertEqual(tools.float_compare(leads[3].automated_probability, 33.49, 2), 0)
self.assertEqual(tools.float_compare(leads[8].automated_probability, 7.74, 2), 0)
lead_13_team_3_proba = leads[13].automated_probability
self.assertEqual(tools.float_compare(lead_13_team_3_proba, 35.09, 2), 0)
# Probability for Lead with no teams should be based on all the leads no matter their team.
# De-assign team 3 and rebuilt frequency table and recompute.
# Proba should be different as "no team" is not considered as a separated team.
leads_with_no_team.write({'team_id': False})
Lead._cron_update_automated_probabilities()
leads.invalidate_cache()
lead_13_no_team_proba = leads[13].automated_probability
self.assertTrue(lead_13_team_3_proba != leads[13].automated_probability, "Probability for leads with no team should be different than if they where in their own team.")
self.assertEqual(tools.float_compare(lead_13_no_team_proba, 36.65, 2), 0)
# Test frequencies
lead_4_stage_0_freq = LeadScoringFrequency.search([('team_id', '=', leads[4].team_id.id), ('variable', '=', 'stage_id'), ('value', '=', stage_ids[0])])
lead_4_stage_won_freq = LeadScoringFrequency.search([('team_id', '=', leads[4].team_id.id), ('variable', '=', 'stage_id'), ('value', '=', won_stage_id)])
lead_4_country_freq = LeadScoringFrequency.search([('team_id', '=', leads[4].team_id.id), ('variable', '=', 'country_id'), ('value', '=', leads[4].country_id.id)])
lead_4_email_state_freq = LeadScoringFrequency.search([('team_id', '=', leads[4].team_id.id), ('variable', '=', 'email_state'), ('value', '=', str(leads[4].email_state))])
lead_9_stage_0_freq = LeadScoringFrequency.search([('team_id', '=', leads[9].team_id.id), ('variable', '=', 'stage_id'), ('value', '=', stage_ids[0])])
lead_9_stage_won_freq = LeadScoringFrequency.search([('team_id', '=', leads[9].team_id.id), ('variable', '=', 'stage_id'), ('value', '=', won_stage_id)])
lead_9_country_freq = LeadScoringFrequency.search([('team_id', '=', leads[9].team_id.id), ('variable', '=', 'country_id'), ('value', '=', leads[9].country_id.id)])
lead_9_email_state_freq = LeadScoringFrequency.search([('team_id', '=', leads[9].team_id.id), ('variable', '=', 'email_state'), ('value', '=', str(leads[9].email_state))])
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1)
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1)
self.assertEqual(lead_4_country_freq.won_count, 0.1)
self.assertEqual(lead_4_email_state_freq.won_count, 1.1)
self.assertEqual(lead_4_stage_0_freq.lost_count, 2.1)
self.assertEqual(lead_4_stage_won_freq.lost_count, 0.1)
self.assertEqual(lead_4_country_freq.lost_count, 1.1)
self.assertEqual(lead_4_email_state_freq.lost_count, 2.1)
self.assertEqual(lead_9_stage_0_freq.won_count, 1.1)
self.assertEqual(lead_9_stage_won_freq.won_count, 1.1)
self.assertEqual(lead_9_country_freq.won_count, 0.0) # frequency does not exist
self.assertEqual(lead_9_email_state_freq.won_count, 1.1)
self.assertEqual(lead_9_stage_0_freq.lost_count, 2.1)
self.assertEqual(lead_9_stage_won_freq.lost_count, 0.1)
self.assertEqual(lead_9_country_freq.lost_count, 0.0) # frequency does not exist
self.assertEqual(lead_9_email_state_freq.lost_count, 2.1)
# B. Test Live Increment
leads[4].action_set_lost()
leads[9].action_set_won()
# re-get frequencies that did not exists before
lead_9_country_freq = LeadScoringFrequency.search([('team_id', '=', leads[9].team_id.id), ('variable', '=', 'country_id'), ('value', '=', leads[9].country_id.id)])
# B.1. Test frequencies - team 1 should not impact team 2
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.won_count, 0.1) # unchanged
self.assertEqual(lead_4_email_state_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_0_freq.lost_count, 3.1) # + 1
self.assertEqual(lead_4_stage_won_freq.lost_count, 0.1) # unchanged - consider stages with <= sequence when lost
self.assertEqual(lead_4_country_freq.lost_count, 2.1) # + 1
self.assertEqual(lead_4_email_state_freq.lost_count, 3.1) # + 1
self.assertEqual(lead_9_stage_0_freq.won_count, 2.1) # + 1
self.assertEqual(lead_9_stage_won_freq.won_count, 2.1) # + 1 - consider every stages when won
self.assertEqual(lead_9_country_freq.won_count, 1.1) # + 1
self.assertEqual(lead_9_email_state_freq.won_count, 2.1) # + 1
self.assertEqual(lead_9_stage_0_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_won_freq.lost_count, 0.1) # unchanged
self.assertEqual(lead_9_country_freq.lost_count, 0.1) # unchanged (did not exists before)
self.assertEqual(lead_9_email_state_freq.lost_count, 2.1) # unchanged
# Propabilities of other leads should not be impacted as only modified lead are recomputed.
self.assertEqual(tools.float_compare(leads[3].automated_probability, 33.49, 2), 0)
self.assertEqual(tools.float_compare(leads[8].automated_probability, 7.74, 2), 0)
self.assertEqual(leads[3].is_automated_probability, True)
self.assertEqual(leads[8].is_automated_probability, True)
# Restore -> Should decrease lost
leads[4].toggle_active()
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.won_count, 0.1) # unchanged
self.assertEqual(lead_4_email_state_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_0_freq.lost_count, 2.1) # - 1
self.assertEqual(lead_4_stage_won_freq.lost_count, 0.1) # unchanged - consider stages with <= sequence when lost
self.assertEqual(lead_4_country_freq.lost_count, 1.1) # - 1
self.assertEqual(lead_4_email_state_freq.lost_count, 2.1) # - 1
self.assertEqual(lead_9_stage_0_freq.won_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_won_freq.won_count, 2.1) # unchanged
self.assertEqual(lead_9_country_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_9_email_state_freq.won_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_0_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_won_freq.lost_count, 0.1) # unchanged
self.assertEqual(lead_9_country_freq.lost_count, 0.1) # unchanged
self.assertEqual(lead_9_email_state_freq.lost_count, 2.1) # unchanged
# set to won stage -> Should increase won
leads[4].stage_id = won_stage_id
self.assertEqual(lead_4_stage_0_freq.won_count, 2.1) # + 1
self.assertEqual(lead_4_stage_won_freq.won_count, 2.1) # + 1
self.assertEqual(lead_4_country_freq.won_count, 1.1) # + 1
self.assertEqual(lead_4_email_state_freq.won_count, 2.1) # + 1
self.assertEqual(lead_4_stage_0_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.lost_count, 0.1) # unchanged
self.assertEqual(lead_4_country_freq.lost_count, 1.1) # unchanged
self.assertEqual(lead_4_email_state_freq.lost_count, 2.1) # unchanged
# Archive (was won, now lost) -> Should decrease won and increase lost
leads[4].toggle_active()
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1) # - 1
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1) # - 1
self.assertEqual(lead_4_country_freq.won_count, 0.1) # - 1
self.assertEqual(lead_4_email_state_freq.won_count, 1.1) # - 1
self.assertEqual(lead_4_stage_0_freq.lost_count, 3.1) # + 1
self.assertEqual(lead_4_stage_won_freq.lost_count, 1.1) # consider stages with <= sequence when lostand as stage is won.. even won_stage lost_count is increased by 1
self.assertEqual(lead_4_country_freq.lost_count, 2.1) # + 1
self.assertEqual(lead_4_email_state_freq.lost_count, 3.1) # + 1
# Move to original stage -> Should do nothing (as lead is still lost)
leads[4].stage_id = stage_ids[0]
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.won_count, 0.1) # unchanged
self.assertEqual(lead_4_email_state_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_0_freq.lost_count, 3.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.lost_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_4_email_state_freq.lost_count, 3.1) # unchanged
# Restore -> Should decrease lost - at the end, frequencies should be like first frequencyes tests (except for 0.0 -> 0.1)
leads[4].toggle_active()
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.won_count, 0.1) # unchanged
self.assertEqual(lead_4_email_state_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_0_freq.lost_count, 2.1) # - 1
self.assertEqual(lead_4_stage_won_freq.lost_count, 1.1) # unchanged - consider stages with <= sequence when lost
self.assertEqual(lead_4_country_freq.lost_count, 1.1) # - 1
self.assertEqual(lead_4_email_state_freq.lost_count, 2.1) # - 1
# Probabilities should only be recomputed after modifying the lead itself.
leads[3].stage_id = stage_ids[0] # probability should only change a bit as frequencies are almost the same (except 0.0 -> 0.1)
leads[8].stage_id = stage_ids[0] # probability should change quite a lot
# Test frequencies (should not have changed)
self.assertEqual(lead_4_stage_0_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.won_count, 0.1) # unchanged
self.assertEqual(lead_4_email_state_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_4_stage_0_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_4_stage_won_freq.lost_count, 1.1) # unchanged
self.assertEqual(lead_4_country_freq.lost_count, 1.1) # unchanged
self.assertEqual(lead_4_email_state_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_0_freq.won_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_won_freq.won_count, 2.1) # unchanged
self.assertEqual(lead_9_country_freq.won_count, 1.1) # unchanged
self.assertEqual(lead_9_email_state_freq.won_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_0_freq.lost_count, 2.1) # unchanged
self.assertEqual(lead_9_stage_won_freq.lost_count, 0.1) # unchanged
self.assertEqual(lead_9_country_freq.lost_count, 0.1) # unchanged
self.assertEqual(lead_9_email_state_freq.lost_count, 2.1) # unchanged
# Continue to test probability computation
leads[3].probability = 40
self.assertEqual(leads[3].is_automated_probability, False)
self.assertEqual(leads[8].is_automated_probability, True)
self.assertEqual(tools.float_compare(leads[3].automated_probability, 20.87, 2), 0)
self.assertEqual(tools.float_compare(leads[8].automated_probability, 2.43, 2), 0)
self.assertEqual(tools.float_compare(leads[3].probability, 40, 2), 0)
self.assertEqual(tools.float_compare(leads[8].probability, 2.43, 2), 0)
# Test modify country_id
leads[8].country_id = country_ids[1]
self.assertEqual(tools.float_compare(leads[8].automated_probability, 34.38, 2), 0)
self.assertEqual(tools.float_compare(leads[8].probability, 34.38, 2), 0)
leads[8].country_id = country_ids[0]
self.assertEqual(tools.float_compare(leads[8].automated_probability, 2.43, 2), 0)
self.assertEqual(tools.float_compare(leads[8].probability, 2.43, 2), 0)
# ----------------------------------------------
# Test tag_id frequencies and probability impact
# ----------------------------------------------
tag_ids = self.env['crm.tag'].create([
{'name': "Tag_test_1"},
{'name': "Tag_test_2"},
]).ids
# tag_ids = self.env['crm.tag'].search([], limit=2).ids
leads_with_tags = self.generate_leads_with_tags(tag_ids)
leads_with_tags[:30].action_set_lost() # 60% lost on tag 1
leads_with_tags[31:50].action_set_won() # 40% won on tag 1
leads_with_tags[50:90].action_set_lost() # 80% lost on tag 2
leads_with_tags[91:100].action_set_won() # 20% won on tag 2
leads_with_tags[100:135].action_set_lost() # 70% lost on tag 1 and 2
leads_with_tags[136:150].action_set_won() # 30% won on tag 1 and 2
# tag 1 : won = 19+14 / lost = 30+35
# tag 2 : won = 9+14 / lost = 40+35
tag_1_freq = LeadScoringFrequency.search([('variable', '=', 'tag_id'), ('value', '=', tag_ids[0])])
tag_2_freq = LeadScoringFrequency.search([('variable', '=', 'tag_id'), ('value', '=', tag_ids[1])])
self.assertEqual(tools.float_compare(tag_1_freq.won_count, 33.1, 1), 0)
self.assertEqual(tools.float_compare(tag_1_freq.lost_count, 65.1, 1), 0)
self.assertEqual(tools.float_compare(tag_2_freq.won_count, 23.1, 1), 0)
self.assertEqual(tools.float_compare(tag_2_freq.lost_count, 75.1, 1), 0)
# Force recompute - A priori, no need to do this as, for each won / lost, we increment tag frequency.
Lead._cron_update_automated_probabilities()
leads_with_tags.invalidate_cache()
lead_tag_1 = leads_with_tags[30]
lead_tag_2 = leads_with_tags[90]
lead_tag_1_2 = leads_with_tags[135]
self.assertEqual(tools.float_compare(lead_tag_1.automated_probability, 33.69, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_2.automated_probability, 23.51, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_1_2.automated_probability, 28.05, 2), 0)
lead_tag_1.tag_ids = [(5, 0, 0)] # remove all tags
lead_tag_1_2.tag_ids = [(3, tag_ids[1], 0)] # remove tag 2
self.assertEqual(tools.float_compare(lead_tag_1.automated_probability, 28.6, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_2.automated_probability, 23.51, 2), 0) # no impact
self.assertEqual(tools.float_compare(lead_tag_1_2.automated_probability, 33.69, 2), 0)
lead_tag_1.tag_ids = [(4, tag_ids[1])] # add tag 2
lead_tag_2.tag_ids = [(4, tag_ids[0])] # add tag 1
lead_tag_1_2.tag_ids = [(3, tag_ids[0]), (4, tag_ids[1])] # remove tag 1 / add tag 2
self.assertEqual(tools.float_compare(lead_tag_1.automated_probability, 23.51, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_2.automated_probability, 28.05, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_1_2.automated_probability, 23.51, 2), 0)
# go back to initial situation
lead_tag_1.tag_ids = [(3, tag_ids[1]), (4, tag_ids[0])] # remove tag 2 / add tag 1
lead_tag_2.tag_ids = [(3, tag_ids[0])] # remove tag 1
lead_tag_1_2.tag_ids = [(4, tag_ids[0])] # add tag 1
self.assertEqual(tools.float_compare(lead_tag_1.automated_probability, 33.69, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_2.automated_probability, 23.51, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_1_2.automated_probability, 28.05, 2), 0)
# set email_state for each lead and update probabilities
leads.filtered(lambda lead: lead.id % 2 == 0).email_state = 'correct'
leads.filtered(lambda lead: lead.id % 2 == 1).email_state = 'incorrect'
Lead._cron_update_automated_probabilities()
leads_with_tags.invalidate_cache()
self.assertEqual(tools.float_compare(leads[3].automated_probability, 4.21, 2), 0)
self.assertEqual(tools.float_compare(leads[8].automated_probability, 0.23, 2), 0)
# remove all pls fields
self.env['ir.config_parameter'].sudo().set_param("crm.pls_fields", False)
Lead._cron_update_automated_probabilities()
leads_with_tags.invalidate_cache()
self.assertEqual(tools.float_compare(leads[3].automated_probability, 34.38, 2), 0)
self.assertEqual(tools.float_compare(leads[8].automated_probability, 50.0, 2), 0)
# check if the probabilities are the same with the old param
self.env['ir.config_parameter'].sudo().set_param("crm.pls_fields", "country_id,state_id,email_state,phone_state,source_id")
Lead._cron_update_automated_probabilities()
leads_with_tags.invalidate_cache()
self.assertEqual(tools.float_compare(leads[3].automated_probability, 4.21, 2), 0)
self.assertEqual(tools.float_compare(leads[8].automated_probability, 0.23, 2), 0)
# remove tag_ids from the calculation
self.assertEqual(tools.float_compare(lead_tag_1.automated_probability, 28.6, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_2.automated_probability, 28.6, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_1_2.automated_probability, 28.6, 2), 0)
lead_tag_1.tag_ids = [(5, 0, 0)] # remove all tags
lead_tag_2.tag_ids = [(4, tag_ids[0])] # add tag 1
lead_tag_1_2.tag_ids = [(3, tag_ids[1], 0)] # remove tag 2
self.assertEqual(tools.float_compare(lead_tag_1.automated_probability, 28.6, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_2.automated_probability, 28.6, 2), 0)
self.assertEqual(tools.float_compare(lead_tag_1_2.automated_probability, 28.6, 2), 0)
def test_settings_pls_start_date(self):
# We test here that settings never crash due to ill-configured config param 'crm.pls_start_date'
set_param = self.env['ir.config_parameter'].sudo().set_param
str_date_8_days_ago = Date.to_string(Date.today() - timedelta(days=8))
resConfig = self.env['res.config.settings']
set_param("crm.pls_start_date", "2021-10-10")
res_config_new = resConfig.new()
self.assertEqual(Date.to_string(res_config_new.predictive_lead_scoring_start_date),
"2021-10-10", "If config param is a valid date, date in settings should match with config param")
set_param("crm.pls_start_date", "")
res_config_new = resConfig.new()
self.assertEqual(Date.to_string(res_config_new.predictive_lead_scoring_start_date),
str_date_8_days_ago, "If config param is empty, date in settings should be set to 8 days before today")
set_param("crm.pls_start_date", "One does not simply walk into system parameters to corrupt them")
res_config_new = resConfig.new()
self.assertEqual(Date.to_string(res_config_new.predictive_lead_scoring_start_date),
str_date_8_days_ago, "If config param is not a valid date, date in settings should be set to 8 days before today")
def test_pls_no_share_stage(self):
""" We test here the situation where all stages are team specific, as there is
a current limitation (can be seen in _pls_get_won_lost_total_count) regarding
the first stage (used to know how many lost and won there is) that requires
to have no team assigned to it."""
Lead = self.env['crm.lead']
team_id = self.env['crm.team'].create([{'name': 'Team Test'}]).id
self.env['crm.stage'].search([('team_id', '=', False)]).write({'team_id': team_id})
lead = Lead.create({'name': 'team', 'team_id': team_id, 'probability': 41.23})
Lead._cron_update_automated_probabilities()
self.assertEqual(tools.float_compare(lead.probability, 41.23, 2), 0)
self.assertEqual(tools.float_compare(lead.automated_probability, 0, 2), 0)
@users('user_sales_manager')
def test_team_unlink(self):
""" Test that frequencies are sent to "no team" when unlinking a team
in order to avoid loosing too much informations. """
pls_team = self.env["crm.team"].browse(self.pls_team.ids)
# clean existing data
self.env["crm.lead.scoring.frequency"].sudo().search([('team_id', '=', False)]).unlink()
# existing no-team data
no_team = [
('stage_id', '1', 20, 10),
('stage_id', '2', 0.1, 0.1),
('stage_id', '3', 10, 0),
('country_id', '1', 10, 0.1),
]
self.env["crm.lead.scoring.frequency"].sudo().create([
{'variable': variable, 'value': value,
'won_count': won_count, 'lost_count': lost_count,
'team_id': False,
} for variable, value, won_count, lost_count in no_team
])
# add some frequencies to team to unlink
team = [
('stage_id', '1', 20, 10), # existing noteam
('country_id', '1', 0.1, 10), # existing noteam
('country_id', '2', 0.1, 0), # new but void
('country_id', '3', 30, 30), # new
]
existing_plsteam = self.env["crm.lead.scoring.frequency"].sudo().create([
{'variable': variable, 'value': value,
'won_count': won_count, 'lost_count': lost_count,
'team_id': pls_team.id,
} for variable, value, won_count, lost_count in team
])
pls_team.unlink()
final_noteam = [
('stage_id', '1', 40, 20),
('stage_id', '2', 0.1, 0.1),
('stage_id', '3', 10, 0),
('country_id', '1', 10, 10),
('country_id', '3', 30, 30),
]
self.assertEqual(
existing_plsteam.exists(), self.env["crm.lead.scoring.frequency"],
'Frequencies of unlinked teams should be unlinked (cascade)')
existing_noteam = self.env["crm.lead.scoring.frequency"].sudo().search([
('team_id', '=', False),
('variable', 'in', ['stage_id', 'country_id']),
])
for frequency in existing_noteam:
stat = next(item for item in final_noteam if item[0] == frequency.variable and item[1] == frequency.value)
self.assertEqual(frequency.won_count, stat[2])
self.assertEqual(frequency.lost_count, stat[3])
self.assertEqual(len(existing_noteam), len(final_noteam))
| 57.060976 | 32,753 |
9,870 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
from odoo.addons.crm.tests.test_crm_lead_assignment import TestLeadAssignCommon
from odoo.tests.common import tagged
from odoo.tools import mute_logger
@tagged('lead_assign', 'crm_performance', 'post_install', '-at_install')
class TestLeadAssignPerf(TestLeadAssignCommon):
""" Test performances of lead assignment feature added in saas-14.2
Assign process is a random process: randomizing teams leads to searching,
assigning and de-duplicating leads in various order. As a lot of search
are implied during assign process query counters may vary from run to run.
"Heavy" performance test included here ranged from 6K to 6.3K queries. Either
we set high counters maximum which makes those tests less useful. Either we
avoid random if possible which is what we decided to do by setting the seed
of random in tests.
"""
@mute_logger('odoo.models.unlink', 'odoo.addons.crm.models.crm_team', 'odoo.addons.crm.models.crm_team_member')
def test_assign_perf_duplicates(self):
""" Test assign process with duplicates on partner. Allow to ensure notably
that de duplication is effectively performed. """
# fix the seed and avoid randomness
random.seed(1940)
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_ids=[self.contact_1.id, self.contact_2.id, False, False, False],
count=200
)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx in range(0, 5):
sliced_leads = leads[idx:len(leads):5]
for lead in sliced_leads:
lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2)
# commit probability and related fields
leads.flush()
# multi: 1444, sometimes 1447 or 1451
with self.with_user('user_sales_manager'):
with self.profile(collectors=['sql']):
#with self.assertQueryCount(user_sales_manager=1444): # crm 1368
# this test was disabled on runbot because of this random query count and is now always failling
self.env['crm.team'].browse(self.sales_teams.ids)._action_assign_leads(work_days=2)
# teams assign
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
leads_st1 = leads.filtered_domain([('team_id', '=', self.sales_team_1.id)])
leads_stc = leads.filtered_domain([('team_id', '=', self.sales_team_convert.id)])
self.assertLessEqual(len(leads_st1), 128)
self.assertLessEqual(len(leads_stc), 96)
self.assertEqual(len(leads_st1) + len(leads_stc), len(leads)) # Make sure all lead are assigned
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4)
self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_convert_m1, 8) # 30 max on 15 (2) + compensation (5.6)
self.assertMemberAssign(self.sales_team_convert_m2, 15) # 60 max on 15 (4) + compsantion (11.2)
@mute_logger('odoo.models.unlink', 'odoo.addons.crm.models.crm_team', 'odoo.addons.crm.models.crm_team_member')
def test_assign_perf_no_duplicates(self):
# fix the seed and avoid randomness
random.seed(1945)
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_ids=[False],
count=100
)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx in range(0, 5):
sliced_leads = leads[idx:len(leads):5]
for lead in sliced_leads:
lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2)
# commit probability and related fields
leads.flush()
with self.with_user('user_sales_manager'):
with self.assertQueryCount(user_sales_manager=675): # crm 675
self.env['crm.team'].browse(self.sales_teams.ids)._action_assign_leads(work_days=2)
# teams assign
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
leads_st1 = leads.filtered_domain([('team_id', '=', self.sales_team_1.id)])
leads_stc = leads.filtered_domain([('team_id', '=', self.sales_team_convert.id)])
self.assertEqual(len(leads_st1) + len(leads_stc), 100)
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4)
self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8)
self.assertMemberAssign(self.sales_team_convert_m1, 8) # 30 max on 15 (2) + compensation (5.6)
self.assertMemberAssign(self.sales_team_convert_m2, 15) # 60 max on 15 (4) + compensation (11.2)
@mute_logger('odoo.models.unlink', 'odoo.addons.crm.models.crm_team', 'odoo.addons.crm.models.crm_team_member')
def test_assign_perf_populated(self):
""" Test assignment on a more high volume oriented test set in order to
have more insights on query counts. """
# fix the seed and avoid randomness
random.seed(1871)
# create leads enough to have interesting counters
_lead_count, _email_dup_count, _partner_count = 600, 50, 150
leads = self._create_leads_batch(
lead_type='lead',
user_ids=[False],
partner_count=_partner_count,
country_ids=[self.env.ref('base.be').id, self.env.ref('base.fr').id, False],
count=_lead_count,
email_dup_count=_email_dup_count)
# commit probability and related fields
leads.flush()
self.assertInitialData()
# assign for one month, aka a lot
self.env.ref('crm.ir_cron_crm_lead_assign').write({'interval_type': 'days', 'interval_number': 30})
# create a third team
sales_team_3 = self.env['crm.team'].create({
'name': 'Sales Team 3',
'sequence': 15,
'alias_name': False,
'use_leads': True,
'use_opportunities': True,
'company_id': False,
'user_id': False,
'assignment_domain': [('country_id', '!=', False)],
})
sales_team_3_m1 = self.env['crm.team.member'].create({
'user_id': self.user_sales_manager.id,
'crm_team_id': sales_team_3.id,
'assignment_max': 60,
'assignment_domain': False,
})
sales_team_3_m2 = self.env['crm.team.member'].create({
'user_id': self.user_sales_leads.id,
'crm_team_id': sales_team_3.id,
'assignment_max': 60,
'assignment_domain': False,
})
sales_team_3_m3 = self.env['crm.team.member'].create({
'user_id': self.user_sales_salesman.id,
'crm_team_id': sales_team_3.id,
'assignment_max': 15,
'assignment_domain': [('probability', '>=', 10)],
})
sales_teams = self.sales_teams | sales_team_3
self.assertEqual(sum(team.assignment_max for team in sales_teams), 300)
self.assertEqual(len(leads), 650)
# assign probability to leads (bypass auto probability as purpose is not to test pls)
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)]) # ensure order
for idx in range(0, 5):
sliced_leads = leads[idx:len(leads):5]
for lead in sliced_leads:
lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2)
# commit probability and related fields
leads.flush()
# randomness: at least 6 queries
with self.with_user('user_sales_manager'):
with self.assertQueryCount(user_sales_manager=6930): # crm 6863 - com 6925
self.env['crm.team'].browse(sales_teams.ids)._action_assign_leads(work_days=30)
# teams assign
leads = self.env['crm.lead'].search([('id', 'in', leads.ids)])
self.assertEqual(leads.team_id, sales_teams)
self.assertEqual(leads.user_id, sales_teams.member_ids)
# salespersons assign
self.members.invalidate_cache(fnames=['lead_month_count'])
self.assertMemberAssign(self.sales_team_1_m1, 45) # 45 max on one month
self.assertMemberAssign(self.sales_team_1_m2, 15) # 15 max on one month
self.assertMemberAssign(self.sales_team_1_m3, 15) # 15 max on one month
self.assertMemberAssign(self.sales_team_convert_m1, 30) # 30 max on one month
self.assertMemberAssign(self.sales_team_convert_m2, 60) # 60 max on one month
self.assertMemberAssign(sales_team_3_m1, 60) # 60 max on one month
self.assertMemberAssign(sales_team_3_m2, 60) # 60 max on one month
self.assertMemberAssign(sales_team_3_m3, 15) # 15 max on one month
| 49.848485 | 9,870 |
2,245 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests import common as crm_common
from odoo.exceptions import AccessError
from odoo.tests.common import tagged, users
@tagged('lead_manage')
class TestLeadConvert(crm_common.TestCrmCommon):
@classmethod
def setUpClass(cls):
super(TestLeadConvert, cls).setUpClass()
cls.lost_reason = cls.env['crm.lost.reason'].create({
'name': 'Test Reason'
})
@users('user_sales_salesman')
def test_lead_lost(self):
self.lead_1.with_user(self.user_sales_manager).write({
'user_id': self.user_sales_salesman.id,
'probability': 32,
})
lead = self.lead_1.with_user(self.env.user)
self.assertEqual(lead.probability, 32)
lost_wizard = self.env['crm.lead.lost'].with_context({
'active_ids': lead.ids,
}).create({
'lost_reason_id': self.lost_reason.id
})
lost_wizard.action_lost_reason_apply()
self.assertEqual(lead.probability, 0)
self.assertEqual(lead.automated_probability, 0)
self.assertFalse(lead.active)
self.assertEqual(lead.lost_reason, self.lost_reason) # TDE FIXME: should be called lost_reason_id non didjou
@users('user_sales_salesman')
def test_lead_lost_crm_rights(self):
lead = self.lead_1.with_user(self.env.user)
# nice try little salesman but only managers can create lost reason to avoid bloating the DB
with self.assertRaises(AccessError):
lost_reason = self.env['crm.lost.reason'].create({
'name': 'Test Reason'
})
with self.with_user('user_sales_manager'):
lost_reason = self.env['crm.lost.reason'].create({
'name': 'Test Reason'
})
lost_wizard = self.env['crm.lead.lost'].with_context({
'active_ids': lead.ids
}).create({
'lost_reason_id': lost_reason.id
})
# nice try little salesman, you cannot invoke a wizard to update other people leads
with self.assertRaises(AccessError):
lost_wizard.action_lost_reason_apply()
| 34.538462 | 2,245 |
25,572 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import SUPERUSER_ID
from odoo.addons.crm.tests import common as crm_common
from odoo.fields import Datetime
from odoo.tests.common import tagged, users
from odoo.tests.common import Form
@tagged('lead_manage')
class TestLeadConvertForm(crm_common.TestLeadConvertCommon):
@users('user_sales_manager')
def test_form_action_default(self):
""" Test Lead._find_matching_partner() """
lead = self.env['crm.lead'].browse(self.lead_1.ids)
customer = self.env['res.partner'].create({
"name": "Amy Wong",
"email": '"Amy, PhD Student, Wong" Tiny <[email protected]>'
})
wizard = Form(self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': lead.id,
'active_ids': lead.ids,
}))
self.assertEqual(wizard.name, 'convert')
self.assertEqual(wizard.action, 'exist')
self.assertEqual(wizard.partner_id, customer)
@users('user_sales_manager')
def test_form_name_onchange(self):
""" Test Lead._find_matching_partner() """
lead = self.env['crm.lead'].browse(self.lead_1.ids)
lead_dup = lead.copy({'name': 'Duplicate'})
customer = self.env['res.partner'].create({
"name": "Amy Wong",
"email": '"Amy, PhD Student, Wong" Tiny <[email protected]>'
})
wizard = Form(self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': lead.id,
'active_ids': lead.ids,
}))
self.assertEqual(wizard.name, 'merge')
self.assertEqual(wizard.action, 'exist')
self.assertEqual(wizard.partner_id, customer)
self.assertEqual(wizard.duplicated_lead_ids[:], lead + lead_dup)
wizard.name = 'convert'
wizard.action = 'create'
self.assertEqual(wizard.action, 'create', 'Should keep user input')
self.assertEqual(wizard.name, 'convert', 'Should keep user input')
@tagged('lead_manage')
class TestLeadConvert(crm_common.TestLeadConvertCommon):
"""
TODO: created partner (handle assignation) has team of lead
TODO: create partner has user_id coming from wizard
"""
@classmethod
def setUpClass(cls):
super(TestLeadConvert, cls).setUpClass()
date = Datetime.from_string('2020-01-20 16:00:00')
cls.crm_lead_dt_mock.now.return_value = date
@users('user_sales_manager')
def test_duplicates_computation(self):
""" Test Lead._get_lead_duplicates() and check won / probability usage """
test_lead = self.env['crm.lead'].browse(self.lead_1.ids)
customer, dup_leads = self._create_duplicates(test_lead)
dup_leads += self.env['crm.lead'].create([
{'name': 'Duplicate lead: same email_from, lost',
'type': 'lead',
'email_from': test_lead.email_from,
'probability': 0, 'active': False,
},
{'name': 'Duplicate lead: same email_from, proba 0 but not lost',
'type': 'lead',
'email_from': test_lead.email_from,
'probability': 0, 'active': True,
},
{'name': 'Duplicate opp: same email_from, won',
'type': 'opportunity',
'email_from': test_lead.email_from,
'probability': 100, 'stage_id': self.stage_team1_won.id,
},
{'name': 'Duplicate opp: same email_from, proba 100 but not won',
'type': 'opportunity',
'email_from': test_lead.email_from,
'probability': 100, 'stage_id': self.stage_team1_2.id,
}
])
lead_lost = dup_leads.filtered(lambda lead: lead.name == 'Duplicate lead: same email_from, lost')
_opp_proba100 = dup_leads.filtered(lambda lead: lead.name == 'Duplicate opp: same email_from, proba 100 but not won')
opp_won = dup_leads.filtered(lambda lead: lead.name == 'Duplicate opp: same email_from, won')
opp_lost = dup_leads.filtered(lambda lead: lead.name == 'Duplicate: lost opportunity')
test_lead.write({'partner_id': customer.id})
# not include_lost = remove archived leads as well as 'won' opportunities
result = test_lead._get_lead_duplicates(
partner=test_lead.partner_id,
email=test_lead.email_from,
include_lost=False
)
self.assertEqual(result, test_lead + dup_leads - (lead_lost + opp_won + opp_lost))
# include_lost = remove archived opp only
result = test_lead._get_lead_duplicates(
partner=test_lead.partner_id,
email=test_lead.email_from,
include_lost=True
)
self.assertEqual(result, test_lead + dup_leads - (lead_lost))
def test_initial_data(self):
""" Ensure initial data to avoid spaghetti test update afterwards """
self.assertFalse(self.lead_1.date_conversion)
self.assertEqual(self.lead_1.date_open, Datetime.from_string('2020-01-15 11:30:00'))
self.assertEqual(self.lead_1.user_id, self.user_sales_leads)
self.assertEqual(self.lead_1.team_id, self.sales_team_1)
self.assertEqual(self.lead_1.stage_id, self.stage_team1_1)
@users('user_sales_manager')
def test_lead_convert_base(self):
""" Test base method ``convert_opportunity`` or crm.lead model """
self.contact_2.phone = False # force Falsy to compare with mobile
self.assertFalse(self.contact_2.phone)
lead = self.lead_1.with_user(self.env.user)
lead.write({
'phone': '123456789',
})
self.assertEqual(lead.team_id, self.sales_team_1)
self.assertEqual(lead.stage_id, self.stage_team1_1)
self.assertEqual(lead.email_from, '[email protected]')
lead.convert_opportunity(self.contact_2.id)
self.assertEqual(lead.type, 'opportunity')
self.assertEqual(lead.partner_id, self.contact_2)
self.assertEqual(lead.email_from, self.contact_2.email)
self.assertEqual(lead.mobile, self.contact_2.mobile)
self.assertEqual(lead.phone, '123456789')
self.assertEqual(lead.team_id, self.sales_team_1)
self.assertEqual(lead.stage_id, self.stage_team1_1)
@users('user_sales_manager')
def test_lead_convert_base_corner_cases(self):
""" Test base method ``convert_opportunity`` or crm.lead model with corner
cases: inactive, won, stage update, ... """
# inactive leads are not converted
lead = self.lead_1.with_user(self.env.user)
lead.action_archive()
self.assertFalse(lead.active)
lead.convert_opportunity(self.contact_2.id)
self.assertEqual(lead.type, 'lead')
self.assertEqual(lead.partner_id, self.env['res.partner'])
lead.action_unarchive()
self.assertTrue(lead.active)
# won leads are not converted
lead.action_set_won()
# TDE FIXME: set won does not take into account sales team when fetching a won stage
# self.assertEqual(lead.stage_id, self.stage_team1_won)
self.assertEqual(lead.stage_id, self.stage_gen_won)
self.assertEqual(lead.probability, 100)
lead.convert_opportunity(self.contact_2.id)
self.assertEqual(lead.type, 'lead')
self.assertEqual(lead.partner_id, self.env['res.partner'])
@users('user_sales_manager')
def test_lead_convert_base_w_salesmen(self):
""" Test base method ``convert_opportunity`` while forcing salesmen, as it
should also force sales team """
lead = self.lead_1.with_user(self.env.user)
self.assertEqual(lead.team_id, self.sales_team_1)
lead.convert_opportunity(False, user_ids=self.user_sales_salesman.ids)
self.assertEqual(lead.user_id, self.user_sales_salesman)
self.assertEqual(lead.team_id, self.sales_team_convert)
# TDE FIXME: convert does not recompute stage based on updated team of assigned user
# self.assertEqual(lead.stage_id, self.stage_team_convert_1)
@users('user_sales_manager')
def test_lead_convert_base_w_team(self):
""" Test base method ``convert_opportunity`` while forcing team """
lead = self.lead_1.with_user(self.env.user)
lead.convert_opportunity(False, team_id=self.sales_team_convert.id)
self.assertEqual(lead.team_id, self.sales_team_convert)
self.assertEqual(lead.user_id, self.user_sales_leads)
# TDE FIXME: convert does not recompute stage based on team
# self.assertEqual(lead.stage_id, self.stage_team_convert_1)
@users('user_sales_manager')
def test_lead_convert_corner_cases_crud(self):
""" Test Lead._find_matching_partner() """
# email formatting
other_lead = self.lead_1.copy()
other_lead.write({'partner_id': self.contact_1.id})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'default_lead_id': other_lead.id,
}).create({})
self.assertEqual(convert.lead_id, other_lead)
self.assertEqual(convert.partner_id, self.contact_1)
self.assertEqual(convert.action, 'exist')
convert = self.env['crm.lead2opportunity.partner'].with_context({
'default_lead_id': other_lead.id,
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
}).create({})
self.assertEqual(convert.lead_id, other_lead)
self.assertEqual(convert.partner_id, self.contact_1)
self.assertEqual(convert.action, 'exist')
@users('user_sales_manager')
def test_lead_convert_corner_cases_matching(self):
""" Test Lead._find_matching_partner() """
# email formatting
self.lead_1.write({
'email_from': 'Amy Wong <[email protected]>'
})
customer = self.env['res.partner'].create({
'name': 'Different Name',
'email': 'Wong AMY <[email protected]>'
})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
# TDE FIXME: should take into account normalized email version, not encoded one
# self.assertEqual(convert.partner_id, customer)
@users('user_sales_manager')
def test_lead_convert_internals(self):
""" Test internals of convert wizard """
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
# test internals of convert wizard
self.assertEqual(convert.lead_id, self.lead_1)
self.assertEqual(convert.user_id, self.lead_1.user_id)
self.assertEqual(convert.team_id, self.lead_1.team_id)
self.assertFalse(convert.partner_id)
self.assertEqual(convert.name, 'convert')
self.assertEqual(convert.action, 'create')
convert.write({'user_id': self.user_sales_salesman.id})
self.assertEqual(convert.user_id, self.user_sales_salesman)
self.assertEqual(convert.team_id, self.sales_team_convert)
convert.action_apply()
# convert test
self.assertEqual(self.lead_1.type, 'opportunity')
self.assertEqual(self.lead_1.user_id, self.user_sales_salesman)
self.assertEqual(self.lead_1.team_id, self.sales_team_convert)
# TDE FIXME: stage is linked to the old sales team and is not updated when converting, could be improved
# self.assertEqual(self.lead_1.stage_id, self.stage_gen_1)
# partner creation test
new_partner = self.lead_1.partner_id
self.assertEqual(new_partner.name, 'Amy Wong')
self.assertEqual(new_partner.email, '[email protected]')
@users('user_sales_manager')
def test_lead_convert_action_exist(self):
""" Test specific use case of 'exist' action in conver wizard """
self.lead_1.write({'partner_id': self.contact_1.id})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
self.assertEqual(convert.action, 'exist')
convert.action_apply()
self.assertEqual(self.lead_1.type, 'opportunity')
self.assertEqual(self.lead_1.partner_id, self.contact_1)
@users('user_sales_manager')
def test_lead_convert_action_nothing(self):
""" Test specific use case of 'nothing' action in conver wizard """
self.lead_1.write({'contact_name': False})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
self.assertEqual(convert.action, 'nothing')
convert.action_apply()
self.assertEqual(self.lead_1.type, 'opportunity')
self.assertEqual(self.lead_1.user_id, self.user_sales_leads)
self.assertEqual(self.lead_1.team_id, self.sales_team_1)
self.assertEqual(self.lead_1.stage_id, self.stage_team1_1)
self.assertEqual(self.lead_1.partner_id, self.env['res.partner'])
@users('user_sales_manager')
def test_lead_convert_contact_mutlicompany(self):
""" Check the wizard convert to opp don't find contact
You are not able to see because they belong to another company """
# Use superuser_id because creating a company with a user add directly
# the company in company_ids of the user.
company_2 = self.env['res.company'].with_user(SUPERUSER_ID).create({'name': 'Company 2'})
partner_company_2 = self.env['res.partner'].with_user(SUPERUSER_ID).create({
'name': 'Contact in other company',
'email': '[email protected]',
'company_id': company_2.id,
})
lead = self.env['crm.lead'].create({
'name': 'LEAD',
'type': 'lead',
'email_from': '[email protected]',
})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': lead.id,
'active_ids': lead.ids,
}).create({'name': 'convert', 'action': 'exist'})
self.assertNotEqual(convert.partner_id, partner_company_2,
"Conversion wizard should not be able to find the partner from another company")
@users('user_sales_manager')
def test_lead_convert_same_partner(self):
""" Check that we don't erase lead information
with existing partner info if the partner is already set
"""
partner = self.env['res.partner'].create({
'name': 'Empty partner',
})
lead = self.env['crm.lead'].create({
'name': 'LEAD',
'partner_id': partner.id,
'type': 'lead',
'email_from': '[email protected]',
'street': 'my street',
'city': 'my city',
})
lead.convert_opportunity(partner.id)
self.assertEqual(lead.email_from, '[email protected]', 'Email From should be preserved during conversion')
self.assertEqual(lead.street, 'my street', 'Street should be preserved during conversion')
self.assertEqual(lead.city, 'my city', 'City should be preserved during conversion')
@users('user_sales_manager')
def test_lead_merge(self):
""" Test convert wizard working in merge mode """
date = Datetime.from_string('2020-01-20 16:00:00')
self.crm_lead_dt_mock.now.return_value = date
leads = self.env['crm.lead']
for x in range(2):
leads |= self.env['crm.lead'].create({
'name': 'Dup-%02d-%s' % (x+1, self.lead_1.name),
'type': 'lead', 'user_id': False, 'team_id': self.lead_1.team_id.id,
'contact_name': 'Duplicate %02d of %s' % (x+1, self.lead_1.contact_name),
'email_from': self.lead_1.email_from,
'probability': 10,
})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
# test internals of convert wizard
self.assertEqual(convert.duplicated_lead_ids, self.lead_1 | leads)
self.assertEqual(convert.user_id, self.lead_1.user_id)
self.assertEqual(convert.team_id, self.lead_1.team_id)
self.assertFalse(convert.partner_id)
self.assertEqual(convert.name, 'merge')
self.assertEqual(convert.action, 'create')
convert.write({'user_id': self.user_sales_salesman.id})
self.assertEqual(convert.user_id, self.user_sales_salesman)
self.assertEqual(convert.team_id, self.sales_team_convert)
convert.action_apply()
self.assertEqual(self.lead_1.type, 'opportunity')
@users('user_sales_salesman')
def test_lead_merge_user(self):
""" Test convert wizard working in merge mode with sales user """
date = Datetime.from_string('2020-01-20 16:00:00')
self.crm_lead_dt_mock.now.return_value = date
leads = self.env['crm.lead']
for x in range(2):
leads |= self.env['crm.lead'].create({
'name': 'Dup-%02d-%s' % (x+1, self.lead_1.name),
'type': 'lead', 'user_id': False, 'team_id': self.lead_1.team_id.id,
'contact_name': 'Duplicate %02d of %s' % (x+1, self.lead_1.contact_name),
'email_from': self.lead_1.email_from,
'probability': 10,
})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': leads[0].id,
'active_ids': leads[0].ids,
}).create({})
# test internals of convert wizard
self.assertEqual(convert.duplicated_lead_ids, leads)
self.assertEqual(convert.name, 'merge')
self.assertEqual(convert.action, 'create')
convert.write({'user_id': self.user_sales_salesman.id})
self.assertEqual(convert.user_id, self.user_sales_salesman)
self.assertEqual(convert.team_id, self.sales_team_convert)
convert.action_apply()
self.assertEqual(leads[0].type, 'opportunity')
@users('user_sales_manager')
def test_lead_merge_duplicates(self):
""" Test Lead._get_lead_duplicates() and check: partner / email fallbacks """
customer, dup_leads = self._create_duplicates(self.lead_1)
lead_partner = dup_leads.filtered(lambda lead: lead.name == 'Duplicate: customer ID')
self.assertTrue(bool(lead_partner))
self.lead_1.write({
'partner_id': customer.id,
})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
self.assertEqual(convert.partner_id, customer)
self.assertEqual(convert.duplicated_lead_ids, self.lead_1 | dup_leads)
# Check: partner fallbacks
self.lead_1.write({
'email_from': False,
'partner_id': customer.id,
})
customer.write({'email': False})
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
self.assertEqual(convert.partner_id, customer)
self.assertEqual(convert.duplicated_lead_ids, self.lead_1 | lead_partner)
@users('user_sales_manager')
def test_lead_merge_duplicates_flow(self):
""" Test Lead._get_lead_duplicates() + merge with active_test """
# Check: email formatting
self.lead_1.write({
'email_from': 'Amy Wong <[email protected]>'
})
customer, dup_leads = self._create_duplicates(self.lead_1)
opp_lost = dup_leads.filtered(lambda lead: lead.name == 'Duplicate: lost opportunity')
self.assertTrue(bool(opp_lost))
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': self.lead_1.ids,
}).create({})
self.assertEqual(convert.partner_id, customer)
self.assertEqual(convert.duplicated_lead_ids, self.lead_1 | dup_leads)
convert.action_apply()
self.assertEqual(
(self.lead_1 | dup_leads).exists(),
opp_lost)
@tagged('lead_manage')
class TestLeadConvertBatch(crm_common.TestLeadConvertMassCommon):
def test_initial_data(self):
""" Ensure initial data to avoid spaghetti test update afterwards """
self.assertFalse(self.lead_1.date_conversion)
self.assertEqual(self.lead_1.date_open, Datetime.from_string('2020-01-15 11:30:00'))
self.assertEqual(self.lead_1.user_id, self.user_sales_leads)
self.assertEqual(self.lead_1.team_id, self.sales_team_1)
self.assertEqual(self.lead_1.stage_id, self.stage_team1_1)
self.assertEqual(self.lead_w_partner.stage_id, self.env['crm.stage'])
self.assertEqual(self.lead_w_partner.user_id, self.user_sales_manager)
self.assertEqual(self.lead_w_partner.team_id, self.sales_team_1)
self.assertEqual(self.lead_w_partner_company.stage_id, self.stage_team1_1)
self.assertEqual(self.lead_w_partner_company.user_id, self.user_sales_manager)
self.assertEqual(self.lead_w_partner_company.team_id, self.sales_team_1)
self.assertEqual(self.lead_w_contact.stage_id, self.stage_gen_1)
self.assertEqual(self.lead_w_contact.user_id, self.user_sales_salesman)
self.assertEqual(self.lead_w_contact.team_id, self.sales_team_convert)
self.assertEqual(self.lead_w_email.stage_id, self.stage_gen_1)
self.assertEqual(self.lead_w_email.user_id, self.user_sales_salesman)
self.assertEqual(self.lead_w_email.team_id, self.sales_team_convert)
self.assertEqual(self.lead_w_email_lost.stage_id, self.stage_team1_2)
self.assertEqual(self.lead_w_email_lost.user_id, self.user_sales_leads)
self.assertEqual(self.lead_w_email_lost.team_id, self.sales_team_1)
@users('user_sales_manager')
def test_lead_convert_batch_internals(self):
""" Test internals of convert wizard, working in batch mode """
date = Datetime.from_string('2020-01-20 16:00:00')
self.crm_lead_dt_mock.now.return_value = date
lead_w_partner = self.lead_w_partner
lead_w_contact = self.lead_w_contact
lead_w_email_lost = self.lead_w_email_lost
lead_w_email_lost.action_set_lost()
self.assertEqual(lead_w_email_lost.active, False)
convert = self.env['crm.lead2opportunity.partner'].with_context({
'active_model': 'crm.lead',
'active_id': self.lead_1.id,
'active_ids': (self.lead_1 | lead_w_partner | lead_w_contact | lead_w_email_lost).ids,
}).create({})
# test internals of convert wizard
# self.assertEqual(convert.lead_id, self.lead_1)
self.assertEqual(convert.user_id, self.lead_1.user_id)
self.assertEqual(convert.team_id, self.lead_1.team_id)
self.assertFalse(convert.partner_id)
self.assertEqual(convert.name, 'convert')
self.assertEqual(convert.action, 'create')
convert.action_apply()
self.assertEqual(convert.user_id, self.user_sales_leads)
self.assertEqual(convert.team_id, self.sales_team_1)
# lost leads are not converted (see crm_lead.convert_opportunity())
self.assertFalse(lead_w_email_lost.active)
self.assertFalse(lead_w_email_lost.date_conversion)
self.assertEqual(lead_w_email_lost.partner_id, self.env['res.partner'])
self.assertEqual(lead_w_email_lost.stage_id, self.stage_team1_2) # did not change
# other leads are converted into opportunities
for opp in (self.lead_1 | lead_w_partner | lead_w_contact):
# team management update: opportunity linked to chosen wizard values
self.assertEqual(opp.type, 'opportunity')
self.assertTrue(opp.active)
self.assertEqual(opp.user_id, convert.user_id)
self.assertEqual(opp.team_id, convert.team_id)
# dates update: convert set them to now
self.assertEqual(opp.date_open, date)
self.assertEqual(opp.date_conversion, date)
# stage update (depends on previous value)
if opp == self.lead_1:
self.assertEqual(opp.stage_id, self.stage_team1_1) # did not change
elif opp == lead_w_partner:
self.assertEqual(opp.stage_id, self.stage_team1_1) # is set to default stage of sales_team_1
elif opp == lead_w_contact:
self.assertEqual(opp.stage_id, self.stage_gen_1) # did not change
else:
self.assertFalse(True)
| 45.021127 | 25,572 |
4,356 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.tests import HttpCase
from odoo.tests.common import tagged, users
@tagged('post_install', '-at_install')
class TestUi(HttpCase):
def test_01_crm_tour(self):
self.start_tour("/web", 'crm_tour', login="admin")
def test_02_crm_tour_rainbowman(self):
# we create a new user to make sure he gets the 'Congrats on your first deal!'
# rainbowman message.
self.env['res.users'].create({
'name': 'Temporary CRM User',
'login': 'temp_crm_user',
'password': 'temp_crm_user',
'groups_id': [(6, 0, [
self.ref('base.group_user'),
self.ref('sales_team.group_sale_salesman')
])]
})
self.start_tour("/web", 'crm_rainbowman', login="temp_crm_user")
def test_03_crm_tour_forecast(self):
self.start_tour("/web", 'crm_forecast', login="admin")
def test_email_and_phone_propagation_edit_save(self):
"""Test the propagation of the email / phone on the partner.
If the partner has no email but the lead has one, it should be propagated
if we edit and save the lead form.
"""
self.env['crm.lead'].search([]).unlink()
user_admin = self.env['res.users'].search([('login', '=', 'admin')])
partner = self.env['res.partner'].create({'name': 'Test Partner'})
lead = self.env['crm.lead'].create({
'name': 'Test Lead Propagation',
'type': 'opportunity',
'user_id': user_admin.id,
'partner_id': partner.id,
'email_from': '[email protected]',
'phone': '+32 494 44 44 44',
})
partner.email = False
partner.phone = False
# Check initial state
self.assertFalse(partner.email)
self.assertFalse(partner.phone)
self.assertEqual(lead.email_from, '[email protected]')
self.assertEqual(lead.phone, '+32 494 44 44 44')
self.assertTrue(lead.partner_email_update)
self.assertTrue(lead.partner_phone_update)
self.start_tour('/web', 'crm_email_and_phone_propagation_edit_save', login='admin')
self.assertEqual(lead.email_from, '[email protected]', 'Should not have changed the lead email')
self.assertEqual(lead.phone, '+32 494 44 44 44', 'Should not have changed the lead phone')
self.assertEqual(partner.email, '[email protected]', 'Should have propagated the lead email on the partner')
self.assertEqual(partner.phone, '+32 494 44 44 44', 'Should have propagated the lead phone on the partner')
def test_email_and_phone_propagation_remove_email_and_phone(self):
"""Test the propagation of the email / phone on the partner.
If we remove the email and phone on the lead, it should be removed on the
partner. This test check that we correctly detect field values changes in JS
(aka undefined VS falsy).
"""
self.env['crm.lead'].search([]).unlink()
user_admin = self.env['res.users'].search([('login', '=', 'admin')])
partner = self.env['res.partner'].create({'name': 'Test Partner'})
lead = self.env['crm.lead'].create({
'name': 'Test Lead Propagation',
'type': 'opportunity',
'user_id': user_admin.id,
'partner_id': partner.id,
'email_from': '[email protected]',
'phone': '+32 494 44 44 44',
})
# Check initial state
self.assertEqual(partner.email, '[email protected]')
self.assertEqual(lead.phone, '+32 494 44 44 44')
self.assertEqual(lead.email_from, '[email protected]')
self.assertEqual(lead.phone, '+32 494 44 44 44')
self.assertFalse(lead.partner_email_update)
self.assertFalse(lead.partner_phone_update)
self.start_tour('/web', 'crm_email_and_phone_propagation_remove_email_and_phone', login='admin')
self.assertFalse(lead.email_from, 'Should have removed the email')
self.assertFalse(lead.phone, 'Should have removed the phone')
self.assertFalse(partner.email, 'Should have removed the email')
self.assertFalse(partner.phone, 'Should have removed the phone')
| 42.705882 | 4,356 |
4,963 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from .common import TestCrmCommon
class NewLeadNotification(TestCrmCommon):
def test_new_lead_notification(self):
""" Test newly create leads like from the website. People and channels
subscribed to the Sales Team shoud be notified. """
# subscribe a partner and a channel to the Sales Team with new lead subtype
sales_team_1 = self.env['crm.team'].create({
'name': 'Test Sales Team',
'alias_name': 'test_sales_team',
})
subtype = self.env.ref("crm.mt_salesteam_lead")
sales_team_1.message_subscribe(partner_ids=[self.user_sales_manager.partner_id.id], subtype_ids=[subtype.id])
# Imitate what happens in the controller when somebody creates a new
# lead from the website form
lead = self.env["crm.lead"].with_context(mail_create_nosubscribe=True).sudo().create({
"contact_name": "Somebody",
"description": "Some question",
"email_from": "[email protected]",
"name": "Some subject",
"partner_name": "Some company",
"team_id": sales_team_1.id,
"phone": "+0000000000"
})
# partner and channel should be auto subscribed
self.assertIn(self.user_sales_manager.partner_id, lead.message_partner_ids)
msg = lead.message_ids[0]
self.assertIn(self.user_sales_manager.partner_id, msg.notified_partner_ids)
# The user should have a new unread message
lead_user = lead.with_user(self.user_sales_manager)
self.assertTrue(lead_user.message_needaction)
def test_new_lead_from_email_multicompany(self):
company0 = self.env.company
company1 = self.env['res.company'].create({'name': 'new_company'})
self.env.user.write({
'company_ids': [(4, company0.id, False), (4, company1.id, False)],
})
crm_team_model = self.env['ir.model'].search([('model', '=', 'crm.team')])
crm_lead_model = self.env['ir.model'].search([('model', '=', 'crm.lead')])
self.env["ir.config_parameter"].sudo().set_param("mail.catchall.domain", 'aqualung.com')
crm_team0 = self.env['crm.team'].create({
'name': 'crm team 0',
'company_id': company0.id,
})
crm_team1 = self.env['crm.team'].create({
'name': 'crm team 1',
'company_id': company1.id,
})
mail_alias0 = self.env['mail.alias'].create({
'alias_name': 'sale_team_0',
'alias_model_id': crm_lead_model.id,
'alias_parent_model_id': crm_team_model.id,
'alias_parent_thread_id': crm_team0.id,
'alias_defaults': "{'type': 'opportunity', 'team_id': %s}" % crm_team0.id,
})
mail_alias1 = self.env['mail.alias'].create({
'alias_name': 'sale_team_1',
'alias_model_id': crm_lead_model.id,
'alias_parent_model_id': crm_team_model.id,
'alias_parent_thread_id': crm_team1.id,
'alias_defaults': "{'type': 'opportunity', 'team_id': %s}" % crm_team1.id,
})
crm_team0.write({'alias_id': mail_alias0.id})
crm_team1.write({'alias_id': mail_alias1.id})
new_message0 = """MIME-Version: 1.0
Date: Thu, 27 Dec 2018 16:27:45 +0100
Message-ID: <blablabla0>
Subject: sale team 0 in company 0
From: A client <[email protected]>
To: [email protected]
Content-Type: multipart/alternative; boundary="000000000000a47519057e029630"
--000000000000a47519057e029630
Content-Type: text/plain; charset="UTF-8"
--000000000000a47519057e029630
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
<div>A good message</div>
--000000000000a47519057e029630--
"""
new_message1 = """MIME-Version: 1.0
Date: Thu, 27 Dec 2018 16:27:45 +0100
Message-ID: <blablabla1>
Subject: sale team 1 in company 1
From: B client <[email protected]>
To: [email protected]
Content-Type: multipart/alternative; boundary="000000000000a47519057e029630"
--000000000000a47519057e029630
Content-Type: text/plain; charset="UTF-8"
--000000000000a47519057e029630
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
<div>A good message bis</div>
--000000000000a47519057e029630--
"""
crm_lead0_id = self.env['mail.thread'].message_process('crm.lead', new_message0)
crm_lead1_id = self.env['mail.thread'].message_process('crm.lead', new_message1)
crm_lead0 = self.env['crm.lead'].browse(crm_lead0_id)
crm_lead1 = self.env['crm.lead'].browse(crm_lead1_id)
self.assertEqual(crm_lead0.team_id, crm_team0)
self.assertEqual(crm_lead1.team_id, crm_team1)
self.assertEqual(crm_lead0.company_id, company0)
self.assertEqual(crm_lead1.company_id, company1)
| 37.598485 | 4,963 |
36,320 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from freezegun import freeze_time
from odoo.addons.crm.models.crm_lead import PARTNER_FIELDS_TO_SYNC, PARTNER_ADDRESS_FIELDS_TO_SYNC
from odoo.addons.crm.tests.common import TestCrmCommon, INCOMING_EMAIL
from odoo.addons.phone_validation.tools.phone_validation import phone_format
from odoo.exceptions import UserError
from odoo.tests.common import Form, tagged, users
from odoo.tools import mute_logger
@tagged('lead_internals')
class TestCRMLead(TestCrmCommon):
@classmethod
def setUpClass(cls):
super(TestCRMLead, cls).setUpClass()
cls.country_ref = cls.env.ref('base.be')
cls.test_email = '"Test Email" <[email protected]>'
cls.test_phone = '0485112233'
def assertLeadAddress(self, lead, street, street2, city, lead_zip, state, country):
self.assertEqual(lead.street, street)
self.assertEqual(lead.street2, street2)
self.assertEqual(lead.city, city)
self.assertEqual(lead.zip, lead_zip)
self.assertEqual(lead.state_id, state)
self.assertEqual(lead.country_id, country)
@users('user_sales_leads')
def test_crm_lead_contact_fields_mixed(self):
""" Test mixed configuration from partner: both user input and coming
from partner, in order to ensure we do not loose information or make
it incoherent. """
lead_data = {
'name': 'TestMixed',
'partner_id': self.contact_1.id,
# address
'country_id': self.country_ref.id,
# other contact fields
'function': 'Parmesan Rappeur',
'lang_id': False,
# specific contact fields
'email_from': self.test_email,
'phone': self.test_phone,
}
lead = self.env['crm.lead'].create(lead_data)
# classic
self.assertEqual(lead.name, "TestMixed")
# address
self.assertLeadAddress(lead, False, False, False, False, self.env['res.country.state'], self.country_ref)
# other contact fields
for fname in set(PARTNER_FIELDS_TO_SYNC) - set(['function']):
self.assertEqual(lead[fname], self.contact_1[fname], 'No user input -> take from contact for field %s' % fname)
self.assertEqual(lead.function, 'Parmesan Rappeur', 'User input should take over partner value')
self.assertFalse(lead.lang_id)
# specific contact fields
self.assertEqual(lead.partner_name, self.contact_company_1.name)
self.assertEqual(lead.contact_name, self.contact_1.name)
self.assertEqual(lead.email_from, self.test_email)
self.assertEqual(lead.phone, self.test_phone)
# update a single address fields -> only those are updated
lead.write({'street': 'Super Street', 'city': 'Super City'})
self.assertLeadAddress(lead, 'Super Street', False, 'Super City', False, self.env['res.country.state'], self.country_ref)
# change partner -> whole address updated
lead.write({'partner_id': self.contact_company_1.id})
for fname in PARTNER_ADDRESS_FIELDS_TO_SYNC:
self.assertEqual(lead[fname], self.contact_company_1[fname])
self.assertEqual(self.contact_company_1.lang, self.lang_en.code)
self.assertEqual(lead.lang_id, self.lang_en)
@users('user_sales_leads')
def test_crm_lead_creation_no_partner(self):
lead_data = {
'name': 'Test',
'country_id': self.country_ref.id,
'email_from': self.test_email,
'phone': self.test_phone,
}
lead = self.env['crm.lead'].new(lead_data)
# get the street should not trigger cache miss
lead.street
# Create the lead and the write partner_id = False: country should remain
lead = self.env['crm.lead'].create(lead_data)
self.assertEqual(lead.country_id, self.country_ref, "Country should be set on the lead")
self.assertEqual(lead.email_from, self.test_email)
self.assertEqual(lead.phone, self.test_phone)
lead.partner_id = False
self.assertEqual(lead.country_id, self.country_ref, "Country should still be set on the lead")
self.assertEqual(lead.email_from, self.test_email)
self.assertEqual(lead.phone, self.test_phone)
@users('user_sales_manager')
def test_crm_lead_creation_partner(self):
lead = self.env['crm.lead'].create({
'name': 'TestLead',
'contact_name': 'Raoulette TestContact',
'email_from': '"Raoulette TestContact" <[email protected]>',
})
self.assertEqual(lead.type, 'lead')
self.assertEqual(lead.user_id, self.user_sales_manager)
self.assertEqual(lead.team_id, self.sales_team_1)
self.assertEqual(lead.stage_id, self.stage_team1_1)
self.assertEqual(lead.contact_name, 'Raoulette TestContact')
self.assertEqual(lead.email_from, '"Raoulette TestContact" <[email protected]>')
# update to a partner, should udpate address
lead.write({'partner_id': self.contact_1.id})
self.assertEqual(lead.partner_name, self.contact_company_1.name)
self.assertEqual(lead.contact_name, self.contact_1.name)
self.assertEqual(lead.email_from, self.contact_1.email)
self.assertEqual(lead.street, self.contact_1.street)
self.assertEqual(lead.city, self.contact_1.city)
self.assertEqual(lead.zip, self.contact_1.zip)
self.assertEqual(lead.country_id, self.contact_1.country_id)
@users('user_sales_manager')
def test_crm_lead_creation_partner_address(self):
""" Test that an address erases all lead address fields (avoid mixed addresses) """
other_country = self.env.ref('base.fr')
empty_partner = self.env['res.partner'].create({
'name': 'Empty partner',
'country_id': other_country.id,
})
lead_data = {
'name': 'Test',
'street': 'My street',
'street2': 'My street',
'city': 'My city',
'zip': '[email protected]',
'state_id': self.env['res.country.state'].create({
'name': 'My state',
'country_id': self.country_ref.id,
'code': 'MST',
}).id,
'country_id': self.country_ref.id,
}
lead = self.env['crm.lead'].create(lead_data)
lead.partner_id = empty_partner
# PARTNER_ADDRESS_FIELDS_TO_SYNC
self.assertEqual(lead.street, empty_partner.street, "Street should be sync from the Partner")
self.assertEqual(lead.street2, empty_partner.street2, "Street 2 should be sync from the Partner")
self.assertEqual(lead.city, empty_partner.city, "City should be sync from the Partner")
self.assertEqual(lead.zip, empty_partner.zip, "Zip should be sync from the Partner")
self.assertEqual(lead.state_id, empty_partner.state_id, "State should be sync from the Partner")
self.assertEqual(lead.country_id, empty_partner.country_id, "Country should be sync from the Partner")
@users('user_sales_manager')
def test_crm_lead_creation_partner_company(self):
""" Test lead / partner synchronization involving company details """
# Test that partner_name (company name) is the partner name if partner is company
lead = self.env['crm.lead'].create({
'name': 'TestLead',
'partner_id': self.contact_company.id,
})
self.assertEqual(lead.contact_name, False,
"Lead contact name should be Falsy when dealing with companies")
self.assertEqual(lead.partner_name, self.contact_company.name,
"Lead company name should be set to partner name if partner is a company")
# Test that partner_name (company name) is the partner company name if partner is an individual
self.contact_company.write({'is_company': False})
lead = self.env['crm.lead'].create({
'name': 'TestLead',
'partner_id': self.contact_company.id,
})
self.assertEqual(lead.contact_name, self.contact_company.name,
"Lead contact name should be set to partner name if partner is not a company")
self.assertEqual(lead.partner_name, self.contact_company.company_name,
"Lead company name should be set to company name if partner is not a company")
@users('user_sales_manager')
def test_crm_lead_creation_partner_no_address(self):
""" Test that an empty address on partner does not void its lead values """
empty_partner = self.env['res.partner'].create({
'name': 'Empty partner',
'is_company': True,
'mobile': '123456789',
'title': self.env.ref('base.res_partner_title_mister').id,
'function': 'My function',
})
lead_data = {
'name': 'Test',
'contact_name': 'Test',
'street': 'My street',
'country_id': self.country_ref.id,
'email_from': self.test_email,
'phone': self.test_phone,
'mobile': '987654321',
'website': 'http://mywebsite.org',
}
lead = self.env['crm.lead'].create(lead_data)
lead.partner_id = empty_partner
# SPECIFIC FIELDS
self.assertEqual(lead.contact_name, lead_data['contact_name'], "Contact should remain")
self.assertEqual(lead.email_from, lead_data['email_from'], "Email From should keep its initial value")
self.assertEqual(lead.partner_name, empty_partner.name, "Partner name should be set as contact is a company")
# PARTNER_ADDRESS_FIELDS_TO_SYNC
self.assertEqual(lead.street, lead_data['street'], "Street should remain since partner has no address field set")
self.assertEqual(lead.street2, False, "Street2 should remain since partner has no address field set")
self.assertEqual(lead.country_id, self.country_ref, "Country should remain since partner has no address field set")
self.assertEqual(lead.city, False, "City should remain since partner has no address field set")
self.assertEqual(lead.zip, False, "Zip should remain since partner has no address field set")
self.assertEqual(lead.state_id, self.env['res.country.state'], "State should remain since partner has no address field set")
# PARTNER_FIELDS_TO_SYNC
self.assertEqual(lead.phone, lead_data['phone'], "Phone should keep its initial value")
self.assertEqual(lead.mobile, empty_partner.mobile, "Mobile from partner should be set on the lead")
self.assertEqual(lead.title, empty_partner.title, "Title from partner should be set on the lead")
self.assertEqual(lead.function, empty_partner.function, "Function from partner should be set on the lead")
self.assertEqual(lead.website, lead_data['website'], "Website should keep its initial value")
@users('user_sales_manager')
def test_crm_lead_create_pipe_data(self):
""" Test creation pipe data: user, team, stage, depending on some default
configuration. """
# gateway-like creation: no user, no team, generic stage
lead = self.env['crm.lead'].with_context(default_user_id=False).create({
'name': 'Test',
'contact_name': 'Test Contact',
'email_from': self.test_email,
'phone': self.test_phone,
})
self.assertEqual(lead.user_id, self.env['res.users'])
self.assertEqual(lead.team_id, self.env['crm.team'])
self.assertEqual(lead.stage_id, self.stage_gen_1)
# pipe creation: current user's best team and default stage
lead = self.env['crm.lead'].create({
'name': 'Test',
'contact_name': 'Test Contact',
'email_from': self.test_email,
'phone': self.test_phone,
})
self.assertEqual(lead.user_id, self.user_sales_manager)
self.assertEqual(lead.team_id, self.sales_team_1)
self.assertEqual(lead.stage_id, self.stage_team1_1)
@users('user_sales_manager')
def test_crm_lead_currency_sync(self):
lead = self.env['crm.lead'].create({
'name': 'Lead 1',
'company_id': self.company_main.id
})
self.assertEqual(lead.company_currency, self.env.ref('base.EUR'))
self.company_main.currency_id = self.env.ref('base.CHF')
lead.with_company(self.company_main).update({'company_id': False})
self.assertEqual(lead.company_currency, self.env.ref('base.CHF'))
#set back original currency
self.company_main.currency_id = self.env.ref('base.EUR')
@users('user_sales_manager')
def test_crm_lead_date_closed(self):
# Test for one won lead
stage_team1_won2 = self.env['crm.stage'].create({
'name': 'Won2',
'sequence': 75,
'team_id': self.sales_team_1.id,
'is_won': True,
})
won_lead = self.lead_team_1_won.with_env(self.env)
other_lead = self.lead_1.with_env(self.env)
old_date_closed = won_lead.date_closed
self.assertTrue(won_lead.date_closed)
self.assertFalse(other_lead.date_closed)
# multi update
leads = won_lead + other_lead
with freeze_time('2020-02-02 18:00'):
leads.stage_id = stage_team1_won2
self.assertEqual(won_lead.date_closed, old_date_closed, 'Should not change date')
self.assertEqual(other_lead.date_closed, datetime(2020, 2, 2, 18, 0, 0))
# back to open stage
leads.write({'stage_id': self.stage_team1_2.id})
self.assertFalse(won_lead.date_closed)
self.assertFalse(other_lead.date_closed)
# close with lost
with freeze_time('2020-02-02 18:00'):
leads.action_set_lost()
self.assertEqual(won_lead.date_closed, datetime(2020, 2, 2, 18, 0, 0))
self.assertEqual(other_lead.date_closed, datetime(2020, 2, 2, 18, 0, 0))
@users('user_sales_leads')
@freeze_time("2012-01-14")
def test_crm_lead_lost_date_closed(self):
lead = self.lead_1.with_env(self.env)
self.assertFalse(lead.date_closed, "Initially, closed date is not set")
# Mark the lead as lost
lead.action_set_lost()
self.assertEqual(lead.date_closed, datetime.now(), "Closed date is updated after marking lead as lost")
@users('user_sales_manager')
def test_crm_lead_partner_sync(self):
lead, partner = self.lead_1.with_user(self.env.user), self.contact_2
partner_email, partner_phone = self.contact_2.email, self.contact_2.phone
lead.partner_id = partner
# email & phone must be automatically set on the lead
lead.partner_id = partner
self.assertEqual(lead.email_from, partner_email)
self.assertEqual(lead.phone, partner_phone)
# writing on the lead field must change the partner field
lead.email_from = '"John Zoidberg" <[email protected]>'
lead.phone = '+1 202 555 7799'
self.assertEqual(partner.email, '"John Zoidberg" <[email protected]>')
self.assertEqual(partner.email_normalized, '[email protected]')
self.assertEqual(partner.phone, '+1 202 555 7799')
# writing on the partner must change the lead values
partner.email = partner_email
partner.phone = '+1 202 555 6666'
self.assertEqual(lead.email_from, partner_email)
self.assertEqual(lead.phone, '+1 202 555 6666')
# resetting lead values also resets partner
lead.email_from, lead.phone = False, False
self.assertFalse(partner.email)
self.assertFalse(partner.email_normalized)
self.assertFalse(partner.phone)
@users('user_sales_manager')
def test_crm_lead_partner_sync_email_phone(self):
""" Specifically test synchronize between a lead and its partner about
phone and email fields. Phone especially has some corner cases due to
automatic formatting (notably with onchange in form view). """
lead, partner = self.lead_1.with_user(self.env.user), self.contact_2
lead_form = Form(lead)
# reset partner phone to a local number and prepare formatted / sanitized values
partner_phone, partner_mobile = self.test_phone_data[2], self.test_phone_data[1]
partner_phone_formatted = phone_format(partner_phone, 'US', '1')
partner_phone_sanitized = phone_format(partner_phone, 'US', '1', force_format='E164')
partner_mobile_formatted = phone_format(partner_mobile, 'US', '1')
partner_mobile_sanitized = phone_format(partner_mobile, 'US', '1', force_format='E164')
partner_email, partner_email_normalized = self.test_email_data[2], self.test_email_data_normalized[2]
self.assertEqual(partner_phone_formatted, '+1 202-555-0888')
self.assertEqual(partner_phone_sanitized, self.test_phone_data_sanitized[2])
self.assertEqual(partner_mobile_formatted, '+1 202-555-0999')
self.assertEqual(partner_mobile_sanitized, self.test_phone_data_sanitized[1])
# ensure initial data
self.assertEqual(partner.phone, partner_phone)
self.assertEqual(partner.mobile, partner_mobile)
self.assertEqual(partner.email, partner_email)
# LEAD/PARTNER SYNC: email and phone are propagated to lead
# as well as mobile (who does not trigger the reverse sync)
lead_form.partner_id = partner
self.assertEqual(lead_form.email_from, partner_email)
self.assertEqual(lead_form.phone, partner_phone_formatted,
'Lead: form automatically formats numbers')
self.assertEqual(lead_form.mobile, partner_mobile_formatted,
'Lead: form automatically formats numbers')
self.assertFalse(lead_form.partner_email_update)
self.assertFalse(lead_form.partner_phone_update)
lead_form.save()
self.assertEqual(partner.phone, partner_phone,
'Lead / Partner: partner values sent to lead')
self.assertEqual(lead.email_from, partner_email,
'Lead / Partner: partner values sent to lead')
self.assertEqual(lead.email_normalized, partner_email_normalized,
'Lead / Partner: equal emails should lead to equal normalized emails')
self.assertEqual(lead.phone, partner_phone_formatted,
'Lead / Partner: partner values (formatted) sent to lead')
self.assertEqual(lead.mobile, partner_mobile_formatted,
'Lead / Partner: partner values (formatted) sent to lead')
self.assertEqual(lead.phone_sanitized, partner_mobile_sanitized,
'Lead: phone_sanitized computed field on mobile')
# for email_from, if only formatting differs, warning should not appear and
# email on partner should not be updated
lead_form.email_from = '"Hermes Conrad" <%s>' % partner_email_normalized
self.assertFalse(lead_form.partner_email_update)
lead_form.save()
self.assertEqual(partner.email, partner_email)
# for phone, if only formatting differs, warning should not appear and
# phone on partner should not be updated
lead_form.phone = partner_phone_sanitized
self.assertFalse(lead_form.partner_phone_update)
lead_form.save()
self.assertEqual(partner.phone, partner_phone)
# LEAD/PARTNER SYNC: lead updates partner
new_email = '"John Zoidberg" <[email protected]>'
new_email_normalized = '[email protected]'
lead_form.email_from = new_email
self.assertTrue(lead_form.partner_email_update)
new_phone = '+1 202 555 7799'
new_phone_formatted = phone_format(new_phone, 'US', '1')
lead_form.phone = new_phone
self.assertEqual(lead_form.phone, new_phone_formatted)
self.assertTrue(lead_form.partner_email_update)
self.assertTrue(lead_form.partner_phone_update)
lead_form.save()
self.assertEqual(partner.email, new_email)
self.assertEqual(partner.email_normalized, new_email_normalized)
self.assertEqual(partner.phone, new_phone_formatted)
# LEAD/PARTNER SYNC: mobile does not update partner
new_mobile = '+1 202 555 6543'
new_mobile_formatted = phone_format(new_mobile, 'US', '1')
lead_form.mobile = new_mobile
lead_form.save()
self.assertEqual(lead.mobile, new_mobile_formatted)
self.assertEqual(partner.mobile, partner_mobile)
# LEAD/PARTNER SYNC: reseting lead values also resets partner for email
# and phone, but not for mobile
lead_form.email_from, lead_form.phone, lead.mobile = False, False, False
self.assertTrue(lead_form.partner_email_update)
self.assertTrue(lead_form.partner_phone_update)
lead_form.save()
self.assertFalse(partner.email)
self.assertFalse(partner.email_normalized)
self.assertFalse(partner.phone)
self.assertFalse(lead.phone)
self.assertFalse(lead.mobile)
self.assertFalse(lead.phone_sanitized)
self.assertEqual(partner.mobile, partner_mobile)
# if SMS is uninstalled, phone_sanitized is not available on partner
if 'phone_sanitized' in partner:
self.assertEqual(partner.phone_sanitized, partner_mobile_sanitized,
'Partner sanitized should be computed on mobile')
@users('user_sales_manager')
def test_crm_lead_partner_sync_email_phone_corner_cases(self):
""" Test corner cases of email and phone sync (False versus '', formatting
differences, wrong input, ...) """
test_email = '[email protected]'
lead = self.lead_1.with_user(self.env.user)
contact = self.env['res.partner'].create({
'name': 'NoContact Partner',
'phone': '',
'email': '',
'mobile': '',
})
lead_form = Form(lead)
self.assertEqual(lead_form.email_from, test_email)
self.assertFalse(lead_form.partner_email_update)
self.assertFalse(lead_form.partner_phone_update)
# email: False versus empty string
lead_form.partner_id = contact
self.assertTrue(lead_form.partner_email_update)
self.assertFalse(lead_form.partner_phone_update)
lead_form.email_from = ''
self.assertFalse(lead_form.partner_email_update)
lead_form.email_from = False
self.assertFalse(lead_form.partner_email_update)
# phone: False versus empty string
lead_form.phone = '+1 202-555-0888'
self.assertFalse(lead_form.partner_email_update)
self.assertTrue(lead_form.partner_phone_update)
lead_form.phone = ''
self.assertFalse(lead_form.partner_phone_update)
lead_form.phone = False
self.assertFalse(lead_form.partner_phone_update)
# email/phone: formatting should not trigger ribbon
lead.write({
'email_from': '"My Name" <%s>' % test_email,
'phone': '+1 202-555-0888',
})
contact.write({
'email': '"My Name" <%s>' % test_email,
'phone': '+1 202-555-0888',
})
lead_form = Form(lead)
self.assertFalse(lead_form.partner_email_update)
self.assertFalse(lead_form.partner_phone_update)
lead_form.partner_id = contact
self.assertFalse(lead_form.partner_email_update)
self.assertFalse(lead_form.partner_phone_update)
lead_form.email_from = '"Another Name" <%s>' % test_email # same email normalized
self.assertFalse(lead_form.partner_email_update, 'Formatting-only change should not trigger write')
self.assertFalse(lead_form.partner_phone_update, 'Formatting-only change should not trigger write')
lead_form.phone = '2025550888' # same number but another format
self.assertFalse(lead_form.partner_email_update, 'Formatting-only change should not trigger write')
self.assertFalse(lead_form.partner_phone_update, 'Formatting-only change should not trigger write')
# wrong value are also propagated
lead_form.phone = '666 789456789456789456'
self.assertTrue(lead_form.partner_phone_update)
# test country propagation allowing to correctly compute sanitized numbers
# by adding missing relevant information from contact
be_country = self.env.ref('base.be')
contact.write({
'country_id': be_country.id,
'phone': '+32456001122',
})
lead.write({'country_id': False})
lead_form = Form(lead)
lead_form.partner_id = contact
lead_form.phone = '0456 00 11 22'
self.assertFalse(lead_form.partner_phone_update)
self.assertEqual(lead_form.country_id, be_country)
@users('user_sales_manager')
def test_crm_lead_stages(self):
lead = self.lead_1.with_user(self.env.user)
self.assertEqual(lead.team_id, self.sales_team_1)
lead.convert_opportunity(self.contact_1.id)
self.assertEqual(lead.team_id, self.sales_team_1)
lead.action_set_won()
self.assertEqual(lead.probability, 100.0)
self.assertEqual(lead.stage_id, self.stage_gen_won) # generic won stage has lower sequence than team won stage
@users('user_sales_manager')
def test_crm_lead_unlink_calendar_event(self):
""" Test res_id / res_model is reset (and hide document button in calendar
event form view) when lead is unlinked """
lead = self.env['crm.lead'].create({'name': 'Lead With Meetings'})
meetings = self.env['calendar.event'].create([
{
'name': 'Meeting 1 of Lead',
'res_id': lead.id,
'res_model_id': self.env['ir.model']._get_id(lead._name),
'start': '2022-07-12 08:00:00',
'stop': '2022-07-12 10:00:00',
}, {
'name': 'Meeting 2 of Lead',
'opportunity_id': lead.id,
'res_id': lead.id,
'res_model_id': self.env['ir.model']._get_id(lead._name),
'start': '2022-07-13 08:00:00',
'stop': '2022-07-13 10:00:00',
}
])
self.assertEqual(lead.calendar_event_count, 1)
self.assertEqual(meetings.opportunity_id, lead)
self.assertEqual(meetings.mapped('res_id'), [lead.id, lead.id])
self.assertEqual(meetings.mapped('res_model'), ['crm.lead', 'crm.lead'])
lead.unlink()
self.assertEqual(meetings.exists(), meetings)
self.assertFalse(meetings.opportunity_id)
self.assertEqual(set(meetings.mapped('res_id')), set([0]))
self.assertEqual(set(meetings.mapped('res_model')), set([False]))
@users('user_sales_leads')
def test_crm_lead_update_contact(self):
# ensure initial data, especially for corner cases
self.assertFalse(self.contact_company_1.phone)
self.assertEqual(self.contact_company_1.country_id.code, "US")
lead = self.env['crm.lead'].create({
'name': 'Test',
'country_id': self.country_ref.id,
'email_from': self.test_email,
'phone': self.test_phone,
})
self.assertEqual(lead.country_id, self.country_ref, "Country should be set on the lead")
lead.partner_id = False
self.assertEqual(lead.country_id, self.country_ref, "Country should still be set on the lead")
self.assertEqual(lead.email_from, self.test_email)
self.assertEqual(lead.phone, self.test_phone)
self.assertEqual(lead.email_state, 'correct')
self.assertEqual(lead.phone_state, 'correct')
lead.partner_id = self.contact_company_1
self.assertEqual(lead.country_id, self.contact_company_1.country_id, "Country should still be the one set on partner")
self.assertEqual(lead.email_from, self.contact_company_1.email)
self.assertEqual(lead.phone, self.test_phone)
self.assertEqual(lead.email_state, 'correct')
# currently we keep phone as partner as a void one -> may lead to inconsistencies
self.assertEqual(lead.phone_state, 'incorrect', "Belgian phone with US country -> considered as incorrect")
lead.email_from = 'broken'
lead.phone = 'alsobroken'
self.assertEqual(lead.email_state, 'incorrect')
self.assertEqual(lead.phone_state, 'incorrect')
self.assertEqual(self.contact_company_1.email, 'broken')
self.assertEqual(self.contact_company_1.phone, 'alsobroken')
@users('user_sales_manager')
def test_crm_team_alias(self):
new_team = self.env['crm.team'].create({
'name': 'TestAlias',
'use_leads': True,
'use_opportunities': True,
'alias_name': 'test.alias'
})
self.assertEqual(new_team.alias_id.alias_name, 'test.alias')
self.assertEqual(new_team.alias_name, 'test.alias')
new_team.write({
'use_leads': False,
'use_opportunities': False,
})
# self.assertFalse(new_team.alias_id.alias_name)
# self.assertFalse(new_team.alias_name)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_mailgateway(self):
new_lead = self.format_and_process(
INCOMING_EMAIL,
'[email protected]',
'%s@%s' % (self.sales_team_1.alias_name, self.alias_domain),
subject='Delivery cost inquiry',
target_model='crm.lead',
)
self.assertEqual(new_lead.email_from, '[email protected]')
self.assertFalse(new_lead.partner_id)
self.assertEqual(new_lead.name, 'Delivery cost inquiry')
message = new_lead.with_user(self.user_sales_manager).message_post(
body='Here is my offer !',
subtype_xmlid='mail.mt_comment')
self.assertEqual(message.author_id, self.user_sales_manager.partner_id)
new_lead._handle_partner_assignment(create_missing=True)
self.assertEqual(new_lead.partner_id.email, '[email protected]')
self.assertEqual(new_lead.partner_id.team_id, self.sales_team_1)
@users('user_sales_manager')
def test_phone_mobile_search(self):
lead_1 = self.env['crm.lead'].create({
'name': 'Lead 1',
'country_id': self.env.ref('base.be').id,
'phone': '+32485001122',
})
lead_2 = self.env['crm.lead'].create({
'name': 'Lead 2',
'country_id': self.env.ref('base.be').id,
'phone': '0032485001122',
})
lead_3 = self.env['crm.lead'].create({
'name': 'Lead 3',
'country_id': self.env.ref('base.be').id,
'phone': 'hello',
})
lead_4 = self.env['crm.lead'].create({
'name': 'Lead 3',
'country_id': self.env.ref('base.be').id,
'phone': '+32485112233',
})
# search term containing less than 3 characters should throw an error (some currently not working)
with self.assertRaises(UserError):
self.env['crm.lead'].search([('phone_mobile_search', 'like', '')])
# with self.assertRaises(UserError):
# self.env['crm.lead'].search([('phone_mobile_search', 'like', '7 ')])
with self.assertRaises(UserError):
self.env['crm.lead'].search([('phone_mobile_search', 'like', 'c')])
with self.assertRaises(UserError):
self.env['crm.lead'].search([('phone_mobile_search', 'like', '+')])
with self.assertRaises(UserError):
self.env['crm.lead'].search([('phone_mobile_search', 'like', '5')])
with self.assertRaises(UserError):
self.env['crm.lead'].search([('phone_mobile_search', 'like', '42')])
# + / 00 prefixes do not block search
self.assertEqual(lead_1 + lead_2, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '+32485001122')
]))
self.assertEqual(lead_1 + lead_2, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '0032485001122')
]))
self.assertEqual(lead_1 + lead_2, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '485001122')
]))
self.assertEqual(lead_1 + lead_2 + lead_4, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '1122')
]))
# textual input still possible
self.assertEqual(
self.env['crm.lead'].search([('phone_mobile_search', 'like', 'hello')]),
lead_3,
'Should behave like a text field'
)
self.assertFalse(
self.env['crm.lead'].search([('phone_mobile_search', 'like', 'Hello')]),
'Should behave like a text field (case sensitive)'
)
self.assertEqual(
self.env['crm.lead'].search([('phone_mobile_search', 'ilike', 'Hello')]),
lead_3,
'Should behave like a text field (case insensitive)'
)
self.assertEqual(
self.env['crm.lead'].search([('phone_mobile_search', 'like', 'hello123')]),
self.env['crm.lead'],
'Should behave like a text field'
)
@users('user_sales_manager')
def test_phone_mobile_search_format(self):
numbers = [
# standard
'0499223311',
# separators
'0499/223311', '0499/22.33.11', '0499/22 33 11', '0499/223 311',
# international format -> currently not working
# '+32499223311', '0032499223311',
]
leads = self.env['crm.lead'].create([
{'name': 'Lead %s' % index,
'country_id': self.env.ref('base.be').id,
'phone': number,
}
for index, number in enumerate(numbers)
])
self.assertEqual(leads, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '0499223311')
]))
self.assertEqual(leads, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '0499/223311')
]))
self.assertEqual(leads, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '0499/22.33.11')
]))
self.assertEqual(leads, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '0499/22 33 11')
]))
self.assertEqual(leads, self.env['crm.lead'].search([
('phone_mobile_search', 'like', '0499/223 311')
]))
@users('user_sales_manager')
def test_phone_mobile_update(self):
lead = self.env['crm.lead'].create({
'name': 'Lead 1',
'country_id': self.env.ref('base.us').id,
'phone': self.test_phone_data[0],
})
self.assertEqual(lead.phone, self.test_phone_data[0])
self.assertFalse(lead.mobile)
self.assertEqual(lead.phone_sanitized, self.test_phone_data_sanitized[0])
lead.write({'phone': False, 'mobile': self.test_phone_data[1]})
self.assertFalse(lead.phone)
self.assertEqual(lead.mobile, self.test_phone_data[1])
self.assertEqual(lead.phone_sanitized, self.test_phone_data_sanitized[1])
lead.write({'phone': self.test_phone_data[1], 'mobile': self.test_phone_data[2]})
self.assertEqual(lead.phone, self.test_phone_data[1])
self.assertEqual(lead.mobile, self.test_phone_data[2])
self.assertEqual(lead.phone_sanitized, self.test_phone_data_sanitized[2])
# updating country should trigger sanitize computation
lead.write({'country_id': self.env.ref('base.be').id})
self.assertEqual(lead.phone, self.test_phone_data[1])
self.assertEqual(lead.mobile, self.test_phone_data[2])
self.assertFalse(lead.phone_sanitized)
| 47.789474 | 36,320 |
28,791 |
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 contextlib import contextmanager
from unittest.mock import patch
from odoo.addons.crm.models.crm_lead import CRM_LEAD_FIELDS_TO_MERGE
from odoo.addons.mail.tests.common import MailCase, mail_new_test_user
from odoo.addons.phone_validation.tools import phone_validation
from odoo.addons.sales_team.tests.common import TestSalesCommon
from odoo.fields import Datetime
from odoo import models, tools
INCOMING_EMAIL = """Return-Path: {return_path}
X-Original-To: {to}
Delivered-To: {to}
Received: by mail.my.com (Postfix, from userid xxx)
id 822ECBFB67; Mon, 24 Oct 2011 07:36:51 +0200 (CEST)
X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on mail.my.com
X-Spam-Level:
X-Spam-Status: No, score=-1.0 required=5.0 tests=ALL_TRUSTED autolearn=ham
version=3.3.1
Received: from [192.168.1.146]
(Authenticated sender: {email_from})
by mail.customer.com (Postfix) with ESMTPSA id 07A30BFAB4
for <{to}>; Mon, 24 Oct 2011 07:36:50 +0200 (CEST)
Message-ID: {msg_id}
Date: Mon, 24 Oct 2011 11:06:29 +0530
From: {email_from}
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.14) Gecko/20110223 Lightning/1.0b2 Thunderbird/3.1.8
MIME-Version: 1.0
To: {to}
Subject: {subject}
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
This is an example email. All sensitive content has been stripped out.
ALL GLORY TO THE HYPNOTOAD !
Cheers,
Somebody."""
class TestCrmCommon(TestSalesCommon, MailCase):
FIELDS_FIRST_SET = [
'name', 'partner_id', 'campaign_id', 'company_id', 'country_id',
'team_id', 'state_id', 'stage_id', 'medium_id', 'source_id', 'user_id',
'title', 'city', 'contact_name', 'mobile', 'partner_name',
'phone', 'probability', 'expected_revenue', 'street', 'street2', 'zip',
'create_date', 'date_action_last', 'email_from', 'email_cc', 'website'
]
merge_fields = ['description', 'type', 'priority']
@classmethod
def setUpClass(cls):
super(TestCrmCommon, cls).setUpClass()
cls._init_mail_gateway()
# Salesmen organization
# ------------------------------------------------------------
# Role: M (team member) R (team manager)
# SALESMAN---------------sales_team_1
# admin------------------M-----------
# user_sales_manager-----R-----------
# user_sales_leads-------M-----------
# user_sales_salesman----/-----------
# Sales teams organization
# ------------------------------------------------------------
# SALESTEAM-----------SEQU-----COMPANY
# sales_team_1--------5--------False
# data----------------9999-----??
cls.sales_team_1.write({
'alias_name': 'sales.test',
'use_leads': True,
'use_opportunities': True,
'assignment_domain': False,
})
cls.sales_team_1_m1.write({
'assignment_max': 45,
'assignment_domain': False,
})
cls.sales_team_1_m2.write({
'assignment_max': 15,
'assignment_domain': False,
})
(cls.user_sales_manager + cls.user_sales_leads + cls.user_sales_salesman).write({
'groups_id': [(4, cls.env.ref('crm.group_use_lead').id)]
})
cls.env['crm.stage'].search([]).write({'sequence': 9999}) # ensure search will find test data first
cls.stage_team1_1 = cls.env['crm.stage'].create({
'name': 'New',
'sequence': 1,
'team_id': cls.sales_team_1.id,
})
cls.stage_team1_2 = cls.env['crm.stage'].create({
'name': 'Proposition',
'sequence': 5,
'team_id': cls.sales_team_1.id,
})
cls.stage_team1_won = cls.env['crm.stage'].create({
'name': 'Won',
'sequence': 70,
'team_id': cls.sales_team_1.id,
'is_won': True,
})
cls.stage_gen_1 = cls.env['crm.stage'].create({
'name': 'Generic stage',
'sequence': 3,
'team_id': False,
})
cls.stage_gen_won = cls.env['crm.stage'].create({
'name': 'Generic Won',
'sequence': 30,
'team_id': False,
'is_won': True,
})
# countries and langs
base_us = cls.env.ref('base.us')
cls.lang_en = cls.env['res.lang']._lang_get('en_US')
# leads
cls.lead_1 = cls.env['crm.lead'].create({
'name': 'Nibbler Spacecraft Request',
'type': 'lead',
'user_id': cls.user_sales_leads.id,
'team_id': cls.sales_team_1.id,
'partner_id': False,
'contact_name': 'Amy Wong',
'email_from': '[email protected]',
'country_id': cls.env.ref('base.us').id,
'probability': 20,
})
# update lead_1: stage_id is not computed anymore by default for leads
cls.lead_1.write({
'stage_id': cls.stage_team1_1.id,
})
# create an history for new team
cls.lead_team_1_won = cls.env['crm.lead'].create({
'name': 'Already Won',
'type': 'lead',
'user_id': cls.user_sales_leads.id,
'team_id': cls.sales_team_1.id,
})
cls.lead_team_1_won.action_set_won()
cls.lead_team_1_lost = cls.env['crm.lead'].create({
'name': 'Already Won',
'type': 'lead',
'user_id': cls.user_sales_leads.id,
'team_id': cls.sales_team_1.id,
})
cls.lead_team_1_lost.action_set_lost()
(cls.lead_team_1_won + cls.lead_team_1_lost).flush()
# email / phone data
cls.test_email_data = [
'"Planet Express" <[email protected]>',
'"Philip, J. Fry" <[email protected]>',
'"Turanga Leela" <[email protected]>',
]
cls.test_email_data_normalized = [
'[email protected]',
'[email protected]',
'[email protected]',
]
cls.test_phone_data = [
'+1 202 555 0122', # formatted US number
'202 555 0999', # local US number
'202 555 0888', # local US number
]
cls.test_phone_data_sanitized = [
'+12025550122',
'+12025550999',
'+12025550888',
]
# create some test contact and companies
cls.contact_company_1 = cls.env['res.partner'].create({
'name': 'Planet Express',
'email': cls.test_email_data[0],
'is_company': True,
'street': '57th Street',
'city': 'New New York',
'country_id': cls.env.ref('base.us').id,
'zip': '12345',
})
cls.contact_1 = cls.env['res.partner'].create({
'name': 'Philip J Fry',
'email': cls.test_email_data[1],
'mobile': cls.test_phone_data[0],
'title': cls.env.ref('base.res_partner_title_mister').id,
'function': 'Delivery Boy',
'phone': False,
'parent_id': cls.contact_company_1.id,
'is_company': False,
'street': 'Actually the sewers',
'city': 'New York',
'country_id': cls.env.ref('base.us').id,
'zip': '54321',
})
cls.contact_2 = cls.env['res.partner'].create({
'name': 'Turanga Leela',
'email': cls.test_email_data[2],
'mobile': cls.test_phone_data[1],
'phone': cls.test_phone_data[2],
'parent_id': False,
'is_company': False,
'street': 'Cookieville Minimum-Security Orphanarium',
'city': 'New New York',
'country_id': cls.env.ref('base.us').id,
'zip': '97648',
})
cls.contact_company = cls.env['res.partner'].create({
'name': 'Mom',
'company_name': 'MomCorp',
'is_company': True,
'street': 'Mom Friendly Robot Street',
'city': 'New new York',
'country_id': base_us.id,
'mobile': '+1 202 555 0888',
'zip': '87654',
})
# test activities
cls.activity_type_1 = cls.env['mail.activity.type'].create({
'name': 'Lead Test Activity 1',
'summary': 'ACT 1 : Presentation, barbecue, ... ',
'res_model': 'crm.lead',
'category': 'meeting',
'delay_count': 5,
})
cls.env['ir.model.data'].create({
'name': cls.activity_type_1.name.lower().replace(' ', '_'),
'module': 'crm',
'model': cls.activity_type_1._name,
'res_id': cls.activity_type_1.id,
})
@classmethod
def _activate_multi_company(cls):
cls.company_2 = cls.env['res.company'].create({
'country_id': cls.env.ref('base.au').id,
'currency_id': cls.env.ref('base.AUD').id,
'email': '[email protected]',
'name': 'New Test Company',
})
cls.user_sales_manager_mc = mail_new_test_user(
cls.env,
company_id=cls.company_2.id,
company_ids=[(4, cls.company_main.id), (4, cls.company_2.id)],
email='[email protected]',
login='user_sales_manager_mc',
groups='sales_team.group_sale_manager,base.group_partner_manager',
name='Myrddin Sales Manager',
notification_type='inbox',
)
cls.team_company2 = cls.env['crm.team'].create({
'company_id': cls.company_2.id,
'name': 'C2 Team',
'sequence': 10,
'user_id': False,
})
cls.team_company2_m1 = cls.env['crm.team.member'].create({
'crm_team_id': cls.team_company2.id,
'user_id': cls.user_sales_manager_mc.id,
'assignment_max': 30,
'assignment_domain': False,
})
cls.team_company1 = cls.env['crm.team'].create({
'company_id': cls.company_main.id,
'name': 'MainCompany Team',
'sequence': 50,
'user_id': cls.user_sales_manager.id,
})
cls.partner_c2 = cls.env['res.partner'].create({
'company_id': cls.company_2.id,
'email': '"Partner C2" <[email protected]>',
'name': 'Customer for C2',
'phone': '+32455001122',
})
def _create_leads_batch(self, lead_type='lead', count=10, email_dup_count=0,
partner_count=0, partner_ids=None, user_ids=None,
country_ids=None, probabilities=None, suffix=''):
""" Helper tool method creating a batch of leads, useful when dealing
with batch processes. Please update me.
:param string type: 'lead', 'opportunity', 'mixed' (lead then opp),
None (depends on configuration);
:param partner_count: if not partner_ids is given, generate partner count
customers; other leads will have no customer;
:param partner_ids: a set of partner ids to cycle when creating leads;
:param user_ids: a set of user ids to cycle when creating leads;
:return: create leads
"""
types = ['lead', 'opportunity']
leads_data = [{
'name': f'TestLead{suffix}_{x:04d}',
'type': lead_type if lead_type else types[x % 2],
'priority': '%s' % (x % 3),
} for x in range(count)]
# generate customer information
partners = []
if partner_count:
partners = self.env['res.partner'].create([{
'name': 'AutoPartner_%04d' % (x),
'email': tools.formataddr((
'AutoPartner_%04d' % (x),
'partner_email_%[email protected]' % (x),
)),
} for x in range(partner_count)])
# customer information
if partner_ids:
for idx, lead_data in enumerate(leads_data):
lead_data['partner_id'] = partner_ids[idx % len(partner_ids)]
else:
for idx, lead_data in enumerate(leads_data):
if partner_count and idx < partner_count:
lead_data['partner_id'] = partners[idx].id
else:
lead_data['email_from'] = tools.formataddr((
'TestCustomer_%02d' % (idx),
'customer_email_%[email protected]' % (idx)
))
# country + phone information
if country_ids:
cid_to_country = dict(
(country.id, country)
for country in self.env['res.country'].browse([cid for cid in country_ids if cid])
)
for idx, lead_data in enumerate(leads_data):
country_id = country_ids[idx % len(country_ids)]
country = cid_to_country.get(country_id, self.env['res.country'])
lead_data['country_id'] = country.id
if lead_data['country_id']:
lead_data['phone'] = phone_validation.phone_format(
'0456%04d99' % (idx),
country.code, country.phone_code,
force_format='E164')
else:
lead_data['phone'] = '+32456%04d99' % (idx)
# salesteam information
if user_ids:
for idx, lead_data in enumerate(leads_data):
lead_data['user_id'] = user_ids[idx % len(user_ids)]
# probabilities
if probabilities:
for idx, lead_data in enumerate(leads_data):
lead_data['probability'] = probabilities[idx % len(probabilities)]
# duplicates (currently only with email)
dups_data = []
if email_dup_count and not partner_ids:
for idx, lead_data in enumerate(leads_data):
if not lead_data.get('partner_id') and lead_data['email_from']:
dup_data = dict(lead_data)
dup_data['name'] = 'Duplicated-%s' % dup_data['name']
dups_data.append(dup_data)
if len(dups_data) >= email_dup_count:
break
return self.env['crm.lead'].create(leads_data + dups_data)
def _create_duplicates(self, lead, create_opp=True):
""" Helper tool method creating, based on a given lead
* a customer (res.partner) based on lead email (to test partner finding)
-> FIXME: using same normalized email does not work currently, only exact email works
* a lead with same email_from
* a lead with same email_normalized (other email_from)
* a lead with customer but another email
* a lost opportunity with same email_from
"""
customer = self.env['res.partner'].create({
'name': 'Lead1 Email Customer',
'email': lead.email_from,
})
lead_email_from = self.env['crm.lead'].create({
'name': 'Duplicate: same email_from',
'type': 'lead',
'team_id': lead.team_id.id,
'email_from': lead.email_from,
'probability': lead.probability,
})
lead_email_normalized = self.env['crm.lead'].create({
'name': 'Duplicate: email_normalize comparison',
'type': 'lead',
'team_id': lead.team_id.id,
'stage_id': lead.stage_id.id,
'email_from': 'CUSTOMER WITH NAME <%s>' % lead.email_normalized.upper(),
'probability': lead.probability,
})
lead_partner = self.env['crm.lead'].create({
'name': 'Duplicate: customer ID',
'type': 'lead',
'team_id': lead.team_id.id,
'partner_id': customer.id,
'probability': lead.probability,
})
if create_opp:
opp_lost = self.env['crm.lead'].create({
'name': 'Duplicate: lost opportunity',
'type': 'opportunity',
'team_id': lead.team_id.id,
'stage_id': lead.stage_id.id,
'email_from': lead.email_from,
'probability': lead.probability,
})
opp_lost.action_set_lost()
else:
opp_lost = self.env['crm.lead']
new_leads = lead_email_from + lead_email_normalized + lead_partner + opp_lost
new_leads.flush() # compute notably probability
return customer, new_leads
@contextmanager
def assertLeadMerged(self, opportunity, leads, **expected):
""" Assert result of lead _merge_opportunity process. This is done using
a context manager in order to save original opportunity (master lead)
values. Indeed those will be modified during merge process. We have to
ensure final values are correct taking into account all leads values
before merging them.
:param opportunity: final opportunity
:param leads: merged leads (including opportunity)
"""
self.assertIn(opportunity, leads)
# save opportunity value before being modified by merge process
fields_all = self.FIELDS_FIRST_SET + self.merge_fields
original_opp_values = dict(
(fname, opportunity[fname])
for fname in fields_all
if fname in opportunity
)
def _find_value(lead, fname):
if lead == opportunity:
return original_opp_values[fname]
return lead[fname]
def _first_set(fname):
values = [_find_value(lead, fname) for lead in leads]
return next((value for value in values if value), False)
def _get_type():
values = [_find_value(lead, 'type') for lead in leads]
return 'opportunity' if 'opportunity' in values else 'lead'
def _get_description():
values = [_find_value(lead, 'description') for lead in leads]
return '<br><br>'.join(value for value in values if value)
def _get_priority():
values = [_find_value(lead, 'priority') for lead in leads]
return max(values)
def _aggregate(fname):
if isinstance(self.env['crm.lead'][fname], models.BaseModel):
values = leads.mapped(fname)
else:
values = [_find_value(lead, fname) for lead in leads]
return values
try:
# merge process will modify opportunity
yield
finally:
# support specific values caller may want to check in addition to generic tests
for fname, expected in expected.items():
self.assertEqual(opportunity[fname], expected)
# classic fields: first not void wins or specific computation
for fname in fields_all:
if fname not in opportunity: # not all fields available when doing -u
continue
opp_value = opportunity[fname]
if fname == 'description':
self.assertEqual(opp_value, _get_description())
elif fname == 'type':
self.assertEqual(opp_value, _get_type())
elif fname == 'priority':
self.assertEqual(opp_value, _get_priority())
elif fname in ('order_ids', 'visitor_ids'):
self.assertEqual(opp_value, _aggregate(fname))
else:
self.assertEqual(
opp_value if opp_value or not isinstance(opp_value, models.BaseModel) else False,
_first_set(fname)
)
class TestLeadConvertCommon(TestCrmCommon):
@classmethod
def setUpClass(cls):
super(TestLeadConvertCommon, cls).setUpClass()
# Sales Team organization
# Role: M (team member) R (team manager)
# SALESMAN---------------sales_team_1-----sales_team_convert
# admin------------------M----------------/ (sales_team_1_m2)
# user_sales_manager-----R----------------R
# user_sales_leads-------M----------------/ (sales_team_1_m1)
# user_sales_salesman----/----------------M (sales_team_convert_m1)
# Stages Team organization
# Name-------------------ST-------------------Sequ
# stage_team1_1----------sales_team_1---------1
# stage_team1_2----------sales_team_1---------5
# stage_team1_won--------sales_team_1---------70
# stage_gen_1------------/--------------------3
# stage_gen_won----------/--------------------30
# stage_team_convert_1---sales_team_convert---1
cls.sales_team_convert = cls.env['crm.team'].create({
'name': 'Convert Sales Team',
'sequence': 10,
'alias_name': False,
'use_leads': True,
'use_opportunities': True,
'company_id': False,
'user_id': cls.user_sales_manager.id,
'assignment_domain': [('priority', 'in', ['1', '2', '3'])],
})
cls.sales_team_convert_m1 = cls.env['crm.team.member'].create({
'user_id': cls.user_sales_salesman.id,
'crm_team_id': cls.sales_team_convert.id,
'assignment_max': 30,
'assignment_domain': False,
})
cls.stage_team_convert_1 = cls.env['crm.stage'].create({
'name': 'New',
'sequence': 1,
'team_id': cls.sales_team_convert.id,
})
cls.lead_1.write({'date_open': Datetime.from_string('2020-01-15 11:30:00')})
cls.crm_lead_dt_patcher = patch('odoo.addons.crm.models.crm_lead.fields.Datetime', wraps=Datetime)
cls.crm_lead_dt_mock = cls.crm_lead_dt_patcher.start()
@classmethod
def tearDownClass(cls):
cls.crm_lead_dt_patcher.stop()
super(TestLeadConvertCommon, cls).tearDownClass()
@classmethod
def _switch_to_multi_membership(cls):
# Sales Team organization
# Role: M (team member) R (team manager)
# SALESMAN---------------sales_team_1-----sales_team_convert
# admin------------------M----------------/ (sales_team_1_m2)
# user_sales_manager-----R----------------R+M <-- NEW (sales_team_convert_m2)
# user_sales_leads-------M----------------/ (sales_team_1_m1)
# user_sales_salesman----M----------------M <-- NEW (sales_team_1_m3 / sales_team_convert_m1)
# SALESMAN--------------sales_team----------assign_max
# admin-----------------sales_team_1--------15 (tot: 0.5/day)
# user_sales_manager----sales_team_convert--60 (tot: 2/day)
# user_sales_leads------sales_team_1--------45 (tot: 1.5/day)
# user_sales_salesman---sales_team_1--------15 (tot: 1.5/day)
# user_sales_salesman---sales_team_convert--30
cls.sales_team_1_m1.write({
'assignment_max': 45,
'assignment_domain': False,
})
cls.sales_team_1_m2.write({
'assignment_max': 15,
'assignment_domain': [('probability', '>=', 10)],
})
cls.env['ir.config_parameter'].set_param('sales_team.membership_multi', True)
cls.sales_team_1_m3 = cls.env['crm.team.member'].create({
'user_id': cls.user_sales_salesman.id,
'crm_team_id': cls.sales_team_1.id,
'assignment_max': 15,
'assignment_domain': [('probability', '>=', 20)],
})
cls.sales_team_convert_m1.write({
'assignment_max': 30,
'assignment_domain': [('probability', '>=', 20)]
})
cls.sales_team_convert_m2 = cls.env['crm.team.member'].create({
'user_id': cls.user_sales_manager.id,
'crm_team_id': cls.sales_team_convert.id,
'assignment_max': 60,
'assignment_domain': False,
})
@classmethod
def _switch_to_auto_assign(cls):
cls.env['ir.config_parameter'].set_param('crm.lead.auto.assignment', True)
cls.assign_cron = cls.env.ref('crm.ir_cron_crm_lead_assign')
cls.assign_cron.update({
'active': True,
'interval_type': 'days',
'interval_number': 1,
})
def assertMemberAssign(self, member, count):
""" Check assign result and that domains are effectively taken into account """
self.assertEqual(member.lead_month_count, count)
member_leads = self.env['crm.lead'].search(member._get_lead_month_domain())
self.assertEqual(len(member_leads), count)
if member.assignment_domain:
self.assertEqual(
member_leads.filtered_domain(literal_eval(member.assignment_domain)),
member_leads
)
# TODO this condition is not fulfilled in case of merge, need to change merge/assignment process
# if member.crm_team_id.assignment_domain:
# self.assertEqual(
# member_leads.filtered_domain(literal_eval(member.crm_team_id.assignment_domain)),
# member_leads,
# 'Assign domain not matching: %s' % member.crm_team_id.assignment_domain
# )
class TestLeadConvertMassCommon(TestLeadConvertCommon):
@classmethod
def setUpClass(cls):
super(TestLeadConvertMassCommon, cls).setUpClass()
# Sales Team organization
# Role: M (team member) R (team manager)
# SALESMAN-------------------sales_team_1-----sales_team_convert
# admin----------------------M----------------/ (sales_team_1_m2)
# user_sales_manager---------R----------------R (sales_team_1_m1)
# user_sales_leads-----------M----------------/
# user_sales_leads_convert---/----------------M <-- NEW (sales_team_convert_m2)
# user_sales_salesman--------/----------------M (sales_team_convert_m1)
cls.user_sales_leads_convert = mail_new_test_user(
cls.env, login='user_sales_leads_convert',
name='Lucien Sales Leads Convert', email='[email protected]',
company_id=cls.env.ref("base.main_company").id,
notification_type='inbox',
groups='sales_team.group_sale_salesman_all_leads,base.group_partner_manager,crm.group_use_lead',
)
cls.sales_team_convert_m2 = cls.env['crm.team.member'].create({
'user_id': cls.user_sales_leads_convert.id,
'crm_team_id': cls.sales_team_convert.id,
})
cls.lead_w_partner = cls.env['crm.lead'].create({
'name': 'New1',
'type': 'lead',
'priority': '0',
'probability': 10,
'user_id': cls.user_sales_manager.id,
'stage_id': False,
'partner_id': cls.contact_1.id,
})
cls.lead_w_partner.write({'stage_id': False})
cls.lead_w_partner_company = cls.env['crm.lead'].create({
'name': 'New1',
'type': 'lead',
'probability': 50,
'user_id': cls.user_sales_manager.id,
'stage_id': cls.stage_team1_1.id,
'partner_id': cls.contact_company_1.id,
'contact_name': 'Hermes Conrad',
'email_from': '[email protected]',
})
cls.lead_w_contact = cls.env['crm.lead'].create({
'name': 'LeadContact',
'type': 'lead',
'probability': 25,
'contact_name': 'TestContact',
'user_id': cls.user_sales_salesman.id,
'stage_id': cls.stage_gen_1.id,
})
cls.lead_w_email = cls.env['crm.lead'].create({
'name': 'LeadEmailAsContact',
'type': 'lead',
'priority': '2',
'probability': 15,
'email_from': '[email protected]',
'user_id': cls.user_sales_salesman.id,
'stage_id': cls.stage_gen_1.id,
})
cls.lead_w_email_lost = cls.env['crm.lead'].create({
'name': 'Lost',
'type': 'lead',
'probability': 15,
'email_from': '[email protected]',
'user_id': cls.user_sales_leads.id,
'stage_id': cls.stage_team1_2.id,
'active': False,
})
(cls.lead_w_partner + cls.lead_w_partner_company + cls.lead_w_contact + cls.lead_w_email + cls.lead_w_email_lost).flush()
| 40.550704 | 28,791 |
9,903 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests import common as crm_common
from odoo.tests.common import tagged, users
@tagged('lead_manage', 'crm_performance', 'post_install', '-at_install')
class TestLeadConvertMass(crm_common.TestLeadConvertMassCommon):
@classmethod
def setUpClass(cls):
super(TestLeadConvertMass, cls).setUpClass()
cls.leads = cls.lead_1 + cls.lead_w_partner + cls.lead_w_email_lost
cls.assign_users = cls.user_sales_manager + cls.user_sales_leads_convert + cls.user_sales_salesman
@users('user_sales_manager')
def test_assignment_salesmen(self):
test_leads = self._create_leads_batch(count=50, user_ids=[False])
user_ids = self.assign_users.ids
self.assertEqual(test_leads.user_id, self.env['res.users'])
with self.assertQueryCount(user_sales_manager=0):
test_leads = self.env['crm.lead'].browse(test_leads.ids)
with self.assertQueryCount(user_sales_manager=585): # crm 585 / com 585
test_leads._handle_salesmen_assignment(user_ids=user_ids, team_id=False)
self.assertEqual(test_leads.team_id, self.sales_team_convert | self.sales_team_1)
self.assertEqual(test_leads[0::3].user_id, self.user_sales_manager)
self.assertEqual(test_leads[1::3].user_id, self.user_sales_leads_convert)
self.assertEqual(test_leads[2::3].user_id, self.user_sales_salesman)
@users('user_sales_manager')
def test_assignment_salesmen_wteam(self):
test_leads = self._create_leads_batch(count=50, user_ids=[False])
user_ids = self.assign_users.ids
team_id = self.sales_team_convert.id
self.assertEqual(test_leads.user_id, self.env['res.users'])
with self.assertQueryCount(user_sales_manager=0):
test_leads = self.env['crm.lead'].browse(test_leads.ids)
# with self.assertQueryCount(user_sales_manager=573): # crm 567 - com 572
# query count randomly failling in 14.0
test_leads._handle_salesmen_assignment(user_ids=user_ids, team_id=team_id)
self.assertEqual(test_leads.team_id, self.sales_team_convert)
self.assertEqual(test_leads[0::3].user_id, self.user_sales_manager)
self.assertEqual(test_leads[1::3].user_id, self.user_sales_leads_convert)
self.assertEqual(test_leads[2::3].user_id, self.user_sales_salesman)
@users('user_sales_manager')
def test_mass_convert_internals(self):
""" Test internals mass converted in convert mode, without duplicate management """
# reset some assigned users to test salesmen assign
(self.lead_w_partner | self.lead_w_email_lost).write({
'user_id': False
})
mass_convert = self.env['crm.lead2opportunity.partner.mass'].with_context({
'active_model': 'crm.lead',
'active_ids': self.leads.ids,
'active_id': self.leads.ids[0]
}).create({
'deduplicate': False,
'user_id': self.user_sales_salesman.id,
'force_assignment': False,
})
# default values
self.assertEqual(mass_convert.name, 'convert')
self.assertEqual(mass_convert.action, 'each_exist_or_create')
# depending on options
self.assertEqual(mass_convert.partner_id, self.env['res.partner'])
self.assertEqual(mass_convert.deduplicate, False)
self.assertEqual(mass_convert.user_id, self.user_sales_salesman)
self.assertEqual(mass_convert.team_id, self.sales_team_convert)
mass_convert.action_mass_convert()
for lead in self.lead_1 | self.lead_w_partner:
self.assertEqual(lead.type, 'opportunity')
if lead == self.lead_w_partner:
self.assertEqual(lead.user_id, self.env['res.users']) # user_id is bypassed
self.assertEqual(lead.partner_id, self.contact_1)
elif lead == self.lead_1:
self.assertEqual(lead.user_id, self.user_sales_leads) # existing value not forced
new_partner = lead.partner_id
self.assertEqual(new_partner.name, 'Amy Wong')
self.assertEqual(new_partner.email, '[email protected]')
# test unforced assignation
mass_convert.write({
'user_ids': self.user_sales_salesman.ids,
})
mass_convert.action_mass_convert()
self.assertEqual(self.lead_w_partner.user_id, self.user_sales_salesman)
self.assertEqual(self.lead_1.user_id, self.user_sales_leads) # existing value not forced
# lost leads are untouched
self.assertEqual(self.lead_w_email_lost.type, 'lead')
self.assertFalse(self.lead_w_email_lost.active)
self.assertFalse(self.lead_w_email_lost.date_conversion)
# TDE FIXME: partner creation is done even on lost leads because not checked in wizard
# self.assertEqual(self.lead_w_email_lost.partner_id, self.env['res.partner'])
@users('user_sales_manager')
def test_mass_convert_deduplicate(self):
""" Test duplicated_lead_ids fields having another behavior in mass convert
because why not. Its use is: among leads under convert, store those with
duplicates if deduplicate is set to True. """
_customer, lead_1_dups = self._create_duplicates(self.lead_1, create_opp=False)
lead_1_final = self.lead_1 # after merge: same but with lower ID
_customer2, lead_w_partner_dups = self._create_duplicates(self.lead_w_partner, create_opp=False)
lead_w_partner_final = lead_w_partner_dups[0] # lead_w_partner has no stage -> lower in sort by confidence
lead_w_partner_dups_partner = lead_w_partner_dups[1] # copy with a partner_id (with the same email)
mass_convert = self.env['crm.lead2opportunity.partner.mass'].with_context({
'active_model': 'crm.lead',
'active_ids': self.leads.ids,
}).create({
'deduplicate': True,
})
self.assertEqual(mass_convert.action, 'each_exist_or_create')
self.assertEqual(mass_convert.name, 'convert')
self.assertEqual(mass_convert.lead_tomerge_ids, self.leads)
self.assertEqual(mass_convert.duplicated_lead_ids, self.lead_1 | self.lead_w_partner)
mass_convert.action_mass_convert()
self.assertEqual(
(lead_1_dups | lead_w_partner_dups | lead_w_partner_dups_partner).exists(),
lead_w_partner_final
)
for lead in lead_1_final | lead_w_partner_final:
self.assertTrue(lead.active)
self.assertEqual(lead.type, 'opportunity')
@users('user_sales_manager')
def test_mass_convert_find_existing(self):
""" Check that we don't find a wrong partner
that have similar name during mass conversion
"""
wrong_partner = self.env['res.partner'].create({
'name': 'casa depapel',
'street': "wrong street"
})
lead = self.env['crm.lead'].create({'name': 'Asa Depape'})
mass_convert = self.env['crm.lead2opportunity.partner.mass'].with_context({
'active_model': 'crm.lead',
'active_ids': lead.ids,
'active_id': lead.ids[0]
}).create({
'deduplicate': False,
'action': 'each_exist_or_create',
'name': 'convert',
})
mass_convert.action_mass_convert()
self.assertNotEqual(lead.partner_id, wrong_partner, "Partner Id should not match the wrong contact")
@users('user_sales_manager')
def test_mass_convert_performances(self):
test_leads = self._create_leads_batch(count=50, user_ids=[False])
user_ids = self.assign_users.ids
# randomness: at least 1 query
with self.assertQueryCount(user_sales_manager=1902): # crm 1608 / com 1895
mass_convert = self.env['crm.lead2opportunity.partner.mass'].with_context({
'active_model': 'crm.lead',
'active_ids': test_leads.ids,
}).create({
'deduplicate': True,
'user_ids': user_ids,
'force_assignment': True,
})
mass_convert.action_mass_convert()
self.assertEqual(set(test_leads.mapped('type')), set(['opportunity']))
self.assertEqual(len(test_leads.partner_id), len(test_leads))
# TDE FIXME: strange
# self.assertEqual(test_leads.team_id, self.sales_team_convert | self.sales_team_1)
self.assertEqual(test_leads.team_id, self.sales_team_1)
self.assertEqual(test_leads[0::3].user_id, self.user_sales_manager)
self.assertEqual(test_leads[1::3].user_id, self.user_sales_leads_convert)
self.assertEqual(test_leads[2::3].user_id, self.user_sales_salesman)
@users('user_sales_manager')
def test_mass_convert_w_salesmen(self):
# reset some assigned users to test salesmen assign
(self.lead_w_partner | self.lead_w_email_lost).write({
'user_id': False
})
mass_convert = self.env['crm.lead2opportunity.partner.mass'].with_context({
'active_model': 'crm.lead',
'active_ids': self.leads.ids,
'active_id': self.leads.ids[0]
}).create({
'deduplicate': False,
'user_ids': self.assign_users.ids,
'force_assignment': True,
})
# TDE FIXME: what happens if we mix people from different sales team ? currently nothing, to check
mass_convert.action_mass_convert()
for idx, lead in enumerate(self.leads - self.lead_w_email_lost):
self.assertEqual(lead.type, 'opportunity')
assigned_user = self.assign_users[idx % len(self.assign_users)]
self.assertEqual(lead.user_id, assigned_user)
| 46.275701 | 9,903 |
6,874 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.tests.common import tagged, users
@tagged('post_install', '-at_install')
class TestCRMLeadSmartCalendar(TestCrmCommon):
@classmethod
def setUpClass(cls):
super(TestCRMLeadSmartCalendar, cls).setUpClass()
# weekstart index : 7 (sunday), tz : UTC -4 / -5
cls.user_NY_en_US = mail_new_test_user(
cls.env, login='user_NY_en_US', lang='en_US', tz='America/New_York',
name='user_NY_en_US User', email='[email protected]',
notification_type='inbox',
groups='sales_team.group_sale_salesman_all_leads,base.group_partner_manager,crm.group_use_lead')
# weekstart index : 1 (monday), tz : UTC+0
cls.env['res.lang']._activate_lang('pt_PT')
cls.user_UTC_pt_PT = mail_new_test_user(
cls.env, login='user_UTC_pt_PT', lang='pt_PT', tz='Europe/Lisbon',
name='user_UTC_pt_PT User', email='[email protected]',
notification_type='inbox',
groups='sales_team.group_sale_salesman_all_leads,base.group_partner_manager,crm.group_use_lead')
cls.next_year = datetime.now().year + 1
cls.calendar_meeting_1 = cls.env['calendar.event'].create({
'name': 'calendar_meeting_1',
'start': datetime(2020, 12, 13, 17),
'stop': datetime(2020, 12, 13, 22)})
cls.calendar_meeting_2 = cls.env['calendar.event'].create({
'name': 'calendar_meeting_2',
'start': datetime(2020, 12, 13, 2),
'stop': datetime(2020, 12, 13, 3)})
cls.calendar_meeting_3 = cls.env['calendar.event'].create({
'name': 'calendar_meeting_3',
'start': datetime(cls.next_year, 5, 4, 12),
'stop': datetime(cls.next_year, 5, 4, 13)})
cls.calendar_meeting_4 = cls.env['calendar.event'].create({
'name': 'calendar_meeting_4',
'allday': True,
'start': datetime(2020, 12, 6, 0, 0, 0),
'stop': datetime(2020, 12, 6, 23, 59, 59)})
cls.calendar_meeting_5 = cls.env['calendar.event'].create({
'name': 'calendar_meeting_5',
'start': datetime(2020, 12, 13, 8),
'stop': datetime(2020, 12, 13, 18),
'allday': True})
cls.calendar_meeting_6 = cls.env['calendar.event'].create({
'name': 'calendar_meeting_6',
'start': datetime(2020, 12, 12, 0),
'stop': datetime(2020, 12, 19, 0)})
@users('user_NY_en_US')
def test_meeting_view_parameters_1(self):
lead_smart_calendar_1 = self.env['crm.lead'].create({'name': 'Lead 1 - user_NY_en_US'})
mode, initial_date = lead_smart_calendar_1._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, False)
self.calendar_meeting_1.write({'opportunity_id': lead_smart_calendar_1.id})
mode, initial_date = lead_smart_calendar_1._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(2020, 12, 13))
self.calendar_meeting_2.write({'opportunity_id': lead_smart_calendar_1.id})
mode, initial_date = lead_smart_calendar_1._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'month')
self.assertEqual(initial_date, date(2020, 12, 12))
self.calendar_meeting_3.write({'opportunity_id': lead_smart_calendar_1.id})
mode, initial_date = lead_smart_calendar_1._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(self.next_year, 5, 4))
lead_smart_calendar_2 = self.env['crm.lead'].create({'name': 'Lead 2 - user_NY_en_US'})
self.calendar_meeting_4.write({'opportunity_id': lead_smart_calendar_2.id})
mode, initial_date = lead_smart_calendar_2._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(2020, 12, 6))
self.calendar_meeting_2.write({'opportunity_id': lead_smart_calendar_2.id})
mode, initial_date = lead_smart_calendar_2._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(2020, 12, 6))
self.calendar_meeting_5.write({'opportunity_id': lead_smart_calendar_2.id})
mode, initial_date = lead_smart_calendar_2._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'month')
self.assertEqual(initial_date, date(2020, 12, 6))
@users('user_UTC_pt_PT')
def test_meeting_view_parameters_2(self):
lead_smart_calendar_1 = self.env['crm.lead'].create({'name': 'Lead 1 - user_UTC_pt_PT'})
self.calendar_meeting_1.write({'opportunity_id': lead_smart_calendar_1.id})
self.calendar_meeting_2.write({'opportunity_id': lead_smart_calendar_1.id})
mode, initial_date = lead_smart_calendar_1._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(2020, 12, 13))
self.calendar_meeting_3.write({'opportunity_id': lead_smart_calendar_1.id})
mode, initial_date = lead_smart_calendar_1._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(self.next_year, 5, 4))
lead_smart_calendar_2 = self.env['crm.lead'].create({'name': 'Lead 2 - user_UTC_pt_PT'})
self.calendar_meeting_6.write({'opportunity_id': lead_smart_calendar_2.id})
mode, initial_date = lead_smart_calendar_2._get_opportunity_meeting_view_parameters()
self.assertEqual(mode, 'week')
self.assertEqual(initial_date, date(2020, 12, 12))
@users('user_sales_leads')
def test_meeting_creation_from_lead_form(self):
""" When going from a lead to the Calendar and adding a meeting, both salesman and customer
should be attendees of the event """
lead = self.env['crm.lead'].create({
'name': 'SuperLead',
'partner_id': self.contact_1.id,
})
calendar_action = lead.action_schedule_meeting()
event = self.env['calendar.event'].with_context(calendar_action['context']).create({
'start': datetime(2020, 12, 13, 17),
'stop': datetime(2020, 12, 13, 22),
})
self.assertEqual(len(event.attendee_ids), 2)
self.assertIn(self.user_sales_leads.partner_id, event.attendee_ids.partner_id)
self.assertIn(self.contact_1, event.attendee_ids.partner_id)
| 50.918519 | 6,874 |
6,329 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.tests.common import tagged, users
@tagged('lead_manage')
class TestLeadConvert(TestCrmCommon):
@users('user_sales_manager')
def test_potential_duplicates(self):
company = self.env['res.partner'].create({
'name': 'My company',
'email': '[email protected]',
'is_company': True,
'street': '57th Street',
'city': 'New New York',
'country_id': self.env.ref('base.us').id,
'zip': '12345',
})
partner_1 = self.env['res.partner'].create({
'name': 'Dave',
'email': '[email protected]',
'mobile': '+1 202 555 0123',
'phone': False,
'parent_id': company.id,
'is_company': False,
'street': 'Pearl street',
'city': 'California',
'country_id': self.env.ref('base.us').id,
'zip': '95826',
})
partner_2 = self.env['res.partner'].create({
'name': 'Eve',
'email': '[email protected]',
'mobile': '+1 202 555 3210',
'phone': False,
'parent_id': company.id,
'is_company': False,
'street': 'Wall street',
'city': 'New York',
'country_id': self.env.ref('base.us').id,
'zip': '54321',
})
lead_1 = self.env['crm.lead'].create({
'name': 'Lead 1',
'type': 'lead',
'partner_name': 'Alice',
'email_from': '[email protected]',
})
lead_2 = self.env['crm.lead'].create({
'name': 'Opportunity 1',
'type': 'opportunity',
'email_from': '[email protected]',
})
lead_3 = self.env['crm.lead'].create({
'name': 'Opportunity 2',
'type': 'opportunity',
'email_from': '[email protected]',
})
lead_4 = self.env['crm.lead'].create({
'name': 'Lead 2',
'type': 'lead',
'partner_name': 'Alice Doe'
})
lead_5 = self.env['crm.lead'].create({
'name': 'Opportunity 3',
'type': 'opportunity',
'partner_name': 'Alice Doe'
})
lead_6 = self.env['crm.lead'].create({
'name': 'Opportunity 4',
'type': 'opportunity',
'partner_name': 'Bob Doe'
})
lead_7 = self.env['crm.lead'].create({
'name': 'Opportunity 5',
'type': 'opportunity',
'partner_name': 'Bob Doe',
'email_from': '[email protected]',
})
lead_8 = self.env['crm.lead'].create({
'name': 'Opportunity 6',
'type': 'opportunity',
'email_from': '[email protected]',
})
lead_9 = self.env['crm.lead'].create({
'name': 'Opportunity 7',
'type': 'opportunity',
'email_from': '[email protected]',
})
lead_10 = self.env['crm.lead'].create({
'name': 'Opportunity 8',
'type': 'opportunity',
'probability': 0,
'active': False,
'email_from': '[email protected]',
})
lead_11 = self.env['crm.lead'].create({
'name': 'Opportunity 9',
'type': 'opportunity',
'contact_name': 'charlie'
})
lead_12 = self.env['crm.lead'].create({
'name': 'Opportunity 10',
'type': 'opportunity',
'contact_name': 'Charlie Chapelin',
})
lead_13 = self.env['crm.lead'].create({
'name': 'Opportunity 8',
'type': 'opportunity',
'partner_id': partner_1.id
})
lead_14 = self.env['crm.lead'].create({
'name': 'Lead 3',
'type': 'lead',
'partner_id': partner_2.id
})
self.assertEqual(lead_1 + lead_2 + lead_3, lead_1.duplicate_lead_ids)
self.assertEqual(lead_1 + lead_2 + lead_3, lead_2.duplicate_lead_ids)
self.assertEqual(lead_1 + lead_2 + lead_3, lead_3.duplicate_lead_ids)
self.assertEqual(lead_4 + lead_5, lead_4.duplicate_lead_ids)
self.assertEqual(lead_4 + lead_5, lead_5.duplicate_lead_ids)
self.assertEqual(lead_6 + lead_7, lead_6.duplicate_lead_ids)
self.assertEqual(lead_6 + lead_7, lead_7.duplicate_lead_ids)
self.assertEqual(lead_8 + lead_9 + lead_10, lead_8.duplicate_lead_ids)
self.assertEqual(lead_8 + lead_9 + lead_10, lead_9.duplicate_lead_ids)
self.assertEqual(lead_8 + lead_9 + lead_10, lead_10.duplicate_lead_ids)
self.assertEqual(lead_11 + lead_12, lead_11.duplicate_lead_ids)
self.assertEqual(lead_12, lead_12.duplicate_lead_ids)
self.assertEqual(lead_13 + lead_14, lead_13.duplicate_lead_ids)
self.assertEqual(lead_13 + lead_14, lead_14.duplicate_lead_ids)
@users('user_sales_manager')
def test_potential_duplicates_with_invalid_email(self):
lead_1 = self.env['crm.lead'].create({
'name': 'Lead 1',
'type': 'lead',
'email_from': 'mail"[email protected]'
})
lead_2 = self.env['crm.lead'].create({
'name': 'Opportunity 1',
'type': 'opportunity',
'email_from': '[email protected]'
})
lead_3 = self.env['crm.lead'].create({
'name': 'Opportunity 2',
'type': 'lead',
'email_from': 'odoo.com'
})
lead_4 = self.env['crm.lead'].create({
'name': 'Opportunity 3',
'type': 'opportunity',
'email_from': 'odoo.com'
})
lead_5 = self.env['crm.lead'].create({
'name': 'Opportunity 3',
'type': 'opportunity',
'email_from': 'myodoo.com'
})
self.assertEqual(lead_1 + lead_2, lead_1.duplicate_lead_ids)
self.assertEqual(lead_1 + lead_2, lead_2.duplicate_lead_ids)
self.assertEqual(lead_3 + lead_4 + lead_5, lead_3.duplicate_lead_ids)
self.assertEqual(lead_3 + lead_4 + lead_5, lead_4.duplicate_lead_ids)
self.assertEqual(lead_5, lead_5.duplicate_lead_ids)
| 37.229412 | 6,329 |
14,872 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo.addons.crm.tests.common import TestLeadConvertMassCommon
from odoo.fields import Datetime
from odoo.tests.common import tagged, users
from odoo.tools import mute_logger
@tagged('lead_manage')
class TestLeadMergeCommon(TestLeadConvertMassCommon):
""" During a mixed merge (involving leads and opps), data should be handled a certain way following their type
(m2o, m2m, text, ...). """
@classmethod
def setUpClass(cls):
super(TestLeadMergeCommon, cls).setUpClass()
cls.leads = cls.lead_1 + cls.lead_w_partner + cls.lead_w_contact + cls.lead_w_email + cls.lead_w_partner_company + cls.lead_w_email_lost
# reset some assigned users to test salesmen assign
(cls.lead_w_partner | cls.lead_w_email_lost).write({
'user_id': False,
})
cls.lead_w_partner.write({'stage_id': False})
cls.lead_w_contact.write({'description': 'lead_w_contact'})
cls.lead_w_email.write({'description': 'lead_w_email'})
cls.lead_1.write({'description': 'lead_1'})
cls.lead_w_partner.write({'description': 'lead_w_partner'})
cls.assign_users = cls.user_sales_manager + cls.user_sales_leads_convert + cls.user_sales_salesman
@tagged('lead_manage')
class TestLeadMerge(TestLeadMergeCommon):
def _run_merge_wizard(self, leads):
res = self.env['crm.merge.opportunity'].with_context({
'active_model': 'crm.lead',
'active_ids': leads.ids,
'active_id': False,
}).create({
'team_id': False,
'user_id': False,
}).action_merge()
return self.env['crm.lead'].browse(res['res_id'])
def test_initial_data(self):
""" Ensure initial data to avoid spaghetti test update afterwards
Original order:
lead_w_contact ----------lead---seq=3----proba=15
lead_w_email ------------lead---seq=3----proba=15
lead_1 ------------------lead---seq=1----proba=?
lead_w_partner ----------lead---seq=False---proba=10
lead_w_partner_company --lead---seq=False---proba=15
"""
self.assertFalse(self.lead_1.date_conversion)
self.assertEqual(self.lead_1.date_open, Datetime.from_string('2020-01-15 11:30:00'))
self.assertEqual(self.lead_1.user_id, self.user_sales_leads)
self.assertEqual(self.lead_1.team_id, self.sales_team_1)
self.assertEqual(self.lead_1.stage_id, self.stage_team1_1)
self.assertEqual(self.lead_w_partner.stage_id, self.env['crm.stage'])
self.assertEqual(self.lead_w_partner.user_id, self.env['res.users'])
self.assertEqual(self.lead_w_partner.team_id, self.sales_team_1)
self.assertEqual(self.lead_w_partner_company.stage_id, self.stage_team1_1)
self.assertEqual(self.lead_w_partner_company.user_id, self.user_sales_manager)
self.assertEqual(self.lead_w_partner_company.team_id, self.sales_team_1)
self.assertEqual(self.lead_w_contact.stage_id, self.stage_gen_1)
self.assertEqual(self.lead_w_contact.user_id, self.user_sales_salesman)
self.assertEqual(self.lead_w_contact.team_id, self.sales_team_convert)
self.assertEqual(self.lead_w_email.stage_id, self.stage_gen_1)
self.assertEqual(self.lead_w_email.user_id, self.user_sales_salesman)
self.assertEqual(self.lead_w_email.team_id, self.sales_team_convert)
self.assertEqual(self.lead_w_email_lost.stage_id, self.stage_team1_2)
self.assertEqual(self.lead_w_email_lost.user_id, self.env['res.users'])
self.assertEqual(self.lead_w_email_lost.team_id, self.sales_team_1)
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_lead_merge_internals(self):
""" Test internals of merge wizard. In this test leads are ordered as
lead_w_contact --lead---seq=3---probability=25
lead_w_email ----lead---seq=3---probability=15
lead_1 ----------lead---seq=1
lead_w_partner --lead---seq=False
"""
# ensure initial data
self.lead_w_partner_company.action_set_won() # won opps should be excluded
merge = self.env['crm.merge.opportunity'].with_context({
'active_model': 'crm.lead',
'active_ids': self.leads.ids,
'active_id': False,
}).create({
'user_id': self.user_sales_leads_convert.id,
})
self.assertEqual(merge.team_id, self.sales_team_convert)
# TDE FIXME: not sure the browse in default get of wizard intended to exlude lost, as it browse ids
# and exclude inactive leads, but that's not written anywhere ... intended ??
self.assertEqual(merge.opportunity_ids, self.leads - self.lead_w_partner_company - self.lead_w_email_lost)
ordered_merge = self.lead_w_contact + self.lead_w_email + self.lead_1 + self.lead_w_partner
ordered_merge_description = '<br><br>'.join(l.description for l in ordered_merge)
# merged opportunity: in this test, all input are leads. Confidence is based on stage
# sequence -> lead_w_contact has a stage sequence of 3 and probability is greater
result = merge.action_merge()
merge_opportunity = self.env['crm.lead'].browse(result['res_id'])
self.assertFalse((ordered_merge - merge_opportunity).exists())
self.assertEqual(merge_opportunity, self.lead_w_contact)
self.assertEqual(merge_opportunity.type, 'lead')
self.assertEqual(merge_opportunity.description, ordered_merge_description)
# merged opportunity has updated salesman / team / stage is ok as generic
self.assertEqual(merge_opportunity.user_id, self.user_sales_leads_convert)
self.assertEqual(merge_opportunity.team_id, self.sales_team_convert)
self.assertEqual(merge_opportunity.stage_id, self.stage_gen_1)
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_lead_merge_mixed(self):
""" In case of mix, opportunities are on top, and result is an opportunity
lead_1 -------------------opp----seq=1---probability=60
lead_w_partner_company ---opp----seq=1---probability=50
lead_w_contact -----------lead---seq=3---probability=25
lead_w_email -------------lead---seq=3---probability=15
lead_w_partner -----------lead---seq=False
"""
# ensure initial data
(self.lead_w_partner_company | self.lead_1).write({'type': 'opportunity'})
self.lead_1.write({'probability': 60})
self.assertEqual(self.lead_w_partner_company.stage_id.sequence, 1)
self.assertEqual(self.lead_1.stage_id.sequence, 1)
merge = self.env['crm.merge.opportunity'].with_context({
'active_model': 'crm.lead',
'active_ids': self.leads.ids,
'active_id': False,
}).create({
'team_id': self.sales_team_convert.id,
'user_id': False,
})
# TDE FIXME: see aa44700dccdc2618e0b8bc94252789264104047c -> no user, no team -> strange
merge.write({'team_id': self.sales_team_convert.id})
# TDE FIXME: not sure the browse in default get of wizard intended to exlude lost, as it browse ids
# and exclude inactive leads, but that's not written anywhere ... intended ??
self.assertEqual(merge.opportunity_ids, self.leads - self.lead_w_email_lost)
ordered_merge = self.lead_w_partner_company + self.lead_w_contact + self.lead_w_email + self.lead_w_partner
result = merge.action_merge()
merge_opportunity = self.env['crm.lead'].browse(result['res_id'])
self.assertFalse((ordered_merge - merge_opportunity).exists())
self.assertEqual(merge_opportunity, self.lead_1)
self.assertEqual(merge_opportunity.type, 'opportunity')
# merged opportunity has same salesman (not updated in wizard)
self.assertEqual(merge_opportunity.user_id, self.user_sales_leads)
# TDE FIXME: as same uer_id is enforced, team is updated through onchange and therefore stage
self.assertEqual(merge_opportunity.team_id, self.sales_team_convert)
# self.assertEqual(merge_opportunity.team_id, self.sales_team_1)
# TDE FIXME: BUT team_id is computed after checking stage, based on wizard's team_id
self.assertEqual(merge_opportunity.stage_id, self.stage_team_convert_1)
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_lead_merge_probability_auto(self):
""" Check master lead keeps its automated probability when merged. """
self.lead_1.write({'type': 'opportunity', 'probability': self.lead_1.automated_probability})
self.assertTrue(self.lead_1.is_automated_probability)
leads = self.env['crm.lead'].browse((self.lead_1 + self.lead_w_partner + self.lead_w_partner_company).ids)
merged_lead = self._run_merge_wizard(leads)
self.assertEqual(merged_lead, self.lead_1)
self.assertTrue(merged_lead.is_automated_probability, "lead with Auto proba should remain with auto probability")
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_lead_merge_probability_auto_empty(self):
""" Check master lead keeps its automated probability when merged
even if its probability is 0. """
self.lead_1.write({'type': 'opportunity', 'probability': 0, 'automated_probability': 0})
self.assertTrue(self.lead_1.is_automated_probability)
leads = self.env['crm.lead'].browse((self.lead_1 + self.lead_w_partner + self.lead_w_partner_company).ids)
merged_lead = self._run_merge_wizard(leads)
self.assertEqual(merged_lead, self.lead_1)
self.assertTrue(merged_lead.is_automated_probability, "lead with Auto proba should remain with auto probability")
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_lead_merge_probability_manual(self):
""" Check master lead keeps its manual probability when merged. """
self.lead_1.write({'probability': 60})
self.assertFalse(self.lead_1.is_automated_probability)
leads = self.env['crm.lead'].browse((self.lead_1 + self.lead_w_partner + self.lead_w_partner_company).ids)
merged_lead = self._run_merge_wizard(leads)
self.assertEqual(merged_lead, self.lead_1)
self.assertEqual(merged_lead.probability, 60, "Manual Probability should remain the same after the merge")
self.assertFalse(merged_lead.is_automated_probability)
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_lead_merge_probability_manual_empty(self):
""" Check master lead keeps its manual probability when merged even if
its probability is 0. """
self.lead_1.write({'type': 'opportunity', 'probability': 0})
leads = self.env['crm.lead'].browse((self.lead_1 + self.lead_w_partner + self.lead_w_partner_company).ids)
merged_lead = self._run_merge_wizard(leads)
self.assertEqual(merged_lead, self.lead_1)
self.assertEqual(merged_lead.probability, 0, "Manual Probability should remain the same after the merge")
self.assertFalse(merged_lead.is_automated_probability)
@users('user_sales_manager')
@mute_logger('odoo.models.unlink')
def test_merge_method(self):
""" In case of mix, opportunities are on top, and result is an opportunity
lead_1 -------------------opp----seq=1---probability=50
lead_w_partner_company ---opp----seq=1---probability=50 (ID greater)
lead_w_contact -----------lead---seq=3
lead_w_email -------------lead---seq=3
lead_w_partner -----------lead---seq=False
"""
# ensure initial data
(self.lead_w_partner_company | self.lead_1).write({'type': 'opportunity', 'probability': 50})
leads = self.env['crm.lead'].browse(self.leads.ids)._sort_by_confidence_level(reverse=True)
with self.assertLeadMerged(self.lead_1, leads,
name='Nibbler Spacecraft Request',
partner_id=self.contact_company_1,
priority='2'):
leads._merge_opportunity(auto_unlink=False, max_length=None)
@users('user_sales_manager')
def test_merge_method_dependencies(self):
""" Test if dependences for leads are not lost while merging leads. In
this test leads are ordered as
lead_w_partner_company ---opp----seq=1 (ID greater)
lead_w_contact -----------lead---seq=3
lead_w_email -------------lead---seq=3----------------attachments
lead_1 -------------------lead---seq=1----------------activity+meeting
lead_w_partner -----------lead---seq=False
"""
self.env['crm.lead'].browse(self.lead_w_partner_company.ids).write({'type': 'opportunity'})
# create side documents
attachments = self.env['ir.attachment'].create([
{'name': '%02d.txt' % idx,
'datas': base64.b64encode(b'Att%02d' % idx),
'res_model': 'crm.lead',
'res_id': self.lead_w_email.id,
} for idx in range(4)
])
lead_1 = self.env['crm.lead'].browse(self.lead_1.ids)
activity = lead_1.activity_schedule('crm.lead_test_activity_1')
calendar_event = self.env['calendar.event'].create({
'name': 'Meeting with partner',
'activity_ids': [(4, activity.id)],
'start': '2021-06-12 21:00:00',
'stop': '2021-06-13 00:00:00',
'res_model_id': self.env['ir.model']._get('crm.crm_lead').id,
'res_id': lead_1.id,
'opportunity_id': lead_1.id,
})
# run merge and check documents are moved to the master record
merge = self.env['crm.merge.opportunity'].with_context({
'active_model': 'crm.lead',
'active_ids': self.leads.ids,
'active_id': False,
}).create({
'team_id': self.sales_team_convert.id,
'user_id': False,
})
result = merge.action_merge()
master_lead = self.leads.filtered(lambda lead: lead.id == result['res_id'])
# check result of merge process
self.assertEqual(master_lead, self.lead_w_partner_company)
# records updated
self.assertEqual(calendar_event.opportunity_id, master_lead)
self.assertEqual(calendar_event.res_id, master_lead.id)
self.assertTrue(all(att.res_id == master_lead.id for att in attachments))
# 2many accessors updated
self.assertEqual(master_lead.activity_ids, activity)
self.assertEqual(master_lead.calendar_event_ids, calendar_event)
| 50.243243 | 14,872 |
9,943 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, timedelta
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.tests.common import users
class TestCrmMailActivity(TestCrmCommon):
@classmethod
def setUpClass(cls):
super(TestCrmMailActivity, cls).setUpClass()
cls.activity_type_1 = cls.env['mail.activity.type'].create({
'name': 'Initial Contact',
'delay_count': 5,
'summary': 'ACT 1 : Presentation, barbecue, ... ',
'res_model': 'crm.lead',
})
cls.activity_type_2 = cls.env['mail.activity.type'].create({
'name': 'Call for Demo',
'delay_count': 6,
'summary': 'ACT 2 : I want to show you my ERP !',
'res_model': 'crm.lead',
})
for activity_type in cls.activity_type_1 + cls.activity_type_2:
cls.env['ir.model.data'].create({
'name': activity_type.name.lower().replace(' ', '_'),
'module': 'crm',
'model': activity_type._name,
'res_id': activity_type.id,
})
@users('user_sales_leads')
def test_crm_activity_ordering(self):
""" Test ordering on "my activities", linked to a hack introduced for a b2b.
Purpose is to be able to order on "my activities", which is a filtered o2m.
In this test we will check search, limit, order and offset linked to the
override of search for this non stored computed field. """
# Initialize some batch data
default_order = self.env['crm.lead']._order
self.assertEqual(default_order, "priority desc, id desc") # force updating this test is order changes
test_leads = self._create_leads_batch(count=10, partner_ids=[self.contact_1.id, self.contact_2.id, False]).sorted('id')
# assert initial data, ensure we did not break base behavior
for lead in test_leads:
self.assertFalse(lead.my_activity_date_deadline)
search_res = self.env['crm.lead'].search([('id', 'in', test_leads.ids)], limit=5, offset=0, order='id ASC')
self.assertEqual(search_res.ids, test_leads[:5].ids)
search_res = self.env['crm.lead'].search([('id', 'in', test_leads.ids)], limit=5, offset=5, order='id ASC')
self.assertEqual(search_res.ids, test_leads[5:10].ids)
# Let's schedule some activities for "myself" and "my bro"and check those are correctly computed
# LEAD NUMBER DEADLINE (MY) PRIORITY LATE DEADLINE (MY)
# 0 +2D 0 +2D
# 1 -1D 1 +2D
# 2 -2D 2 +2D
# 3 -1D 0 -1D
# 4 -2D 1 -2D
# 5 +2D 2 +2D
# 6+ / 0/1/2/0 /
today = date.today()
deadline_in2d, deadline_in1d = today + timedelta(days=2), today + timedelta(days=1)
deadline_was2d, deadline_was1d = today + timedelta(days=-2), today + timedelta(days=-1)
deadlines_my = [deadline_in2d, deadline_was1d, deadline_was2d, deadline_was1d, deadline_was2d,
deadline_in2d, False, False, False, False]
deadlines_gl = [deadline_in1d, deadline_was1d, deadline_was2d, deadline_was1d, deadline_was2d,
deadline_in2d, False, False, False, False]
test_leads[0:4].activity_schedule(act_type_xmlid='crm.call_for_demo', user_id=self.user_sales_manager.id, date_deadline=deadline_in1d)
test_leads[0:3].activity_schedule(act_type_xmlid='crm.initial_contact', date_deadline=deadline_in2d)
test_leads[5].activity_schedule(act_type_xmlid='crm.initial_contact', date_deadline=deadline_in2d)
(test_leads[1] | test_leads[3]).activity_schedule(act_type_xmlid='crm.initial_contact', date_deadline=deadline_was1d)
(test_leads[2] | test_leads[4]).activity_schedule(act_type_xmlid='crm.call_for_demo', date_deadline=deadline_was2d)
test_leads.invalidate_cache()
expected_ids_asc = [2, 4, 1, 3, 5, 0, 8, 7, 9, 6]
expected_leads_asc = self.env['crm.lead'].browse([test_leads[lid].id for lid in expected_ids_asc])
expected_ids_desc = [5, 0, 1, 3, 2, 4, 8, 7, 9, 6]
expected_leads_desc = self.env['crm.lead'].browse([test_leads[lid].id for lid in expected_ids_desc])
for idx, lead in enumerate(test_leads):
self.assertEqual(lead.my_activity_date_deadline, deadlines_my[idx])
self.assertEqual(lead.activity_date_deadline, deadlines_gl[idx], 'Fail at %s' % idx)
# Let's go for a first batch of search
_order = 'my_activity_date_deadline ASC, %s' % default_order
_domain = [('id', 'in', test_leads.ids)]
search_res = self.env['crm.lead'].search(_domain, limit=None, offset=0, order=_order)
self.assertEqual(expected_leads_asc.ids, search_res.ids)
search_res = self.env['crm.lead'].search(_domain, limit=4, offset=0, order=_order)
self.assertEqual(expected_leads_asc[:4].ids, search_res.ids)
search_res = self.env['crm.lead'].search(_domain, limit=4, offset=3, order=_order)
self.assertEqual(expected_leads_asc[3:7].ids, search_res.ids)
search_res = self.env['crm.lead'].search(_domain, limit=None, offset=3, order=_order)
self.assertEqual(expected_leads_asc[3:].ids, search_res.ids)
_order = 'my_activity_date_deadline DESC, %s' % default_order
search_res = self.env['crm.lead'].search(_domain, limit=None, offset=0, order=_order)
self.assertEqual(expected_leads_desc.ids, search_res.ids)
search_res = self.env['crm.lead'].search(_domain, limit=4, offset=0, order=_order)
self.assertEqual(expected_leads_desc[:4].ids, search_res.ids)
search_res = self.env['crm.lead'].search(_domain, limit=4, offset=3, order=_order)
self.assertEqual(expected_leads_desc[3:7].ids, search_res.ids)
search_res = self.env['crm.lead'].search(_domain, limit=None, offset=3, order=_order)
self.assertEqual(expected_leads_desc[3:].ids, search_res.ids)
def test_crm_activity_recipients(self):
""" This test case checks
- no internal subtype followed by client
- activity subtype are not default ones
- only activity followers are recipients when this kind of activity is logged
"""
# Add explicitly a the client as follower
self.lead_1.message_subscribe(partner_ids=[self.contact_1.id])
# Check the client is not follower of any internal subtype
internal_subtypes = self.lead_1.message_follower_ids.filtered(lambda fol: fol.partner_id == self.contact_1).mapped('subtype_ids').filtered(lambda subtype: subtype.internal)
self.assertFalse(internal_subtypes)
# Add sale manager as follower of default subtypes
self.lead_1.message_subscribe(partner_ids=[self.user_sales_manager.partner_id.id], subtype_ids=[self.env.ref('mail.mt_activities').id, self.env.ref('mail.mt_comment').id])
activity = self.env['mail.activity'].with_user(self.user_sales_leads).create({
'activity_type_id': self.activity_type_1.id,
'note': 'Content of the activity to log',
'res_id': self.lead_1.id,
'res_model_id': self.env.ref('crm.model_crm_lead').id,
})
activity._onchange_activity_type_id()
self.assertEqual(self.lead_1.activity_type_id, self.activity_type_1)
self.assertEqual(self.lead_1.activity_summary, self.activity_type_1.summary)
# self.assertEqual(self.lead.activity_date_deadline, self.activity_type_1.summary)
# mark as done, check lead and posted message
activity.action_done()
self.assertFalse(self.lead_1.activity_type_id.id)
self.assertFalse(self.lead_1.activity_ids)
activity_message = self.lead_1.message_ids[0]
self.assertEqual(activity_message.notified_partner_ids, self.user_sales_manager.partner_id)
self.assertEqual(activity_message.subtype_id, self.env.ref('mail.mt_activities'))
def test_crm_activity_next_action(self):
""" This test case set the next activity on a lead, log another, and schedule a third. """
# Add the next activity (like we set it from a form view)
lead_model_id = self.env['ir.model']._get('crm.lead').id
activity = self.env['mail.activity'].with_user(self.user_sales_manager).create({
'activity_type_id': self.activity_type_1.id,
'summary': 'My Own Summary',
'res_id': self.lead_1.id,
'res_model_id': lead_model_id,
})
activity._onchange_activity_type_id()
# Check the next activity is correct
self.assertEqual(self.lead_1.activity_summary, activity.summary)
self.assertEqual(self.lead_1.activity_type_id, activity.activity_type_id)
# self.assertEqual(fields.Datetime.from_string(self.lead.activity_date_deadline), datetime.now() + timedelta(days=activity.activity_type_id.days))
activity.write({
'activity_type_id': self.activity_type_2.id,
'summary': '',
'note': 'Content of the activity to log',
})
activity._onchange_activity_type_id()
self.assertEqual(self.lead_1.activity_summary, activity.activity_type_id.summary)
self.assertEqual(self.lead_1.activity_type_id, activity.activity_type_id)
# self.assertEqual(fields.Datetime.from_string(self.lead.activity_date_deadline), datetime.now() + timedelta(days=activity.activity_type_id.days))
activity.action_done()
# Check the next activity on the lead has been removed
self.assertFalse(self.lead_1.activity_type_id)
| 56.175141 | 9,943 |
1,681 |
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 CrmUpdateProbabilities(models.TransientModel):
_name = 'crm.lead.pls.update'
_description = "Update the probabilities"
def _get_default_pls_start_date(self):
pls_start_date_config = self.env['ir.config_parameter'].sudo().get_param('crm.pls_start_date')
return fields.Date.to_date(pls_start_date_config)
def _get_default_pls_fields(self):
pls_fields_config = self.env['ir.config_parameter'].sudo().get_param('crm.pls_fields')
if pls_fields_config:
names = pls_fields_config.split(',')
fields = self.env['ir.model.fields'].search([('name', 'in', names), ('model', '=', 'crm.lead')])
return self.env['crm.lead.scoring.frequency.field'].search([('field_id', 'in', fields.ids)])
else:
return None
pls_start_date = fields.Date(required=True, default=_get_default_pls_start_date)
pls_fields = fields.Many2many('crm.lead.scoring.frequency.field', default=_get_default_pls_fields)
def action_update_crm_lead_probabilities(self):
if self.env.user._is_admin():
set_param = self.env['ir.config_parameter'].sudo().set_param
if self.pls_fields:
pls_fields_str = ','.join(self.pls_fields.mapped('field_id.name'))
set_param('crm.pls_fields', pls_fields_str)
else:
set_param('crm.pls_fields', "")
set_param('crm.pls_start_date', str(self.pls_start_date))
self.env['crm.lead'].sudo()._cron_update_automated_probabilities()
| 46.694444 | 1,681 |
7,258 |
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.tools.translate import _
class Lead2OpportunityPartner(models.TransientModel):
_name = 'crm.lead2opportunity.partner'
_description = 'Convert Lead to Opportunity (not in mass)'
@api.model
def default_get(self, fields):
""" Allow support of active_id / active_model instead of jut default_lead_id
to ease window action definitions, and be backward compatible. """
result = super(Lead2OpportunityPartner, self).default_get(fields)
if not result.get('lead_id') and self.env.context.get('active_id'):
result['lead_id'] = self.env.context.get('active_id')
return result
name = fields.Selection([
('convert', 'Convert to opportunity'),
('merge', 'Merge with existing opportunities')
], 'Conversion Action', compute='_compute_name', readonly=False, store=True, compute_sudo=False)
action = fields.Selection([
('create', 'Create a new customer'),
('exist', 'Link to an existing customer'),
('nothing', 'Do not link to a customer')
], string='Related Customer', compute='_compute_action', readonly=False, store=True, compute_sudo=False)
lead_id = fields.Many2one('crm.lead', 'Associated Lead', required=True)
duplicated_lead_ids = fields.Many2many(
'crm.lead', string='Opportunities', context={'active_test': False},
compute='_compute_duplicated_lead_ids', readonly=False, store=True, compute_sudo=False)
partner_id = fields.Many2one(
'res.partner', 'Customer',
compute='_compute_partner_id', readonly=False, store=True, compute_sudo=False)
user_id = fields.Many2one(
'res.users', 'Salesperson',
compute='_compute_user_id', readonly=False, store=True, compute_sudo=False)
team_id = fields.Many2one(
'crm.team', 'Sales Team',
compute='_compute_team_id', readonly=False, store=True, compute_sudo=False)
force_assignment = fields.Boolean(
'Force assignment', default=True,
help='If checked, forces salesman to be updated on updated opportunities even if already set.')
@api.depends('duplicated_lead_ids')
def _compute_name(self):
for convert in self:
if not convert.name:
convert.name = 'merge' if convert.duplicated_lead_ids and len(convert.duplicated_lead_ids) >= 2 else 'convert'
@api.depends('lead_id')
def _compute_action(self):
for convert in self:
if not convert.lead_id:
convert.action = 'nothing'
else:
partner = convert.lead_id._find_matching_partner()
if partner:
convert.action = 'exist'
elif convert.lead_id.contact_name:
convert.action = 'create'
else:
convert.action = 'nothing'
@api.depends('lead_id', 'partner_id')
def _compute_duplicated_lead_ids(self):
for convert in self:
if not convert.lead_id:
convert.duplicated_lead_ids = False
continue
convert.duplicated_lead_ids = self.env['crm.lead']._get_lead_duplicates(
convert.partner_id,
convert.lead_id.partner_id.email if convert.lead_id.partner_id.email else convert.lead_id.email_from,
include_lost=True).ids
@api.depends('action', 'lead_id')
def _compute_partner_id(self):
for convert in self:
if convert.action == 'exist':
convert.partner_id = convert.lead_id._find_matching_partner()
else:
convert.partner_id = False
@api.depends('lead_id')
def _compute_user_id(self):
for convert in self:
convert.user_id = convert.lead_id.user_id if convert.lead_id.user_id else False
@api.depends('user_id')
def _compute_team_id(self):
""" When changing the user, also set a team_id or restrict team id
to the ones user_id is member of. """
for convert in self:
# setting user as void should not trigger a new team computation
if not convert.user_id:
continue
user = convert.user_id
if convert.team_id and user in convert.team_id.member_ids | convert.team_id.user_id:
continue
team = self.env['crm.team']._get_default_team_id(user_id=user.id, domain=None)
convert.team_id = team.id
@api.model
def view_init(self, fields):
# JEM TDE FIXME: clean that brol
""" Check some preconditions before the wizard executes. """
for lead in self.env['crm.lead'].browse(self._context.get('active_ids', [])):
if lead.probability == 100:
raise UserError(_("Closed/Dead leads cannot be converted into opportunities."))
return False
def action_apply(self):
if self.name == 'merge':
result_opportunity = self._action_merge()
else:
result_opportunity = self._action_convert()
return result_opportunity.redirect_lead_opportunity_view()
def _action_merge(self):
to_merge = self.duplicated_lead_ids
result_opportunity = to_merge.merge_opportunity(auto_unlink=False)
result_opportunity.action_unarchive()
if result_opportunity.type == "lead":
self._convert_and_allocate(result_opportunity, [self.user_id.id], team_id=self.team_id.id)
else:
if not result_opportunity.user_id or self.force_assignment:
result_opportunity.write({
'user_id': self.user_id.id,
'team_id': self.team_id.id,
})
(to_merge - result_opportunity).sudo().unlink()
return result_opportunity
def _action_convert(self):
""" """
result_opportunities = self.env['crm.lead'].browse(self._context.get('active_ids', []))
self._convert_and_allocate(result_opportunities, [self.user_id.id], team_id=self.team_id.id)
return result_opportunities[0]
def _convert_and_allocate(self, leads, user_ids, team_id=False):
self.ensure_one()
for lead in leads:
if lead.active and self.action != 'nothing':
self._convert_handle_partner(
lead, self.action, self.partner_id.id or lead.partner_id.id)
lead.convert_opportunity(lead.partner_id.id, user_ids=False, team_id=False)
leads_to_allocate = leads
if not self.force_assignment:
leads_to_allocate = leads_to_allocate.filtered(lambda lead: not lead.user_id)
if user_ids:
leads_to_allocate._handle_salesmen_assignment(user_ids, team_id=team_id)
def _convert_handle_partner(self, lead, action, partner_id):
# used to propagate user_id (salesman) on created partners during conversion
lead.with_context(default_user_id=self.user_id.id)._handle_partner_assignment(
force_partner_id=partner_id,
create_missing=(action == 'create')
)
| 42.946746 | 7,258 |
437 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models
class CrmLeadLost(models.TransientModel):
_name = 'crm.lead.lost'
_description = 'Get Lost Reason'
lost_reason_id = fields.Many2one('crm.lost.reason', 'Lost Reason')
def action_lost_reason_apply(self):
leads = self.env['crm.lead'].browse(self.env.context.get('active_ids'))
return leads.action_set_lost(lost_reason=self.lost_reason_id.id)
| 31.214286 | 437 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.