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
|
|---|---|---|---|---|---|---|
1,041
|
py
|
PYTHON
|
15.0
|
{
"name": "Taiwan - Accounting",
"author": "Odoo PS",
"version": "1.0",
"category": "Accounting/Localizations/Account Charts",
"description": """
This is the base module to manage the accounting chart for Taiwan in Odoo.
==============================================================================
""",
"depends": [
"account",
"base_address_city",
"l10n_multilang",
],
"data": [
"data/l10n_tw_chart_data.xml",
"data/account.account.template.csv",
"data/res.country.state.csv",
"data/account_chart_template_data.xml",
"data/account.tax.group.csv",
"data/account_tax_template_data.xml",
"data/account_chart_template_configure_data.xml",
"data/res_currency_data.xml",
"data/res_country_data.xml",
"data/res.city.csv",
],
'demo': [
'demo/demo_company.xml',
],
"icon": "/base/static/img/country_flags/tw.png",
"post_init_hook": "load_translations",
"license": "LGPL-3",
}
| 31.545455
| 1,041
|
1,235
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) David Arnold (XOE Solutions).
# Author David Arnold (XOE Solutions), dar@xoe.solutions
# Co-Authors Juan Pablo Aries (devCO), jpa@devco.co
# Hector Ivan Valencia Muñoz (TIX SAS)
# Nhomar Hernandez (Vauxoo)
# Humberto Ochoa (Vauxoo)
{
'name': 'Colombia - Accounting',
'version': '0.8',
'category': 'Accounting/Localizations/Account Charts',
'description': 'Colombian Accounting and Tax Preconfiguration',
'author': 'David Arnold (XOE Solutions)',
'website': 'https://www.odoo.com/colombia',
'depends': [
'account',
'base_address_city',
'account_debit_note',
'l10n_latam_base',
],
'data': [
'data/l10n_co_chart_data.xml',
'data/account.account.template.csv',
'data/account_chart_template_data.xml',
'data/account.tax.group.csv',
'data/account_tax_template.xml',
'data/account_chart_template_configure_data.xml',
'data/l10n_latam.identification.type.csv',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 33.351351
| 1,234
|
255
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class L10nCoDocumentType(models.Model):
_inherit = "l10n_latam.identification.type"
l10n_co_document_code = fields.Char("Document Code")
| 31.875
| 255
|
941
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.constrains('vat', 'country_id', 'l10n_latam_identification_type_id')
def check_vat(self):
# check_vat is implemented by base_vat which this localization
# doesn't directly depend on. It is however automatically
# installed for Colombia.
if self.sudo().env.ref('base.module_base_vat').state == 'installed':
# don't check Colombian partners unless they have RUT (= Colombian VAT) set as document type
self = self.filtered(lambda partner: partner.country_id.code != "CO" or\
partner.l10n_latam_identification_type_id.l10n_co_document_code == 'rut')
return super(ResPartner, self).check_vat()
else:
return True
| 47.05
| 941
|
775
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Website Mail Group",
'summary': "Add a website snippet for the mail groups.",
'description': "",
'version': '1.0',
'depends': ['mail_group', 'website'],
'auto_install': True,
'data': [
'views/snippets/s_group.xml',
'views/snippets/snippets.xml',
'views/mail_group_views.xml',
'views/website_mail_group_menus.xml',
],
'assets': {
'website.assets_wysiwyg': [
'website_mail_group/static/src/snippets/s_group/options.js',
],
'web.assets_frontend': [
'website_mail_group/static/src/snippets/s_group/000.js',
],
},
'license': 'LGPL-3',
}
| 29.807692
| 775
|
475
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.addons.http_routing.models.ir_http import slug
class MailGroup(models.Model):
_name = 'mail.group'
_inherit = 'mail.group'
def action_go_to_website(self):
self.ensure_one()
return {
'type': 'ir.actions.act_url',
'target': 'self',
'url': '/groups/%s' % slug(self),
}
| 26.388889
| 475
|
1,270
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.exceptions import AccessError
from odoo.http import request
class WebsiteMailGroup(http.Controller):
@http.route('/group/is_member', type='json', auth='public', website=True)
def group_is_member(self, group_id=0, email=None, **kw):
"""Return the email of the member if found, otherwise None."""
group = request.env['mail.group'].browse(int(group_id)).exists()
if not group:
return
token = kw.get('token')
if token and token != group._generate_group_access_token():
return
if token:
group = group.sudo()
try:
group.check_access_rights('read')
group.check_access_rule('read')
except AccessError:
return
if not request.env.user._is_public():
email = request.env.user.email_normalized
partner_id = request.env.user.partner_id.id
else:
partner_id = None
member = group.sudo()._find_member(email, partner_id)
return {
'is_member': bool(member),
'email': member.email if member else email,
}
| 30.238095
| 1,270
|
672
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'IoT Box Homepage',
'category': 'Sales/Point of Sale',
'sequence': 6,
'website': 'https://www.odoo.com/app/point-of-sale-hardware',
'summary': 'A homepage for the IoT Box',
'description': """
IoT Box Homepage
================
This module overrides Odoo web interface to display a simple
Homepage that explains what's the iotbox and shows the status,
and where to find documentation.
If you activate this module, you won't be able to access the
regular Odoo interface anymore.
""",
'installable': False,
'license': 'LGPL-3',
}
| 28
| 672
|
16,769
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import jinja2
import logging
import os
from pathlib import Path
import socket
import subprocess
import sys
import threading
from odoo import http
from odoo.http import Response
from odoo.modules.module import get_resource_path
from odoo.addons.hw_drivers.main import iot_devices
from odoo.addons.hw_drivers.tools import helpers
from odoo.addons.web.controllers import main as web
_logger = logging.getLogger(__name__)
#----------------------------------------------------------
# Controllers
#----------------------------------------------------------
if hasattr(sys, 'frozen'):
# When running on compiled windows binary, we don't have access to package loader.
path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views'))
loader = jinja2.FileSystemLoader(path)
else:
loader = jinja2.PackageLoader('odoo.addons.hw_posbox_homepage', "views")
jinja_env = jinja2.Environment(loader=loader, autoescape=True)
jinja_env.filters["json"] = json.dumps
homepage_template = jinja_env.get_template('homepage.html')
server_config_template = jinja_env.get_template('server_config.html')
wifi_config_template = jinja_env.get_template('wifi_config.html')
handler_list_template = jinja_env.get_template('handler_list.html')
remote_connect_template = jinja_env.get_template('remote_connect.html')
configure_wizard_template = jinja_env.get_template('configure_wizard.html')
six_payment_terminal_template = jinja_env.get_template('six_payment_terminal.html')
list_credential_template = jinja_env.get_template('list_credential.html')
upgrade_page_template = jinja_env.get_template('upgrade_page.html')
class IoTboxHomepage(web.Home):
def __init__(self):
super(IoTboxHomepage,self).__init__()
self.updating = threading.Lock()
def clean_partition(self):
subprocess.check_call(['sudo', 'bash', '-c', '. /home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/upgrade.sh; cleanup'])
def get_six_terminal(self):
terminal_id = helpers.read_file_first_line('odoo-six-payment-terminal.conf')
return terminal_id or 'Not Configured'
def get_homepage_data(self):
hostname = str(socket.gethostname())
ssid = helpers.get_ssid()
wired = subprocess.check_output(['cat', '/sys/class/net/eth0/operstate']).decode('utf-8').strip('\n')
if wired == 'up':
network = 'Ethernet'
elif ssid:
if helpers.access_point():
network = 'Wifi access point'
else:
network = 'Wifi : ' + ssid
else:
network = 'Not Connected'
is_certificate_ok, certificate_details = helpers.get_certificate_status()
iot_device = []
for device in iot_devices:
iot_device.append({
'name': iot_devices[device].device_name + ' : ' + str(iot_devices[device].data['value']),
'type': iot_devices[device].device_type.replace('_', ' '),
'identifier': iot_devices[device].device_identifier,
})
return {
'hostname': hostname,
'ip': helpers.get_ip(),
'mac': helpers.get_mac_address(),
'iot_device_status': iot_device,
'server_status': helpers.get_odoo_server_url() or 'Not Configured',
'six_terminal': self.get_six_terminal(),
'network_status': network,
'version': helpers.get_version(),
'is_certificate_ok': is_certificate_ok,
'certificate_details': certificate_details,
}
@http.route('/', type='http', auth='none')
def index(self):
wifi = Path.home() / 'wifi_network.txt'
remote_server = Path.home() / 'odoo-remote-server.conf'
if (wifi.exists() == False or remote_server.exists() == False) and helpers.access_point():
return "<meta http-equiv='refresh' content='0; url=http://" + helpers.get_ip() + ":8069/steps'>"
else:
return homepage_template.render(self.get_homepage_data())
@http.route('/list_handlers', type='http', auth='none', website=True)
def list_handlers(self):
drivers_list = []
for driver in os.listdir(get_resource_path('hw_drivers', 'iot_handlers/drivers')):
if driver != '__pycache__':
drivers_list.append(driver)
interfaces_list = []
for interface in os.listdir(get_resource_path('hw_drivers', 'iot_handlers/interfaces')):
if interface != '__pycache__':
interfaces_list.append(interface)
return handler_list_template.render({
'title': "Odoo's IoT Box - Handlers list",
'breadcrumb': 'Handlers list',
'drivers_list': drivers_list,
'interfaces_list': interfaces_list,
'server': helpers.get_odoo_server_url()
})
@http.route('/load_iot_handlers', type='http', auth='none', website=True)
def load_iot_handlers(self):
helpers.download_iot_handlers(False)
subprocess.check_call(["sudo", "service", "odoo", "restart"])
return "<meta http-equiv='refresh' content='20; url=http://" + helpers.get_ip() + ":8069/list_handlers'>"
@http.route('/list_credential', type='http', auth='none', website=True)
def list_credential(self):
return list_credential_template.render({
'title': "Odoo's IoT Box - List credential",
'breadcrumb': 'List credential',
'db_uuid': helpers.read_file_first_line('odoo-db-uuid.conf'),
'enterprise_code': helpers.read_file_first_line('odoo-enterprise-code.conf'),
})
@http.route('/save_credential', type='http', auth='none', cors='*', csrf=False)
def save_credential(self, db_uuid, enterprise_code):
helpers.add_credential(db_uuid, enterprise_code)
subprocess.check_call(["sudo", "service", "odoo", "restart"])
return "<meta http-equiv='refresh' content='20; url=http://" + helpers.get_ip() + ":8069'>"
@http.route('/clear_credential', type='http', auth='none', cors='*', csrf=False)
def clear_credential(self):
helpers.unlink_file('odoo-db-uuid.conf')
helpers.unlink_file('odoo-enterprise-code.conf')
subprocess.check_call(["sudo", "service", "odoo", "restart"])
return "<meta http-equiv='refresh' content='20; url=http://" + helpers.get_ip() + ":8069'>"
@http.route('/wifi', type='http', auth='none', website=True)
def wifi(self):
return wifi_config_template.render({
'title': 'Wifi configuration',
'breadcrumb': 'Configure Wifi',
'loading_message': 'Connecting to Wifi',
'ssid': helpers.get_wifi_essid(),
})
@http.route('/wifi_connect', type='http', auth='none', cors='*', csrf=False)
def connect_to_wifi(self, essid, password, persistent=False):
if persistent:
persistent = "1"
else:
persistent = ""
subprocess.check_call([get_resource_path('point_of_sale', 'tools/posbox/configuration/connect_to_wifi.sh'), essid, password, persistent])
server = helpers.get_odoo_server_url()
res_payload = {
'message': 'Connecting to ' + essid,
}
if server:
res_payload['server'] = {
'url': server,
'message': 'Redirect to Odoo Server'
}
else:
res_payload['server'] = {
'url': 'http://' + helpers.get_ip() + ':8069',
'message': 'Redirect to IoT Box'
}
return json.dumps(res_payload)
@http.route('/wifi_clear', type='http', auth='none', cors='*', csrf=False)
def clear_wifi_configuration(self):
helpers.unlink_file('wifi_network.txt')
return "<meta http-equiv='refresh' content='0; url=http://" + helpers.get_ip() + ":8069'>"
@http.route('/server_clear', type='http', auth='none', cors='*', csrf=False)
def clear_server_configuration(self):
helpers.unlink_file('odoo-remote-server.conf')
return "<meta http-equiv='refresh' content='0; url=http://" + helpers.get_ip() + ":8069'>"
@http.route('/handlers_clear', type='http', auth='none', cors='*', csrf=False)
def clear_handlers_list(self):
for directory in ['drivers', 'interfaces']:
for file in os.listdir(get_resource_path('hw_drivers', 'iot_handlers', directory)):
if file != '__pycache__':
helpers.unlink_file(get_resource_path('hw_drivers', 'iot_handlers', directory, file))
return "<meta http-equiv='refresh' content='0; url=http://" + helpers.get_ip() + ":8069/list_handlers'>"
@http.route('/server_connect', type='http', auth='none', cors='*', csrf=False)
def connect_to_server(self, token, iotname):
if token:
credential = token.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)
else:
url = helpers.get_odoo_server_url()
token = helpers.get_token()
reboot = 'reboot'
subprocess.check_call([get_resource_path('point_of_sale', 'tools/posbox/configuration/connect_to_server.sh'), url, iotname, token, reboot])
return 'http://' + helpers.get_ip() + ':8069'
@http.route('/steps', type='http', auth='none', cors='*', csrf=False)
def step_by_step_configure_page(self):
return configure_wizard_template.render({
'title': 'Configure IoT Box',
'breadcrumb': 'Configure IoT Box',
'loading_message': 'Configuring your IoT Box',
'ssid': helpers.get_wifi_essid(),
'server': helpers.get_odoo_server_url() or '',
'hostname': subprocess.check_output('hostname').decode('utf-8').strip('\n'),
})
@http.route('/step_configure', type='http', auth='none', cors='*', csrf=False)
def step_by_step_configure(self, token, iotname, essid, password, persistent=False):
if token:
url = token.split('|')[0]
token = token.split('|')[1]
else:
url = ''
subprocess.check_call([get_resource_path('point_of_sale', 'tools/posbox/configuration/connect_to_server_wifi.sh'), url, iotname, token, essid, password, persistent])
return url
# Set server address
@http.route('/server', type='http', auth='none', website=True)
def server(self):
return server_config_template.render({
'title': 'IoT -> Odoo server configuration',
'breadcrumb': 'Configure Odoo Server',
'hostname': subprocess.check_output('hostname').decode('utf-8').strip('\n'),
'server_status': helpers.get_odoo_server_url() or 'Not configured yet',
'loading_message': 'Configure Domain Server'
})
@http.route('/remote_connect', type='http', auth='none', cors='*')
def remote_connect(self):
"""
Establish a link with a customer box trough internet with a ssh tunnel
1 - take a new auth_token on https://dashboard.ngrok.com/
2 - copy past this auth_token on the IoT Box : http://IoT_Box:8069/remote_connect
3 - check on ngrok the port and url to get access to the box
4 - you can connect to the box with this command : ssh -p port -v pi@url
"""
return remote_connect_template.render({
'title': 'Remote debugging',
'breadcrumb': 'Remote Debugging',
})
@http.route('/enable_ngrok', type='http', auth='none', cors='*', csrf=False)
def enable_ngrok(self, auth_token):
if subprocess.call(['pgrep', 'ngrok']) == 1:
subprocess.Popen(['ngrok', 'tcp', '-authtoken', auth_token, '-log', '/tmp/ngrok.log', '22'])
return 'starting with ' + auth_token
else:
return 'already running'
@http.route('/six_payment_terminal', type='http', auth='none', cors='*', csrf=False)
def six_payment_terminal(self):
return six_payment_terminal_template.render({
'title': 'Six Payment Terminal',
'breadcrumb': 'Six Payment Terminal',
'terminalId': self.get_six_terminal(),
})
@http.route('/six_payment_terminal_add', type='http', auth='none', cors='*', csrf=False)
def add_six_payment_terminal(self, terminal_id):
helpers.write_file('odoo-six-payment-terminal.conf', terminal_id)
subprocess.check_call(["sudo", "service", "odoo", "restart"])
return 'http://' + helpers.get_ip() + ':8069'
@http.route('/six_payment_terminal_clear', type='http', auth='none', cors='*', csrf=False)
def clear_six_payment_terminal(self):
helpers.unlink_file('odoo-six-payment-terminal.conf')
subprocess.check_call(["sudo", "service", "odoo", "restart"])
return "<meta http-equiv='refresh' content='0; url=http://" + helpers.get_ip() + ":8069'>"
@http.route('/hw_proxy/upgrade', type='http', auth='none', )
def upgrade(self):
commit = subprocess.check_output(["git", "--work-tree=/home/pi/odoo/", "--git-dir=/home/pi/odoo/.git", "log", "-1"]).decode('utf-8').replace("\n", "<br/>")
flashToVersion = helpers.check_image()
actualVersion = helpers.get_version()
if flashToVersion:
flashToVersion = '%s.%s' % (flashToVersion.get('major', ''), flashToVersion.get('minor', ''))
return upgrade_page_template.render({
'title': "Odoo's IoTBox - Software Upgrade",
'breadcrumb': 'IoT Box Software Upgrade',
'loading_message': 'Updating IoT box',
'commit': commit,
'flashToVersion': flashToVersion,
'actualVersion': actualVersion,
})
@http.route('/hw_proxy/perform_upgrade', type='http', auth='none')
def perform_upgrade(self):
self.updating.acquire()
os.system('/home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/posbox_update.sh')
self.updating.release()
return 'SUCCESS'
@http.route('/hw_proxy/get_version', type='http', auth='none')
def check_version(self):
return helpers.get_version()
@http.route('/hw_proxy/perform_flashing_create_partition', type='http', auth='none')
def perform_flashing_create_partition(self):
try:
response = subprocess.check_output(['sudo', 'bash', '-c', '. /home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/upgrade.sh; create_partition']).decode().split('\n')[-2]
if response in ['Error_Card_Size', 'Error_Upgrade_Already_Started']:
raise Exception(response)
return Response('success', status=200)
except subprocess.CalledProcessError as e:
raise Exception(e.output)
except Exception as e:
_logger.error('A error encountered : %s ' % e)
return Response(str(e), status=500)
@http.route('/hw_proxy/perform_flashing_download_raspios', type='http', auth='none')
def perform_flashing_download_raspios(self):
try:
response = subprocess.check_output(['sudo', 'bash', '-c', '. /home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/upgrade.sh; download_raspios']).decode().split('\n')[-2]
if response == 'Error_Raspios_Download':
raise Exception(response)
return Response('success', status=200)
except subprocess.CalledProcessError as e:
raise Exception(e.output)
except Exception as e:
self.clean_partition()
_logger.error('A error encountered : %s ' % e)
return Response(str(e), status=500)
@http.route('/hw_proxy/perform_flashing_copy_raspios', type='http', auth='none')
def perform_flashing_copy_raspios(self):
try:
response = subprocess.check_output(['sudo', 'bash', '-c', '. /home/pi/odoo/addons/point_of_sale/tools/posbox/configuration/upgrade.sh; copy_raspios']).decode().split('\n')[-2]
if response == 'Error_Iotbox_Download':
raise Exception(response)
return Response('success', status=200)
except subprocess.CalledProcessError as e:
raise Exception(e.output)
except Exception as e:
self.clean_partition()
_logger.error('A error encountered : %s ' % e)
return Response(str(e), status=500)
| 46.195592
| 16,769
|
1,073
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Sales Teams',
'version': '1.1',
'category': 'Sales/Sales',
'summary': 'Sales Teams',
'description': """
Using this application you can manage Sales Teams with CRM and/or Sales
=======================================================================
""",
'website': 'https://www.odoo.com/app/crm',
'depends': ['base', 'mail'],
'data': [
'security/sales_team_security.xml',
'security/ir.model.access.csv',
'data/crm_team_data.xml',
'views/crm_tag_views.xml',
'views/crm_team_views.xml',
'views/crm_team_member_views.xml',
'views/mail_activity_views.xml',
'views/res_partner_views.xml',
],
'demo': [
'data/crm_team_demo.xml',
'data/crm_tag_demo.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'web.assets_backend': [
'sales_team/static/**/*',
],
},
'license': 'LGPL-3',
}
| 29
| 1,073
|
16,610
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import exceptions
from odoo.addons.sales_team.tests.common import TestSalesCommon
from odoo.tests.common import users
from odoo.tools import mute_logger
class TestMembership(TestSalesCommon):
"""Tests to ensure membership behavior """
@classmethod
def setUpClass(cls):
super(TestMembership, cls).setUpClass()
cls.new_team = cls.env['crm.team'].create({
'name': 'Test Specific',
'sequence': 10,
})
cls.env['ir.config_parameter'].set_param('sales_team.membership_multi', True)
@users('user_sales_manager')
def test_fields(self):
self.assertTrue(self.sales_team_1.with_user(self.env.user).is_membership_multi)
self.assertTrue(self.new_team.with_user(self.env.user).is_membership_multi)
self.env['ir.config_parameter'].sudo().set_param('sales_team.membership_multi', False)
self.assertFalse(self.sales_team_1.with_user(self.env.user).is_membership_multi)
self.assertFalse(self.new_team.with_user(self.env.user).is_membership_multi)
@users('user_sales_manager')
def test_members_mono(self):
""" Test mono mode using the user m2m relationship """
self.env['ir.config_parameter'].sudo().set_param('sales_team.membership_multi', False)
# ensure initial data
sales_team_1 = self.sales_team_1.with_user(self.env.user)
new_team = self.new_team.with_user(self.env.user)
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
# test various add / remove on computed m2m
self.assertEqual(new_team.member_ids, self.env['res.users'])
new_team.write({'member_ids': [(4, self.env.uid)]})
self.assertEqual(new_team.member_ids, self.env.user)
new_team.write({'member_ids': [(4, self.user_sales_leads.id)]})
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
new_team.write({'member_ids': [(3, self.user_sales_leads.id)]})
self.assertEqual(new_team.member_ids, self.env.user)
new_team.write({'member_ids': [(6, 0, (self.user_sales_leads | self.env.user).ids)]})
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
# archived memberships on sales_team_1 for user_sales_leads
self.assertEqual(sales_team_1.member_ids, self.user_admin)
# create a new user on the fly, just for testing
self.user_sales_manager.write({'groups_id': [(4, self.env.ref('base.group_system').id)]})
new_team.write({'member_ids': [(0, 0, {
'name': 'Marty OnTheMCFly',
'login': 'mcfly@test.example.com',
})]})
new_user = self.env['res.users'].search([('login', '=', 'mcfly@test.example.com')])
self.assertTrue(len(new_user))
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads | new_user)
self.user_sales_manager.write({'groups_id': [(3, self.env.ref('base.group_system').id)]})
new_team.flush()
memberships = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)])
self.assertEqual(len(memberships), 3) # subscribed twice to new_team + subscribed to sales_team_1
self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team)
self.assertFalse(memberships.filtered(lambda m: m.crm_team_id == sales_team_1).active)
new_team_memberships = memberships.filtered(lambda m: m.crm_team_id == new_team)
self.assertEqual(len(new_team_memberships), 2) # subscribed, removed, then subscribed again
self.assertTrue(set(new_team_memberships.mapped('active')), set([False, True]))
# still avoid duplicated team / user entries
with self.assertRaises(exceptions.UserError):
self.env['crm.team.member'].create({'crm_team_id': new_team.id, 'user_id': new_user.id})
@users('user_sales_manager')
def test_members_multi(self):
# ensure initial data
sales_team_1 = self.sales_team_1.with_user(self.env.user)
new_team = self.new_team.with_user(self.env.user)
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
# test various add / remove on computed m2m
self.assertEqual(new_team.member_ids, self.env['res.users'])
new_team.write({'member_ids': [(4, self.env.uid), (4, self.user_sales_leads.id)]})
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
new_team.write({'member_ids': [(3, self.user_sales_leads.id)]})
self.assertEqual(new_team.member_ids, self.env.user)
new_team.write({'member_ids': [(6, 0, (self.user_sales_leads | self.env.user).ids)]})
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
# nothing changed on sales_team_1
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
# create a new user on the fly, just for testing
self.user_sales_manager.write({'groups_id': [(4, self.env.ref('base.group_system').id)]})
new_team.write({'member_ids': [(0, 0, {
'name': 'Marty OnTheMCFly',
'login': 'mcfly@test.example.com',
})]})
new_user = self.env['res.users'].search([('login', '=', 'mcfly@test.example.com')])
self.assertTrue(len(new_user))
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads | new_user)
self.user_sales_manager.write({'groups_id': [(3, self.env.ref('base.group_system').id)]})
new_team.flush()
# still avoid duplicated team / user entries
with self.assertRaises(exceptions.UserError):
self.env['crm.team.member'].create({'crm_team_id': new_team.id, 'user_id': new_user.id})
@users('user_sales_manager')
def test_memberships_mono(self):
""" Test mono mode: updating crm_team_member_ids field """
self.env['ir.config_parameter'].sudo().set_param('sales_team.membership_multi', False)
# ensure initial data
sales_team_1 = self.env['crm.team'].browse(self.sales_team_1.ids)
new_team = self.env['crm.team'].browse(self.new_team.ids)
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
# subscribe on new team (user_sales_leads will have two memberships -> old one deactivated)
self.assertEqual(new_team.member_ids, self.env['res.users'])
new_team.write({'crm_team_member_ids': [
(0, 0, {'user_id': self.user_sales_leads.id}),
(0, 0, {'user_id': self.uid}),
]})
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
self.assertEqual(sales_team_1.member_ids, self.user_admin)
new_team.flush()
memberships = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)])
self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team)
self.assertFalse(memberships.filtered(lambda m: m.crm_team_id == sales_team_1).active)
self.assertTrue(memberships.filtered(lambda m: m.crm_team_id == new_team).active)
# subscribe user_sales_leads on old team -> old membership still archived and kept
sales_team_1.write({'crm_team_member_ids': [(0, 0, {'user_id': self.user_sales_leads.id})]})
memberships_new = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)])
self.assertTrue(memberships < memberships_new)
self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team)
# old membership is still inactive, new membership is active
old_st_1 = memberships_new.filtered(lambda m: m.crm_team_id == sales_team_1 and m in memberships)
new_st_1 = memberships_new.filtered(lambda m: m.crm_team_id == sales_team_1 and m not in memberships)
new_nt = memberships_new.filtered(lambda m: m.crm_team_id == new_team)
self.assertFalse(old_st_1.active)
self.assertTrue(new_st_1.active)
self.assertFalse(new_nt.active)
# check members fields
self.assertEqual(new_team.member_ids, self.env.user)
self.assertEqual(sales_team_1.member_ids, self.user_admin | self.user_sales_leads)
# activate another team membership: previous team membership should be de activated
new_nt.toggle_active()
self.assertTrue(new_nt.active)
self.assertFalse(old_st_1.active)
self.assertFalse(new_st_1.active)
# activate another team membership: previous team membership should be de activated
old_st_1.toggle_active()
self.assertFalse(new_nt.active)
self.assertTrue(old_st_1.active)
self.assertFalse(new_st_1.active)
# try to activate duplicate memberships again, which should trigger issues
with self.assertRaises(exceptions.UserError):
new_st_1.toggle_active()
@users('user_sales_manager')
def test_memberships_multi(self):
# ensure initial data
sales_team_1 = self.env['crm.team'].browse(self.sales_team_1.ids)
new_team = self.env['crm.team'].browse(self.new_team.ids)
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
# subscribe on new team (user_sales_leads will have two memberships -> old one deactivated)
self.assertEqual(new_team.member_ids, self.env['res.users'])
new_team.write({'crm_team_member_ids': [
(0, 0, {'user_id': self.user_sales_leads.id}),
(0, 0, {'user_id': self.uid}),
]})
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
new_team.flush()
memberships = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)])
self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team)
self.assertTrue(memberships.filtered(lambda m: m.crm_team_id == sales_team_1).active)
self.assertTrue(memberships.filtered(lambda m: m.crm_team_id == new_team).active)
# archive membership on sales_team_1 and try creating a new one
memberships.filtered(lambda m: m.crm_team_id == sales_team_1).write({'active': False})
# subscribe user_sales_leads on old team -> old membership still archived and kept
sales_team_1.write({'crm_team_member_ids': [(0, 0, {'user_id': self.user_sales_leads.id})]})
memberships_new = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)])
self.assertTrue(memberships < memberships_new)
self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team)
# old membership is still inactive, new membership is active
old_st_1 = memberships_new.filtered(lambda m: m.crm_team_id == sales_team_1 and m in memberships)
new_st_1 = memberships_new.filtered(lambda m: m.crm_team_id == sales_team_1 and m not in memberships)
new_nt = memberships_new.filtered(lambda m: m.crm_team_id == new_team)
self.assertFalse(old_st_1.active)
self.assertTrue(new_st_1.active)
self.assertTrue(new_nt.active)
# check members fields
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
self.assertEqual(sales_team_1.member_ids, self.user_admin | self.user_sales_leads)
# try to activate duplicate memberships again, which should trigger issues
with self.assertRaises(exceptions.UserError):
old_st_1.toggle_active()
@users('user_sales_manager')
def test_memberships_sync(self):
sales_team_1 = self.env['crm.team'].browse(self.sales_team_1.ids)
new_team = self.env['crm.team'].browse(self.new_team.ids)
self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin)
self.assertEqual(new_team.crm_team_member_ids, self.env['crm.team.member'])
self.assertEqual(new_team.crm_team_member_all_ids, self.env['crm.team.member'])
self.assertEqual(new_team.member_ids, self.env['res.users'])
# creating memberships correctly updates m2m without any refresh
new_member = self.env['crm.team.member'].create({
'user_id': self.env.user.id,
'crm_team_id': self.new_team.id,
})
self.assertEqual(new_team.crm_team_member_ids, new_member)
self.assertEqual(new_team.crm_team_member_all_ids, new_member)
self.assertEqual(new_team.member_ids, self.env.user)
# adding members correctly update o2m with right values
new_team.write({
'member_ids': [(4, self.user_sales_leads.id)]
})
added = self.env['crm.team.member'].search([('crm_team_id', '=', new_team.id), ('user_id', '=', self.user_sales_leads.id)])
self.assertEqual(new_team.crm_team_member_ids, new_member + added)
self.assertEqual(new_team.crm_team_member_all_ids, new_member + added)
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
# archiving membership correctly updates m2m and o2m
added.write({'active': False})
self.assertEqual(new_team.crm_team_member_ids, new_member)
self.assertEqual(new_team.crm_team_member_all_ids, new_member + added)
self.assertEqual(new_team.member_ids, self.env.user)
# reactivating correctly updates m2m and o2m
added.write({'active': True})
self.assertEqual(new_team.crm_team_member_ids, new_member + added)
self.assertEqual(new_team.crm_team_member_all_ids, new_member + added)
self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads)
# archived are kept if duplicated on write
admin_original = self.env['crm.team.member'].search([
('crm_team_id', '=', sales_team_1.id),
('user_id', '=', self.user_admin.id)
])
self.assertTrue(bool(admin_original))
admin_archived = self.env['crm.team.member'].create({
'crm_team_id': new_team.id,
'user_id': self.user_admin.id,
'active': False,
})
admin_original.write({'crm_team_id': new_team.id})
# send to db as errors may pop at that step (like trying to set NULL on a m2o inverse of o2m)
self.new_team.flush()
self.assertTrue(self.user_admin in new_team.member_ids)
self.assertTrue(admin_original.active)
self.assertTrue(admin_archived.exists())
self.assertFalse(admin_archived.active)
# change team of membership should raise unicity constraint
with self.assertRaises(exceptions.UserError), mute_logger('odoo.sql_db'):
added.write({'crm_team_id': sales_team_1.id})
self.new_team.flush()
def test_users_sale_team_id(self):
self.assertTrue(self.sales_team_1.sequence < self.new_team.sequence)
self.assertEqual(self.user_sales_leads.crm_team_ids, self.sales_team_1)
self.assertEqual(self.user_sales_leads.sale_team_id, self.sales_team_1)
# subscribe to new team -> default team is still the old one
self.new_team.write({
'member_ids': [(4, self.user_sales_leads.id)]
})
self.assertEqual(self.user_sales_leads.crm_team_ids, self.sales_team_1 | self.new_team)
self.assertEqual(self.user_sales_leads.sale_team_id, self.sales_team_1)
# archive membership to first team -> second one becomes default
self.sales_team_1_m1.write({'active': False})
self.assertEqual(self.user_sales_leads.crm_team_ids, self.new_team)
self.assertEqual(self.user_sales_leads.sale_team_id, self.new_team)
# activate membership to first team -> first one becomes default again
self.sales_team_1_m1.write({'active': True})
self.assertEqual(self.user_sales_leads.crm_team_ids, self.sales_team_1 | self.new_team)
self.assertEqual(self.user_sales_leads.sale_team_id, self.sales_team_1)
# keep only one membership -> default team
self.sales_team_1_m1.unlink()
self.assertEqual(self.user_sales_leads.crm_team_ids, self.new_team)
self.assertEqual(self.user_sales_leads.sale_team_id, self.new_team)
| 54.459016
| 16,610
|
3,645
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import exceptions
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.sales_team.tests.common import TestSalesMC
from odoo.tests.common import users, TransactionCase
from odoo.tools import mute_logger
class TestCornerCases(TransactionCase):
def setUp(self):
super(TestCornerCases, self).setUp()
self.user_sales_leads = mail_new_test_user(
self.env, login='user_sales_leads',
name='Laetitia Sales Leads', email='crm_leads@test.example.com',
company_id=self.env.user.company_id.id,
notification_type='inbox',
groups='sales_team.group_sale_salesman_all_leads,base.group_partner_manager',
)
self.sales_team_1 = self.env['crm.team'].create({
'name': 'Test Sales Team',
'sequence': 5,
'company_id': False,
'user_id': self.env.user.id,
})
def test_unicity(self):
""" Archived memberships should be removed when detecting duplicates.
Creating duplicates should raise unicity constraint.
Note: redoing the data set to avoid clashing with SavepointCase as
we expect a db-level assert """
sales_team_1_m1 = self.env['crm.team.member'].create({
'user_id': self.user_sales_leads.id,
'crm_team_id': self.sales_team_1.id,
})
sales_team_1_m1.write({'active': False})
sales_team_1_m1.flush()
sales_team_1_m2 = self.env['crm.team.member'].create({
'user_id': self.user_sales_leads.id,
'crm_team_id': self.sales_team_1.id,
})
found = self.env['crm.team.member'].search([
('user_id', '=', self.user_sales_leads.id),
('crm_team_id', '=', self.sales_team_1.id),
])
self.assertEqual(found, sales_team_1_m2)
with self.assertRaises(exceptions.UserError), mute_logger('odoo.sql_db'):
self.env['crm.team.member'].create({
'user_id': self.user_sales_leads.id,
'crm_team_id': self.sales_team_1.id,
})
def test_unicity_multicreate(self):
""" Test constraint works with creating duplicates in the same create
method. """
with self.assertRaises(exceptions.UserError), mute_logger('odoo.sql_db'):
self.env['crm.team.member'].create([
{'user_id': self.user_sales_leads.id, 'crm_team_id': self.sales_team_1.id},
{'user_id': self.user_sales_leads.id, 'crm_team_id': self.sales_team_1.id}
])
class TestSecurity(TestSalesMC):
@users('user_sales_leads')
def test_team_access(self):
sales_team = self.sales_team_1.with_user(self.env.user)
sales_team.read(['name'])
for member in sales_team.member_ids:
member.read(['name'])
with self.assertRaises(exceptions.AccessError):
sales_team.write({'name': 'Trolling'})
for membership in sales_team.crm_team_member_ids:
membership.read(['name'])
with self.assertRaises(exceptions.AccessError):
membership.write({'active': False})
with self.assertRaises(exceptions.AccessError):
sales_team.write({'member_ids': [(5, 0)]})
@users('user_sales_leads')
def test_team_multi_company(self):
self.sales_team_1.with_user(self.env.user).read(['name'])
with self.assertRaises(exceptions.AccessError):
self.team_c2.with_user(self.env.user).read(['name'])
| 38.368421
| 3,645
|
9,033
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import exceptions
from odoo.addons.sales_team.tests.common import TestSalesCommon, TestSalesMC
from odoo.tests.common import users
class TestDefaultTeam(TestSalesCommon):
"""Tests to check if correct default team is found."""
@classmethod
def setUpClass(cls):
"""Set up data for default team tests."""
super(TestDefaultTeam, cls).setUpClass()
cls.env['ir.config_parameter'].set_param('sales_team.membership_multi', True)
# Salesmen organization
# ------------------------------------------------------------
# Role: M (team member) R (team manager)
# SALESMAN---------------sales_team_1---C2Team1---LowSequ---Team3
# admin------------------M-------------- --------- ---------
# user_sales_manager-----R-------------- --------- ---------R
# user_sales_leads-------M-------------- ---------M---------
# user_sales_salesman----/-------------- --------- ---------
# Sales teams organization
# ------------------------------------------------------------
# SALESTEAM-----------SEQU-----COMPANY
# LowSequence---------0--------False
# C2Team1-------------1--------C2
# Team3---------------3--------Main
# sales_team_1--------5--------False
# data----------------9999-----??
cls.company_2 = cls.env['res.company'].create({
'name': 'New Test Company',
'email': 'company.2@test.example.com',
'country_id': cls.env.ref('base.fr').id,
})
cls.team_c2 = cls.env['crm.team'].create({
'name': 'C2 Team1',
'sequence': 1,
'company_id': cls.company_2.id,
'user_id': False,
})
cls.team_sequence = cls.env['crm.team'].create({
'company_id': False,
'name': 'Team LowSequence',
'member_ids': [(4, cls.user_sales_leads.id)],
'sequence': 0,
'user_id': False,
})
cls.team_responsible = cls.env['crm.team'].create({
'company_id': cls.company_main.id,
'name': 'Team 3',
'user_id': cls.user_sales_manager.id,
'sequence': 3,
})
def test_default_team_fallback(self):
""" Test fallbacks when computing default team without any memberships:
domain, order """
self.sales_team_1.member_ids = [(5,)]
self.team_sequence.member_ids = [(5,)]
(self.sales_team_1 + self.team_sequence).flush()
self.assertFalse(self.env['crm.team.member'].search([('user_id', '=', self.user_sales_leads.id)]))
# default is better sequence matching company criterion
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_sequence)
# next one is team_responsible with sequence = 3 (team_c2 is in another company)
self.team_sequence.active = False
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_responsible)
self.user_sales_leads.write({
'company_ids': [(4, self.company_2.id)],
'company_id': self.company_2.id,
})
# multi company: switch company
self.user_sales_leads.write({
'company_id': self.company_2.id,
'company_ids': [(4, self.company_2.id)],
})
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_c2)
def test_default_team_member(self):
""" Test default team choice based on sequence, when having several
possible choices due to membership """
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_sequence)
self.team_sequence.member_ids = [(5,)]
self.team_sequence.flush()
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.sales_team_1)
# responsible with lower sequence better than member with higher sequence
self.team_responsible.user_id = self.user_sales_leads.id
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_responsible)
# in case of same sequence: take latest team
self.team_responsible.sequence = self.sales_team_1.sequence
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_responsible)
def test_default_team_wcontext(self):
""" Test default team choice when having a value in context """
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_sequence)
team = self.env['crm.team'].with_context(
default_team_id=self.sales_team_1.id
)._get_default_team_id()
self.assertEqual(
team, self.sales_team_1,
'SalesTeam: default takes over ordering when member / responsible'
)
# remove all memberships
self.sales_team_1.member_ids = [(5,)]
self.team_sequence.member_ids = [(5,)]
(self.sales_team_1 + self.team_sequence).flush()
self.assertFalse(self.env['crm.team.member'].search([('user_id', '=', self.user_sales_leads.id)]))
with self.with_user('user_sales_leads'):
team = self.env['crm.team']._get_default_team_id()
self.assertEqual(team, self.team_sequence)
team = self.env['crm.team'].with_context(
default_team_id=self.sales_team_1.id
)._get_default_team_id()
self.assertEqual(
team, self.sales_team_1,
'SalesTeam: default taken into account when no member / responsible'
)
class TestMultiCompany(TestSalesMC):
"""Tests to check multi company management with sales team and their
members. """
@users('user_sales_manager')
def test_team_members(self):
""" Test update of team users involving company check """
team_c2 = self.env['crm.team'].browse(self.team_c2.id)
team_c2.write({'name': 'Manager Update'})
self.assertEqual(team_c2.member_ids, self.env['res.users'])
# can add someone from same company
self.env.user.write({'company_id': self.company_2.id})
team_c2.write({'member_ids': [(4, self.env.user.id)]})
self.assertEqual(team_c2.member_ids, self.env.user)
# cannot add someone from another company
with self.assertRaises(exceptions.UserError):
team_c2.write({'member_ids': [(4, self.user_sales_salesman.id)]})
# reset members, change company
team_c2.write({'member_ids': [(5, 0)], 'company_id': self.company_main.id})
self.assertEqual(team_c2.member_ids, self.env['res.users'])
team_c2.write({'member_ids': [(4, self.user_sales_salesman.id)]})
self.assertEqual(team_c2.member_ids, self.user_sales_salesman)
# cannot change company as it breaks memberships mc check
with self.assertRaises(exceptions.UserError):
team_c2.write({'company_id': self.company_2.id})
@users('user_sales_manager')
def test_team_memberships(self):
""" Test update of team member involving company check """
team_c2 = self.env['crm.team'].browse(self.team_c2.id)
team_c2.write({'name': 'Manager Update'})
self.assertEqual(team_c2.member_ids, self.env['res.users'])
# can add someone from same company
self.env.user.write({'company_id': self.company_2.id})
team_c2.write({'crm_team_member_ids': [(0, 0, {'user_id': self.env.user.id})]})
self.assertEqual(team_c2.member_ids, self.env.user)
# cannot add someone from another company
with self.assertRaises(exceptions.UserError):
team_c2.write({'crm_team_member_ids': [(0, 0, {'user_id': self.user_sales_salesman.id})]})
# reset members, change company
team_c2.write({'member_ids': [(5, 0)], 'company_id': self.company_main.id})
self.assertEqual(team_c2.member_ids, self.env['res.users'])
team_c2.write({'crm_team_member_ids': [(0, 0, {'user_id': self.user_sales_salesman.id})]})
self.assertEqual(team_c2.member_ids, self.user_sales_salesman)
# cannot change company as it breaks memberships mc check
with self.assertRaises(exceptions.UserError):
team_c2.write({'company_id': self.company_2.id})
| 44.279412
| 9,033
|
4,000
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.tests.common import TransactionCase
class TestSalesCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestSalesCommon, cls).setUpClass()
cls.env['ir.config_parameter'].set_param('sales_team.membership_multi', False)
# 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.company_main = cls.env.user.company_id
cls.user_admin = cls.env.ref('base.user_admin')
cls.user_sales_manager = mail_new_test_user(
cls.env, login='user_sales_manager',
name='Martin Sales Manager', email='crm_manager@test.example.com',
company_id=cls.company_main.id,
notification_type='inbox',
groups='sales_team.group_sale_manager,base.group_partner_manager',
)
cls.user_sales_leads = mail_new_test_user(
cls.env, login='user_sales_leads',
name='Laetitia Sales Leads', email='crm_leads@test.example.com',
company_id=cls.company_main.id,
notification_type='inbox',
groups='sales_team.group_sale_salesman_all_leads,base.group_partner_manager',
)
cls.user_sales_salesman = mail_new_test_user(
cls.env, login='user_sales_salesman',
name='Orteil Sales Own', email='crm_salesman@test.example.com',
company_id=cls.company_main.id,
notification_type='inbox',
groups='sales_team.group_sale_salesman',
)
cls.user_admin = cls.env.ref('base.user_admin')
cls.env['crm.team'].search([]).write({'sequence': 9999})
cls.sales_team_1 = cls.env['crm.team'].create({
'name': 'Test Sales Team',
'sequence': 5,
'company_id': False,
'user_id': cls.user_sales_manager.id,
})
cls.sales_team_1_m1 = cls.env['crm.team.member'].create({
'user_id': cls.user_sales_leads.id,
'crm_team_id': cls.sales_team_1.id,
})
cls.sales_team_1_m2 = cls.env['crm.team.member'].create({
'user_id': cls.user_admin.id,
'crm_team_id': cls.sales_team_1.id,
})
class TestSalesMC(TestSalesCommon):
""" Multi Company / Multi Sales Team environment """
@classmethod
def setUpClass(cls):
""" Teams / Company
* sales_team_1: False
* team_c2: company_2
* team_mc: company_main
"""
super(TestSalesMC, cls).setUpClass()
cls.company_2 = cls.env['res.company'].create({
'name': 'New Test Company',
'email': 'company.2@test.example.com',
'country_id': cls.env.ref('base.fr').id,
})
cls.team_c2 = cls.env['crm.team'].create({
'name': 'C2 Team1',
'sequence': 1,
'user_id': False,
'company_id': cls.company_2.id,
})
cls.team_mc = cls.env['crm.team'].create({
'name': 'MainCompany Team',
'user_id': cls.user_admin.id,
'sequence': 3,
'company_id': cls.company_main.id
})
# admin and sale manager belong to new company also
(cls.user_admin | cls.user_sales_manager).write({
'company_ids': [(4, cls.company_2.id)]
})
| 38.095238
| 4,000
|
17,801
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import random
from babel.dates import format_date
from datetime import date
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.release import version
class CrmTeam(models.Model):
_name = "crm.team"
_inherit = ['mail.thread']
_description = "Sales Team"
_order = "sequence ASC, create_date DESC, id DESC"
_check_company_auto = True
def _get_default_team_id(self, user_id=None, domain=None):
""" Compute default team id for sales related documents. Note that this
method is not called by default_get as it takes some additional
parameters and is meant to be called by other default methods.
Heuristic (when multiple match: take from default context value or first
sequence ordered)
1- any of my teams (member OR responsible) matching domain, either from
context or based on _order;
2- any of my teams (member OR responsible), either from context or based
on _order;
3- default from context
4- any team matching my company and domain (based on company rule)
5- any team matching my company (based on company rule)
Note: ResPartner.team_id field is explicitly not taken into account. We
think this field causes a lot of noises compared to its added value.
Think notably: team not in responsible teams, team company not matching
responsible or lead company, asked domain not matching, ...
:param user_id: salesperson to target, fallback on env.uid;
:domain: optional domain to filter teams (like use_lead = True);
"""
if user_id is None:
user = self.env.user
else:
user = self.env['res.users'].sudo().browse(user_id)
default_team = self.env['crm.team'].browse(
self.env.context['default_team_id']
) if self.env.context.get('default_team_id') else self.env['crm.team']
valid_cids = [False] + [c for c in user.company_ids.ids if c in self.env.companies.ids]
# 1- find in user memberships - note that if current user in C1 searches
# for team belonging to a user in C1/C2 -> only results for C1 will be returned
team = self.env['crm.team']
teams = self.env['crm.team'].search([
('company_id', 'in', valid_cids),
'|', ('user_id', '=', user.id), ('member_ids', 'in', [user.id])
])
if teams and domain:
filtered_teams = teams.filtered_domain(domain)
if default_team and default_team in filtered_teams:
team = default_team
else:
team = filtered_teams[:1]
# 2- any of my teams
if not team:
if default_team and default_team in teams:
team = default_team
else:
team = teams[:1]
# 3- default: context
if not team and default_team:
team = default_team
if not team:
teams = self.env['crm.team'].search([('company_id', 'in', valid_cids)])
# 4- default: based on company rule, first one matching domain
if teams and domain:
team = teams.filtered_domain(domain)[:1]
# 5- default: based on company rule, first one
if not team:
team = teams[:1]
return team
def _get_default_favorite_user_ids(self):
return [(6, 0, [self.env.uid])]
# description
name = fields.Char('Sales Team', required=True, translate=True)
sequence = fields.Integer('Sequence', default=10)
active = fields.Boolean(default=True, help="If the active field is set to false, it will allow you to hide the Sales Team without removing it.")
company_id = fields.Many2one(
'res.company', string='Company', index=True,
default=lambda self: self.env.company)
currency_id = fields.Many2one(
"res.currency", string="Currency",
related='company_id.currency_id', readonly=True)
user_id = fields.Many2one('res.users', string='Team Leader', check_company=True)
# memberships
is_membership_multi = fields.Boolean(
'Multiple Memberships Allowed', compute='_compute_is_membership_multi',
help='If True, users may belong to several sales teams. Otherwise membership is limited to a single sales team.')
member_ids = fields.Many2many(
'res.users', string='Salespersons',
domain="['&', ('share', '=', False), ('company_ids', 'in', member_company_ids)]",
compute='_compute_member_ids', inverse='_inverse_member_ids', search='_search_member_ids',
help="Users assigned to this team.")
member_company_ids = fields.Many2many(
'res.company', compute='_compute_member_company_ids',
help='UX: Limit to team company or all if no company')
member_warning = fields.Text('Membership Issue Warning', compute='_compute_member_warning')
crm_team_member_ids = fields.One2many(
'crm.team.member', 'crm_team_id', string='Sales Team Members',
help="Add members to automatically assign their documents to this sales team.")
crm_team_member_all_ids = fields.One2many(
'crm.team.member', 'crm_team_id', string='Sales Team Members (incl. inactive)',
context={'active_test': False})
# UX options
color = fields.Integer(string='Color Index', help="The color of the channel")
favorite_user_ids = fields.Many2many(
'res.users', 'team_favorite_user_rel', 'team_id', 'user_id',
string='Favorite Members', default=_get_default_favorite_user_ids)
is_favorite = fields.Boolean(
string='Show on dashboard', compute='_compute_is_favorite', inverse='_inverse_is_favorite',
help="Favorite teams to display them in the dashboard and access them easily.")
dashboard_button_name = fields.Char(string="Dashboard Button", compute='_compute_dashboard_button_name')
dashboard_graph_data = fields.Text(compute='_compute_dashboard_graph')
@api.depends('sequence') # TDE FIXME: force compute in new mode
def _compute_is_membership_multi(self):
multi_enabled = self.env['ir.config_parameter'].sudo().get_param('sales_team.membership_multi', False)
self.is_membership_multi = multi_enabled
@api.depends('crm_team_member_ids.active')
def _compute_member_ids(self):
for team in self:
team.member_ids = team.crm_team_member_ids.user_id
def _inverse_member_ids(self):
for team in self:
# pre-save value to avoid having _compute_member_ids interfering
# while building membership status
memberships = team.crm_team_member_ids
users_current = team.member_ids
users_new = users_current - memberships.user_id
# add missing memberships
self.env['crm.team.member'].create([{'crm_team_id': team.id, 'user_id': user.id} for user in users_new])
# activate or deactivate other memberships depending on members
for membership in memberships:
membership.active = membership.user_id in users_current
@api.depends('is_membership_multi', 'member_ids')
def _compute_member_warning(self):
""" Display a warning message to warn user they are about to archive
other memberships. Only valid in mono-membership mode and take into
account only active memberships as we may keep several archived
memberships. """
self.member_warning = False
if all(team.is_membership_multi for team in self):
return
# done in a loop, but to be used in form view only -> not optimized
for team in self:
member_warning = False
other_memberships = self.env['crm.team.member'].search([
('crm_team_id', '!=', team.id if team.ids else False), # handle NewID
('user_id', 'in', team.member_ids.ids)
])
if other_memberships and len(other_memberships) == 1:
member_warning = _("Adding %(user_name)s in this team would remove him/her from its current team %(team_name)s.",
user_name=other_memberships.user_id.name,
team_name=other_memberships.crm_team_id.name
)
elif other_memberships:
member_warning = _("Adding %(user_names)s in this team would remove them from their current teams (%(team_names)s).",
user_names=", ".join(other_memberships.mapped('user_id.name')),
team_names=", ".join(other_memberships.mapped('crm_team_id.name'))
)
if member_warning:
team.member_warning = member_warning + " " + _("To add a Salesperson into multiple Teams, activate the Multi-Team option in settings.")
def _search_member_ids(self, operator, value):
return [('crm_team_member_ids.user_id', operator, value)]
@api.depends('company_id')
def _compute_member_company_ids(self):
""" Available companies for members. Either team company if set, either
any company if not set on team. """
all_companies = self.env['res.company'].search([])
for team in self:
team.member_company_ids = team.company_id or all_companies
def _compute_is_favorite(self):
for team in self:
team.is_favorite = self.env.user in team.favorite_user_ids
def _inverse_is_favorite(self):
sudoed_self = self.sudo()
to_fav = sudoed_self.filtered(lambda team: self.env.user not in team.favorite_user_ids)
to_fav.write({'favorite_user_ids': [(4, self.env.uid)]})
(sudoed_self - to_fav).write({'favorite_user_ids': [(3, self.env.uid)]})
return True
def _compute_dashboard_button_name(self):
""" Sets the adequate dashboard button name depending on the Sales Team's options
"""
for team in self:
team.dashboard_button_name = _("Big Pretty Button :)") # placeholder
def _compute_dashboard_graph(self):
for team in self:
team.dashboard_graph_data = json.dumps(team._get_dashboard_graph_data())
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
teams = super(CrmTeam, self.with_context(mail_create_nosubscribe=True)).create(vals_list)
teams.filtered(lambda t: t.member_ids)._add_members_to_favorites()
return teams
def write(self, values):
res = super(CrmTeam, self).write(values)
# manually launch company sanity check
if values.get('company_id'):
self.crm_team_member_ids._check_company(fnames=['crm_team_id'])
if values.get('member_ids'):
self._add_members_to_favorites()
return res
@api.ondelete(at_uninstall=False)
def _unlink_except_default(self):
default_teams = [
self.env.ref('sales_team.salesteam_website_sales'),
self.env.ref('sales_team.pos_sales_team'),
self.env.ref('sales_team.ebay_sales_team')
]
for team in self:
if team in default_teams:
raise UserError(_('Cannot delete default team "%s"', team.name))
# ------------------------------------------------------------
# ACTIONS
# ------------------------------------------------------------
def action_primary_channel_button(self):
""" Skeleton function to be overloaded It will return the adequate action
depending on the Sales Team's options. """
return False
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
def _add_members_to_favorites(self):
for team in self:
team.favorite_user_ids = [(4, member.id) for member in team.member_ids]
# ------------------------------------------------------------
# GRAPH
# ------------------------------------------------------------
def _graph_get_model(self):
""" skeleton function defined here because it'll be called by crm and/or sale
"""
raise UserError(_('Undefined graph model for Sales Team: %s', self.name))
def _graph_get_dates(self, today):
""" return a coherent start and end date for the dashboard graph covering a month period grouped by week.
"""
start_date = today - relativedelta(months=1)
# we take the start of the following week if we group by week
# (to avoid having twice the same week from different month)
start_date += relativedelta(days=8 - start_date.isocalendar()[2])
return [start_date, today]
def _graph_date_column(self):
return 'create_date'
def _graph_x_query(self):
return 'EXTRACT(WEEK FROM %s)' % self._graph_date_column()
def _graph_y_query(self):
raise UserError(_('Undefined graph model for Sales Team: %s', self.name))
def _extra_sql_conditions(self):
return ''
def _graph_title_and_key(self):
""" Returns an array containing the appropriate graph title and key respectively.
The key is for lineCharts, to have the on-hover label.
"""
return ['', '']
def _graph_data(self, start_date, end_date):
""" return format should be an iterable of dicts that contain {'x_value': ..., 'y_value': ...}
x_values should be weeks.
y_values are floats.
"""
query = """SELECT %(x_query)s as x_value, %(y_query)s as y_value
FROM %(table)s
WHERE team_id = %(team_id)s
AND DATE(%(date_column)s) >= %(start_date)s
AND DATE(%(date_column)s) <= %(end_date)s
%(extra_conditions)s
GROUP BY x_value;"""
# apply rules
dashboard_graph_model = self._graph_get_model()
GraphModel = self.env[dashboard_graph_model]
graph_table = GraphModel._table
extra_conditions = self._extra_sql_conditions()
where_query = GraphModel._where_calc([])
GraphModel._apply_ir_rules(where_query, 'read')
from_clause, where_clause, where_clause_params = where_query.get_sql()
if where_clause:
extra_conditions += " AND " + where_clause
query = query % {
'x_query': self._graph_x_query(),
'y_query': self._graph_y_query(),
'table': graph_table,
'team_id': "%s",
'date_column': self._graph_date_column(),
'start_date': "%s",
'end_date': "%s",
'extra_conditions': extra_conditions
}
self._cr.execute(query, [self.id, start_date, end_date] + where_clause_params)
return self.env.cr.dictfetchall()
def _get_dashboard_graph_data(self):
def get_week_name(start_date, locale):
""" Generates a week name (string) from a datetime according to the locale:
E.g.: locale start_date (datetime) return string
"en_US" November 16th "16-22 Nov"
"en_US" December 28th "28 Dec-3 Jan"
"""
if (start_date + relativedelta(days=6)).month == start_date.month:
short_name_from = format_date(start_date, 'd', locale=locale)
else:
short_name_from = format_date(start_date, 'd MMM', locale=locale)
short_name_to = format_date(start_date + relativedelta(days=6), 'd MMM', locale=locale)
return short_name_from + '-' + short_name_to
self.ensure_one()
values = []
today = fields.Date.from_string(fields.Date.context_today(self))
start_date, end_date = self._graph_get_dates(today)
graph_data = self._graph_data(start_date, end_date)
x_field = 'label'
y_field = 'value'
# generate all required x_fields and update the y_values where we have data for them
locale = self._context.get('lang') or 'en_US'
weeks_in_start_year = int(date(start_date.year, 12, 28).isocalendar()[1]) # This date is always in the last week of ISO years
week_count = (end_date.isocalendar()[1] - start_date.isocalendar()[1]) % weeks_in_start_year + 1
for week in range(week_count):
short_name = get_week_name(start_date + relativedelta(days=7 * week), locale)
values.append({x_field: short_name, y_field: 0, 'type': 'future' if week + 1 == week_count else 'past'})
for data_item in graph_data:
index = int((data_item.get('x_value') - start_date.isocalendar()[1]) % weeks_in_start_year)
values[index][y_field] = data_item.get('y_value')
[graph_title, graph_key] = self._graph_title_and_key()
color = '#875A7B' if '+e' in version else '#7c7bad'
# If no actual data available, show some sample data
if not graph_data:
graph_key = _('Sample data')
for value in values:
value['type'] = 'o_sample_data'
# we use unrealistic values for the sample data
value['value'] = random.randint(0, 20)
return [{'values': values, 'area': True, 'title': graph_title, 'key': graph_key, 'color': color}]
| 45.64359
| 17,801
|
10,050
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, exceptions, fields, models, _
class CrmTeamMember(models.Model):
_name = 'crm.team.member'
_inherit = ['mail.thread']
_description = 'Sales Team Member'
_rec_name = 'user_id'
_order = 'create_date ASC'
_check_company_auto = True
crm_team_id = fields.Many2one(
'crm.team', string='Sales Team',
default=False, # TDE: temporary fix to activate depending computed fields
check_company=True, index=True, ondelete="cascade", required=True)
user_id = fields.Many2one(
'res.users', string='Salesperson', # TDE FIXME check responsible field
check_company=True, index=True, ondelete='cascade', required=True,
domain="[('share', '=', False), ('id', 'not in', user_in_teams_ids), ('company_ids', 'in', user_company_ids)]")
user_in_teams_ids = fields.Many2many(
'res.users', compute='_compute_user_in_teams_ids',
help='UX: Give users not to add in the currently chosen team to avoid duplicates')
user_company_ids = fields.Many2many(
'res.company', compute='_compute_user_company_ids',
help='UX: Limit to team company or all if no company')
active = fields.Boolean(string='Active', default=True)
is_membership_multi = fields.Boolean(
'Multiple Memberships Allowed', compute='_compute_is_membership_multi',
help='If True, users may belong to several sales teams. Otherwise membership is limited to a single sales team.')
member_warning = fields.Text(compute='_compute_member_warning')
# salesman information
image_1920 = fields.Image("Image", related="user_id.image_1920", max_width=1920, max_height=1920)
image_128 = fields.Image("Image (128)", related="user_id.image_128", max_width=128, max_height=128)
name = fields.Char(string='Name', related='user_id.display_name', readonly=False)
email = fields.Char(string='Email', related='user_id.email')
phone = fields.Char(string='Phone', related='user_id.phone')
mobile = fields.Char(string='Mobile', related='user_id.mobile')
company_id = fields.Many2one('res.company', string='Company', related='user_id.company_id')
@api.constrains('crm_team_id', 'user_id', 'active')
def _constrains_membership(self):
# In mono membership mode: check crm_team_id / user_id is unique for active
# memberships. Inactive memberships can create duplicate pairs which is whyy
# we don't use a SQL constraint. Include "self" in search in case we use create
# multi with duplicated user / team pairs in it. Use an explicit active leaf
# in domain as we may have an active_test in context that would break computation
existing = self.env['crm.team.member'].search([
('crm_team_id', 'in', self.crm_team_id.ids),
('user_id', 'in', self.user_id.ids),
('active', '=', True)
])
duplicates = self.env['crm.team.member']
active_records = dict(
(membership.user_id.id, membership.crm_team_id.id)
for membership in self if membership.active
)
for membership in self:
potential = existing.filtered(lambda m: m.user_id == membership.user_id and \
m.crm_team_id == membership.crm_team_id and m.id != membership.id
)
if not potential or len(potential) > 1:
duplicates += potential
continue
if active_records.get(potential.user_id.id):
duplicates += potential
else:
active_records[potential.user_id.id] = potential.crm_team_id.id
if duplicates:
raise exceptions.ValidationError(
_("You are trying to create duplicate membership(s). We found that %(duplicates)s already exist(s).",
duplicates=", ".join("%s (%s)" % (m.user_id.name, m.crm_team_id.name) for m in duplicates)
))
@api.depends('crm_team_id', 'is_membership_multi', 'user_id')
@api.depends_context('default_crm_team_id')
def _compute_user_in_teams_ids(self):
""" Give users not to add in the currently chosen team to avoid duplicates.
In multi membership mode this field is empty as duplicates are allowed. """
if all(m.is_membership_multi for m in self):
member_user_ids = self.env['res.users']
elif self.ids:
member_user_ids = self.env['crm.team.member'].search([('id', 'not in', self.ids)]).user_id
else:
member_user_ids = self.env['crm.team.member'].search([]).user_id
for member in self:
if member_user_ids:
member.user_in_teams_ids = member_user_ids
elif member.crm_team_id:
member.user_in_teams_ids = member.crm_team_id.member_ids
elif self.env.context.get('default_crm_team_id'):
member.user_in_teams_ids = self.env['crm.team'].browse(self.env.context['default_crm_team_id']).member_ids
else:
member.user_in_teams_ids = self.env['res.users']
@api.depends('crm_team_id')
def _compute_user_company_ids(self):
all_companies = self.env['res.company'].search([])
for member in self:
member.user_company_ids = member.crm_team_id.company_id or all_companies
@api.depends('crm_team_id')
def _compute_is_membership_multi(self):
multi_enabled = self.env['ir.config_parameter'].sudo().get_param('sales_team.membership_multi', False)
self.is_membership_multi = multi_enabled
@api.depends('is_membership_multi', 'active', 'user_id', 'crm_team_id')
def _compute_member_warning(self):
""" Display a warning message to warn user they are about to archive
other memberships. Only valid in mono-membership mode and take into
account only active memberships as we may keep several archived
memberships. """
if all(m.is_membership_multi for m in self):
self.member_warning = False
else:
active = self.filtered('active')
(self - active).member_warning = False
if not active:
return
existing = self.env['crm.team.member'].search([('user_id', 'in', active.user_id.ids)])
user_mapping = dict.fromkeys(existing.user_id, self.env['crm.team'])
for membership in existing:
user_mapping[membership.user_id] |= membership.crm_team_id
for member in active:
teams = user_mapping.get(member.user_id, self.env['crm.team'])
remaining = teams - (member.crm_team_id | member._origin.crm_team_id)
if remaining:
member.member_warning = _("Adding %(user_name)s in this team would remove him/her from its current teams %(team_names)s.",
user_name=member.user_id.name,
team_names=", ".join(remaining.mapped('name'))
)
else:
member.member_warning = False
@api.model_create_multi
def create(self, values_list):
""" Specific behavior implemented on create
* mono membership mode: other user memberships are automatically
archived (a warning already told it in form view);
* creating a membership already existing as archived: do nothing as
people can manage them from specific menu "Members";
"""
is_membership_multi = self.env['ir.config_parameter'].sudo().get_param('sales_team.membership_multi', False)
if not is_membership_multi:
self._synchronize_memberships(values_list)
return super(CrmTeamMember, self).create(values_list)
def write(self, values):
""" Specific behavior about active. If you change user_id / team_id user
get warnings in form view and a raise in constraint check. We support
archive / activation of memberships that toggles other memberships. But
we do not support manual creation or update of user_id / team_id. This
either works, either crashes). Indeed supporting it would lead to complex
code with low added value. Users should create or remove members, and
maybe archive / activate them. Updating manually memberships by
modifying user_id or team_id is advanced and does not benefit from our
support. """
is_membership_multi = self.env['ir.config_parameter'].sudo().get_param('sales_team.membership_multi', False)
if not is_membership_multi and values.get('active'):
self._synchronize_memberships([
dict(user_id=membership.user_id.id, crm_team_id=membership.crm_team_id.id)
for membership in self
])
return super(CrmTeamMember, self).write(values)
def _synchronize_memberships(self, user_team_ids):
""" Synchronize memberships: archive other memberships.
:param user_team_ids: list of pairs (user_id, crm_team_id)
"""
existing = self.search([
('active', '=', True), # explicit search on active only, whatever context
('user_id', 'in', [values['user_id'] for values in user_team_ids])
])
user_memberships = dict.fromkeys(existing.user_id.ids, self.env['crm.team.member'])
for membership in existing:
user_memberships[membership.user_id.id] += membership
existing_to_archive = self.env['crm.team.member']
for values in user_team_ids:
existing_to_archive += user_memberships.get(values['user_id'], self.env['crm.team.member']).filtered(
lambda m: m.crm_team_id.id != values['crm_team_id']
)
if existing_to_archive:
existing_to_archive.action_archive()
return existing_to_archive
| 51.538462
| 10,050
|
535
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from random import randint
from odoo import fields, models
class Tag(models.Model):
_name = "crm.tag"
_description = "CRM Tag"
def _get_default_color(self):
return randint(1, 11)
name = fields.Char('Tag Name', required=True, translate=True)
color = fields.Integer('Color', default=_get_default_color)
_sql_constraints = [
('name_uniq', 'unique (name)', "Tag name already exists !"),
]
| 25.47619
| 535
|
1,599
|
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 ResUsers(models.Model):
_inherit = 'res.users'
crm_team_ids = fields.Many2many(
'crm.team', 'crm_team_member', 'user_id', 'crm_team_id', string='Sales Teams',
check_company=True, copy=False, readonly=True,
compute='_compute_crm_team_ids', search='_search_crm_team_ids')
crm_team_member_ids = fields.One2many('crm.team.member', 'user_id', string='Sales Team Members')
sale_team_id = fields.Many2one(
'crm.team', string='User Sales Team', compute='_compute_sale_team_id',
readonly=True, store=True,
help="Main user sales team. Used notably for pipeline, or to set sales team in invoicing or subscription.")
@api.depends('crm_team_member_ids.active')
def _compute_crm_team_ids(self):
for user in self:
user.crm_team_ids = user.crm_team_member_ids.crm_team_id
def _search_crm_team_ids(self, operator, value):
return [('crm_team_member_ids.crm_team_id', operator, value)]
@api.depends('crm_team_member_ids.crm_team_id', 'crm_team_member_ids.create_date', 'crm_team_member_ids.active')
def _compute_sale_team_id(self):
for user in self:
if not user.crm_team_member_ids.ids:
user.sale_team_id = False
else:
sorted_memberships = user.crm_team_member_ids # sorted by create date
user.sale_team_id = sorted_memberships[0].crm_team_id if sorted_memberships else False
| 45.685714
| 1,599
|
364
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
team_id = fields.Many2one(
'crm.team', 'Sales Team',
help='If set, this Sales Team will be used for sales and assignments related to this partner')
| 30.333333
| 364
|
446
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Gift Card",
'summary': "Use gift card",
'description': """Integrate gift card mechanism""",
'category': 'Sales/Sales',
'version': '1.0',
'depends': ['product'],
'data': [
'data/gift_card_data.xml',
'views/views.xml',
'security/ir.model.access.csv',
],
'license': 'LGPL-3',
}
| 26.235294
| 446
|
795
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class ProductTemplate(models.Model):
_inherit = "product.template"
detailed_type = fields.Selection(selection_add=[
('gift', 'Gift Card'),
], ondelete={'gift': 'set service'})
def _detailed_type_mapping(self):
type_mapping = super()._detailed_type_mapping()
type_mapping['gift'] = 'service'
return type_mapping
@api.ondelete(at_uninstall=False)
def _unlink_gift_card_product(self):
if self.env.ref('gift_card.pay_with_gift_card_product').product_tmpl_id in self:
raise UserError(_('Deleting the Gift Card Pay product is not allowed.'))
| 34.565217
| 795
|
2,387
|
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 uuid import uuid4
class GiftCard(models.Model):
_name = "gift.card"
_description = "Gift Card"
_order = 'id desc'
_check_company_auto = True
@api.model
def _generate_code(self):
return '044' + str(uuid4())[4:-8][3:]
name = fields.Char(compute='_compute_name')
code = fields.Char(default=lambda x: x._generate_code(), required=True, readonly=True, copy=False)
partner_id = fields.Many2one('res.partner', help="If empty, all users can use it")
company_id = fields.Many2one('res.company', default=lambda self: self.env.company)
currency_id = fields.Many2one('res.currency', readonly=True, related='company_id.currency_id')
initial_amount = fields.Monetary(required=True, currency_field='currency_id')
balance = fields.Monetary(compute="_compute_balance") # in company currency
expired_date = fields.Date(default=lambda self: fields.Date.add(fields.Date.today(), years=1))
state = fields.Selection(
selection=[('valid', 'Valid'), ('expired', 'Expired')],
default='valid',
copy=False
)
_sql_constraints = [
('unique_gift_card_code', 'UNIQUE(code)', 'The gift card code must be unique.'),
('check_amount', 'CHECK(initial_amount >= 0)', 'The initial amount must be positive.')
]
def _compute_name(self):
for record in self:
record.name = _("Gift #%s", record.id)
@api.autovacuum
def _gc_mark_expired_gift_card(self):
self.env['gift.card'].search([
'&', ('state', '=', 'valid'), ('expired_date', '<', fields.Date.today())
]).write({'state': 'expired'})
def balance_converted(self, currency_id=False):
# helper to convert the current balance in the currency provided
return self.currency_id._convert(self.balance, currency_id, self.env.company, fields.Date.today())
def can_be_used(self):
# expired state are computed once a day, so can be not synchro
return self.state == 'valid' and self.balance > 0 and (not self.expired_date or self.expired_date >= fields.Date.today())
@api.depends("initial_amount")
def _compute_balance(self):
for record in self:
record.balance = record.initial_amount
| 41.155172
| 2,387
|
1,027
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Twitter Snippet',
'category': 'Website/Website',
'summary': 'Twitter scroller snippet in website',
'version': '1.0',
'description': """
This module adds a Twitter scroller building block to the website builder, so that you can display Twitter feeds on any page of your website.
""",
'depends': ['website'],
'data': [
'security/ir.model.access.csv',
'data/website_twitter_data.xml',
'views/res_config_settings_views.xml',
'views/website_twitter_snippet_templates.xml'
],
'installable': True,
'assets': {
'web.assets_frontend': [
'website_twitter/static/src/scss/website_twitter.scss',
'website_twitter/static/src/js/website.twitter.animation.js',
],
'website.assets_editor': [
'website_twitter/static/src/js/website.twitter.editor.js',
],
},
'license': 'LGPL-3',
}
| 34.233333
| 1,027
|
766
|
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 WebsiteTwitterTweet(models.Model):
_name = 'website.twitter.tweet'
_description = 'Website Twitter'
website_id = fields.Many2one('website', string='Website', ondelete='cascade')
screen_name = fields.Char(string='Screen Name')
tweet = fields.Text(string='Tweets')
# Twitter IDs are 64-bit unsigned ints, so we need to store them in
# unlimited precision NUMERIC columns, which can be done with a
# float field. Used digits=(0,0) to indicate unlimited.
# Using VARCHAR would work too but would have sorting problems.
tweet_id = fields.Float(string='Tweet ID', digits=(0, 0)) # Twitter
| 40.315789
| 766
|
4,114
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import requests
from odoo import api, fields, models, _, _lt
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
TWITTER_EXCEPTION = {
304: _lt('There was no new data to return.'),
400: _lt('The request was invalid or cannot be otherwise served. Requests without authentication are considered invalid and will yield this response.'),
401: _lt('Authentication credentials were missing or incorrect. Maybe screen name tweets are protected.'),
403: _lt('The request is understood, but it has been refused or access is not allowed. Please check your Twitter API Key and Secret.'),
429: _lt('Request cannot be served due to the applications rate limit having been exhausted for the resource.'),
500: _lt('Twitter seems broken. Please retry later. You may consider posting an issue on Twitter forums to get help.'),
502: _lt('Twitter is down or being upgraded.'),
503: _lt('The Twitter servers are up, but overloaded with requests. Try again later.'),
504: _lt('The Twitter servers are up, but the request could not be serviced due to some failure within our stack. Try again later.')
}
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
twitter_api_key = fields.Char(
related='website_id.twitter_api_key', readonly=False,
string='API Key',
help='Twitter API key you can get it from https://apps.twitter.com/')
twitter_api_secret = fields.Char(
related='website_id.twitter_api_secret', readonly=False,
string='API secret',
help='Twitter API secret you can get it from https://apps.twitter.com/')
twitter_screen_name = fields.Char(
related='website_id.twitter_screen_name', readonly=False,
string='Favorites From',
help='Screen Name of the Twitter Account from which you want to load favorites.'
'It does not have to match the API Key/Secret.')
twitter_server_uri = fields.Char(string='Twitter server uri', readonly=True)
def _get_twitter_exception_message(self, error_code):
if error_code in TWITTER_EXCEPTION:
return TWITTER_EXCEPTION[error_code]
else:
return _('HTTP Error: Something is misconfigured')
def _check_twitter_authorization(self):
try:
self.website_id.fetch_favorite_tweets()
except requests.HTTPError as e:
_logger.info("%s - %s" % (e.response.status_code, e.response.reason), exc_info=True)
raise UserError("%s - %s" % (e.response.status_code, e.response.reason) + ':' + self._get_twitter_exception_message(e.response.status_code))
except IOError:
_logger.info('We failed to reach a twitter server.', exc_info=True)
raise UserError(_('Internet connection refused: We failed to reach a twitter server.'))
except Exception:
_logger.info('Please double-check your Twitter API Key and Secret!', exc_info=True)
raise UserError(_('Twitter authorization error! Please double-check your Twitter API Key and Secret!'))
@api.model
def create(self, vals):
TwitterConfig = super(ResConfigSettings, self).create(vals)
if vals.get('twitter_api_key') or vals.get('twitter_api_secret') or vals.get('twitter_screen_name'):
TwitterConfig._check_twitter_authorization()
return TwitterConfig
def write(self, vals):
TwitterConfig = super(ResConfigSettings, self).write(vals)
if vals.get('twitter_api_key') or vals.get('twitter_api_secret') or vals.get('twitter_screen_name'):
self._check_twitter_authorization()
return TwitterConfig
@api.model
def get_values(self):
res = super(ResConfigSettings, self).get_values()
Params = self.env['ir.config_parameter'].sudo()
res.update({
'twitter_server_uri': '%s/' % Params.get_param('web.base.url', default='http://yourcompany.odoo.com'),
})
return res
| 48.97619
| 4,114
|
4,056
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import requests
from odoo import api, fields, models
API_ENDPOINT = 'https://api.twitter.com'
API_VERSION = '1.1'
REQUEST_TOKEN_URL = '%s/oauth2/token' % API_ENDPOINT
REQUEST_FAVORITE_LIST_URL = '%s/%s/favorites/list.json' % (API_ENDPOINT, API_VERSION)
URLOPEN_TIMEOUT = 10
_logger = logging.getLogger(__name__)
class WebsiteTwitter(models.Model):
_inherit = 'website'
twitter_api_key = fields.Char(string='Twitter API key', help='Twitter API Key')
twitter_api_secret = fields.Char(string='Twitter API secret', help='Twitter API Secret')
twitter_screen_name = fields.Char(string='Get favorites from this screen name')
@api.model
def _request(self, website, url, params=None):
"""Send an authenticated request to the Twitter API."""
access_token = self._get_access_token(website)
try:
request = requests.get(url, params=params, headers={'Authorization': 'Bearer %s' % access_token}, timeout=URLOPEN_TIMEOUT)
request.raise_for_status()
return request.json()
except requests.HTTPError as e:
_logger.debug("Twitter API request failed with code: %r, msg: %r, content: %r",
e.response.status_code, e.response.reason, e.response.content)
raise
@api.model
def _refresh_favorite_tweets(self):
''' called by cron job '''
website = self.env['website'].search([('twitter_api_key', '!=', False),
('twitter_api_secret', '!=', False),
('twitter_screen_name', '!=', False)])
_logger.debug("Refreshing tweets for website IDs: %r", website.ids)
website.fetch_favorite_tweets()
def fetch_favorite_tweets(self):
WebsiteTweets = self.env['website.twitter.tweet']
tweet_ids = []
for website in self:
if not all((website.twitter_api_key, website.twitter_api_secret, website.twitter_screen_name)):
_logger.debug("Skip fetching favorite tweets for unconfigured website %s", website)
continue
params = {'screen_name': website.twitter_screen_name}
last_tweet = WebsiteTweets.search([('website_id', '=', website.id),
('screen_name', '=', website.twitter_screen_name)],
limit=1, order='tweet_id desc')
if last_tweet:
params['since_id'] = int(last_tweet.tweet_id)
_logger.debug("Fetching favorite tweets using params %r", params)
response = self._request(website, REQUEST_FAVORITE_LIST_URL, params=params)
for tweet_dict in response:
tweet_id = tweet_dict['id'] # unsigned 64-bit snowflake ID
tweet_ids = WebsiteTweets.search([('tweet_id', '=', tweet_id)]).ids
if not tweet_ids:
new_tweet = WebsiteTweets.create(
{
'website_id': website.id,
'tweet': json.dumps(tweet_dict),
'tweet_id': tweet_id, # stored in NUMERIC PG field
'screen_name': website.twitter_screen_name,
})
_logger.debug("Found new favorite: %r, %r", tweet_id, tweet_dict)
tweet_ids.append(new_tweet.id)
return tweet_ids
def _get_access_token(self, website):
"""Obtain a bearer token."""
r = requests.post(
REQUEST_TOKEN_URL,
data={'grant_type': 'client_credentials',},
auth=(website.twitter_api_key, website.twitter_api_secret),
timeout=URLOPEN_TIMEOUT,
)
r.raise_for_status()
data = r.json()
access_token = data['access_token']
return access_token
| 45.573034
| 4,056
|
1,885
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import _
from odoo import http
from odoo.http import request
class Twitter(http.Controller):
@http.route(['/website_twitter/reload'], type='json', auth="user", website=True)
def twitter_reload(self):
return request.website.fetch_favorite_tweets()
@http.route(['/website_twitter/get_favorites'], type='json', auth="public", website=True)
def get_tweets(self, limit=20):
key = request.website.twitter_api_key
secret = request.website.twitter_api_secret
screen_name = request.website.twitter_screen_name
debug = request.env['res.users'].has_group('website.group_website_publisher')
if not key or not secret:
if debug:
return {"error": _("Please set the Twitter API Key and Secret in the Website Settings.")}
return []
if not screen_name:
if debug:
return {"error": _("Please set a Twitter screen name to load favorites from, "
"in the Website Settings (it does not have to be yours)")}
return []
TwitterTweets = request.env['website.twitter.tweet']
tweets = TwitterTweets.search(
[('website_id', '=', request.website.id),
('screen_name', '=', screen_name)],
limit=int(limit), order="tweet_id desc")
if len(tweets) < 12:
if debug:
return {"error": _("Twitter user @%(username)s has less than 12 favorite tweets. "
"Please add more or choose a different screen name.") % \
{'username': screen_name}}
else:
return []
return tweets.mapped(lambda t: json.loads(t.tweet))
| 44.880952
| 1,885
|
3,018
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Main contributor: Nicolas Bessi. Camptocamp SA
# Financial contributors: Hasa SA, Open Net SA,
# Prisme Solutions Informatique SA, Quod SA
# Translation contributors: brain-tec AG, Agile Business Group
{
'name': "Switzerland - Accounting",
'description': """
Swiss localization
==================
This module defines a chart of account for Switzerland (Swiss PME/KMU 2015), taxes and enables the generation of ISR and QR-bill when you print an invoice or send it by mail.
An ISR will be generated if you specify the information it needs :
- The bank account you expect to be paid on must be set, and have a valid postal reference.
- Your invoice must have been set assigned a bank account to receive its payment
(this can be done manually, but a default value is automatically set if you have defined a bank account).
- You must have set the postal references of your bank.
- Your invoice must be in EUR or CHF (as ISRs do not accept other currencies)
A QR-bill will be generated if:
- The partner set on your invoice has a complete address (street, city, postal code and country) in Switzerland
- The option to generate the Swiss QR-code is selected on the invoice (done by default)
- A correct account number/QR IBAN is set on your bank journal
- (when using a QR-IBAN): the payment reference of the invoice is a QR-reference
The generation of the ISR and QR-bill is automatic if you meet the previous criteria.
Here is how it works:
- Printing the invoice will trigger the download of three files: the invoice, its ISR and its QR-bill
- Clicking the 'Send by mail' button will attach three files to your draft mail : the invoice, the ISR and the QR-bill.
""",
'version': '11.1',
'category': 'Accounting/Localizations/Account Charts',
'depends': ['account', 'l10n_multilang', 'base_iban'],
'data': [
'data/l10n_ch_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_ch_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_report_data.xml',
'data/account_vat2011_data.xml',
'data/account_tax_template_data_2024.xml',
'data/account_fiscal_position_data.xml',
'data/account_fiscal_position_data_2024.xml',
'data/account_chart_template_data.xml',
'report/isr_report.xml',
'report/swissqr_report.xml',
'views/res_bank_view.xml',
'views/account_invoice_view.xml',
'views/account_invoice.xml',
'views/res_config_settings_views.xml',
'views/setup_wizard_views.xml',
],
'demo': [
'demo/account_cash_rounding.xml',
'demo/demo_company.xml',
],
'post_init_hook': 'post_init',
'assets': {
'web.report_assets_common': [
'l10n_ch/static/src/scss/**/*',
],
},
'license': 'LGPL-3',
}
| 43.73913
| 3,018
|
266
|
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_ch')
| 29.555556
| 266
|
694
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
def migrate(cr, version):
""" From 12.0, to saas-13.3, l10n_ch_swissqr_template
used to inherit from another template. This isn't the case
anymore since https://github.com/odoo/odoo/commit/719f087b1b5be5f1f276a0f87670830d073f6ef4
(made in 12.0, and forward-ported). The module will not be updatable if we
don't manually clean inherit_id.
"""
cr.execute("""
update ir_ui_view v
set inherit_id = NULL, mode='primary'
from ir_model_data mdata
where
v.id = mdata.res_id
and mdata.model= 'ir.ui.view'
and mdata.name = 'l10n_ch_swissqr_template'
and mdata.module='l10n_ch';
""")
| 34.7
| 694
|
503
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, SUPERUSER_ID
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
new_template_to_tax = update_taxes_from_templates(cr, 'l10n_ch.l10nch_chart_template')
if new_template_to_tax:
_, new_tax_ids = zip(*new_template_to_tax)
env = api.Environment(cr, SUPERUSER_ID, {})
env['account.tax'].browse(new_tax_ids).active = True
| 45.727273
| 503
|
4,125
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged
from odoo.tests.common import Form, TransactionCase
CH_ISR_ISSUER = '01-162-8'
CH_IBAN = 'CH15 3881 5158 3845 3843 7'
FR_IBAN = 'FR83 8723 4133 8709 9079 4002 530'
CH_POST_IBAN = 'CH09 0900 0000 1000 8060 7'
CH_POSTAL_ACC = '10-8060-7'
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestOnchangePostal(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.partner = cls.env['res.partner'].create({
'name': 'Swiss Company',
'street': 'Route de Berne 41',
'zip': '1000',
'city': 'Lausanne',
'is_company': 1,
'country_id': cls.env.ref('base.ch').id,
})
cls.ch_bank = cls.env['res.bank'].create({
'name': 'Alternative Bank Schweiz AG',
'bic': 'ALSWCH21XXX',
})
cls.post_bank = cls.env['res.bank'].search(
[('bic', '=', 'POFICHBEXXX')])
if not cls.post_bank:
cls.post_bank = cls.env['res.bank'].create({
'name': 'PostFinance AG',
'bic': 'POFICHBEXXX',
})
def new_partner_bank_form(self):
form = Form(
self.env['res.partner.bank'],
view="l10n_ch.isr_partner_bank_form",
)
form.partner_id = self.partner
return form
def test_onchange_acc_number_isr_issuer(self):
"""The user entered ISR issuer number into acc_number
We detect and move it to l10n_ch_postal.
It must be moved as it is not unique.
"""
bank_acc = self.new_partner_bank_form()
bank_acc.acc_number = CH_ISR_ISSUER
account = bank_acc.save()
self.assertEqual(
account.acc_number,
"{} {}".format(CH_ISR_ISSUER, self.partner.name)
)
self.assertEqual(account.l10n_ch_postal, CH_ISR_ISSUER)
self.assertEqual(account.acc_type, 'postal')
def test_onchange_acc_number_postal(self):
"""The user entered postal number into acc_number
We detect and copy it to l10n_ch_postal.
"""
bank_acc = self.new_partner_bank_form()
bank_acc.acc_number = CH_POSTAL_ACC
account = bank_acc.save()
self.assertEqual(account.acc_number, CH_POSTAL_ACC)
self.assertEqual(account.l10n_ch_postal, CH_POSTAL_ACC)
self.assertEqual(account.acc_type, 'postal')
def test_onchange_acc_number_iban_ch(self):
bank_acc = self.new_partner_bank_form()
bank_acc.acc_number = CH_IBAN
account = bank_acc.save()
self.assertEqual(account.acc_number, CH_IBAN)
self.assertFalse(account.l10n_ch_postal)
self.assertEqual(account.acc_type, 'iban')
def test_onchange_acc_number_iban_ch_postfinance(self):
"""The user enter a postal IBAN, postal number can be deduced"""
bank_acc = self.new_partner_bank_form()
bank_acc.acc_number = CH_POST_IBAN
account = bank_acc.save()
self.assertEqual(account.acc_number, CH_POST_IBAN)
self.assertEqual(account.l10n_ch_postal, CH_POSTAL_ACC)
self.assertEqual(account.acc_type, 'iban')
def test_onchange_acc_number_iban_foreign(self):
"""Check IBAN still works changed"""
bank_acc = self.new_partner_bank_form()
bank_acc.acc_number = FR_IBAN
account = bank_acc.save()
self.assertEqual(account.acc_number, FR_IBAN)
self.assertFalse(account.l10n_ch_postal)
self.assertEqual(account.acc_type, 'iban')
def test_onchange_acc_number_none(self):
"""Check misc format still works"""
bank_acc = self.new_partner_bank_form()
bank_acc.acc_number = 'anything'
account = bank_acc.save()
self.assertEqual(account.acc_number, 'anything')
self.assertFalse(account.l10n_ch_postal)
self.assertEqual(account.acc_type, 'bank')
| 35.25641
| 4,125
|
3,645
|
py
|
PYTHON
|
15.0
|
# -*- coding:utf-8 -*-
from odoo.tests import tagged
from odoo.exceptions import UserError
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestSwissQRCode(AccountTestInvoicingCommon):
""" Tests the generation of Swiss QR-codes on invoices
"""
@classmethod
def setUpClass(cls, chart_template_ref='l10n_ch.l10nch_chart_template'):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.company_data['company'].qr_code = True
cls.company_data['company'].country_id = None
cls.swiss_iban = cls.env['res.partner.bank'].create({
'acc_number': 'CH15 3881 5158 3845 3843 7',
'partner_id': cls.company_data['company'].partner_id.id,
})
cls.swiss_qr_iban = cls.env['res.partner.bank'].create({
'acc_number': 'CH21 3080 8001 2345 6782 7',
'partner_id': cls.company_data['company'].partner_id.id,
})
cls.ch_qr_invoice = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'currency_id': cls.env.ref('base.CHF').id,
'partner_bank_id': cls.swiss_iban.id,
'company_id': cls.company_data['company'].id,
'payment_reference': "Papa a vu le fifi de lolo",
'invoice_line_ids': [
(0, 0, {'quantity': 1, 'price_unit': 100})
],
})
def _assign_partner_address(self, partner):
partner.write({
'country_id': self.env.ref('base.ch').id,
'street': "Crab street, 11",
'city': "Crab City",
'zip': "4242",
})
def test_swiss_qr_code_generation(self):
""" Check different cases of Swiss QR-code generation, when qr_method is
specified beforehand.
"""
self.ch_qr_invoice.qr_code_method = 'ch_qr'
# First check with a regular IBAN
with self.assertRaises(UserError, msg="It shouldn't be possible to generate a Swiss QR-code for partners without a complete Swiss address."):
self.ch_qr_invoice.generate_qr_code()
# Setting the address should make it work
self._assign_partner_address(self.ch_qr_invoice.company_id.partner_id)
self._assign_partner_address(self.ch_qr_invoice.partner_id)
self.ch_qr_invoice.generate_qr_code()
# Now, check with a QR-IBAN as the payment account
self.ch_qr_invoice.partner_bank_id = self.swiss_qr_iban
with self.assertRaises(UserError, msg="It shouldn't be possible to generate a Swiss QR-cde for a QR-IBAN without giving it a valid QR-reference as payment reference."):
self.ch_qr_invoice.generate_qr_code()
# Assigning a QR reference should fix it
self.ch_qr_invoice.payment_reference = '210000000003139471430009017'
# even if the invoice is not issued from Switzerland we want to generate the code
self.ch_qr_invoice.company_id.partner_id.country_id = self.env.ref('base.fr')
self.ch_qr_invoice.generate_qr_code()
def test_ch_qr_code_detection(self):
""" Checks Swiss QR-code auto-detection when no specific QR-method
is given to the invoice.
"""
self._assign_partner_address(self.ch_qr_invoice.company_id.partner_id)
self._assign_partner_address(self.ch_qr_invoice.partner_id)
self.ch_qr_invoice.generate_qr_code()
self.assertEqual(self.ch_qr_invoice.qr_code_method, 'ch_qr', "Swiss QR-code generator should have been chosen for this invoice.")
| 42.383721
| 3,645
|
2,953
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo.exceptions import ValidationError
@tagged('post_install_l10n', 'post_install', '-at_install')
class ISRTest(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_ch.l10nch_chart_template'):
super().setUpClass(chart_template_ref=chart_template_ref)
def print_isr(self, invoice):
try:
invoice.isr_print()
return True
except ValidationError:
return False
def test_l10n_ch_postals(self):
def assertBankAccountValid(account_number, expected_account_type, expected_postal=None):
partner_bank = self.env['res.partner.bank'].create({
'acc_number': account_number,
'partner_id': self.partner_a.id,
})
expected_vals = {'acc_type': expected_account_type}
if expected_postal is not None:
expected_vals['l10n_ch_postal'] = expected_postal
self.assertRecordValues(partner_bank, [expected_vals])
assertBankAccountValid('010391391', 'postal', expected_postal='010391391')
assertBankAccountValid('CH6309000000250097798', 'iban', expected_postal='25-9779-8')
assertBankAccountValid('GR1601101250000000012300695', 'iban', expected_postal=False)
partner_bank = self.env['res.partner.bank'].create({
'acc_number': '010391394',
'partner_id': self.partner_a.id,
})
self.assertNotEqual(partner_bank.acc_type, 'postal')
def test_isr(self):
isr_bank_account = self.env['res.partner.bank'].create({
'acc_number': "ISR {} number",
'partner_id': self.env.company.partner_id.id,
'l10n_ch_isr_subscription_chf': '01-39139-1',
})
invoice_chf = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'partner_bank_id': isr_bank_account.id,
'currency_id': self.env.ref('base.CHF').id,
'invoice_date': '2019-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id})],
})
invoice_chf.action_post()
self.assertTrue(self.print_isr(invoice_chf))
self.env.ref('base.EUR').active = True
invoice_eur = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'partner_bank_id': isr_bank_account.id,
'currency_id': self.env.ref('base.EUR').id,
'invoice_date': '2019-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id})],
})
invoice_eur.action_post()
self.assertFalse(self.print_isr(invoice_eur))
| 41.013889
| 2,953
|
4,577
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
QR_IBAN = 'CH21 3080 8001 2345 6782 7'
ISR_SUBS_NUMBER = "01-162-8"
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestGenISRReference(AccountTestInvoicingCommon):
"""Check condition of generation of and content of the structured ref"""
@classmethod
def setUpClass(cls, chart_template_ref="l10n_ch.l10nch_chart_template"):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.bank = cls.env["res.bank"].create(
{
"name": "Alternative Bank Schweiz AG",
"bic": "ALSWCH21XXX",
}
)
cls.bank_acc_isr = cls.env["res.partner.bank"].create(
{
"acc_number": "ISR",
"l10n_ch_isr_subscription_chf": "01-162-8",
"bank_id": cls.bank.id,
"partner_id": cls.partner_a.id,
}
)
cls.bank_acc_qriban = cls.env["res.partner.bank"].create(
{
"acc_number": QR_IBAN,
"bank_id": cls.bank.id,
"partner_id": cls.partner_a.id,
}
)
cls.invoice = cls.init_invoice("out_invoice", products=cls.product_a+cls.product_b)
def test_isr(self):
self.invoice.partner_bank_id = self.bank_acc_isr
self.invoice.name = "INV/01234567890"
expected_isr = "000000000000000012345678903"
expected_isr_spaced = "00 00000 00000 00001 23456 78903"
expected_optical_line = "0100001307807>000000000000000012345678903+ 010001628>"
self.assertEqual(self.invoice.l10n_ch_isr_number, expected_isr)
self.assertEqual(self.invoice.l10n_ch_isr_number_spaced, expected_isr_spaced)
self.assertEqual(self.invoice.l10n_ch_isr_optical_line, expected_optical_line)
def test_qrr(self):
self.invoice.partner_bank_id = self.bank_acc_qriban
self.invoice.name = "INV/01234567890"
expected_isr = "000000000000000012345678903"
expected_isr_spaced = "00 00000 00000 00001 23456 78903"
self.assertEqual(self.invoice.l10n_ch_isr_number, expected_isr)
self.assertEqual(self.invoice.l10n_ch_isr_number_spaced, expected_isr_spaced)
# No need to check optical line, we have no use for it with QR-bill
def test_isr_long_reference(self):
self.invoice.partner_bank_id = self.bank_acc_isr
self.invoice.name = "INV/123456789012345678901234567890"
expected_isr = "567890123456789012345678901"
expected_isr_spaced = "56 78901 23456 78901 23456 78901"
expected_optical_line = "0100001307807>567890123456789012345678901+ 010001628>"
self.assertEqual(self.invoice.l10n_ch_isr_number, expected_isr)
self.assertEqual(self.invoice.l10n_ch_isr_number_spaced, expected_isr_spaced)
self.assertEqual(self.invoice.l10n_ch_isr_optical_line, expected_optical_line)
def test_missing_isr_subscription_num(self):
self.bank_acc_isr.l10n_ch_isr_subscription_chf = False
self.invoice.partner_bank_id = self.bank_acc_isr
self.assertFalse(self.invoice.l10n_ch_isr_number)
self.assertFalse(self.invoice.l10n_ch_isr_number_spaced)
self.assertFalse(self.invoice.l10n_ch_isr_optical_line)
def test_missing_isr_subscription_num_in_wrong_field(self):
self.bank_acc_isr.l10n_ch_isr_subscription_chf = False
self.bank_acc_isr.l10n_ch_postal = ISR_SUBS_NUMBER
self.invoice.partner_bank_id = self.bank_acc_isr
self.assertFalse(self.invoice.l10n_ch_isr_number)
self.assertFalse(self.invoice.l10n_ch_isr_number_spaced)
self.assertFalse(self.invoice.l10n_ch_isr_optical_line)
def test_no_bank_account(self):
self.invoice.partner_bank_id = False
self.assertFalse(self.invoice.l10n_ch_isr_number)
self.assertFalse(self.invoice.l10n_ch_isr_number_spaced)
self.assertFalse(self.invoice.l10n_ch_isr_optical_line)
def test_wrong_currency(self):
self.invoice.partner_bank_id = self.bank_acc_isr
self.invoice.currency_id = self.env.ref("base.BTN")
self.assertFalse(self.invoice.l10n_ch_isr_number)
self.assertFalse(self.invoice.l10n_ch_isr_number_spaced)
self.assertFalse(self.invoice.l10n_ch_isr_optical_line)
| 41.990826
| 4,577
|
6,488
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
CH_IBAN = 'CH15 3881 5158 3845 3843 7'
QR_IBAN = 'CH21 3080 8001 2345 6782 7'
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestSwissQR(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_ch.l10nch_chart_template'):
super().setUpClass(chart_template_ref=chart_template_ref)
def setUp(self):
super(TestSwissQR, self).setUp()
# Activate SwissQR in Swiss invoices
self.env['ir.config_parameter'].create(
{'key': 'l10n_ch.print_qrcode', 'value': '1'}
)
self.customer = self.env['res.partner'].create(
{
"name": "Partner",
"street": "Route de Berne 41",
"street2": "",
"zip": "1000",
"city": "Lausanne",
"country_id": self.env.ref("base.ch").id,
}
)
self.env.user.company_id.partner_id.write(
{
"street": "Route de Berne 88",
"street2": "",
"zip": "2000",
"city": "Neuchâtel",
"country_id": self.env.ref('base.ch').id,
}
)
self.product = self.env['product.product'].create({
'name': 'Customizable Desk',
})
self.invoice1 = self.create_invoice('base.CHF')
sale_journal = self.env['account.journal'].search([("type", "=", "sale")])
sale_journal.invoice_reference_model = "ch"
def create_invoice(self, currency_to_use='base.CHF'):
""" Generates a test invoice """
acc_type = self.env.ref('account.data_account_type_current_assets')
account = self.env['account.account'].search(
[('user_type_id', '=', acc_type.id)], limit=1
)
invoice = (
self.env['account.move']
.create(
{
'move_type': 'out_invoice',
'partner_id': self.customer.id,
'currency_id': self.env.ref(currency_to_use).id,
'date': time.strftime('%Y') + '-12-22',
'invoice_line_ids': [
(
0,
0,
{
'name': self.product.name,
'product_id': self.product.id,
'account_id': account.id,
'quantity': 1,
'price_unit': 42.0,
},
)
],
}
)
)
return invoice
def create_account(self, number):
""" Generates a test res.partner.bank. """
return self.env['res.partner.bank'].create(
{
'acc_number': number,
'partner_id': self.env.user.company_id.partner_id.id,
}
)
def swissqr_not_generated(self, invoice):
""" Prints the given invoice and tests that no Swiss QR generation is triggered. """
self.assertFalse(
invoice.partner_bank_id._eligible_for_qr_code('ch_qr', invoice.partner_id, invoice.currency_id),
'No Swiss QR should be generated for this invoice',
)
def swissqr_generated(self, invoice, ref_type='NON'):
""" Ensure correct params for Swiss QR generation. """
self.assertTrue(
invoice.partner_bank_id._eligible_for_qr_code('ch_qr', invoice.partner_id, invoice.currency_id), 'A Swiss QR can be generated'
)
if ref_type == 'QRR':
self.assertTrue(invoice.payment_reference)
struct_ref = invoice.payment_reference
unstr_msg = invoice.ref or invoice.name or ''
else:
struct_ref = ''
unstr_msg = invoice.payment_reference or invoice.ref or invoice.name or ''
unstr_msg = unstr_msg or invoice.number
payload = (
"SPC\n"
"0200\n"
"1\n"
"{iban}\n"
"K\n"
"company_1_data\n"
"Route de Berne 88\n"
"2000 Neuchâtel\n"
"\n\n"
"CH\n"
"\n\n\n\n\n\n\n"
"42.00\n"
"CHF\n"
"K\n"
"Partner\n"
"Route de Berne 41\n"
"1000 Lausanne\n"
"\n\n"
"CH\n"
"{ref_type}\n"
"{struct_ref}\n"
"{unstr_msg}\n"
"EPD"
).format(
iban=invoice.partner_bank_id.sanitized_acc_number,
ref_type=ref_type,
struct_ref=struct_ref or '',
unstr_msg=unstr_msg,
)
expected_params = {
'barcode_type': 'QR',
'barLevel': 'M',
'width': 256,
'height': 256,
'quiet': 1,
'mask': 'ch_cross',
'value': payload,
}
params = invoice.partner_bank_id._get_qr_code_generation_params(
'ch_qr', 42.0, invoice.currency_id, invoice.partner_id, unstr_msg, struct_ref
)
self.assertEqual(params, expected_params)
def test_swissQR_missing_bank(self):
# Let us test the generation of a SwissQR for an invoice, first by showing an
# QR is included in the invoice is only generated when Odoo has all the data it needs.
self.invoice1.action_post()
self.swissqr_not_generated(self.invoice1)
def test_swissQR_iban(self):
# Now we add an account for payment to our invoice
# Here we don't use a structured reference
iban_account = self.create_account(CH_IBAN)
self.invoice1.partner_bank_id = iban_account
self.invoice1.action_post()
self.swissqr_generated(self.invoice1, ref_type="NON")
def test_swissQR_qriban(self):
# Now use a proper QR-IBAN, we are good to print a QR Bill
qriban_account = self.create_account(QR_IBAN)
self.assertTrue(qriban_account.l10n_ch_qr_iban)
self.invoice1.partner_bank_id = qriban_account
self.invoice1.action_post()
self.swissqr_generated(self.invoice1, ref_type="QRR")
| 35.25
| 6,486
|
4,521
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form, common, tagged
from odoo.exceptions import ValidationError
CH_ISR_SUBSCRIPTION = "01-162-8"
CH_POSTAL = "10-8060-7"
CH_IBAN = "CH15 3881 5158 3845 3843 7"
ISR_REFERENCE_GOOD = "16 00011 23456 78901 23456 78901"
ISR_REFERENCE_ZEROS = "00 00000 00000 00001 23456 78903"
ISR_REFERENCE_NO_ZEROS = "1 23456 78903"
ISR_REFERENCE_BAD = "11 11111 11111 11111 11111 11111"
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestVendorBillISR(common.TransactionCase):
"""Check we can encode Vendor bills with ISR references
The ISR is a structured reference with a checksum.
User are guided to ensure they don't encode wrong ISR references.
Only vendors with ISR issuer accounts send ISR references.
ISR references can be received at least till 2022.
"""
@classmethod
def setUpClass(cls):
super(TestVendorBillISR, cls).setUpClass()
cls.abs_bank = cls.env["res.bank"].create(
{"name": "Alternative Bank Schweiz", "bic": "ABSOCH22XXX"}
)
cls.supplier1 = cls.env["res.partner"].create({"name": "Supplier ISR"})
cls.supplier2 = cls.env["res.partner"].create({"name": "Supplier postal"})
cls.supplier3 = cls.env["res.partner"].create({"name": "Supplier IBAN"})
cls.bank_acc_isr = cls.env['res.partner.bank'].create({
"acc_number": "ISR 01-162-8 Supplier ISR",
"partner_id": cls.supplier1.id,
"l10n_ch_postal": CH_ISR_SUBSCRIPTION,
})
cls.bank_acc_postal = cls.env['res.partner.bank'].create({
"acc_number": CH_POSTAL,
"partner_id": cls.supplier2.id,
"l10n_ch_postal": CH_POSTAL,
})
cls.bank_acc_iban = cls.env['res.partner.bank'].create({
"acc_number": CH_IBAN,
"partner_id": cls.supplier2.id,
"l10n_ch_postal": False,
})
def test_isr_ref(self):
"""Enter ISR reference with ISR subscription account number
The vendor bill can be saved.
"""
self.env.company.country_id = self.env.ref('base.ch')
form = Form(self.env["account.move"].with_context(
default_move_type="in_invoice"), view="l10n_ch.isr_invoice_form")
form.partner_id = self.supplier1
form.partner_bank_id = self.bank_acc_isr
form.payment_reference = ISR_REFERENCE_GOOD
invoice = form.save()
self.assertFalse(invoice.l10n_ch_isr_needs_fixing)
def test_isr_ref_with_zeros(self):
"""Enter ISR reference with ISR subscription account number
An ISR Reference can have lots of zeros on the left.
The vendor bill can be saved.
"""
self.env.company.country_id = self.env.ref('base.ch')
form = Form(self.env["account.move"].with_context(
default_move_type="in_invoice"), view="l10n_ch.isr_invoice_form")
form.partner_id = self.supplier1
form.partner_bank_id = self.bank_acc_isr
form.payment_reference = ISR_REFERENCE_ZEROS
invoice = form.save()
self.assertFalse(invoice.l10n_ch_isr_needs_fixing)
def test_isr_ref_no_zeros(self):
"""Enter ISR reference with ISR subscription account number
An ISR Reference full of zeros can be entered starting by the
first non zero digit.
The vendor bill can be saved.
"""
self.env.company.country_id = self.env.ref('base.ch')
form = Form(self.env["account.move"].with_context(
default_move_type="in_invoice"), view="l10n_ch.isr_invoice_form")
form.partner_id = self.supplier1
form.partner_bank_id = self.bank_acc_isr
form.payment_reference = ISR_REFERENCE_NO_ZEROS
invoice = form.save()
self.assertFalse(invoice.l10n_ch_isr_needs_fixing)
def test_isr_wrong_ref(self):
"""Mistype ISR reference with ISR subscription account number
Check it will show the warning
"""
self.env.company.country_id = self.env.ref('base.ch')
form = Form(self.env["account.move"].with_context(
default_move_type="in_invoice"), view="l10n_ch.isr_invoice_form")
form.partner_id = self.supplier1
form.partner_bank_id = self.bank_acc_isr
form.payment_reference = ISR_REFERENCE_BAD
invoice = form.save()
self.assertTrue(invoice.l10n_ch_isr_needs_fixing)
| 37.675
| 4,521
|
706
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, models
class SwissSetupBarBankConfigWizard(models.TransientModel):
_inherit = 'account.setup.bank.manual.config'
@api.onchange('acc_number')
def _onchange_recompute_qr_iban(self):
# Needed because ORM doesn't properly call the compute in 'new' mode, due to inherits, and
# we want this field to be displayed in the wizard. We need to manually set acc_number
# on the inherits m2o before calling the compute function manually.
self.res_partner_bank_id.acc_number = self.acc_number
self.res_partner_bank_id._compute_l10n_ch_qr_iban()
self.l10n_ch_qr_iban = self.res_partner_bank_id.l10n_ch_qr_iban
| 44.125
| 706
|
1,264
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
from pathlib import Path
from reportlab.graphics.shapes import Image as ReportLabImage
from reportlab.lib.units import mm
CH_QR_CROSS_SIZE_RATIO = 0.1522 # Ratio between the side length of the Swiss QR-code cross image and the QR-code's
CH_QR_CROSS_FILE = Path('../static/src/img/CH-Cross_7mm.png') # Image file containing the Swiss QR-code cross to add on top of the QR-code
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'
@api.model
def get_available_barcode_masks(self):
rslt = super(IrActionsReport, self).get_available_barcode_masks()
rslt['ch_cross'] = self.apply_qr_code_ch_cross_mask
return rslt
@api.model
def apply_qr_code_ch_cross_mask(self, width, height, barcode_drawing):
cross_width = CH_QR_CROSS_SIZE_RATIO * width
cross_height = CH_QR_CROSS_SIZE_RATIO * height
cross_path = Path(__file__).absolute().parent / CH_QR_CROSS_FILE
qr_cross = ReportLabImage((width/2 - cross_width/2) / mm, (height/2 - cross_height/2) / mm, cross_width / mm, cross_height / mm, cross_path.as_posix())
barcode_drawing.add(qr_cross)
| 45.142857
| 1,264
|
575
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.addons.base_iban.models.res_partner_bank import validate_iban
from odoo.addons.base.models.res_bank import sanitize_account_number
class AccountJournal(models.Model):
_inherit = 'account.journal'
invoice_reference_model = fields.Selection(selection_add=[
('ch', 'Switzerland')
], ondelete={'ch': lambda recs: recs.write({'invoice_reference_model': 'odoo'})})
| 33.823529
| 575
|
2,216
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo import api, models
class MailTemplate(models.Model):
_inherit = 'mail.template'
def generate_email(self, res_ids, fields):
""" Method overridden in order to add an attachment containing the ISR
to the draft message when opening the 'send by mail' wizard on an invoice.
This attachment generation will only occur if all the required data are
present on the invoice. Otherwise, no ISR attachment will be created, and
the mail will only contain the invoice (as defined in the mother method).
"""
result = super(MailTemplate, self).generate_email(res_ids, fields)
if self.model != 'account.move':
return result
multi_mode = True
if isinstance(res_ids, int):
res_ids = [res_ids]
multi_mode = False
if self.model == 'account.move':
for record in self.env[self.model].browse(res_ids):
inv_print_name = self._render_field('report_name', record.ids, compute_lang=True)[record.id]
new_attachments = []
include_qr_report = 'l10n_ch.l10n_ch_qr_report' not in self.env.context.get('l10n_ch_mail_skip_report', [])
if include_qr_report and record.move_type == 'out_invoice' and record.partner_bank_id._eligible_for_qr_code('ch_qr', record.partner_id, record.currency_id):
# We add an attachment containing the QR-bill
qr_report_name = 'QR-bill-' + inv_print_name + '.pdf'
qr_pdf = self.env.ref('l10n_ch.l10n_ch_qr_report')._render_qweb_pdf(record.ids)[0]
qr_pdf = base64.b64encode(qr_pdf)
new_attachments.append((qr_report_name, qr_pdf))
record_dict = multi_mode and result[record.id] or result
attachments_list = record_dict.get('attachments', False)
if attachments_list:
attachments_list.extend(new_attachments)
else:
record_dict['attachments'] = new_attachments
return result
| 47.148936
| 2,216
|
19,683
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from stdnum.util import clean
from odoo import api, fields, models, _
from odoo.addons.base.models.res_bank import sanitize_account_number
from odoo.addons.base_iban.models.res_partner_bank import normalize_iban, pretty_iban, validate_iban
from odoo.exceptions import ValidationError
from odoo.tools.misc import mod10r
ISR_SUBSCRIPTION_CODE = {'CHF': '01', 'EUR': '03'}
CLEARING = "09000"
_re_postal = re.compile('^[0-9]{2}-[0-9]{1,6}-[0-9]$')
def _is_l10n_ch_postal(account_ref):
""" Returns True if the string account_ref is a valid postal account number,
i.e. it only contains ciphers and is last cipher is the result of a recursive
modulo 10 operation ran over the rest of it. Shorten form with - is also accepted.
"""
if _re_postal.match(account_ref or ''):
ref_subparts = account_ref.split('-')
account_ref = ref_subparts[0] + ref_subparts[1].rjust(6, '0') + ref_subparts[2]
if re.match('\d+$', account_ref or ''):
account_ref_without_check = account_ref[:-1]
return mod10r(account_ref_without_check) == account_ref
return False
def _is_l10n_ch_isr_issuer(account_ref, currency_code):
""" Returns True if the string account_ref is a valid a valid ISR issuer
An ISR issuer is postal account number that starts by 01 (CHF) or 03 (EUR),
"""
if (account_ref or '').startswith(ISR_SUBSCRIPTION_CODE[currency_code]):
return _is_l10n_ch_postal(account_ref)
return False
def validate_qr_iban(qr_iban):
# Check first if it's a valid IBAN.
validate_iban(qr_iban)
# We sanitize first so that _check_qr_iban_range() can extract correct IID from IBAN to validate it.
sanitized_qr_iban = sanitize_account_number(qr_iban)
if sanitized_qr_iban[:2] not in ['CH', 'LI']:
raise ValidationError(_("QR-IBAN numbers are only available in Switzerland."))
# Now, check if it's valid QR-IBAN (based on its IID).
if not check_qr_iban_range(sanitized_qr_iban):
raise ValidationError(_("QR-IBAN '%s' is invalid.") % qr_iban)
return True
def check_qr_iban_range(iban):
if not iban or len(iban) < 9:
return False
iid_start_index = 4
iid_end_index = 8
iid = iban[iid_start_index : iid_end_index+1]
return re.match(r'\d+', iid) and 30000 <= int(iid) <= 31999 # Those values for iid are reserved for QR-IBANs only
class ResPartnerBank(models.Model):
_inherit = 'res.partner.bank'
l10n_ch_postal = fields.Char(
string="Swiss Postal Account",
readonly=False, store=True,
compute='_compute_l10n_ch_postal',
help="This field is used for the Swiss postal account number on a vendor account and for the client number on "
"your own account. The client number is mostly 6 numbers without -, while the postal account number can "
"be e.g. 01-162-8")
l10n_ch_qr_iban = fields.Char(string='QR-IBAN',
compute='_compute_l10n_ch_qr_iban',
store=True,
readonly=False,
help="Put the QR-IBAN here for your own bank accounts. That way, you can "
"still use the main IBAN in the Account Number while you will see the "
"QR-IBAN for the barcode. ")
# fields to configure ISR payment slip generation
l10n_ch_isr_subscription_chf = fields.Char(string='CHF ISR Subscription Number', help='The subscription number provided by the bank or Postfinance to identify the bank, used to generate ISR in CHF. eg. 01-162-8')
l10n_ch_isr_subscription_eur = fields.Char(string='EUR ISR Subscription Number', help='The subscription number provided by the bank or Postfinance to identify the bank, used to generate ISR in EUR. eg. 03-162-5')
l10n_ch_show_subscription = fields.Boolean(compute='_compute_l10n_ch_show_subscription', default=lambda self: self.env.company.account_fiscal_country_id.code == 'CH')
def _is_isr_issuer(self):
return (_is_l10n_ch_isr_issuer(self.l10n_ch_postal, 'CHF')
or _is_l10n_ch_isr_issuer(self.l10n_ch_postal, 'EUR'))
@api.constrains("l10n_ch_postal", "partner_id")
def _check_postal_num(self):
"""Validate postal number format"""
for rec in self:
if rec.l10n_ch_postal and not _is_l10n_ch_postal(rec.l10n_ch_postal):
# l10n_ch_postal is used for the purpose of Client Number on your own accounts, so don't do the check there
if rec.partner_id and not rec.partner_id.ref_company_ids:
raise ValidationError(
_("The postal number {} is not valid.\n"
"It must be a valid postal number format. eg. 10-8060-7").format(rec.l10n_ch_postal))
return True
@api.constrains("l10n_ch_isr_subscription_chf", "l10n_ch_isr_subscription_eur")
def _check_subscription_num(self):
"""Validate ISR subscription number format
Subscription number can only starts with 01 or 03
"""
for rec in self:
for currency in ["CHF", "EUR"]:
subscrip = rec.l10n_ch_isr_subscription_chf if currency == "CHF" else rec.l10n_ch_isr_subscription_eur
if subscrip and not _is_l10n_ch_isr_issuer(subscrip, currency):
example = "01-162-8" if currency == "CHF" else "03-162-5"
raise ValidationError(
_("The ISR subcription {} for {} number is not valid.\n"
"It must starts with {} and we a valid postal number format. eg. {}"
).format(subscrip, currency, ISR_SUBSCRIPTION_CODE[currency], example))
return True
@api.depends('partner_id', 'company_id')
def _compute_l10n_ch_show_subscription(self):
for bank in self:
if bank.partner_id:
bank.l10n_ch_show_subscription = bank.partner_id.ref_company_ids.country_id.code in ('CH', 'LI')
elif bank.company_id:
bank.l10n_ch_show_subscription = bank.company_id.account_fiscal_country_id.code in ('CH', 'LI')
else:
bank.l10n_ch_show_subscription = self.env.company.account_fiscal_country_id.code in ('CH', 'LI')
@api.depends('acc_number', 'acc_type')
def _compute_sanitized_acc_number(self):
#Only remove spaces in case it is not postal
postal_banks = self.filtered(lambda b: b.acc_type == "postal")
for bank in postal_banks:
bank.sanitized_acc_number = bank.acc_number
super(ResPartnerBank, self - postal_banks)._compute_sanitized_acc_number()
@api.depends('acc_number')
def _compute_l10n_ch_qr_iban(self):
for record in self:
try:
validate_qr_iban(record.acc_number)
valid_qr_iban = True
except ValidationError:
valid_qr_iban = False
if valid_qr_iban:
record.l10n_ch_qr_iban = record.sanitized_acc_number
else:
record.l10n_ch_qr_iban = None
@api.model
def create(self, vals):
if vals.get('l10n_ch_qr_iban'):
validate_qr_iban(vals['l10n_ch_qr_iban'])
vals['l10n_ch_qr_iban'] = pretty_iban(normalize_iban(vals['l10n_ch_qr_iban']))
return super().create(vals)
def write(self, vals):
if vals.get('l10n_ch_qr_iban'):
validate_qr_iban(vals['l10n_ch_qr_iban'])
vals['l10n_ch_qr_iban'] = pretty_iban(normalize_iban(vals['l10n_ch_qr_iban']))
return super().write(vals)
@api.model
def _get_supported_account_types(self):
rslt = super(ResPartnerBank, self)._get_supported_account_types()
rslt.append(('postal', _('Postal')))
return rslt
@api.model
def retrieve_acc_type(self, acc_number):
""" Overridden method enabling the recognition of swiss postal bank
account numbers.
"""
acc_number_split = ""
# acc_number_split is needed to continue to recognize the account
# as a postal account even if the difference
if acc_number and " " in acc_number:
acc_number_split = acc_number.split(" ")[0]
if _is_l10n_ch_postal(acc_number) or (acc_number_split and _is_l10n_ch_postal(acc_number_split)):
return 'postal'
else:
return super(ResPartnerBank, self).retrieve_acc_type(acc_number)
@api.depends('acc_number', 'partner_id', 'acc_type')
def _compute_l10n_ch_postal(self):
for record in self:
if record.acc_type == 'iban':
record.l10n_ch_postal = self._retrieve_l10n_ch_postal(record.sanitized_acc_number)
elif record.acc_type == 'postal':
if record.acc_number and " " in record.acc_number:
record.l10n_ch_postal = record.acc_number.split(" ")[0]
else:
record.l10n_ch_postal = record.acc_number
# In case of ISR issuer, this number is not
# unique and we fill acc_number with partner
# name to give proper information to the user
if record.partner_id and record.acc_number[:2] in ["01", "03"]:
record.acc_number = ("{} {}").format(record.acc_number, record.partner_id.name)
@api.model
def _is_postfinance_iban(self, iban):
"""Postfinance IBAN have format
CHXX 0900 0XXX XXXX XXXX K
Where 09000 is the clearing number
"""
return iban.startswith(('CH', 'LI')) and iban[4:9] == CLEARING
@api.model
def _pretty_postal_num(self, number):
"""format a postal account number or an ISR subscription number
as per specifications with '-' separators.
eg. 010001628 -> 01-162-8
"""
if re.match('^[0-9]{2}-[0-9]{1,6}-[0-9]$', number or ''):
return number
currency_code = number[:2]
middle_part = number[2:-1]
trailing_cipher = number[-1]
middle_part = middle_part.lstrip("0")
return currency_code + '-' + middle_part + '-' + trailing_cipher
@api.model
def _retrieve_l10n_ch_postal(self, iban):
"""Reads a swiss postal account number from a an IBAN and returns it as
a string. Returns None if no valid postal account number was found, or
the given iban was not from Swiss Postfinance.
CH09 0900 0000 1000 8060 7 -> 10-8060-7
"""
if self._is_postfinance_iban(iban):
# the IBAN corresponds to a swiss account
return self._pretty_postal_num(iban[-9:])
return None
def _l10n_ch_get_qr_vals(self, amount, currency, debtor_partner, free_communication, structured_communication):
comment = ""
if free_communication:
comment = (free_communication[:137] + '...') if len(free_communication) > 140 else free_communication
creditor_addr_1, creditor_addr_2 = self._get_partner_address_lines(self.partner_id)
debtor_addr_1, debtor_addr_2 = self._get_partner_address_lines(debtor_partner)
# Compute reference type (empty by default, only mandatory for QR-IBAN,
# and must then be 27 characters-long, with mod10r check digit as the 27th one,
# just like ISR number for invoices)
reference_type = 'NON'
reference = ''
acc_number = self.sanitized_acc_number
if self.l10n_ch_qr_iban:
# _check_for_qr_code_errors ensures we can't have a QR-IBAN without a QR-reference here
reference_type = 'QRR'
reference = structured_communication
acc_number = sanitize_account_number(self.l10n_ch_qr_iban)
elif self._is_iso11649_reference(structured_communication):
reference_type = 'SCOR'
reference = structured_communication.replace(' ', '')
currency = currency or self.currency_id or self.company_id.currency_id
return [
'SPC', # QR Type
'0200', # Version
'1', # Coding Type
acc_number, # IBAN / QR-IBAN
'K', # Creditor Address Type
(self.acc_holder_name or self.partner_id.name)[:70], # Creditor Name
creditor_addr_1, # Creditor Address Line 1
creditor_addr_2, # Creditor Address Line 2
'', # Creditor Postal Code (empty, since we're using combined addres elements)
'', # Creditor Town (empty, since we're using combined addres elements)
self.partner_id.country_id.code, # Creditor Country
'', # Ultimate Creditor Address Type
'', # Name
'', # Ultimate Creditor Address Line 1
'', # Ultimate Creditor Address Line 2
'', # Ultimate Creditor Postal Code
'', # Ultimate Creditor Town
'', # Ultimate Creditor Country
'{:.2f}'.format(amount), # Amount
currency.name, # Currency
'K', # Ultimate Debtor Address Type
debtor_partner.commercial_partner_id.name[:70], # Ultimate Debtor Name
debtor_addr_1, # Ultimate Debtor Address Line 1
debtor_addr_2, # Ultimate Debtor Address Line 2
'', # Ultimate Debtor Postal Code (not to be provided for address type K)
'', # Ultimate Debtor Postal City (not to be provided for address type K)
debtor_partner.country_id.code, # Ultimate Debtor Postal Country
reference_type, # Reference Type
reference, # Reference
comment, # Unstructured Message
'EPD', # Mandatory trailer part
]
def _get_qr_vals(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication):
if qr_method == 'ch_qr':
return self._l10n_ch_get_qr_vals(amount, currency, debtor_partner, free_communication, structured_communication)
return super()._get_qr_vals(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)
def _get_qr_code_generation_params(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication):
if qr_method == 'ch_qr':
return {
'barcode_type': 'QR',
'width': 256,
'height': 256,
'quiet': 1,
'mask': 'ch_cross',
'value': '\n'.join(self._get_qr_vals(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)),
# Swiss QR code requires Error Correction Level = 'M' by specification
'barLevel': 'M',
}
return super()._get_qr_code_generation_params(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)
def _get_partner_address_lines(self, partner):
""" Returns a tuple of two elements containing the address lines to use
for this partner. Line 1 contains the street and number, line 2 contains
zip and city. Those two lines are limited to 70 characters
"""
streets = [partner.street, partner.street2]
line_1 = ' '.join(filter(None, streets))
line_2 = partner.zip + ' ' + partner.city
return line_1[:70], line_2[:70]
@api.model
def _is_qr_reference(self, reference):
""" Checks whether the given reference is a QR-reference, i.e. it is
made of 27 digits, the 27th being a mod10r check on the 26 previous ones.
"""
return reference \
and len(reference) == 27 \
and re.match('\d+$', reference) \
and reference == mod10r(reference[:-1])
@api.model
def _is_iso11649_reference(self, reference):
""" Checks whether the given reference is a ISO11649 (SCOR) reference.
"""
return reference \
and len(reference) >= 5 \
and len(reference) <= 25 \
and reference.startswith('RF') \
and int(''.join(str(int(x, 36)) for x in clean(reference[4:] + reference[:4], ' -.,/:').upper().strip())) % 97 == 1
# see https://github.com/arthurdejong/python-stdnum/blob/master/stdnum/iso11649.py
def _eligible_for_qr_code(self, qr_method, debtor_partner, currency):
if qr_method == 'sct_qr' and debtor_partner.country_id.code == 'CH' and self.journal_id.country_code == 'CH':
return False
if qr_method == 'ch_qr':
return self.acc_type == 'iban' and \
(not debtor_partner or debtor_partner.country_id.code in ('CH', 'LI')) \
and currency.name in ('EUR', 'CHF')
return super()._eligible_for_qr_code(qr_method, debtor_partner, currency)
def _check_for_qr_code_errors(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication):
def _partner_fields_set(partner):
return partner.zip and \
partner.city and \
partner.country_id.code and \
(partner.street or partner.street2)
if qr_method == 'ch_qr':
if not _partner_fields_set(self.partner_id):
return _("The partner set on the bank account meant to receive the payment (%s) must have a complete postal address (street, zip, city and country).", self.acc_number)
if debtor_partner and not _partner_fields_set(debtor_partner):
return _("The partner must have a complete postal address (street, zip, city and country).")
if self.l10n_ch_qr_iban and not self._is_qr_reference(structured_communication):
return _("When using a QR-IBAN as the destination account of a QR-code, the payment reference must be a QR-reference.")
return super()._check_for_qr_code_errors(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)
@api.model
def _get_available_qr_methods(self):
rslt = super()._get_available_qr_methods()
rslt.append(('ch_qr', _("Swiss QR bill"), 10))
return rslt
| 51.526178
| 19,683
|
17,155
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, UserError
from odoo.tools.float_utils import float_split_str
from odoo.tools.misc import mod10r
l10n_ch_ISR_NUMBER_LENGTH = 27
l10n_ch_ISR_ID_NUM_LENGTH = 6
class AccountMove(models.Model):
_inherit = 'account.move'
l10n_ch_isr_subscription = fields.Char(compute='_compute_l10n_ch_isr_subscription', help='ISR subscription number identifying your company or your bank to generate ISR.')
l10n_ch_isr_subscription_formatted = fields.Char(compute='_compute_l10n_ch_isr_subscription', help="ISR subscription number your company or your bank, formated with '-' and without the padding zeros, to generate ISR report.")
l10n_ch_isr_number = fields.Char(compute='_compute_l10n_ch_isr_number', store=True, help='The reference number associated with this invoice')
l10n_ch_isr_number_spaced = fields.Char(compute='_compute_l10n_ch_isr_number_spaced', help="ISR number split in blocks of 5 characters (right-justified), to generate ISR report.")
l10n_ch_isr_optical_line = fields.Char(compute="_compute_l10n_ch_isr_optical_line", help='Optical reading line, as it will be printed on ISR')
l10n_ch_isr_valid = fields.Boolean(compute='_compute_l10n_ch_isr_valid', help='Boolean value. True iff all the data required to generate the ISR are present')
l10n_ch_isr_sent = fields.Boolean(default=False, help="Boolean value telling whether or not the ISR corresponding to this invoice has already been printed or sent by mail.")
l10n_ch_currency_name = fields.Char(related='currency_id.name', readonly=True, string="Currency Name", help="The name of this invoice's currency") #This field is used in the "invisible" condition field of the 'Print ISR' button.
l10n_ch_isr_needs_fixing = fields.Boolean(compute="_compute_l10n_ch_isr_needs_fixing", help="Used to show a warning banner when the vendor bill needs a correct ISR payment reference. ")
@api.depends('partner_bank_id.l10n_ch_isr_subscription_eur', 'partner_bank_id.l10n_ch_isr_subscription_chf')
def _compute_l10n_ch_isr_subscription(self):
""" Computes the ISR subscription identifying your company or the bank that allows to generate ISR. And formats it accordingly"""
def _format_isr_subscription(isr_subscription):
#format the isr as per specifications
currency_code = isr_subscription[:2]
middle_part = isr_subscription[2:-1]
trailing_cipher = isr_subscription[-1]
middle_part = re.sub('^0*', '', middle_part)
return currency_code + '-' + middle_part + '-' + trailing_cipher
def _format_isr_subscription_scanline(isr_subscription):
# format the isr for scanline
return isr_subscription[:2] + isr_subscription[2:-1].rjust(6, '0') + isr_subscription[-1:]
for record in self:
record.l10n_ch_isr_subscription = False
record.l10n_ch_isr_subscription_formatted = False
if record.partner_bank_id:
if record.currency_id.name == 'EUR':
isr_subscription = record.partner_bank_id.l10n_ch_isr_subscription_eur
elif record.currency_id.name == 'CHF':
isr_subscription = record.partner_bank_id.l10n_ch_isr_subscription_chf
else:
#we don't format if in another currency as EUR or CHF
continue
if isr_subscription:
isr_subscription = isr_subscription.replace("-", "") # In case the user put the -
record.l10n_ch_isr_subscription = _format_isr_subscription_scanline(isr_subscription)
record.l10n_ch_isr_subscription_formatted = _format_isr_subscription(isr_subscription)
def _get_isrb_id_number(self):
"""Hook to fix the lack of proper field for ISR-B Customer ID"""
# FIXME
# replace l10n_ch_postal by an other field to not mix ISR-B
# customer ID as it forbid the following validations on l10n_ch_postal
# number for Vendor bank accounts:
# - validation of format xx-yyyyy-c
# - validation of checksum
self.ensure_one()
return self.partner_bank_id.l10n_ch_postal or ''
@api.depends('name', 'partner_bank_id.l10n_ch_postal')
def _compute_l10n_ch_isr_number(self):
"""Generates the ISR or QRR reference
An ISR references are 27 characters long.
QRR is a recycling of ISR for QR-bills. Thus works the same.
The invoice sequence number is used, removing each of its non-digit characters,
and pad the unused spaces on the left of this number with zeros.
The last digit is a checksum (mod10r).
There are 2 types of references:
* ISR (Postfinance)
The reference is free but for the last
digit which is a checksum.
If shorter than 27 digits, it is filled with zeros on the left.
e.g.
120000000000234478943216899
\________________________/|
1 2
(1) 12000000000023447894321689 | reference
(2) 9: control digit for identification number and reference
* ISR-B (Indirect through a bank, requires a customer ID)
In case of ISR-B The firsts digits (usually 6), contain the customer ID
at the Bank of this ISR's issuer.
The rest (usually 20 digits) is reserved for the reference plus the
control digit.
If the [customer ID] + [the reference] + [the control digit] is shorter
than 27 digits, it is filled with zeros between the customer ID till
the start of the reference.
e.g.
150001123456789012345678901
\____/\__________________/|
1 2 3
(1) 150001 | id number of the customer (size may vary)
(2) 12345678901234567890 | reference
(3) 1: control digit for identification number and reference
"""
for record in self:
if (record.partner_bank_id.l10n_ch_qr_iban or record.l10n_ch_isr_subscription) and record.name:
id_number = record._get_isrb_id_number()
if id_number:
id_number = id_number.zfill(l10n_ch_ISR_ID_NUM_LENGTH)
invoice_ref = re.sub('[^\d]', '', record.name)
# keep only the last digits if it exceed boundaries
full_len = len(id_number) + len(invoice_ref)
ref_payload_len = l10n_ch_ISR_NUMBER_LENGTH - 1
extra = full_len - ref_payload_len
if extra > 0:
invoice_ref = invoice_ref[extra:]
internal_ref = invoice_ref.zfill(ref_payload_len - len(id_number))
record.l10n_ch_isr_number = mod10r(id_number + internal_ref)
else:
record.l10n_ch_isr_number = False
@api.depends('l10n_ch_isr_number')
def _compute_l10n_ch_isr_number_spaced(self):
def _space_isr_number(isr_number):
to_treat = isr_number
res = ''
while to_treat:
res = to_treat[-5:] + res
to_treat = to_treat[:-5]
if to_treat:
res = ' ' + res
return res
for record in self:
if record.l10n_ch_isr_number:
record.l10n_ch_isr_number_spaced = _space_isr_number(record.l10n_ch_isr_number)
else:
record.l10n_ch_isr_number_spaced = False
def _get_l10n_ch_isr_optical_amount(self):
"""Prepare amount string for ISR optical line"""
self.ensure_one()
currency_code = None
if self.currency_id.name == 'CHF':
currency_code = '01'
elif self.currency_id.name == 'EUR':
currency_code = '03'
units, cents = float_split_str(self.amount_residual, 2)
amount_to_display = units + cents
amount_ref = amount_to_display.zfill(10)
optical_amount = currency_code + amount_ref
optical_amount = mod10r(optical_amount)
return optical_amount
@api.depends(
'currency_id.name', 'amount_residual', 'name',
'partner_bank_id.l10n_ch_isr_subscription_eur',
'partner_bank_id.l10n_ch_isr_subscription_chf')
def _compute_l10n_ch_isr_optical_line(self):
""" Compute the optical line to print on the bottom of the ISR.
This line is read by an OCR.
It's format is:
amount>reference+ creditor>
Where:
- amount: currency and invoice amount
- reference: ISR structured reference number
- in case of ISR-B contains the Customer ID number
- it can also contains a partner reference (of the debitor)
- creditor: Subscription number of the creditor
An optical line can have the 2 following formats:
* ISR (Postfinance)
0100003949753>120000000000234478943216899+ 010001628>
|/\________/| \________________________/| \_______/
1 2 3 4 5 6
(1) 01 | currency
(2) 0000394975 | amount 3949.75
(3) 4 | control digit for amount
(5) 12000000000023447894321689 | reference
(6) 9: control digit for identification number and reference
(7) 010001628: subscription number (01-162-8)
* ISR-B (Indirect through a bank, requires a customer ID)
0100000494004>150001123456789012345678901+ 010234567>
|/\________/| \____/\__________________/| \_______/
1 2 3 4 5 6 7
(1) 01 | currency
(2) 0000049400 | amount 494.00
(3) 4 | control digit for amount
(4) 150001 | id number of the customer (size may vary, usually 6 chars)
(5) 12345678901234567890 | reference
(6) 1: control digit for identification number and reference
(7) 010234567: subscription number (01-23456-7)
"""
for record in self:
record.l10n_ch_isr_optical_line = ''
if record.l10n_ch_isr_number and record.l10n_ch_isr_subscription and record.currency_id.name:
# Final assembly (the space after the '+' is no typo, it stands in the specs.)
record.l10n_ch_isr_optical_line = '{amount}>{reference}+ {creditor}>'.format(
amount=record._get_l10n_ch_isr_optical_amount(),
reference=record.l10n_ch_isr_number,
creditor=record.l10n_ch_isr_subscription,
)
@api.depends(
'move_type', 'name', 'currency_id.name',
'partner_bank_id.l10n_ch_isr_subscription_eur',
'partner_bank_id.l10n_ch_isr_subscription_chf')
def _compute_l10n_ch_isr_valid(self):
"""Returns True if all the data required to generate the ISR are present"""
for record in self:
record.l10n_ch_isr_valid = record.move_type == 'out_invoice' and\
record.name and \
record.l10n_ch_isr_subscription and \
record.l10n_ch_currency_name in ['EUR', 'CHF']
@api.depends('move_type', 'partner_bank_id', 'payment_reference')
def _compute_l10n_ch_isr_needs_fixing(self):
for inv in self:
if inv.move_type == 'in_invoice' and inv.company_id.account_fiscal_country_id.code in ('CH', 'LI'):
partner_bank = inv.partner_bank_id
needs_isr_ref = partner_bank.l10n_ch_qr_iban or partner_bank._is_isr_issuer()
if needs_isr_ref and not inv._has_isr_ref():
inv.l10n_ch_isr_needs_fixing = True
continue
inv.l10n_ch_isr_needs_fixing = False
def _has_isr_ref(self):
"""Check if this invoice has a valid ISR reference (for Switzerland)
e.g.
12371
000000000000000000000012371
210000000003139471430009017
21 00000 00003 13947 14300 09017
"""
self.ensure_one()
ref = self.payment_reference or self.ref
if not ref:
return False
ref = ref.replace(' ', '')
if re.match(r'^(\d{2,27})$', ref):
return ref == mod10r(ref[:-1])
return False
def split_total_amount(self):
""" Splits the total amount of this invoice in two parts, using the dot as
a separator, and taking two precision digits (always displayed).
These two parts are returned as the two elements of a tuple, as strings
to print in the report.
This function is needed on the model, as it must be called in the report
template, which cannot reference static functions
"""
return float_split_str(self.amount_residual, 2)
def isr_print(self):
""" Triggered by the 'Print ISR' button.
This button isn't available anymore and will be removed in 16.2.
This function is kept for stable policy.
"""
self.ensure_one()
if self.l10n_ch_isr_valid:
self.l10n_ch_isr_sent = True
return self.env.ref('l10n_ch.l10n_ch_isr_report').report_action(self)
else:
raise ValidationError(_("""You cannot generate an ISR yet.\n
For this, you need to :\n
- set a valid postal account number (or an IBAN referencing one) for your company\n
- define its bank\n
- associate this bank with a postal reference for the currency used in this invoice\n
- fill the 'bank account' field of the invoice with the postal to be used to receive the related payment. A default account will be automatically set for all invoices created after you defined a postal account for your company."""))
def print_ch_qr_bill(self):
""" Triggered by the 'Print QR-bill' button.
"""
self.ensure_one()
if not self.partner_bank_id:
raise UserError(_("QR-Bill can not be generated on paid invoices. If the invoice is not fully paid, please make sure Recipient Bank field is not empty and try again."))
if not self.partner_bank_id._eligible_for_qr_code('ch_qr', self.partner_id, self.currency_id):
raise UserError(_("Cannot generate the QR-bill. Please check you have configured the address of your company and debtor. If you are using a QR-IBAN, also check the invoice's payment reference is a QR reference."))
self.l10n_ch_isr_sent = True
return self.env.ref('l10n_ch.l10n_ch_qr_report').report_action(self)
def action_invoice_sent(self):
# OVERRIDE
rslt = super(AccountMove, self).action_invoice_sent()
if self.l10n_ch_isr_valid:
rslt['context']['l10n_ch_mark_isr_as_sent'] = True
return rslt
@api.returns('mail.message', lambda value: value.id)
def message_post(self, **kwargs):
if self.env.context.get('l10n_ch_mark_isr_as_sent'):
self.filtered(lambda inv: not inv.l10n_ch_isr_sent).write({'l10n_ch_isr_sent': True})
return super(AccountMove, self.with_context(mail_post_autofollow=self.env.context.get('mail_post_autofollow', True))).message_post(**kwargs)
def _get_invoice_reference_ch_invoice(self):
""" This sets ISR reference number which is generated based on customer's `Bank Account` and set it as
`Payment Reference` of the invoice when invoice's journal is using Switzerland's communication standard
"""
self.ensure_one()
return self.l10n_ch_isr_number
def _get_invoice_reference_ch_partner(self):
""" This sets ISR reference number which is generated based on customer's `Bank Account` and set it as
`Payment Reference` of the invoice when invoice's journal is using Switzerland's communication standard
"""
self.ensure_one()
return self.l10n_ch_isr_number
@api.model
def space_qrr_reference(self, qrr_ref):
""" Makes the provided QRR reference human-friendly, spacing its elements
by blocks of 5 from right to left.
"""
spaced_qrr_ref = ''
i = len(qrr_ref) # i is the index after the last index to consider in substrings
while i > 0:
spaced_qrr_ref = qrr_ref[max(i-5, 0) : i] + ' ' + spaced_qrr_ref
i -= 5
return spaced_qrr_ref
@api.model
def space_scor_reference(self, iso11649_ref):
""" Makes the provided SCOR reference human-friendly, spacing its elements
by blocks of 5 from right to left.
"""
return ' '.join(iso11649_ref[i:i + 4] for i in range(0, len(iso11649_ref), 4))
| 47.652778
| 17,155
|
2,083
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Company(models.Model):
_inherit = "res.company"
l10n_ch_isr_preprinted_account = fields.Boolean(string='Preprinted account', compute='_compute_l10n_ch_isr', inverse='_set_l10n_ch_isr')
l10n_ch_isr_preprinted_bank = fields.Boolean(string='Preprinted bank', compute='_compute_l10n_ch_isr', inverse='_set_l10n_ch_isr')
l10n_ch_isr_print_bank_location = fields.Boolean(string='Print bank location', default=False, help='Boolean option field indicating whether or not the alternate layout (the one printing bank name and address) must be used when generating an ISR.')
l10n_ch_isr_scan_line_left = fields.Float(string='Scan line horizontal offset (mm)', compute='_compute_l10n_ch_isr', inverse='_set_l10n_ch_isr')
l10n_ch_isr_scan_line_top = fields.Float(string='Scan line vertical offset (mm)', compute='_compute_l10n_ch_isr', inverse='_set_l10n_ch_isr')
def _compute_l10n_ch_isr(self):
get_param = self.env['ir.config_parameter'].sudo().get_param
for company in self:
company.l10n_ch_isr_preprinted_account = bool(get_param('l10n_ch.isr_preprinted_account', default=False))
company.l10n_ch_isr_preprinted_bank = bool(get_param('l10n_ch.isr_preprinted_bank', default=False))
company.l10n_ch_isr_scan_line_top = float(get_param('l10n_ch.isr_scan_line_top', default=0))
company.l10n_ch_isr_scan_line_left = float(get_param('l10n_ch.isr_scan_line_left', default=0))
def _set_l10n_ch_isr(self):
set_param = self.env['ir.config_parameter'].sudo().set_param
for company in self:
set_param("l10n_ch.isr_preprinted_account", company.l10n_ch_isr_preprinted_account)
set_param("l10n_ch.isr_preprinted_bank", company.l10n_ch_isr_preprinted_bank)
set_param("l10n_ch.isr_scan_line_top", company.l10n_ch_isr_scan_line_top)
set_param("l10n_ch.isr_scan_line_left", company.l10n_ch_isr_scan_line_left)
| 71.827586
| 2,083
|
999
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
l10n_ch_isr_preprinted_account = fields.Boolean(string='Preprinted account',
related="company_id.l10n_ch_isr_preprinted_account", readonly=False)
l10n_ch_isr_preprinted_bank = fields.Boolean(string='Preprinted bank',
related="company_id.l10n_ch_isr_preprinted_bank", readonly=False)
l10n_ch_isr_print_bank_location = fields.Boolean(string="Print bank on ISR",
related="company_id.l10n_ch_isr_print_bank_location", readonly=False,
required=True)
l10n_ch_isr_scan_line_left = fields.Float(string='Horizontal offset',
related="company_id.l10n_ch_isr_scan_line_left", readonly=False)
l10n_ch_isr_scan_line_top = fields.Float(string='Vertical offset',
related="company_id.l10n_ch_isr_scan_line_top", readonly=False)
| 49.95
| 999
|
1,139
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.addons.l10n_ch.models.res_bank import _is_l10n_ch_postal
class AccountBankStatementLine(models.Model):
_inherit = "account.bank.statement.line"
def _find_or_create_bank_account(self):
if self.company_id.account_fiscal_country_id.code in ('CH', 'LI') and _is_l10n_ch_postal(self.account_number):
bank_account = self.env['res.partner.bank'].search(
[('company_id', '=', self.company_id.id),
('sanitized_acc_number', 'like', self.account_number + '%'),
('partner_id', '=', self.partner_id.id)])
if not bank_account:
bank_account = self.env['res.partner.bank'].create({
'company_id': self.company_id.id,
'acc_number': self.account_number + " " + self.partner_id.name,
'partner_id': self.partner_id.id
})
return bank_account
else:
return super()._find_or_create_bank_account()
| 45.56
| 1,139
|
776
|
py
|
PYTHON
|
15.0
|
# -*- coding:utf-8 -*-
from odoo import api, models
class ReportSwissQR(models.AbstractModel):
_name = 'report.l10n_ch.qr_report_main'
_description = 'Swiss QR-bill report'
@api.model
def _get_report_values(self, docids, data=None):
docs = self.env['account.move'].browse(docids)
qr_code_urls = {}
for invoice in docs:
qr_code_urls[invoice.id] = invoice.partner_bank_id.build_qr_code_base64(invoice.amount_residual, invoice.ref or invoice.name, invoice.payment_reference, invoice.currency_id, invoice.partner_id, qr_method='ch_qr', silent_errors=False)
return {
'doc_ids': docids,
'doc_model': 'account.move',
'docs': docs,
'qr_code_urls': qr_code_urls,
}
| 35.272727
| 776
|
782
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Purchase and MRP Management',
'version': '1.0',
'category': 'Inventory/Purchase',
'description': """
This module provides facility to the user to install mrp and purchase modules at a time.
========================================================================================
It is basically used when we want to keep track of production orders generated
from purchase order.
""",
'data': [
'views/purchase_order_views.xml',
'views/mrp_production_views.xml',
'security/ir.model.access.csv',
],
'depends': ['mrp', 'purchase_stock'],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 31.28
| 782
|
3,575
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.fields import Date
from odoo.tests import Form, tagged
from odoo.tests.common import TransactionCase
from odoo.addons.stock_account.tests.test_stockvaluationlayer import TestStockValuationCommon
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
@tagged('post_install', '-at_install')
class TestAngloSaxonValuationPurchaseMRP(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestAngloSaxonValuationPurchaseMRP, cls).setUpClass()
cls.vendor01 = cls.env['res.partner'].create({'name': "Super Vendor"})
cls.stock_input_account, cls.stock_output_account, cls.stock_valuation_account, cls.expense_account, cls.stock_journal = _create_accounting_data(cls.env)
cls.avco_category = cls.env['product.category'].create({
'name': 'AVCO',
'property_cost_method': 'average',
'property_valuation': 'real_time',
'property_stock_account_input_categ_id': cls.stock_input_account.id,
'property_stock_account_output_categ_id': cls.stock_output_account.id,
'property_stock_journal': cls.stock_journal.id,
'property_stock_valuation_account_id': cls.stock_valuation_account.id,
})
cls.env.company.anglo_saxon_accounting = True
def test_kit_anglo_saxo_price_diff(self):
"""
Suppose an automated-AVCO configuration and a Price Difference Account defined on
the product category. When buying a kit of that category at a higher price than its
cost, the difference should be published on the Price Difference Account
"""
price_diff_account = self.env['account.account'].create({
'name': 'Super Price Difference Account',
'code': 'SPDA',
'user_type_id': self.env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
self.avco_category.property_account_creditor_price_difference_categ = price_diff_account
kit, compo01, compo02 = self.env['product.product'].create([{
'name': name,
'standard_price': price,
'type': 'product',
'categ_id': self.avco_category.id,
} for name, price in [('Kit', 0), ('Compo 01', 10), ('Compo 02', 20)]])
self.env['mrp.bom'].create({
'product_tmpl_id': kit.product_tmpl_id.id,
'type': 'phantom',
'bom_line_ids': [(0, 0, {
'product_id': p.id,
'product_qty': 1,
}) for p in [compo01, compo02]]
})
kit.button_bom_cost()
po_form = Form(self.env['purchase.order'])
po_form.partner_id = self.vendor01
with po_form.order_line.new() as pol_form:
pol_form.product_id = kit
pol_form.price_unit = 100
po = po_form.save()
po.button_confirm()
action = po.picking_ids.button_validate()
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
wizard.process()
action = po.action_create_invoice()
invoice = self.env['account.move'].browse(action['res_id'])
invoice.invoice_date = Date.today()
invoice.action_post()
price_diff_aml = invoice.line_ids.filtered(lambda l: l.account_id == price_diff_account)
self.assertEqual(price_diff_aml.balance, 70, "Should be the purchase price minus the kit cost (i.e. 100 - 30)")
| 44.6875
| 3,575
|
23,426
|
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, TransactionCase
from odoo.tests import tagged
from odoo import fields
@tagged('post_install', '-at_install')
class TestSaleMrpFlow(TransactionCase):
def setUp(self):
super(TestSaleMrpFlow, self).setUp()
# Useful models
self.UoM = self.env['uom.uom']
self.categ_unit = self.env.ref('uom.product_uom_categ_unit')
self.categ_kgm = self.env.ref('uom.product_uom_categ_kgm')
self.stock_location = self.env.ref('stock.stock_location_stock')
self.warehouse = self.env.ref('stock.warehouse0')
self.uom_kg = self.env['uom.uom'].search([('category_id', '=', self.categ_kgm.id), ('uom_type', '=', 'reference')],
limit=1)
self.uom_kg.write({
'name': 'Test-KG',
'rounding': 0.000001})
self.uom_gm = self.UoM.create({
'name': 'Test-G',
'category_id': self.categ_kgm.id,
'uom_type': 'smaller',
'factor': 1000.0,
'rounding': 0.001})
self.uom_unit = self.env['uom.uom'].search(
[('category_id', '=', self.categ_unit.id), ('uom_type', '=', 'reference')], limit=1)
self.uom_unit.write({
'name': 'Test-Unit',
'rounding': 0.01})
self.uom_dozen = self.UoM.create({
'name': 'Test-DozenA',
'category_id': self.categ_unit.id,
'factor_inv': 12,
'uom_type': 'bigger',
'rounding': 0.001})
# Creating all components
self.component_a = self._create_product('Comp A', self.uom_unit)
self.component_b = self._create_product('Comp B', self.uom_unit)
self.component_c = self._create_product('Comp C', self.uom_unit)
self.component_d = self._create_product('Comp D', self.uom_unit)
self.component_e = self._create_product('Comp E', self.uom_unit)
self.component_f = self._create_product('Comp F', self.uom_unit)
self.component_g = self._create_product('Comp G', self.uom_unit)
# Create a kit 'kit_1' :
# -----------------------
#
# kit_1 --|- component_a x2
# |- component_b x1
# |- component_c x3
self.kit_1 = self._create_product('Kit 1', self.uom_unit)
self.bom_kit_1 = self.env['mrp.bom'].create({
'product_tmpl_id': self.kit_1.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine = self.env['mrp.bom.line']
BomLine.create({
'product_id': self.component_a.id,
'product_qty': 2.0,
'bom_id': self.bom_kit_1.id})
BomLine.create({
'product_id': self.component_b.id,
'product_qty': 1.0,
'bom_id': self.bom_kit_1.id})
BomLine.create({
'product_id': self.component_c.id,
'product_qty': 3.0,
'bom_id': self.bom_kit_1.id})
# Create a kit 'kit_parent' :
# ---------------------------
#
# kit_parent --|- kit_2 x2 --|- component_d x1
# | |- kit_1 x2 -------|- component_a x2
# | |- component_b x1
# | |- component_c x3
# |
# |- kit_3 x1 --|- component_f x1
# | |- component_g x2
# |
# |- component_e x1
# Creating all kits
self.kit_2 = self._create_product('Kit 2', self.uom_unit)
self.kit_3 = self._create_product('kit 3', self.uom_unit)
self.kit_parent = self._create_product('Kit Parent', self.uom_unit)
# Linking the kits and the components via some 'phantom' BoMs
bom_kit_2 = self.env['mrp.bom'].create({
'product_tmpl_id': self.kit_2.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine.create({
'product_id': self.component_d.id,
'product_qty': 1.0,
'bom_id': bom_kit_2.id})
BomLine.create({
'product_id': self.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': self.component_e.id,
'product_qty': 1.0,
'bom_id': bom_kit_parent.id})
BomLine.create({
'product_id': self.kit_2.id,
'product_qty': 2.0,
'bom_id': bom_kit_parent.id})
bom_kit_3 = self.env['mrp.bom'].create({
'product_tmpl_id': self.kit_3.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'phantom'})
BomLine.create({
'product_id': self.component_f.id,
'product_qty': 1.0,
'bom_id': bom_kit_3.id})
BomLine.create({
'product_id': self.component_g.id,
'product_qty': 2.0,
'bom_id': bom_kit_3.id})
BomLine.create({
'product_id': self.kit_3.id,
'product_qty': 2.0,
'bom_id': bom_kit_parent.id})
def _create_product(self, name, uom_id, routes=()):
p = Form(self.env['product.product'])
p.name = name
p.detailed_type = 'product'
p.uom_id = uom_id
p.uom_po_id = uom_id
p.route_ids.clear()
for r in routes:
p.route_ids.add(r)
return p.save()
# Helper to process quantities based on a dict following this structure :
#
# qty_to_process = {
# product_id: qty
# }
def _process_quantities(self, moves, quantities_to_process):
""" Helper to process quantities based on a dict following this structure :
qty_to_process = {
product_id: qty
}
"""
moves_to_process = moves.filtered(lambda m: m.product_id in quantities_to_process.keys())
for move in moves_to_process:
move.write({'quantity_done': quantities_to_process[move.product_id]})
def _assert_quantities(self, moves, quantities_to_process):
""" Helper to check expected quantities based on a dict following this structure :
qty_to_process = {
product_id: qty
...
}
"""
moves_to_process = moves.filtered(lambda m: m.product_id in quantities_to_process.keys())
for move in moves_to_process:
self.assertEqual(move.product_uom_qty, quantities_to_process[move.product_id])
def _create_move_quantities(self, qty_to_process, components, warehouse):
""" Helper to creates moves in order to update the quantities of components
on a specific warehouse. This ensure that all compute fields are triggered.
The structure of qty_to_process should be the following :
qty_to_process = {
component: (qty, uom),
...
}
"""
for comp in components:
f = Form(self.env['stock.move'])
f.name = 'Test Receipt Components'
f.location_id = self.env.ref('stock.stock_location_suppliers')
f.location_dest_id = warehouse.lot_stock_id
f.product_id = comp
f.product_uom = qty_to_process[comp][1]
f.product_uom_qty = qty_to_process[comp][0]
move = f.save()
move._action_confirm()
move._action_assign()
move_line = move.move_line_ids[0]
move_line.qty_done = qty_to_process[comp][0]
move._action_done()
def test_01_sale_mrp_kit_qty_delivered(self):
""" Test that the quantities delivered are correct when
a kit with subkits is ordered with multiple backorders and returns
"""
# 'kit_parent' structure:
# ---------------------------
#
# kit_parent --|- kit_2 x2 --|- component_d x1
# | |- kit_1 x2 -------|- component_a x2
# | |- component_b x1
# | |- component_c x3
# |
# |- kit_3 x1 --|- component_f x1
# | |- component_g x2
# |
# |- component_e x1
# Creation of a sale order for x7 kit_parent
partner = self.env['res.partner'].create({'name': 'My Test Partner'})
f = Form(self.env['purchase.order'])
f.partner_id = partner
with f.order_line.new() as line:
line.product_id = self.kit_parent
line.product_qty = 7.0
line.price_unit = 10
po = f.save()
po.button_confirm()
# Check picking creation, its move lines should concern
# only components. Also checks that the quantities are corresponding
# to the PO
self.assertEqual(len(po.picking_ids), 1)
order_line = po.order_line[0]
picking_original = po.picking_ids[0]
move_lines = picking_original.move_lines
products = move_lines.mapped('product_id')
kits = [self.kit_parent, self.kit_3, self.kit_2, self.kit_1]
components = [self.component_a, self.component_b, self.component_c, self.component_d, self.component_e,
self.component_f, self.component_g]
expected_quantities = {
self.component_a: 56.0,
self.component_b: 28.0,
self.component_c: 84.0,
self.component_d: 14.0,
self.component_e: 7.0,
self.component_f: 14.0,
self.component_g: 28.0
}
self.assertEqual(len(move_lines), 7)
self.assertTrue(not any(kit in products for kit in kits))
self.assertTrue(all(component in products for component in components))
self._assert_quantities(move_lines, expected_quantities)
# Process only 7 units of each component
qty_to_process = 7
move_lines.write({'quantity_done': qty_to_process})
# Create a backorder for the missing componenents
pick = po.picking_ids[0]
res = pick.button_validate()
Form(self.env[res['res_model']].with_context(res['context'])).save().process()
# Check that a backorded is created
self.assertEqual(len(po.picking_ids), 2)
backorder_1 = po.picking_ids - picking_original
self.assertEqual(backorder_1.backorder_id.id, picking_original.id)
# Even if some components are received completely,
# no KitParent should be received
self.assertEqual(order_line.qty_received, 0)
# Process just enough components to make 1 kit_parent
qty_to_process = {
self.component_a: 1,
self.component_c: 5,
}
self._process_quantities(backorder_1.move_lines, qty_to_process)
# Create a backorder for the missing componenents
res = backorder_1.button_validate()
Form(self.env[res['res_model']].with_context(res['context'])).save().process()
# Only 1 kit_parent should be received at this point
self.assertEqual(order_line.qty_received, 1)
# Check that the second backorder is created
self.assertEqual(len(po.picking_ids), 3)
backorder_2 = po.picking_ids - picking_original - backorder_1
self.assertEqual(backorder_2.backorder_id.id, backorder_1.id)
# Set the components quantities that backorder_2 should have
expected_quantities = {
self.component_a: 48,
self.component_b: 21,
self.component_c: 72,
self.component_d: 7,
self.component_f: 7,
self.component_g: 21
}
# Check that the computed quantities are matching the theorical ones.
# Since component_e was totally processed, this componenent shouldn't be
# present in backorder_2
self.assertEqual(len(backorder_2.move_lines), 6)
move_comp_e = backorder_2.move_lines.filtered(lambda m: m.product_id.id == self.component_e.id)
self.assertFalse(move_comp_e)
self._assert_quantities(backorder_2.move_lines, expected_quantities)
# Process enough components to make x3 kit_parents
qty_to_process = {
self.component_a: 16,
self.component_b: 5,
self.component_c: 24,
self.component_g: 5
}
self._process_quantities(backorder_2.move_lines, qty_to_process)
# Create a backorder for the missing componenents
res = backorder_2.button_validate()
Form(self.env[res['res_model']].with_context(res['context'])).save().process()
# Check that x3 kit_parents are indeed received
self.assertEqual(order_line.qty_received, 3)
# Check that the third backorder is created
self.assertEqual(len(po.picking_ids), 4)
backorder_3 = po.picking_ids - (picking_original + backorder_1 + backorder_2)
self.assertEqual(backorder_3.backorder_id.id, backorder_2.id)
# Check the components quantities that backorder_3 should have
expected_quantities = {
self.component_a: 32,
self.component_b: 16,
self.component_c: 48,
self.component_d: 7,
self.component_f: 7,
self.component_g: 16
}
self._assert_quantities(backorder_3.move_lines, expected_quantities)
# Process all missing components
self._process_quantities(backorder_3.move_lines, expected_quantities)
# Validating the last backorder now it's complete.
# All kits should be received
backorder_3.button_validate()
self.assertEqual(order_line.qty_received, 7.0)
# Return all components processed by backorder_3
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=backorder_3.ids, active_id=backorder_3.ids[0],
active_model='stock.picking'))
return_wiz = stock_return_picking_form.save()
for return_move in return_wiz.product_return_moves:
return_move.write({
'quantity': expected_quantities[return_move.product_id],
'to_refund': True
})
res = return_wiz.create_returns()
return_pick = self.env['stock.picking'].browse(res['res_id'])
# Process all components and validate the picking
wiz_act = return_pick.button_validate()
wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save()
wiz.process()
# Now quantity received should be 3 again
self.assertEqual(order_line.qty_received, 3)
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=return_pick.ids, active_id=return_pick.ids[0],
active_model='stock.picking'))
return_wiz = stock_return_picking_form.save()
for move in return_wiz.product_return_moves:
move.quantity = expected_quantities[move.product_id]
res = return_wiz.create_returns()
return_of_return_pick = self.env['stock.picking'].browse(res['res_id'])
# Process all components except one of each
for move in return_of_return_pick.move_lines:
move.write({
'quantity_done': expected_quantities[move.product_id] - 1,
'to_refund': True
})
wiz_act = return_of_return_pick.button_validate()
wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save()
wiz.process()
# As one of each component is missing, only 6 kit_parents should be received
self.assertEqual(order_line.qty_received, 6)
# Check that the 4th backorder is created.
self.assertEqual(len(po.picking_ids), 7)
backorder_4 = po.picking_ids - (
picking_original + backorder_1 + backorder_2 + backorder_3 + return_of_return_pick + return_pick)
self.assertEqual(backorder_4.backorder_id.id, return_of_return_pick.id)
# Check the components quantities that backorder_4 should have
for move in backorder_4.move_lines:
self.assertEqual(move.product_qty, 1)
def test_concurent_procurements(self):
""" Check a production created to fulfill a procurement will not
replenish more that needed if others procurements have the same products
than the production component. """
warehouse = self.env.ref('stock.warehouse0')
buy_route = warehouse.buy_pull_id.route_id
manufacture_route = warehouse.manufacture_pull_id.route_id
vendor1 = self.env['res.partner'].create({'name': 'aaa', 'email': 'from.test@example.com'})
supplier_info1 = self.env['product.supplierinfo'].create({
'name': vendor1.id,
'price': 50,
})
component = self.env['product.product'].create({
'name': 'component',
'type': 'product',
'route_ids': [(4, buy_route.id)],
'seller_ids': [(6, 0, [supplier_info1.id])],
})
finished = self.env['product.product'].create({
'name': 'finished',
'type': 'product',
'route_ids': [(4, manufacture_route.id)],
})
self.env['stock.warehouse.orderpoint'].create({
'name': 'A RR',
'location_id': warehouse.lot_stock_id.id,
'product_id': component.id,
'route_id': buy_route.id,
'product_min_qty': 0,
'product_max_qty': 0,
})
self.env['stock.warehouse.orderpoint'].create({
'name': 'A RR',
'location_id': warehouse.lot_stock_id.id,
'product_id': finished.id,
'route_id': manufacture_route.id,
'product_min_qty': 0,
'product_max_qty': 0,
})
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,
'consumption': 'flexible',
'operation_ids': [
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': component.id, 'product_qty': 1}),
]})
# Delivery to trigger replenishment
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = warehouse.out_type_id
with picking_form.move_ids_without_package.new() as move:
move.product_id = finished
move.product_uom_qty = 3
with picking_form.move_ids_without_package.new() as move:
move.product_id = component
move.product_uom_qty = 2
picking = picking_form.save()
picking.action_confirm()
# Find PO
purchase = self.env['purchase.order.line'].search([
('product_id', '=', component.id),
]).order_id
self.assertTrue(purchase)
self.assertEqual(purchase.order_line.product_qty, 5)
def test_01_purchase_mrp_kit_qty_change(self):
self.partner = self.env.ref('base.res_partner_1')
# Create a PO with one unit of the kit product
self.po = self.env['purchase.order'].create({
'partner_id': self.partner.id,
'order_line': [(0, 0, {'name': self.kit_1.name, 'product_id': self.kit_1.id, 'product_qty': 1, 'product_uom': self.kit_1.uom_id.id, 'price_unit': 60.0, 'date_planned': fields.Datetime.now()})],
})
# Validate the PO
self.po.button_confirm()
# Check the component qty in the created picking
self.assertEqual(self.po.picking_ids.move_ids_without_package[0].product_uom_qty,2, "The quantity of components must be created according to the BOM")
self.assertEqual(self.po.picking_ids.move_ids_without_package[1].product_uom_qty,1, "The quantity of components must be created according to the BOM")
self.assertEqual(self.po.picking_ids.move_ids_without_package[2].product_uom_qty,3, "The quantity of components must be created according to the BOM")
# Update the kit quantity in the PO
self.po.order_line[0].product_qty = 2
# Check the component qty after the update
self.assertEqual(self.po.picking_ids.move_ids_without_package[0].product_uom_qty,4, "The amount of the kit components must be updated when changing the quantity of the kit.")
self.assertEqual(self.po.picking_ids.move_ids_without_package[1].product_uom_qty,2, "The amount of the kit components must be updated when changing the quantity of the kit.")
self.assertEqual(self.po.picking_ids.move_ids_without_package[2].product_uom_qty,6, "The amount of the kit components must be updated when changing the quantity of the kit.")
def test_procurement_with_preferred_route(self):
"""
3-steps receipts. Suppose a product that has both buy and manufacture
routes. The user runs an orderpoint with the preferred route defined to
"Buy". A purchase order should be generated.
"""
self.warehouse.reception_steps = 'three_steps'
manu_route = self.warehouse.manufacture_pull_id.route_id
buy_route = self.warehouse.buy_pull_id.route_id
# un-prioritize the buy rules
self.env['stock.rule'].search([]).sequence = 1
buy_route.rule_ids.sequence = 2
vendor = self.env['res.partner'].create({'name': 'super vendor'})
product = self.env['product.product'].create({
'name': 'super product',
'type': 'product',
'seller_ids': [(0, 0, {'name': vendor.id})],
'route_ids': [(4, manu_route.id), (4, buy_route.id)],
})
rr = self.env['stock.warehouse.orderpoint'].create({
'name': product.name,
'location_id': self.warehouse.lot_stock_id.id,
'product_id': product.id,
'product_min_qty': 1,
'product_max_qty': 1,
'route_id': buy_route.id,
})
rr.action_replenish()
move_stock, move_check = self.env['stock.move'].search([('product_id', '=', product.id)])
self.assertRecordValues(move_check | move_stock, [
{'location_id': self.warehouse.wh_input_stock_loc_id.id, 'location_dest_id': self.warehouse.wh_qc_stock_loc_id.id, 'state': 'waiting', 'move_dest_ids': move_stock.ids},
{'location_id': self.warehouse.wh_qc_stock_loc_id.id, 'location_dest_id': self.warehouse.lot_stock_id.id, 'state': 'waiting', 'move_dest_ids': []},
])
po = self.env['purchase.order'].search([('partner_id', '=', vendor.id)])
self.assertTrue(po)
po.button_confirm()
move_in = po.picking_ids.move_lines
self.assertEqual(move_in.move_dest_ids.ids, move_check.ids)
| 41.906977
| 23,426
|
3,904
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import api, fields, models, _
from odoo.tools import OrderedSet
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
mrp_production_count = fields.Integer(
"Count of MO Source",
compute='_compute_mrp_production_count',
groups='mrp.group_mrp_user')
@api.depends('order_line.move_dest_ids.group_id.mrp_production_ids')
def _compute_mrp_production_count(self):
for purchase in self:
purchase.mrp_production_count = len(purchase._get_mrp_productions())
def _get_mrp_productions(self, **kwargs):
return self.order_line.move_dest_ids.group_id.mrp_production_ids | self.order_line.move_ids.move_dest_ids.group_id.mrp_production_ids
def action_view_mrp_productions(self):
self.ensure_one()
mrp_production_ids = self._get_mrp_productions().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': _("Manufacturing Source of %s", self.name),
'domain': [('id', 'in', mrp_production_ids)],
'view_mode': 'tree,form',
})
return action
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
def _compute_qty_received(self):
kit_lines = self.env['purchase.order.line']
lines_stock = self.filtered(lambda l: l.qty_received_method == 'stock_moves' and l.move_ids and l.state != 'cancel')
product_by_company = defaultdict(OrderedSet)
for line in lines_stock:
product_by_company[line.company_id].add(line.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 line in lines_stock:
kit_bom = kits_by_company[line.company_id].get(line.product_id)
if kit_bom:
moves = line.move_ids.filtered(lambda m: m.state == 'done' and not m.scrapped)
order_qty = line.product_uom._compute_quantity(line.product_uom_qty, kit_bom.product_uom_id)
filters = {
'incoming_moves': lambda m: m.location_id.usage == 'supplier' and (not m.origin_returned_move_id or (m.origin_returned_move_id and m.to_refund)),
'outgoing_moves': lambda m: m.location_id.usage != 'supplier' and m.to_refund
}
line.qty_received = moves._compute_kit_quantities(line.product_id, order_qty, kit_bom, filters)
kit_lines += line
super(PurchaseOrderLine, self - kit_lines)._compute_qty_received()
def _get_upstream_documents_and_responsibles(self, visited):
return [(self.order_id, self.order_id.user_id, visited)]
def _get_qty_procurement(self):
self.ensure_one()
# Specific case when we change the qty on a PO for a kit product.
# We don't try to be too smart and keep a simple approach: we compare the quantity before
# and after update, and return the difference. We don't take into account what was already
# sent, or any other exceptional case.
bom = self.env['mrp.bom'].sudo()._bom_find(self.product_id, bom_type='phantom')[self.product_id]
if bom and 'previous_product_qty' in self.env.context:
return self.env.context['previous_product_qty'].get(self.id, 0.0)
return super()._get_qty_procurement()
| 45.395349
| 3,904
|
2,018
|
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.float_utils import float_is_zero
from odoo.exceptions import UserError
class StockMove(models.Model):
_inherit = 'stock.move'
def _prepare_phantom_move_values(self, bom_line, product_qty, quantity_done):
vals = super(StockMove, self)._prepare_phantom_move_values(bom_line, product_qty, quantity_done)
if self.purchase_line_id:
vals['purchase_line_id'] = self.purchase_line_id.id
return vals
def _get_valuation_price_and_qty(self, related_aml, to_curr):
valuation_price_unit_total, valuation_total_qty = super()._get_valuation_price_and_qty(related_aml, to_curr)
boms = self.env['mrp.bom']._bom_find(related_aml.product_id, company_id=related_aml.company_id.id, bom_type='phantom')
if related_aml.product_id in boms:
kit_bom = boms[related_aml.product_id]
order_qty = related_aml.product_id.uom_id._compute_quantity(related_aml.quantity, kit_bom.product_uom_id)
filters = {
'incoming_moves': lambda m: m.location_id.usage == 'supplier' and (not m.origin_returned_move_id or (m.origin_returned_move_id and m.to_refund)),
'outgoing_moves': lambda m: m.location_id.usage != 'supplier' and m.to_refund
}
valuation_total_qty = self._compute_kit_quantities(related_aml.product_id, order_qty, kit_bom, filters)
valuation_total_qty = kit_bom.product_uom_id._compute_quantity(valuation_total_qty, related_aml.product_id.uom_id)
if float_is_zero(valuation_total_qty, precision_rounding=related_aml.product_uom_id.rounding or related_aml.product_id.uom_id.rounding):
raise UserError(_('Odoo is not able to generate the anglo saxon entries. The total valuation of %s is zero.') % related_aml.product_id.display_name)
return valuation_price_unit_total, valuation_total_qty
| 63.0625
| 2,018
|
1,999
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class MrpProduction(models.Model):
_inherit = 'mrp.production'
purchase_order_count = fields.Integer(
"Count of generated PO",
compute='_compute_purchase_order_count',
groups='purchase.group_purchase_user')
@api.depends('procurement_group_id.stock_move_ids.created_purchase_line_id.order_id', 'procurement_group_id.stock_move_ids.move_orig_ids.purchase_line_id.order_id')
def _compute_purchase_order_count(self):
for production in self:
production.purchase_order_count = len(production.procurement_group_id.stock_move_ids.created_purchase_line_id.order_id |
production.procurement_group_id.stock_move_ids.move_orig_ids.purchase_line_id.order_id)
def action_view_purchase_orders(self):
self.ensure_one()
purchase_order_ids = (self.procurement_group_id.stock_move_ids.created_purchase_line_id.order_id | self.procurement_group_id.stock_move_ids.move_orig_ids.purchase_line_id.order_id).ids
action = {
'res_model': 'purchase.order',
'type': 'ir.actions.act_window',
}
if len(purchase_order_ids) == 1:
action.update({
'view_mode': 'form',
'res_id': purchase_order_ids[0],
})
else:
action.update({
'name': _("Purchase Order generated from %s", self.name),
'domain': [('id', 'in', purchase_order_ids)],
'view_mode': 'tree,form',
})
return action
def _get_document_iterate_key(self, move_raw_id):
iterate_key = super(MrpProduction, self)._get_document_iterate_key(move_raw_id)
if not iterate_key and move_raw_id.created_purchase_line_id:
iterate_key = 'created_purchase_line_id'
return iterate_key
| 44.422222
| 1,999
|
660
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'PayuMoney Payment Acquirer',
'version': '2.0',
'category': 'Accounting/Payment Acquirers',
'sequence': 375,
'summary': 'Payment Acquirer: PayuMoney Implementation',
'description': """
PayuMoney Payment Acquirer for India.
PayUmoney payment gateway supports only INR currency.
""",
'depends': ['payment'],
'data': [
'views/payment_views.xml',
'views/payment_payumoney_templates.xml',
'data/payment_acquirer_data.xml',
],
'application': True,
'uninstall_hook': 'uninstall_hook',
'license': 'LGPL-3',
}
| 28.695652
| 660
|
2,262
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged
from odoo.tools import mute_logger
from .common import PayumoneyCommon
from ..controllers.main import PayUMoneyController
from odoo.addons.payment import utils as payment_utils
@tagged('post_install', '-at_install')
class PayumoneyTest(PayumoneyCommon):
def test_compatible_acquirers(self):
acquirers = self.env['payment.acquirer']._get_compatible_acquirers(
partner_id=self.partner.id,
company_id=self.company.id,
currency_id=self.currency.id,
)
self.assertIn(self.payumoney, acquirers)
acquirers = self.env['payment.acquirer']._get_compatible_acquirers(
partner_id=self.partner.id,
company_id=self.company.id,
currency_id=self.currency_euro.id,
)
self.assertNotIn(self.payumoney, acquirers)
def test_redirect_form_values(self):
tx = self.create_transaction(flow='redirect')
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = tx._get_processing_values()
form_info = self._extract_values_from_html_form(processing_values['redirect_form_html'])
first_name, last_name = payment_utils.split_partner_name(self.partner.name)
return_url = self._build_url(PayUMoneyController._return_url)
expected_values = {
'key': self.payumoney.payumoney_merchant_key,
'txnid': self.reference,
'amount': str(self.amount),
'productinfo': self.reference,
'firstname': first_name,
'lastname': last_name,
'email': self.partner.email,
'phone': self.partner.phone,
'surl': return_url,
'furl': return_url,
'service_provider': 'payu_paisa',
}
expected_values['hash'] = self.payumoney._payumoney_generate_sign(
expected_values, incoming=False,
)
self.assertEqual(form_info['action'],
'https://sandboxsecure.payu.in/_payment')
self.assertDictEqual(form_info['inputs'], expected_values,
"PayUMoney: invalid inputs specified in the redirect form.")
| 40.392857
| 2,262
|
614
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.payment.tests.common import PaymentCommon
class PayumoneyCommon(PaymentCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.payumoney = cls._prepare_acquirer('payumoney', update_values={
'payumoney_merchant_key': 'dummy',
'payumoney_merchant_salt': 'dummy',
})
# Override default values
cls.acquirer = cls.payumoney
cls.currency = cls._prepare_currency('INR')
| 34.111111
| 614
|
4,415
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug import urls
from odoo import _, api, models
from odoo.exceptions import ValidationError
from odoo.addons.payment import utils as payment_utils
from odoo.addons.payment_payumoney.controllers.main import PayUMoneyController
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
def _get_specific_rendering_values(self, processing_values):
""" Override of payment to return Payumoney-specific rendering values.
Note: self.ensure_one() from `_get_processing_values`
:param dict processing_values: The generic and specific processing values of the transaction
:return: The dict of acquirer-specific processing values
:rtype: dict
"""
res = super()._get_specific_rendering_values(processing_values)
if self.provider != 'payumoney':
return res
first_name, last_name = payment_utils.split_partner_name(self.partner_id.name)
api_url = 'https://secure.payu.in/_payment' if self.acquirer_id.state == 'enabled' \
else 'https://sandboxsecure.payu.in/_payment'
payumoney_values = {
'key': self.acquirer_id.payumoney_merchant_key,
'txnid': self.reference,
'amount': self.amount,
'productinfo': self.reference,
'firstname': first_name,
'lastname': last_name,
'email': self.partner_email,
'phone': self.partner_phone,
'return_url': urls.url_join(self.get_base_url(), PayUMoneyController._return_url),
'api_url': api_url,
}
payumoney_values['hash'] = self.acquirer_id._payumoney_generate_sign(
payumoney_values, incoming=False,
)
return payumoney_values
@api.model
def _get_tx_from_feedback_data(self, provider, data):
""" Override of payment to find the transaction based on Payumoney data.
:param str provider: The provider of the acquirer that handled the transaction
:param dict data: The feedback data sent by the provider
:return: The transaction if found
:rtype: recordset of `payment.transaction`
:raise: ValidationError if inconsistent data were received
:raise: ValidationError if the data match no transaction
:raise: ValidationError if the signature can not be verified
"""
tx = super()._get_tx_from_feedback_data(provider, data)
if provider != 'payumoney':
return tx
reference = data.get('txnid')
shasign = data.get('hash')
if not reference or not shasign:
raise ValidationError(
"PayUmoney: " + _(
"Received data with missing reference (%(ref)s) or shasign (%(sign)s)",
ref=reference, sign=shasign,
)
)
tx = self.search([('reference', '=', reference), ('provider', '=', 'payumoney')])
if not tx:
raise ValidationError(
"PayUmoney: " + _("No transaction found matching reference %s.", reference)
)
# Verify shasign
shasign_check = tx.acquirer_id._payumoney_generate_sign(data, incoming=True)
if shasign_check != shasign:
raise ValidationError(
"PayUmoney: " + _(
"Invalid shasign: received %(sign)s, computed %(computed)s.",
sign=shasign, computed=shasign_check
)
)
return tx
def _process_feedback_data(self, data):
""" Override of payment to process the transaction based on Payumoney data.
Note: self.ensure_one()
:param dict data: The feedback data sent by the provider
:return: None
"""
super()._process_feedback_data(data)
if self.provider != 'payumoney':
return
status = data.get('status')
self.acquirer_reference = data.get('payuMoneyId')
if status == 'success':
self._set_done()
else: # 'failure'
# See https://www.payumoney.com/pdf/PayUMoney-Technical-Integration-Document.pdf
error_code = data.get('Error')
self._set_error(
"PayUmoney: " + _("The payment encountered an error with code %s", error_code)
)
| 38.72807
| 4,415
|
432
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class AccountPaymentMethod(models.Model):
_inherit = 'account.payment.method'
@api.model
def _get_payment_method_information(self):
res = super()._get_payment_method_information()
res['payumoney'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]}
return res
| 30.857143
| 432
|
2,529
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import hashlib
from odoo import api, fields, models
class PaymentAcquirer(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(
selection_add=[('payumoney', "PayUmoney")], ondelete={'payumoney': 'set default'})
payumoney_merchant_key = fields.Char(
string="Merchant Key", help="The key solely used to identify the account with PayU money",
required_if_provider='payumoney')
payumoney_merchant_salt = fields.Char(
string="Merchant Salt", required_if_provider='payumoney', groups='base.group_system')
@api.model
def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs):
""" Override of payment to unlist PayUmoney acquirers when the currency is not INR. """
acquirers = super()._get_compatible_acquirers(*args, currency_id=currency_id, **kwargs)
currency = self.env['res.currency'].browse(currency_id).exists()
if currency and currency.name != 'INR':
acquirers = acquirers.filtered(lambda a: a.provider != 'payumoney')
return acquirers
def _payumoney_generate_sign(self, values, incoming=True):
""" Generate the shasign for incoming or outgoing communications.
:param dict values: The values used to generate the signature
:param bool incoming: Whether the signature must be generated for an incoming (PayUmoney to
Odoo) or outgoing (Odoo to PayUMoney) communication.
:return: The shasign
:rtype: str
"""
sign_values = {
**values,
'key': self.payumoney_merchant_key,
'salt': self.payumoney_merchant_salt,
}
if incoming:
keys = 'salt|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|' \
'txnid|key'
sign = '|'.join(f'{sign_values.get(k) or ""}' for k in keys.split('|'))
else: # outgoing
keys = 'key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||salt'
sign = '|'.join(f'{sign_values.get(k) or ""}' for k in keys.split('|'))
return hashlib.sha512(sign.encode('utf-8')).hexdigest()
def _get_default_payment_method_id(self):
self.ensure_one()
if self.provider != 'payumoney':
return super()._get_default_payment_method_id()
return self.env.ref('payment_payumoney.payment_method_payumoney').id
| 44.368421
| 2,529
|
1,523
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
from odoo import http
from odoo.http import request
_logger = logging.getLogger(__name__)
class PayUMoneyController(http.Controller):
_return_url = '/payment/payumoney/return'
@http.route(
_return_url, type='http', auth='public', methods=['GET', 'POST'], csrf=False,
save_session=False
)
def payumoney_return(self, **data):
""" Process the data returned by PayUmoney after redirection.
The route is flagged with `save_session=False` to prevent Odoo from assigning a new session
to the user if they are redirected to this route with a POST request. Indeed, as the session
cookie is created without a `SameSite` attribute, some browsers that don't implement the
recommended default `SameSite=Lax` behavior will not include the cookie in the redirection
request from the payment provider to Odoo. As the redirection to the '/payment/status' page
will satisfy any specification of the `SameSite` attribute, the session of the user will be
retrieved and with it the transaction which will be immediately post-processed.
:param dict data: The feedback data to process
"""
_logger.info("entering handle_feedback_data with data:\n%s", pprint.pformat(data))
request.env['payment.transaction'].sudo()._handle_feedback_data('payumoney', data)
return request.redirect('/payment/status')
| 44.794118
| 1,523
|
582
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Website Event CRM Questions',
'version': '1.0',
'category': 'Marketing/Events',
'website': 'https://www.odoo.com/app/events',
'description': """
Add information when we build the description of a lead to include
the questions and answers linked to the registrations.
""",
'depends': ['website_event_crm', 'website_event_questions'],
'data': [],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 32.333333
| 582
|
1,266
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
class EventRegistration(models.Model):
_inherit = 'event.registration'
def _get_lead_description_registration(self, line_suffix=''):
"""Add the questions and answers linked to the registrations into the description of the lead."""
reg_description = super(EventRegistration, self)._get_lead_description_registration(line_suffix=line_suffix)
if not self.registration_answer_ids:
return reg_description
answer_descriptions = []
for answer in self.registration_answer_ids:
answer_value = answer.value_answer_id.name if answer.question_type == "simple_choice" else answer.value_text_box
answer_value = "<br/>".join([" %s" % line for line in answer_value.split('\n')])
answer_descriptions.append(" - %s<br/>%s" % (answer.question_id.title, answer_value))
return "%s%s<br/>%s" % (reg_description, _("Questions"), '<br/>'.join(answer_descriptions))
def _get_lead_description_fields(self):
res = super(EventRegistration, self)._get_lead_description_fields()
res.append('registration_answer_ids')
return res
| 48.692308
| 1,266
|
888
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Product Matrix",
'summary': """
Technical module: Matrix Implementation
""",
'description': """
Please refer to Sale Matrix or Purchase Matrix for the use of this module.
""",
'category': 'Sales/Sales',
'version': '1.0',
'depends': ['account'],
# Account dependency for section_and_note widget.
'data': [
'views/matrix_templates.xml',
],
'demo': [
'data/product_matrix_demo.xml',
],
'assets': {
'web.assets_backend': [
'product_matrix/static/src/js/section_and_note_widget.js',
'product_matrix/static/src/scss/product_matrix.scss',
],
'web.assets_qweb': [
'product_matrix/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 28.645161
| 888
|
1,863
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged, common
@tagged('post_install', '-at_install')
class TestMatrixCommon(common.HttpCase):
def setUp(self):
super(TestMatrixCommon, self).setUp()
# Prepare relevant test data
# This is not included in demo data to avoid useless noise
product_attributes = self.env['product.attribute'].create([{
'name': 'PA1',
'create_variant': 'always',
'sequence': 1
}, {
'name': 'PA2',
'create_variant': 'always',
'sequence': 2
}, {
'name': 'PA3',
'create_variant': 'dynamic',
'sequence': 3
}, {
'name': 'PA4',
'create_variant': 'no_variant',
'sequence': 4
}])
self.env['product.attribute.value'].create([{
'name': 'PAV' + str(product_attribute.sequence) + str(i),
'attribute_id': product_attribute.id
} for i in range(1, 3) for product_attribute in product_attributes])
self.matrix_template = self.env['product.template'].create({
'name': "Matrix",
'type': "consu",
'uom_id': self.ref("uom.product_uom_unit"),
'uom_po_id': self.ref("uom.product_uom_unit"),
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)]
}) for attribute in product_attributes],
})
def get_ptav(pav_name):
return self.env['product.template.attribute.value']\
.search([('product_attribute_value_id.name', '=', pav_name)])
get_ptav('PAV12').price_extra = 50
get_ptav('PAV31').price_extra = -25
| 36.529412
| 1,863
|
3,466
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import itertools
from odoo import models, fields
class ProductTemplate(models.Model):
_inherit = 'product.template'
def _get_template_matrix(self, **kwargs):
self.ensure_one()
company_id = kwargs.get('company_id', None) or self.company_id or self.env.company
currency_id = kwargs.get('currency_id', None) or self.currency_id
display_extra = kwargs.get('display_extra_price', False)
attribute_lines = self.valid_product_template_attribute_line_ids
Attrib = self.env['product.template.attribute.value']
first_line_attributes = attribute_lines[0].product_template_value_ids._only_active()
attribute_ids_by_line = [line.product_template_value_ids._only_active().ids for line in attribute_lines]
header = [{"name": self.display_name}] + [
attr._grid_header_cell(
fro_currency=self.currency_id,
to_currency=currency_id,
company=company_id,
display_extra=display_extra
) for attr in first_line_attributes]
result = [[]]
for pool in attribute_ids_by_line:
result = [x + [y] for y in pool for x in result]
args = [iter(result)] * len(first_line_attributes)
rows = itertools.zip_longest(*args)
matrix = []
for row in rows:
row_attributes = Attrib.browse(row[0][1:])
row_header_cell = row_attributes._grid_header_cell(
fro_currency=self.currency_id,
to_currency=currency_id,
company=company_id,
display_extra=display_extra)
result = [row_header_cell]
for cell in row:
combination = Attrib.browse(cell)
is_possible_combination = self._is_combination_possible(combination)
cell.sort()
result.append({
"ptav_ids": cell,
"qty": 0,
"is_possible_combination": is_possible_combination
})
matrix.append(result)
return {
"header": header,
"matrix": matrix,
}
class ProductTemplateAttributeValue(models.Model):
_inherit = "product.template.attribute.value"
def _grid_header_cell(self, fro_currency, to_currency, company, display_extra=True):
"""Generate a header matrix cell for 1 or multiple attributes.
:param res.currency fro_currency:
:param res.currency to_currency:
:param res.company company:
:param bool display_extra: whether extra prices should be displayed in the cell
True by default, used to avoid showing extra prices on purchases.
:returns: cell with name (and price if any price_extra is defined on self)
:rtype: dict
"""
header_cell = {
'name': ' • '.join([attr.name for attr in self]) if self else " "
} # The " " is to avoid having 'Not available' if the template has only one attribute line.
extra_price = sum(self.mapped('price_extra')) if display_extra else 0
if extra_price:
header_cell['currency_id'] = to_currency.id
header_cell['price'] = fro_currency._convert(
extra_price, to_currency, company, fields.Date.today())
return header_cell
| 40.752941
| 3,464
|
477
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Saudi Arabia - Invoice',
'version': '1.0.0',
'author': 'Odoo S.A.',
'category': 'Accounting/Localizations',
'license': 'LGPL-3',
'description': """
Invoices for the Kingdom of Saudi Arabia
""",
'depends': ['l10n_sa', 'l10n_gcc_invoice'],
'data': [
'views/view_move_form.xml',
'views/report_invoice.xml',
],
}
| 28.058824
| 477
|
3,394
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_repr
class AccountMove(models.Model):
_inherit = 'account.move'
l10n_sa_delivery_date = fields.Date(string='Delivery Date', default=fields.Date.context_today, copy=False,
readonly=True, states={'draft': [('readonly', False)]},
help="In case of multiple deliveries, you should take the date of the latest one. ")
l10n_sa_show_delivery_date = fields.Boolean(compute='_compute_show_delivery_date')
l10n_sa_qr_code_str = fields.Char(string='Zatka QR Code', compute='_compute_qr_code_str')
l10n_sa_confirmation_datetime = fields.Datetime(string='Confirmation Date', readonly=True, copy=False)
@api.depends('country_code', 'move_type')
def _compute_show_delivery_date(self):
for move in self:
move.l10n_sa_show_delivery_date = move.country_code == 'SA' and move.move_type in ('out_invoice', 'out_refund')
@api.depends('amount_total_signed', 'amount_tax_signed', 'l10n_sa_confirmation_datetime', 'company_id', 'company_id.vat')
def _compute_qr_code_str(self):
""" Generate the qr code for Saudi e-invoicing. Specs are available at the following link at page 23
https://zatca.gov.sa/ar/E-Invoicing/SystemsDevelopers/Documents/20210528_ZATCA_Electronic_Invoice_Security_Features_Implementation_Standards_vShared.pdf
"""
def get_qr_encoding(tag, field):
company_name_byte_array = field.encode()
company_name_tag_encoding = tag.to_bytes(length=1, byteorder='big')
company_name_length_encoding = len(company_name_byte_array).to_bytes(length=1, byteorder='big')
return company_name_tag_encoding + company_name_length_encoding + company_name_byte_array
for record in self:
qr_code_str = ''
if record.l10n_sa_confirmation_datetime and record.company_id.vat:
seller_name_enc = get_qr_encoding(1, record.company_id.display_name)
company_vat_enc = get_qr_encoding(2, record.company_id.vat)
time_sa = fields.Datetime.context_timestamp(self.with_context(tz='Asia/Riyadh'), record.l10n_sa_confirmation_datetime)
timestamp_enc = get_qr_encoding(3, time_sa.isoformat())
invoice_total_enc = get_qr_encoding(4, float_repr(abs(record.amount_total_signed), 2))
total_vat_enc = get_qr_encoding(5, float_repr(abs(record.amount_tax_signed), 2))
str_to_encode = seller_name_enc + company_vat_enc + timestamp_enc + invoice_total_enc + total_vat_enc
qr_code_str = base64.b64encode(str_to_encode).decode()
record.l10n_sa_qr_code_str = qr_code_str
def _post(self, soft=True):
res = super()._post(soft)
for record in self:
if record.country_code == 'SA' and record.move_type in ('out_invoice', 'out_refund'):
if not record.l10n_sa_show_delivery_date:
raise UserError(_('Delivery Date cannot be empty'))
self.write({
'l10n_sa_confirmation_datetime': fields.Datetime.now()
})
return res
| 57.525424
| 3,394
|
2,159
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Canada - Accounting',
'author': 'Savoir-faire Linux',
'website': 'https://www.savoirfairelinux.com',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the module to manage the Canadian accounting chart in Odoo.
===========================================================================================
Canadian accounting charts and localizations.
Fiscal positions
----------------
When considering taxes to be applied, it is the province where the delivery occurs that matters.
Therefore we decided to implement the most common case in the fiscal positions: delivery is the
responsibility of the vendor and done at the customer location.
Some examples:
1) You have a customer from another province and you deliver to his location.
On the customer, set the fiscal position to his province.
2) You have a customer from another province. However this customer comes to your location
with their truck to pick up products. On the customer, do not set any fiscal position.
3) An international vendor doesn't charge you any tax. Taxes are charged at customs
by the customs broker. On the vendor, set the fiscal position to International.
4) An international vendor charge you your provincial tax. They are registered with your
position.
""",
'depends': [
'account',
'base_iban',
'l10n_multilang',
],
'data': [
'data/account_chart_template_data.xml',
'data/account.account.template.csv',
'data/account_chart_template_after_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_data.xml',
'data/fiscal_templates_data.xml',
'data/account_chart_template_configure_data.xml',
'data/res_company_data.xml',
'views/res_partner_view.xml',
'views/res_company_view.xml',
'views/report_invoice.xml',
'views/report_template.xml'
],
'demo': [
'demo/demo_company.xml',
],
'post_init_hook': 'load_translations',
'license': 'LGPL-3',
}
| 35.983333
| 2,159
|
484
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
from odoo import models, fields
class ResCompany(models.Model):
_inherit = 'res.company'
l10n_ca_pst = fields.Char(related='partner_id.l10n_ca_pst', string='PST', store=False)
class BaseDocumentLayout(models.TransientModel):
_inherit = 'base.document.layout'
l10n_ca_pst = fields.Char(related='company_id.l10n_ca_pst', readonly=True)
account_fiscal_country_id = fields.Many2one(related="company_id.account_fiscal_country_id", readonly=True)
| 30.25
| 484
|
157
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
from odoo import api, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
l10n_ca_pst = fields.Char('PST')
| 19.625
| 157
|
1,159
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Italy - Accounting',
'version': '0.3',
'depends': [
'account',
'base_iban',
'base_vat',
],
'author': 'OpenERP Italian Community',
'description': """
Piano dei conti italiano di un'impresa generica.
================================================
Italian accounting chart and localization.
""",
'category': 'Accounting/Localizations/Account Charts',
'website': 'http://www.odoo.com/',
'data': [
'data/account_account_tag.xml',
'data/account_chart_template.xml',
'data/account.account.template.csv',
'data/account_chart_template_accounts.xml',
'data/account.tax.group.csv',
'data/account_tax_report_data.xml',
'data/account_tax_template.xml',
'data/account.fiscal.position.template.csv',
'data/account_fiscal_position_tax_template_data.xml',
'data/account_chart_template_data.xml',
'data/report_invoice.xml'
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 30.5
| 1,159
|
739
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, SUPERUSER_ID
def migrate(cr, version):
cr.execute("""
INSERT INTO account_account_account_tag
SELECT DISTINCT account.id, template_tag.account_account_tag_id
FROM account_account_template AS template
JOIN account_account AS account
ON account.code LIKE CONCAT(template.code, '%')
JOIN account_account_template_account_tag AS template_tag
ON template.id = template_tag.account_account_template_id
JOIN res_company ON res_company.id = account.company_id
JOIN res_country ON res_country.id = res_company.account_fiscal_country_id
AND res_country.code = 'IT'
ON CONFLICT DO NOTHING
""")
| 41.055556
| 739
|
2,446
|
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 AccountTaxReportLine(models.AbstractModel):
_inherit = "account.tax.report.line"
carry_over_condition_method = fields.Selection(
selection_add=[
('vp14_debt_carryover_condition', 'Italian line vp14 debt carryover'),
('vp14_credit_carryover_condition', 'Italian line vp14 credit carryover'),
]
)
def vp14_debt_carryover_condition(self, options, line_amount, carried_over_amount):
"""
The vp14 debt line will be carried over to the vp7 line of the next period, if the amount is between 0 and 25.82
Else the amount in vp7 will stay 0
"""
if options['tax_unit'] == 'company_only':
company = self.env.company
else:
tax_unit = self.env['account.tax.unit'].browse(options['tax_unit'])
company = tax_unit.main_company_id
base_currency = company.currency_id
target_currency = self.env.ref('base.EUR')
amount_in_euro = base_currency._convert(line_amount, target_currency, company, options['date']['date_to'])
if amount_in_euro <= 25.82:
return (None, 0)
else:
return (None, None)
def vp14_credit_carryover_condition(self, options, line_amount, carried_over_amount):
"""
If there is a credit, this amount will be carried over to the vp8 line of the next period.
This is only done during the same year.
If we are between two years, we want to carry it over to the vp9 line.
"""
return (None, 0)
def _get_carryover_destination_line(self, options):
self.ensure_one()
italian_report_id = self.env['ir.model.data']._xmlid_to_res_id('l10n_it.tax_report_vat')
if self.report_id.id != italian_report_id or self.code != 'VP14b':
return super()._get_carryover_destination_line(options)
end_of_period_month = fields.Date.from_string(options['date']['date_to']).month
# For the line 14, we are having a different target between periods or years
if end_of_period_month == 12:
# Between two years, we carryover to the line VP9
line = self.env.ref('l10n_it.tax_report_line_vp9')
else:
line = self.carry_over_destination_line_id or self
return line
| 40.766667
| 2,446
|
560
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Gauge Widget for Kanban',
'category': 'Hidden',
'description': """
This widget allows to display gauges using d3 library.
""",
'version': '1.0',
'depends': ['web'],
'assets' : {
'web.assets_backend': [
'web_kanban_gauge/static/src/**/*',
],
'web.qunit_suite_tests': [
'web_kanban_gauge/static/tests/**/*',
],
},
'auto_install': True,
'license': 'LGPL-3',
}
| 25.454545
| 560
|
666
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Argentinean eCommerce',
'version': '1.0',
'category': 'Accounting/Localizations/Website',
'sequence': 14,
'author': 'Odoo, ADHOC SA',
'description': """Be able to see Identification Type and AFIP Responsibility in ecommerce checkout form.""",
'depends': [
'website_sale',
'l10n_ar',
],
'data': [
'data/ir_model_fields.xml',
'views/templates.xml',
],
'demo': [
'demo/website_demo.xml',
],
'installable': True,
'auto_install': True,
'application': False,
'license': 'LGPL-3',
}
| 27.75
| 666
|
549
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import _, api, models
from odoo.exceptions import ValidationError
class View(models.Model):
_inherit = 'ir.ui.view'
@api.constrains('active', 'key', 'website_id')
def _check_active(self):
for record in self:
if record.key == 'website_sale.address_b2b' and record.website_id:
if record.website_id.company_id.country_id.code == "AR" and not record.active:
raise ValidationError(_("B2B fields must always be displayed with Argentinian website."))
| 39.214286
| 549
|
3,640
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _
from odoo.addons.website_sale.controllers.main import WebsiteSale
from odoo.http import request
class L10nARWebsiteSale(WebsiteSale):
def _get_mandatory_fields_billing(self, country_id=False):
"""Extend mandatory fields to add new identification and responsibility fields when company is argentina"""
res = super()._get_mandatory_fields_billing(country_id)
if request.website.sudo().company_id.country_id.code == "AR":
res += ["l10n_latam_identification_type_id", "l10n_ar_afip_responsibility_type_id", "vat"]
return res
def _get_country_related_render_values(self, kw, render_values):
res = super()._get_country_related_render_values(kw, render_values)
if request.website.sudo().company_id.country_id.code == "AR":
res.update({'identification': kw.get('l10n_latam_identification_type_id'),
'responsibility': kw.get('l10n_ar_afip_responsibility_type_id'),
'responsibility_types': request.env['l10n_ar.afip.responsibility.type'].search([]),
'identification_types': request.env['l10n_latam.identification.type'].search(
['|', ('country_id', '=', False), ('country_id.code', '=', 'AR')])})
return res
def _get_vat_validation_fields(self, data):
res = super()._get_vat_validation_fields(data)
if request.website.sudo().company_id.country_id.code == "AR":
res.update({'l10n_latam_identification_type_id': int(data['l10n_latam_identification_type_id'])
if data.get('l10n_latam_identification_type_id') else False})
res.update({'name': data['name'] if data.get('name') else False})
return res
def checkout_form_validate(self, mode, all_form_values, data):
""" We extend the method to add a new validation. If AFIP Resposibility is:
* Final Consumer or Foreign Customer: then it can select any identification type.
* Any other (Monotributista, RI, etc): should select always "CUIT" identification type"""
error, error_message = super().checkout_form_validate(mode, all_form_values, data)
# Identification type and AFIP Responsibility Combination
if request.website.sudo().company_id.country_id.code == "AR":
if mode[1] == 'billing':
if error and any(field in error for field in ['l10n_latam_identification_type_id', 'l10n_ar_afip_responsibility_type_id']):
return error, error_message
id_type_id = data.get("l10n_latam_identification_type_id")
afip_resp_id = data.get("l10n_ar_afip_responsibility_type_id")
id_type = request.env['l10n_latam.identification.type'].browse(id_type_id) if id_type_id else False
afip_resp = request.env['l10n_ar.afip.responsibility.type'].browse(afip_resp_id) if afip_resp_id else False
cuit_id_type = request.env.ref('l10n_ar.it_cuit')
# Check if the AFIP responsibility is different from Final Consumer or Foreign Customer,
# and if the identification type is different from CUIT
if afip_resp.code not in ['5', '9'] and id_type != cuit_id_type:
error["l10n_latam_identification_type_id"] = 'error'
error_message.append(_('For the selected AFIP Responsibility you will need to set CUIT Identification Type'))
return error, error_message
| 61.694915
| 3,640
|
2,239
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Events Organization',
'version': '1.6',
'website': 'https://www.odoo.com/app/events',
'category': 'Marketing/Events',
'summary': 'Trainings, Conferences, Meetings, Exhibitions, Registrations',
'description': """
Organization and management of Events.
======================================
The event module allows you to efficiently organize events and all related tasks: planning, registration tracking,
attendances, etc.
Key Features
------------
* Manage your Events and Registrations
* Use emails to automatically confirm and send acknowledgments for any event registration
""",
'depends': ['base_setup', 'mail', 'portal', 'utm'],
'data': [
'security/event_security.xml',
'security/ir.model.access.csv',
'views/event_menu_views.xml',
'views/event_ticket_views.xml',
'views/event_views.xml',
'views/event_stage_views.xml',
'report/event_event_templates.xml',
'report/event_event_reports.xml',
'data/ir_cron_data.xml',
'data/mail_template_data.xml',
'data/event_data.xml',
'views/res_config_settings_views.xml',
'views/event_templates.xml',
'views/res_partner_views.xml',
'views/event_tag_views.xml'
],
'demo': [
'data/res_users_demo.xml',
'data/res_partner_demo.xml',
'data/event_demo_misc.xml',
'data/event_demo.xml',
'data/event_registration_demo.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'web.assets_backend': [
'event/static/src/scss/event.scss',
'event/static/src/js/field_icon_selection.js',
],
'web.assets_common': [
'event/static/src/js/tours/**/*',
],
'web.assets_qweb': [
'event/static/src/xml/**/*',
],
'web.report_assets_common': [
'/event/static/src/scss/event_foldable_badge_report.scss',
'/event/static/src/scss/event_full_page_ticket_report.scss',
],
'web.report_assets_pdf': [
'/event/static/src/scss/event_full_page_ticket_report_pdf.scss',
],
},
'license': 'LGPL-3',
}
| 33.41791
| 2,239
|
16,400
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from dateutil.relativedelta import relativedelta
from freezegun import freeze_time
from odoo.addons.event.tests.common import TestEventCommon
from odoo.addons.mail.tests.common import MockEmail
from odoo.tools import formataddr, mute_logger
class TestMailSchedule(TestEventCommon, MockEmail):
@mute_logger('odoo.addons.base.models.ir_model', 'odoo.models')
def test_event_mail_schedule(self):
""" Test mail scheduling for events """
event_cron_id = self.env.ref('event.event_mail_scheduler')
# deactivate other schedulers to avoid messing with crons
self.env['event.mail'].search([]).unlink()
# freeze some datetimes, and ensure more than 1D+1H before event starts
# to ease time-based scheduler check
now = datetime(2021, 3, 20, 14, 30, 15)
event_date_begin = datetime(2021, 3, 22, 8, 0, 0)
event_date_end = datetime(2021, 3, 24, 18, 0, 0)
with freeze_time(now):
# create with admin to force create_date
test_event = self.env['event.event'].create({
'name': 'TestEventMail',
'create_date': now,
'user_id': self.user_eventmanager.id,
'auto_confirm': True,
'date_begin': event_date_begin,
'date_end': event_date_end,
'event_mail_ids': [
(0, 0, { # right at subscription
'interval_unit': 'now',
'interval_type': 'after_sub',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_subscription')}),
(0, 0, { # one day after subscription
'interval_nbr': 1,
'interval_unit': 'hours',
'interval_type': 'after_sub',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_subscription')}),
(0, 0, { # 1 days before event
'interval_nbr': 1,
'interval_unit': 'days',
'interval_type': 'before_event',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_reminder')}),
(0, 0, { # immediately after event
'interval_nbr': 1,
'interval_unit': 'hours',
'interval_type': 'after_event',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_reminder')}),
]
})
self.assertEqual(test_event.create_date, now)
# check subscription scheduler
after_sub_scheduler = self.env['event.mail'].search([('event_id', '=', test_event.id), ('interval_type', '=', 'after_sub'), ('interval_unit', '=', 'now')])
self.assertEqual(len(after_sub_scheduler), 1, 'event: wrong scheduler creation')
self.assertEqual(after_sub_scheduler.scheduled_date, test_event.create_date)
self.assertFalse(after_sub_scheduler.mail_done)
self.assertEqual(after_sub_scheduler.mail_state, 'running')
self.assertEqual(after_sub_scheduler.mail_count_done, 0)
after_sub_scheduler_2 = self.env['event.mail'].search([('event_id', '=', test_event.id), ('interval_type', '=', 'after_sub'), ('interval_unit', '=', 'hours')])
self.assertEqual(len(after_sub_scheduler_2), 1, 'event: wrong scheduler creation')
self.assertEqual(after_sub_scheduler_2.scheduled_date, test_event.create_date + relativedelta(hours=1))
self.assertFalse(after_sub_scheduler_2.mail_done)
self.assertEqual(after_sub_scheduler_2.mail_state, 'running')
self.assertEqual(after_sub_scheduler_2.mail_count_done, 0)
# check before event scheduler
event_prev_scheduler = self.env['event.mail'].search([('event_id', '=', test_event.id), ('interval_type', '=', 'before_event')])
self.assertEqual(len(event_prev_scheduler), 1, 'event: wrong scheduler creation')
self.assertEqual(event_prev_scheduler.scheduled_date, event_date_begin + relativedelta(days=-1))
self.assertFalse(event_prev_scheduler.mail_done)
self.assertEqual(event_prev_scheduler.mail_state, 'scheduled')
self.assertEqual(event_prev_scheduler.mail_count_done, 0)
# check after event scheduler
event_next_scheduler = self.env['event.mail'].search([('event_id', '=', test_event.id), ('interval_type', '=', 'after_event')])
self.assertEqual(len(event_next_scheduler), 1, 'event: wrong scheduler creation')
self.assertEqual(event_next_scheduler.scheduled_date, event_date_end + relativedelta(hours=1))
self.assertFalse(event_next_scheduler.mail_done)
self.assertEqual(event_next_scheduler.mail_state, 'scheduled')
self.assertEqual(event_next_scheduler.mail_count_done, 0)
# create some registrations
with freeze_time(now), self.mock_mail_gateway():
reg1 = self.env['event.registration'].with_user(self.user_eventuser).create({
'event_id': test_event.id,
'name': 'Reg1',
'email': 'reg1@example.com',
})
reg2 = self.env['event.registration'].with_user(self.user_eventuser).create({
'event_id': test_event.id,
'name': 'Reg2',
'email': 'reg2@example.com',
})
# REGISTRATIONS / PRE SCHEDULERS
# --------------------------------------------------
# check registration state
self.assertTrue(all(reg.state == 'open' for reg in reg1 + reg2), 'Registrations: should be auto-confirmed')
self.assertTrue(all(reg.date_open == now for reg in reg1 + reg2), 'Registrations: should have open date set to confirm date')
# verify that subscription scheduler was auto-executed after each registration
self.assertEqual(len(after_sub_scheduler.mail_registration_ids), 2, 'event: should have 2 scheduled communication (1 / registration)')
for mail_registration in after_sub_scheduler.mail_registration_ids:
self.assertEqual(mail_registration.scheduled_date, now)
self.assertTrue(mail_registration.mail_sent, 'event: registration mail should be sent at registration creation')
self.assertTrue(after_sub_scheduler.mail_done, 'event: all subscription mails should have been sent')
self.assertEqual(after_sub_scheduler.mail_state, 'running')
self.assertEqual(after_sub_scheduler.mail_count_done, 2)
# check emails effectively sent
self.assertEqual(len(self._new_mails), 2, 'event: should have 2 scheduled emails (1 / registration)')
self.assertMailMailWEmails(
[formataddr((reg1.name, reg1.email)), formataddr((reg2.name, reg2.email))],
'outgoing',
content=None,
fields_values={'subject': 'Your registration at %s' % test_event.name,
'email_from': self.user_eventmanager.company_id.email_formatted,
})
# same for second scheduler: scheduled but not sent
self.assertEqual(len(after_sub_scheduler_2.mail_registration_ids), 2, 'event: should have 2 scheduled communication (1 / registration)')
for mail_registration in after_sub_scheduler_2.mail_registration_ids:
self.assertEqual(mail_registration.scheduled_date, now + relativedelta(hours=1))
self.assertFalse(mail_registration.mail_sent, 'event: registration mail should be scheduled, not sent')
self.assertFalse(after_sub_scheduler_2.mail_done, 'event: all subscription mails should be scheduled, not sent')
self.assertEqual(after_sub_scheduler_2.mail_count_done, 0)
# execute event reminder scheduler explicitly, before scheduled date -> should not do anything
with freeze_time(now), self.mock_mail_gateway():
after_sub_scheduler_2.execute()
self.assertFalse(any(mail_reg.mail_sent for mail_reg in after_sub_scheduler_2.mail_registration_ids))
self.assertFalse(after_sub_scheduler_2.mail_done)
self.assertEqual(after_sub_scheduler_2.mail_count_done, 0)
self.assertEqual(len(self._new_mails), 0, 'event: should not send mails before scheduled date')
# execute event reminder scheduler explicitly, right at scheduled date -> should sent mails
now_registration = now + relativedelta(hours=1)
with freeze_time(now_registration), self.mock_mail_gateway():
after_sub_scheduler_2.execute()
# verify that subscription scheduler was auto-executed after each registration
self.assertEqual(len(after_sub_scheduler_2.mail_registration_ids), 2, 'event: should have 2 scheduled communication (1 / registration)')
self.assertTrue(all(mail_reg.mail_sent for mail_reg in after_sub_scheduler_2.mail_registration_ids))
self.assertTrue(after_sub_scheduler_2.mail_done, 'event: all subscription mails should have been sent')
self.assertEqual(after_sub_scheduler_2.mail_state, 'running')
self.assertEqual(after_sub_scheduler_2.mail_count_done, 2)
# check emails effectively sent
self.assertEqual(len(self._new_mails), 2, 'event: should have 2 scheduled emails (1 / registration)')
self.assertMailMailWEmails(
[formataddr((reg1.name, reg1.email)), formataddr((reg2.name, reg2.email))],
'outgoing',
content=None,
fields_values={'subject': 'Your registration at %s' % test_event.name,
'email_from': self.user_eventmanager.company_id.email_formatted,
})
# PRE SCHEDULERS (MOVE FORWARD IN TIME)
# --------------------------------------------------
self.assertFalse(event_prev_scheduler.mail_done)
self.assertEqual(event_prev_scheduler.mail_state, 'scheduled')
# simulate cron running before scheduled date -> should not do anything
now_start = event_date_begin + relativedelta(hours=-25)
with freeze_time(now_start), self.mock_mail_gateway():
event_cron_id.method_direct_trigger()
self.assertFalse(event_prev_scheduler.mail_done)
self.assertEqual(event_prev_scheduler.mail_state, 'scheduled')
self.assertEqual(event_prev_scheduler.mail_count_done, 0)
self.assertEqual(len(self._new_mails), 0)
# execute cron to run schedulers after scheduled date
now_start = event_date_begin + relativedelta(hours=-23)
with freeze_time(now_start), self.mock_mail_gateway():
event_cron_id.method_direct_trigger()
# check that scheduler is finished
self.assertTrue(event_prev_scheduler.mail_done, 'event: reminder scheduler should have run')
self.assertEqual(event_prev_scheduler.mail_state, 'sent', 'event: reminder scheduler should have run')
# check emails effectively sent
self.assertEqual(len(self._new_mails), 2, 'event: should have scheduled 2 mails (1 / registration)')
self.assertMailMailWEmails(
[formataddr((reg1.name, reg1.email)), formataddr((reg2.name, reg2.email))],
'outgoing',
content=None,
fields_values={'subject': '%s: tomorrow' % test_event.name,
'email_from': self.user_eventmanager.company_id.email_formatted,
})
# NEW REGISTRATION EFFECT ON SCHEDULERS
# --------------------------------------------------
test_event.write({'auto_confirm': False})
with freeze_time(now_start), self.mock_mail_gateway():
reg3 = self.env['event.registration'].with_user(self.user_eventuser).create({
'event_id': test_event.id,
'name': 'Reg3',
'email': 'reg3@example.com',
})
# no more seats
self.assertEqual(reg3.state, 'draft')
# schedulers state untouched
self.assertTrue(event_prev_scheduler.mail_done)
self.assertFalse(event_next_scheduler.mail_done)
self.assertTrue(after_sub_scheduler.mail_done, 'event: scheduler on registration not updated next to draft registration')
self.assertTrue(after_sub_scheduler_2.mail_done, 'event: scheduler on registration not updated next to draft registration')
# confirm registration -> should trigger registration schedulers
# NOTE: currently all schedulers are based on date_open which equals create_date
# meaning several communications may be sent in the time time
with freeze_time(now_start + relativedelta(hours=1)), self.mock_mail_gateway():
reg3.action_confirm()
# verify that subscription scheduler was auto-executed after new registration confirmed
self.assertEqual(len(after_sub_scheduler.mail_registration_ids), 3, 'event: should have 3 scheduled communication (1 / registration)')
new_mail_reg = after_sub_scheduler.mail_registration_ids.filtered(lambda mail_reg: mail_reg.registration_id == reg3)
self.assertEqual(new_mail_reg.scheduled_date, now_start)
self.assertTrue(new_mail_reg.mail_sent, 'event: registration mail should be sent at registration creation')
self.assertTrue(after_sub_scheduler.mail_done, 'event: all subscription mails should have been sent')
self.assertEqual(after_sub_scheduler.mail_count_done, 3)
# verify that subscription scheduler was auto-executed after new registration confirmed
self.assertEqual(len(after_sub_scheduler_2.mail_registration_ids), 3, 'event: should have 3 scheduled communication (1 / registration)')
new_mail_reg = after_sub_scheduler_2.mail_registration_ids.filtered(lambda mail_reg: mail_reg.registration_id == reg3)
self.assertEqual(new_mail_reg.scheduled_date, now_start + relativedelta(hours=1))
self.assertTrue(new_mail_reg.mail_sent, 'event: registration mail should be sent at registration creation')
self.assertTrue(after_sub_scheduler_2.mail_done, 'event: all subscription mails should have been sent')
self.assertEqual(after_sub_scheduler_2.mail_count_done, 3)
# check emails effectively sent
self.assertEqual(len(self._new_mails), 2, 'event: should have 1 scheduled emails (new registration only)')
# manual check because 2 identical mails are sent and mail tools do not support it easily
for mail in self._new_mails:
self.assertEqual(mail.email_from, self.user_eventmanager.company_id.email_formatted)
self.assertEqual(mail.subject, 'Your registration at %s' % test_event.name)
self.assertEqual(mail.state, 'outgoing')
self.assertEqual(mail.email_to, formataddr((reg3.name, reg3.email)))
# POST SCHEDULERS (MOVE FORWARD IN TIME)
# --------------------------------------------------
self.assertFalse(event_next_scheduler.mail_done)
# execute event reminder scheduler explicitly after its schedule date
new_end = event_date_end + relativedelta(hours=2)
with freeze_time(new_end), self.mock_mail_gateway():
event_cron_id.method_direct_trigger()
# check that scheduler is finished
self.assertTrue(event_next_scheduler.mail_done, 'event: reminder scheduler should should have run')
self.assertEqual(event_next_scheduler.mail_state, 'sent', 'event: reminder scheduler should have run')
self.assertEqual(event_next_scheduler.mail_count_done, 3)
# check emails effectively sent
self.assertEqual(len(self._new_mails), 3, 'event: should have scheduled 3 mails, one for each registration')
self.assertMailMailWEmails(
[formataddr((reg1.name, reg1.email)), formataddr((reg2.name, reg2.email)), formataddr((reg3.name, reg3.email))],
'outgoing',
content=None,
fields_values={'subject': '%s: today' % test_event.name,
'email_from': self.user_eventmanager.company_id.email_formatted,
})
| 59.636364
| 16,400
|
6,443
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from dateutil.relativedelta import relativedelta
from odoo.addons.event.tests.common import TestEventCommon
from odoo.exceptions import ValidationError
from odoo.tests.common import Form
from odoo.tools import mute_logger
class TestEventUI(TestEventCommon):
def test_event_registration_partner_sync(self):
""" Ensure onchange on partner_id is kept for interface, not for computed
fields. """
registration_form = Form(self.env['event.registration'].with_context(
default_name='WrongName',
default_event_id=self.event_0.id
))
self.assertEqual(registration_form.event_id, self.event_0)
self.assertEqual(registration_form.name, 'WrongName')
self.assertFalse(registration_form.email)
self.assertFalse(registration_form.phone)
self.assertFalse(registration_form.mobile)
# trigger onchange
registration_form.partner_id = self.event_customer
self.assertEqual(registration_form.name, self.event_customer.name)
self.assertEqual(registration_form.email, self.event_customer.email)
self.assertEqual(registration_form.phone, self.event_customer.phone)
self.assertEqual(registration_form.mobile, self.event_customer.mobile)
# save, check record matches Form values
registration = registration_form.save()
self.assertEqual(registration.partner_id, self.event_customer)
self.assertEqual(registration.name, self.event_customer.name)
self.assertEqual(registration.email, self.event_customer.email)
self.assertEqual(registration.phone, self.event_customer.phone)
self.assertEqual(registration.mobile, self.event_customer.mobile)
# allow writing on some fields independently from customer config
registration.write({'phone': False, 'mobile': False})
self.assertFalse(registration.phone)
self.assertFalse(registration.mobile)
# reset partner should not reset other fields
registration.write({'partner_id': False})
self.assertEqual(registration.partner_id, self.env['res.partner'])
self.assertEqual(registration.name, self.event_customer.name)
self.assertEqual(registration.email, self.event_customer.email)
self.assertFalse(registration.phone)
self.assertFalse(registration.mobile)
# update to a new partner not through UI -> update only void feilds
registration.write({'partner_id': self.event_customer2.id})
self.assertEqual(registration.partner_id, self.event_customer2)
self.assertEqual(registration.name, self.event_customer.name)
self.assertEqual(registration.email, self.event_customer.email)
self.assertEqual(registration.phone, self.event_customer2.phone)
self.assertEqual(registration.mobile, self.event_customer2.mobile)
class TestEventFlow(TestEventCommon):
@mute_logger('odoo.addons.base.models.ir_model', 'odoo.models')
def test_event_auto_confirm(self):
""" Basic event management with auto confirmation """
# EventUser creates a new event: ok
test_event = self.env['event.event'].with_user(self.user_eventmanager).create({
'name': 'TestEvent',
'auto_confirm': True,
'date_begin': datetime.datetime.now() + relativedelta(days=-1),
'date_end': datetime.datetime.now() + relativedelta(days=1),
'seats_max': 2,
'seats_limited': True,
})
self.assertTrue(test_event.auto_confirm)
# EventUser create registrations for this event
test_reg1 = self.env['event.registration'].with_user(self.user_eventuser).create({
'name': 'TestReg1',
'event_id': test_event.id,
})
self.assertEqual(test_reg1.state, 'open', 'Event: auto_confirmation of registration failed')
self.assertEqual(test_event.seats_reserved, 1, 'Event: wrong number of reserved seats after confirmed registration')
test_reg2 = self.env['event.registration'].with_user(self.user_eventuser).create({
'name': 'TestReg2',
'event_id': test_event.id,
})
self.assertEqual(test_reg2.state, 'open', 'Event: auto_confirmation of registration failed')
self.assertEqual(test_event.seats_reserved, 2, 'Event: wrong number of reserved seats after confirmed registration')
# EventUser create registrations for this event: too much registrations
with self.assertRaises(ValidationError):
self.env['event.registration'].with_user(self.user_eventuser).create({
'name': 'TestReg3',
'event_id': test_event.id,
})
# EventUser validates registrations
test_reg1.action_set_done()
self.assertEqual(test_reg1.state, 'done', 'Event: wrong state of attended registration')
self.assertEqual(test_event.seats_used, 1, 'Event: incorrect number of attendees after closing registration')
test_reg2.action_set_done()
self.assertEqual(test_reg1.state, 'done', 'Event: wrong state of attended registration')
self.assertEqual(test_event.seats_used, 2, 'Event: incorrect number of attendees after closing registration')
@mute_logger('odoo.addons.base.models.ir_model', 'odoo.models')
def test_event_flow(self):
""" Advanced event flow: no auto confirmation, manage minimum / maximum
seats, ... """
# EventUser creates a new event: ok
test_event = self.env['event.event'].with_user(self.user_eventmanager).create({
'name': 'TestEvent',
'date_begin': datetime.datetime.now() + relativedelta(days=-1),
'date_end': datetime.datetime.now() + relativedelta(days=1),
'seats_limited': True,
'seats_max': 10,
})
self.assertFalse(test_event.auto_confirm)
# EventUser create registrations for this event -> no auto confirmation
test_reg1 = self.env['event.registration'].with_user(self.user_eventuser).create({
'name': 'TestReg1',
'event_id': test_event.id,
})
self.assertEqual(
test_reg1.state, 'draft',
'Event: new registration should not be confirmed with auto_confirmation parameter being False')
| 48.810606
| 6,443
|
4,853
|
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.addons.mail.tests.common import mail_new_test_user
from odoo.tests import common
class TestEventCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestEventCommon, cls).setUpClass()
# Test users to use through the various tests
cls.user_portal = mail_new_test_user(
cls.env, login='portal_test',
name='Patrick Portal', email='patrick.portal@test.example.com',
notification_type='email', company_id=cls.env.ref("base.main_company").id,
groups='base.group_portal')
cls.user_employee = mail_new_test_user(
cls.env, login='user_employee',
name='Eglantine Employee', email='eglantine.employee@test.example.com',
tz='Europe/Brussels', notification_type='inbox',
company_id=cls.env.ref("base.main_company").id,
groups='base.group_user',
)
cls.user_eventregistrationdesk = mail_new_test_user(
cls.env, login='user_eventregistrationdesk',
name='Ursule EventRegistration', email='ursule.eventregistration@test.example.com',
tz='Europe/Brussels', notification_type='inbox',
company_id=cls.env.ref("base.main_company").id,
groups='base.group_user,event.group_event_registration_desk',
)
cls.user_eventuser = mail_new_test_user(
cls.env, login='user_eventuser',
name='Ursule EventUser', email='ursule.eventuser@test.example.com',
tz='Europe/Brussels', notification_type='inbox',
company_id=cls.env.ref("base.main_company").id,
groups='base.group_user,event.group_event_user',
)
cls.user_eventmanager = mail_new_test_user(
cls.env, login='user_eventmanager',
name='Martine EventManager', email='martine.eventmanager@test.example.com',
tz='Europe/Brussels', notification_type='inbox',
company_id=cls.env.ref("base.main_company").id,
groups='base.group_user,event.group_event_manager',
)
cls.event_customer = cls.env['res.partner'].create({
'name': 'Constantin Customer',
'email': 'constantin@test.example.com',
'country_id': cls.env.ref('base.be').id,
'phone': '0485112233',
'mobile': False,
})
cls.event_customer2 = cls.env['res.partner'].create({
'name': 'Constantin Customer 2',
'email': 'constantin2@test.example.com',
'country_id': cls.env.ref('base.be').id,
'phone': '0456987654',
'mobile': '0456654321',
})
cls.event_type_complex = cls.env['event.type'].create({
'name': 'Update Type',
'auto_confirm': True,
'has_seats_limitation': True,
'seats_max': 30,
'default_timezone': 'Europe/Paris',
'event_type_ticket_ids': [(0, 0, {
'name': 'First Ticket',
}), (0, 0, {
'name': 'Second Ticket',
})
],
'event_type_mail_ids': [
(0, 0, { # right at subscription
'interval_unit': 'now',
'interval_type': 'after_sub',
'template_ref': 'mail.template,%i' % cls.env['ir.model.data']._xmlid_to_res_id('event.event_subscription')}),
(0, 0, { # 1 days before event
'interval_nbr': 1,
'interval_unit': 'days',
'interval_type': 'before_event',
'template_ref': 'mail.template,%i' % cls.env['ir.model.data']._xmlid_to_res_id('event.event_reminder')}),
],
})
cls.event_0 = cls.env['event.event'].create({
'name': 'TestEvent',
'auto_confirm': True,
'date_begin': fields.Datetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': fields.Datetime.to_string(datetime.today() + timedelta(days=15)),
'date_tz': 'Europe/Brussels',
})
# set country in order to format Belgian numbers
cls.event_0.company_id.write({'country_id': cls.env.ref('base.be').id})
@classmethod
def _create_registrations(cls, event, reg_count):
# create some registrations
registrations = cls.env['event.registration'].create([{
'event_id': event.id,
'name': 'Test Registration %s' % x,
'email': '_test_reg_%s@example.com' % x,
'phone': '04560000%s%s' % (x, x),
} for x in range(0, reg_count)])
return registrations
| 43.720721
| 4,853
|
30,568
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime, timedelta
from unittest.mock import patch
from odoo import Command
from odoo.addons.event.tests.common import TestEventCommon
from odoo import exceptions
from odoo.fields import Datetime as FieldsDatetime, Date as FieldsDate
from odoo.tests.common import users, Form
from odoo.tools import mute_logger
class TestEventData(TestEventCommon):
@classmethod
def setUpClass(cls):
super(TestEventData, cls).setUpClass()
cls.patcher = patch('odoo.addons.event.models.event_event.fields.Datetime', wraps=FieldsDatetime)
cls.mock_datetime = cls.patcher.start()
cls.mock_datetime.now.return_value = datetime(2020, 1, 31, 10, 0, 0)
cls.addClassCleanup(cls.patcher.stop)
cls.event_0.write({
'date_begin': datetime(2020, 2, 1, 8, 30, 0),
'date_end': datetime(2020, 2, 4, 18, 45, 0),
})
@users('user_eventmanager')
def test_event_date_computation(self):
event = self.event_0.with_user(self.env.user)
event.write({
'registration_ids': [(0, 0, {'partner_id': self.event_customer.id, 'name': 'test_reg'})],
'date_begin': datetime(2020, 1, 31, 15, 0, 0),
'date_end': datetime(2020, 4, 5, 18, 0, 0),
})
registration = event.registration_ids[0]
self.assertEqual(registration.get_date_range_str(), u'today')
event.date_begin = datetime(2020, 2, 1, 15, 0, 0)
self.assertEqual(registration.get_date_range_str(), u'tomorrow')
event.date_begin = datetime(2020, 2, 2, 6, 0, 0)
self.assertEqual(registration.get_date_range_str(), u'in 2 days')
event.date_begin = datetime(2020, 2, 20, 17, 0, 0)
self.assertEqual(registration.get_date_range_str(), u'next month')
event.date_begin = datetime(2020, 3, 1, 10, 0, 0)
self.assertEqual(registration.get_date_range_str(), u'on Mar 1, 2020, 11:00:00 AM')
# Is actually 8:30 to 20:00 in Mexico
event.write({
'date_begin': datetime(2020, 1, 31, 14, 30, 0),
'date_end': datetime(2020, 2, 1, 2, 0, 0),
'date_tz': 'Mexico/General'
})
self.assertTrue(event.is_one_day)
@users('user_eventmanager')
def test_event_date_timezone(self):
event = self.event_0.with_user(self.env.user)
# Is actually 8:30 to 20:00 in Mexico
event.write({
'date_begin': datetime(2020, 1, 31, 14, 30, 0),
'date_end': datetime(2020, 2, 1, 2, 0, 0),
'date_tz': 'Mexico/General'
})
self.assertTrue(event.is_one_day)
self.assertFalse(event.is_ongoing)
@users('user_eventmanager')
@mute_logger('odoo.models.unlink')
def test_event_configuration_from_type(self):
""" Test data computation of event coming from its event.type template. """
self.assertEqual(self.env.user.tz, 'Europe/Brussels')
# ------------------------------------------------------------
# STARTING DATA
# ------------------------------------------------------------
event_type = self.env['event.type'].browse(self.event_type_complex.id)
event = self.env['event.event'].create({
'name': 'Event Update Type',
'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
'event_mail_ids': False,
})
self.assertEqual(event.date_tz, self.env.user.tz)
self.assertFalse(event.seats_limited)
self.assertFalse(event.auto_confirm)
self.assertEqual(event.event_mail_ids, self.env['event.mail'])
self.assertEqual(event.event_ticket_ids, self.env['event.event.ticket'])
registration = self._create_registrations(event, 1)
self.assertEqual(registration.state, 'draft') # event is not auto confirm
# ------------------------------------------------------------
# FILL SYNC TEST
# ------------------------------------------------------------
# change template to a one with mails -> fill event as it is void
event_type.write({
'event_type_mail_ids': [(5, 0), (0, 0, {
'interval_nbr': 1, 'interval_unit': 'days', 'interval_type': 'before_event',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_reminder')})
],
'event_type_ticket_ids': [(5, 0), (0, 0, {'name': 'TestRegistration'})],
})
event.write({'event_type_id': event_type.id})
self.assertEqual(event.date_tz, 'Europe/Paris')
self.assertTrue(event.seats_limited)
self.assertEqual(event.seats_max, event_type.seats_max)
self.assertTrue(event.auto_confirm)
# check 2many fields being populated
self.assertEqual(len(event.event_mail_ids), 1)
self.assertEqual(event.event_mail_ids.interval_nbr, 1)
self.assertEqual(event.event_mail_ids.interval_unit, 'days')
self.assertEqual(event.event_mail_ids.interval_type, 'before_event')
self.assertEqual(event.event_mail_ids.template_ref, self.env.ref('event.event_reminder'))
self.assertEqual(len(event.event_ticket_ids), 1)
# update template, unlink from event -> should not impact event
event_type.write({'has_seats_limitation': False})
self.assertEqual(event_type.seats_max, 0)
self.assertTrue(event.seats_limited)
self.assertEqual(event.seats_max, 30) # original template value
event.write({'event_type_id': False})
self.assertEqual(event.event_type_id, self.env["event.type"])
# set template back -> update event
event.write({'event_type_id': event_type.id})
self.assertFalse(event.seats_limited)
self.assertEqual(event.seats_max, 0)
self.assertEqual(len(event.event_ticket_ids), 1)
event_ticket1 = event.event_ticket_ids[0]
self.assertEqual(event_ticket1.name, 'TestRegistration')
@users('user_eventmanager')
def test_event_configuration_mails_from_type(self):
""" Test data computation (related to mails) of event coming from its event.type template.
This test uses pretty low level Form data checks, as manipulations in a non-saved Form are
required to highlight an undesired behavior when switching event_type templates :
event_mail_ids not linked to a registration were generated and kept when switching between
different templates in the Form, which could rapidly lead to a substantial amount of
undesired lines. """
# setup test records
event_type_default = self.env['event.type'].create({
'name': 'Type Default',
'auto_confirm': True,
'event_type_mail_ids': False,
})
event_type_mails = self.env['event.type'].create({
'name': 'Type Mails',
'auto_confirm': False,
'event_type_mail_ids': [
Command.clear(),
Command.create({
'notification_type': 'mail',
'interval_nbr': 77,
'interval_unit': 'days',
'interval_type': 'after_event',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_reminder'),
})
],
})
event = self.env['event.event'].create({
'name': 'Event',
'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
'event_type_id': event_type_default.id
})
event.write({
'event_mail_ids': [
Command.clear(),
Command.create({
'notification_type': 'mail',
'interval_unit': 'now',
'interval_type': 'after_sub',
'template_ref': 'mail.template,%i' % self.env['ir.model.data']._xmlid_to_res_id('event.event_subscription'),
})
]
})
mail = event.event_mail_ids[0]
registration = self._create_registrations(event, 1)
self.assertEqual(registration.state, 'open') # event auto confirms
# verify that mail is linked to the registration
self.assertEqual(
set(mail.mapped('mail_registration_ids.registration_id.id')),
set([registration.id])
)
# start test scenario
event_form = Form(event)
# verify that mail is linked to the event in the form
self.assertEqual(
set(map(lambda m: m.get('id', None), event_form.event_mail_ids._records)),
set([mail.id])
)
# switch to an event_type with a mail template which should be computed
event_form.event_type_id = event_type_mails
# verify that 2 mails were computed
self.assertEqual(len(event_form.event_mail_ids._records), 2)
# verify that the mail linked to the registration was kept
self.assertTrue(filter(lambda m: m.get('id', None) == mail.id, event_form.event_mail_ids._records))
# since the other computed event.mail is to be created from an event.type.mail template,
# verify that its attributes are the correct ones
computed_mail = next(filter(lambda m: m.get('id', None) != mail.id, event_form.event_mail_ids._records), {})
self.assertEqual(computed_mail.get('interval_nbr', None), 77)
self.assertEqual(computed_mail.get('interval_unit', None), 'days')
self.assertEqual(computed_mail.get('interval_type', None), 'after_event')
# switch back to an event type without a mail template
event_form.event_type_id = event_type_default
# verify that the mail linked to the registration was kept, and the other removed
self.assertEqual(
set(map(lambda m: m.get('id', None), event_form.event_mail_ids._records)),
set([mail.id])
)
@users('user_eventmanager')
def test_event_configuration_note_from_type(self):
event_type = self.env['event.type'].browse(self.event_type_complex.id)
event = self.env['event.event'].create({
'name': 'Event Update Type Note',
'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
})
# verify that note is not propagated if the event type contains blank html
event.write({'note': '<p>Event Note</p>'})
event_type.write({'note': '<p><br></p>'})
event.write({'event_type_id': event_type.id})
self.assertEqual(event.note, '<p>Event Note</p>')
# verify that note is correctly propagated if it contains non empty html
event.write({'event_type_id': False})
event_type.write({'note': '<p>Event Type Note</p>'})
event.write({'event_type_id': event_type.id})
self.assertEqual(event.note, '<p>Event Type Note</p>')
@users('user_eventmanager')
def test_event_configuration_tickets_from_type(self):
""" Test data computation (related to tickets) of event coming from its event.type template.
This test uses pretty low level Form data checks, as manipulations in a non-saved Form are
required to highlight an undesired behavior when switching event_type templates :
event_ticket_ids not linked to a registration were generated and kept when switching between
different templates in the Form, which could rapidly lead to a substantial amount of
undesired lines. """
# setup test records
event_type_default = self.env['event.type'].create({
'name': 'Type Default',
'auto_confirm': True
})
event_type_tickets = self.env['event.type'].create({
'name': 'Type Tickets',
'auto_confirm': False
})
event_type_tickets.write({
'event_type_ticket_ids': [
Command.clear(),
Command.create({
'name': 'Default Ticket',
'seats_max': 10,
})
]
})
event = self.env['event.event'].create({
'name': 'Event',
'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
'event_type_id': event_type_default.id
})
event.write({
'event_ticket_ids': [
Command.clear(),
Command.create({
'name': 'Registration Ticket',
'seats_max': 10,
})
]
})
ticket = event.event_ticket_ids[0]
registration = self._create_registrations(event, 1)
# link the ticket to the registration
registration.write({'event_ticket_id': ticket.id})
# start test scenario
event_form = Form(event)
# verify that the ticket is linked to the event in the form
self.assertEqual(
set(map(lambda m: m.get('name', None), event_form.event_ticket_ids._records)),
set(['Registration Ticket'])
)
# switch to an event_type with a ticket template which should be computed
event_form.event_type_id = event_type_tickets
# verify that both tickets are computed
self.assertEqual(
set(map(lambda m: m.get('name', None), event_form.event_ticket_ids._records)),
set(['Registration Ticket', 'Default Ticket'])
)
# switch back to an event_type without default tickets
event_form.event_type_id = event_type_default
# verify that the ticket linked to the registration was kept, and the other removed
self.assertEqual(
set(map(lambda m: m.get('name', None), event_form.event_ticket_ids._records)),
set(['Registration Ticket'])
)
@users('user_eventmanager')
def test_event_mail_default_config(self):
event = self.env['event.event'].create({
'name': 'Event Update Type',
'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
})
self.assertEqual(event.date_tz, self.env.user.tz)
self.assertFalse(event.seats_limited)
self.assertFalse(event.auto_confirm)
#Event Communications: when no event type, default configuration
self.assertEqual(len(event.event_mail_ids), 3)
self.assertEqual(event.event_mail_ids[0].interval_unit, 'now')
self.assertEqual(event.event_mail_ids[0].interval_type, 'after_sub')
self.assertEqual(event.event_mail_ids[0].template_ref, self.env.ref('event.event_subscription'))
self.assertEqual(event.event_mail_ids[1].interval_nbr, 1)
self.assertEqual(event.event_mail_ids[1].interval_unit, 'hours')
self.assertEqual(event.event_mail_ids[1].interval_type, 'before_event')
self.assertEqual(event.event_mail_ids[1].template_ref, self.env.ref('event.event_reminder'))
self.assertEqual(event.event_mail_ids[2].interval_nbr, 3)
self.assertEqual(event.event_mail_ids[2].interval_unit, 'days')
self.assertEqual(event.event_mail_ids[2].interval_type, 'before_event')
self.assertEqual(event.event_mail_ids[2].template_ref, self.env.ref('event.event_reminder'))
event.write({
'event_mail_ids': False
})
self.assertEqual(event.event_mail_ids, self.env['event.mail'])
def test_event_mail_filter_template_on_event(self):
"""Test that the mail template are filtered to show only those which are related to the event registration model.
This is important to be able to show only relevant mail templates on the related
field "template_ref".
"""
self.env['mail.template'].search([('model', '=', 'event.registration')]).unlink()
self.env['mail.template'].create({'model_id': self.env['ir.model']._get('event.registration').id, 'name': 'test template'})
self.env['mail.template'].create({'model_id': self.env['ir.model']._get('res.partner').id, 'name': 'test template'})
templates = self.env['mail.template'].with_context(filter_template_on_event=True).name_search('test template')
self.assertEqual(len(templates), 1, 'Should return only mail templates related to the event registration model')
@users('user_eventmanager')
def test_event_registrable(self):
"""Test if `_compute_event_registrations_open` works properly."""
event = self.event_0.with_user(self.env.user)
event.write({
'date_begin': datetime(2020, 1, 30, 8, 0, 0),
'date_end': datetime(2020, 1, 31, 8, 0, 0),
})
self.assertFalse(event.event_registrations_open)
event.write({
'date_end': datetime(2020, 2, 4, 8, 0, 0),
})
self.assertTrue(event.event_registrations_open)
# ticket without dates boundaries -> ok
ticket = self.env['event.event.ticket'].create({
'name': 'TestTicket',
'event_id': event.id,
})
self.assertTrue(event.event_registrations_open)
# even with valid tickets, date limits registrations
event.write({
'date_begin': datetime(2020, 1, 28, 15, 0, 0),
'date_end': datetime(2020, 1, 30, 15, 0, 0),
})
self.assertFalse(event.event_registrations_open)
# no more seats available
registration = self.env['event.registration'].create({
'name': 'Albert Test',
'event_id': event.id,
})
registration.action_confirm()
event.write({
'date_end': datetime(2020, 2, 1, 15, 0, 0),
'seats_max': 1,
'seats_limited': True,
})
self.assertEqual(event.seats_available, 0)
self.assertFalse(event.event_registrations_open)
# seats available are back
registration.unlink()
self.assertEqual(event.seats_available, 1)
self.assertTrue(event.event_registrations_open)
# but tickets are expired
ticket.write({'end_sale_datetime': datetime(2020, 1, 30, 15, 0, 0)})
self.assertTrue(ticket.is_expired)
self.assertFalse(event.event_registrations_open)
@users('user_eventmanager')
def test_event_ongoing(self):
event_1 = self.env['event.event'].create({
'name': 'Test Event 1',
'date_begin': datetime(2020, 1, 25, 8, 0, 0),
'date_end': datetime(2020, 2, 1, 18, 0, 0),
})
self.assertTrue(event_1.is_ongoing)
ongoing_event_ids = self.env['event.event']._search([('is_ongoing', '=', True)])
self.assertIn(event_1.id, ongoing_event_ids)
event_1.update({'date_begin': datetime(2020, 2, 1, 9, 0, 0)})
self.assertFalse(event_1.is_ongoing)
ongoing_event_ids = self.env['event.event']._search([('is_ongoing', '=', True)])
self.assertNotIn(event_1.id, ongoing_event_ids)
event_2 = self.env['event.event'].create({
'name': 'Test Event 2',
'date_begin': datetime(2020, 1, 25, 8, 0, 0),
'date_end': datetime(2020, 1, 28, 8, 0, 0),
})
self.assertFalse(event_2.is_ongoing)
finished_or_upcoming_event_ids = self.env['event.event']._search([('is_ongoing', '=', False)])
self.assertIn(event_2.id, finished_or_upcoming_event_ids)
event_2.update({'date_end': datetime(2020, 2, 2, 8, 0, 1)})
self.assertTrue(event_2.is_ongoing)
finished_or_upcoming_event_ids = self.env['event.event']._search([('is_ongoing', '=', False)])
self.assertNotIn(event_2.id, finished_or_upcoming_event_ids)
@users('user_eventmanager')
def test_event_seats(self):
event_type = self.event_type_complex.with_user(self.env.user)
event = self.env['event.event'].create({
'name': 'Event Update Type',
'event_type_id': event_type.id,
'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
})
self.assertEqual(event.address_id, self.env.user.company_id.partner_id)
# seats: coming from event type configuration
self.assertTrue(event.seats_limited)
self.assertEqual(event.seats_available, event.event_type_id.seats_max)
self.assertEqual(event.seats_unconfirmed, 0)
self.assertEqual(event.seats_reserved, 0)
self.assertEqual(event.seats_used, 0)
self.assertEqual(event.seats_expected, 0)
# create registration in order to check the seats computation
self.assertTrue(event.auto_confirm)
for x in range(5):
reg = self.env['event.registration'].create({
'event_id': event.id,
'name': 'reg_open',
})
self.assertEqual(reg.state, 'open')
reg_draft = self.env['event.registration'].create({
'event_id': event.id,
'name': 'reg_draft',
})
reg_draft.write({'state': 'draft'})
reg_done = self.env['event.registration'].create({
'event_id': event.id,
'name': 'reg_done',
})
reg_done.write({'state': 'done'})
self.assertEqual(event.seats_available, event.event_type_id.seats_max - 6)
self.assertEqual(event.seats_unconfirmed, 1)
self.assertEqual(event.seats_reserved, 5)
self.assertEqual(event.seats_used, 1)
self.assertEqual(event.seats_expected, 7)
class TestEventRegistrationData(TestEventCommon):
@users('user_eventmanager')
def test_registration_partner_sync(self):
""" Test registration computed fields about partner """
test_email = '"Nibbler In Space" <nibbler@futurama.example.com>'
test_phone = '0456001122'
event = self.env['event.event'].browse(self.event_0.ids)
customer = self.env['res.partner'].browse(self.event_customer.id)
# take all from partner
event.write({
'registration_ids': [(0, 0, {
'partner_id': customer.id,
})]
})
new_reg = event.registration_ids[0]
self.assertEqual(new_reg.partner_id, customer)
self.assertEqual(new_reg.name, customer.name)
self.assertEqual(new_reg.email, customer.email)
self.assertEqual(new_reg.phone, customer.phone)
# partial update
event.write({
'registration_ids': [(0, 0, {
'partner_id': customer.id,
'name': 'Nibbler In Space',
'email': test_email,
})]
})
new_reg = event.registration_ids.sorted()[0]
self.assertEqual(new_reg.partner_id, customer)
self.assertEqual(
new_reg.name, 'Nibbler In Space',
'Registration should take user input over computed partner value')
self.assertEqual(
new_reg.email, test_email,
'Registration should take user input over computed partner value')
self.assertEqual(
new_reg.phone, customer.phone,
'Registration should take partner value if not user input')
# already filled information should not be updated
event.write({
'registration_ids': [(0, 0, {
'name': 'Nibbler In Space',
'phone': test_phone,
})]
})
new_reg = event.registration_ids.sorted()[0]
self.assertEqual(new_reg.name, 'Nibbler In Space')
self.assertEqual(new_reg.email, False)
self.assertEqual(new_reg.phone, test_phone)
new_reg.write({'partner_id': customer.id})
self.assertEqual(new_reg.partner_id, customer)
self.assertEqual(new_reg.name, 'Nibbler In Space')
self.assertEqual(new_reg.email, customer.email)
self.assertEqual(new_reg.phone, test_phone)
@users('user_eventmanager')
def test_registration_partner_sync_company(self):
""" Test synchronization involving companies """
event = self.env['event.event'].browse(self.event_0.ids)
customer = self.env['res.partner'].browse(self.event_customer.id)
# create company structure (using sudo as required partner manager group)
company = self.env['res.partner'].sudo().create({
'name': 'Customer Company',
'is_company': True,
'type': 'other',
})
customer.sudo().write({'type': 'invoice', 'parent_id': company.id})
contact = self.env['res.partner'].sudo().create({
'name': 'ContactName',
'parent_id': company.id,
'type': 'contact',
'email': 'ContactEmail <contact.email@test.example.com>',
'phone': '+32456998877',
})
# take all from partner
event.write({
'registration_ids': [(0, 0, {
'partner_id': customer.id,
})]
})
new_reg = event.registration_ids[0]
self.assertEqual(new_reg.partner_id, customer)
self.assertEqual(new_reg.name, contact.name)
self.assertEqual(new_reg.email, contact.email)
self.assertEqual(new_reg.phone, contact.phone)
class TestEventTicketData(TestEventCommon):
def setUp(self):
super(TestEventTicketData, self).setUp()
self.ticket_date_patcher = patch('odoo.addons.event.models.event_ticket.fields.Date', wraps=FieldsDate)
self.ticket_date_patcher_mock = self.ticket_date_patcher.start()
self.ticket_date_patcher_mock.context_today.return_value = date(2020, 1, 31)
self.ticket_datetime_patcher = patch('odoo.addons.event.models.event_ticket.fields.Datetime', wraps=FieldsDatetime)
self.ticket_datetime_patcher_mock = self.ticket_datetime_patcher.start()
self.ticket_datetime_patcher_mock.now.return_value = datetime(2020, 1, 31, 10, 0, 0)
def tearDown(self):
super(TestEventTicketData, self).tearDown()
self.ticket_date_patcher.stop()
self.ticket_datetime_patcher.stop()
@users('user_eventmanager')
def test_event_ticket_fields(self):
""" Test event ticket fields synchronization """
event = self.event_0.with_user(self.env.user)
event.write({
'event_ticket_ids': [
(5, 0),
(0, 0, {
'name': 'First Ticket',
'seats_max': 30,
}), (0, 0, { # limited in time, available (01/10 (start) < 01/31 (today) < 02/10 (end))
'name': 'Second Ticket',
'start_sale_datetime': datetime(2020, 1, 10, 0, 0, 0),
'end_sale_datetime': datetime(2020, 2, 10, 23, 59, 59),
})
],
})
first_ticket = event.event_ticket_ids.filtered(lambda t: t.name == 'First Ticket')
second_ticket = event.event_ticket_ids.filtered(lambda t: t.name == 'Second Ticket')
self.assertTrue(first_ticket.seats_limited)
self.assertTrue(first_ticket.sale_available)
self.assertFalse(first_ticket.is_expired)
self.assertFalse(second_ticket.seats_limited)
self.assertTrue(second_ticket.sale_available)
self.assertFalse(second_ticket.is_expired)
# sale is ended
second_ticket.write({'end_sale_datetime': datetime(2020, 1, 20, 23, 59, 59)})
self.assertFalse(second_ticket.sale_available)
self.assertTrue(second_ticket.is_expired)
# sale has not started
second_ticket.write({
'start_sale_datetime': datetime(2020, 2, 10, 0, 0, 0),
'end_sale_datetime': datetime(2020, 2, 20, 23, 59, 59),
})
self.assertFalse(second_ticket.sale_available)
self.assertFalse(second_ticket.is_expired)
# sale started today
second_ticket.write({
'start_sale_datetime': datetime(2020, 1, 31, 0, 0, 0),
'end_sale_datetime': datetime(2020, 2, 20, 23, 59, 59),
})
self.assertTrue(second_ticket.sale_available)
self.assertTrue(second_ticket.is_launched())
self.assertFalse(second_ticket.is_expired)
# incoherent dates are invalid
with self.assertRaises(exceptions.UserError):
second_ticket.write({'end_sale_datetime': datetime(2020, 1, 20, 23, 59, 59)})
#test if event start/end dates are taking datetime fields (hours, minutes, seconds) into account
second_ticket.write({'start_sale_datetime': datetime(2020, 1, 31, 11, 0, 0)})
self.assertFalse(second_ticket.sale_available)
self.assertFalse(second_ticket.is_launched())
second_ticket.write({
'start_sale_datetime': datetime(2020, 1, 31, 7, 0, 0),
'end_sale_datetime': datetime(2020, 2, 27, 13, 0, 0)
})
self.assertTrue(second_ticket.sale_available)
self.assertTrue(second_ticket.is_launched())
self.assertFalse(second_ticket.is_expired)
second_ticket.write({
'end_sale_datetime': datetime(2020, 1, 31, 9, 0, 0)
})
self.assertFalse(second_ticket.sale_available)
self.assertTrue(second_ticket.is_expired)
class TestEventTypeData(TestEventCommon):
@users('user_eventmanager')
def test_event_type_fields(self):
""" Test event type fields synchronization """
# create test type and ensure its initial values
event_type = self.env['event.type'].create({
'name': 'Testing fields computation',
'has_seats_limitation': True,
'seats_max': 30,
})
self.assertTrue(event_type.has_seats_limitation)
self.assertEqual(event_type.seats_max, 30)
# reset seats limitation
event_type.write({'has_seats_limitation': False})
self.assertFalse(event_type.has_seats_limitation)
self.assertEqual(event_type.seats_max, 0)
| 45.152142
| 30,568
|
14,340
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import random
import threading
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
from odoo.tools import exception_to_unicode
from odoo.tools.translate import _
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)
_INTERVALS = {
'hours': lambda interval: relativedelta(hours=interval),
'days': lambda interval: relativedelta(days=interval),
'weeks': lambda interval: relativedelta(days=7*interval),
'months': lambda interval: relativedelta(months=interval),
'now': lambda interval: relativedelta(hours=0),
}
class EventTypeMail(models.Model):
""" Template of event.mail to attach to event.type. Those will be copied
upon all events created in that type to ease event creation. """
_name = 'event.type.mail'
_description = 'Mail Scheduling on Event Category'
@api.model
def _selection_template_model(self):
return [('mail.template', 'Mail')]
event_type_id = fields.Many2one(
'event.type', string='Event Type',
ondelete='cascade', required=True)
notification_type = fields.Selection([('mail', 'Mail')], string='Send', default='mail', required=True)
interval_nbr = fields.Integer('Interval', default=1)
interval_unit = fields.Selection([
('now', 'Immediately'),
('hours', 'Hours'), ('days', 'Days'),
('weeks', 'Weeks'), ('months', 'Months')],
string='Unit', default='hours', required=True)
interval_type = fields.Selection([
('after_sub', 'After each registration'),
('before_event', 'Before the event'),
('after_event', 'After the event')],
string='Trigger', default="before_event", required=True)
template_model_id = fields.Many2one('ir.model', string='Template Model', compute='_compute_template_model_id', compute_sudo=True)
template_ref = fields.Reference(string='Template', selection='_selection_template_model', required=True)
@api.depends('notification_type')
def _compute_template_model_id(self):
mail_model = self.env['ir.model']._get('mail.template')
for mail in self:
mail.template_model_id = mail_model if mail.notification_type == 'mail' else False
def _prepare_event_mail_values(self):
self.ensure_one()
return {
'notification_type': self.notification_type,
'interval_nbr': self.interval_nbr,
'interval_unit': self.interval_unit,
'interval_type': self.interval_type,
'template_ref': '%s,%i' % (self.template_ref._name, self.template_ref.id)
}
class EventMailScheduler(models.Model):
""" Event automated mailing. This model replaces all existing fields and
configuration allowing to send emails on events since Odoo 9. A cron exists
that periodically checks for mailing to run. """
_name = 'event.mail'
_rec_name = 'event_id'
_description = 'Event Automated Mailing'
@api.model
def _selection_template_model(self):
return [('mail.template', 'Mail')]
def _selection_template_model_get_mapping(self):
return {'mail': 'mail.template'}
@api.onchange('notification_type')
def set_template_ref_model(self):
mail_model = self.env['mail.template']
if self.notification_type == 'mail':
record = mail_model.search([('model', '=', 'event.registration')], limit=1)
self.template_ref = "{},{}".format('mail.template', record.id) if record else False
event_id = fields.Many2one('event.event', string='Event', required=True, ondelete='cascade')
sequence = fields.Integer('Display order')
notification_type = fields.Selection([('mail', 'Mail')], string='Send', default='mail', required=True)
interval_nbr = fields.Integer('Interval', default=1)
interval_unit = fields.Selection([
('now', 'Immediately'),
('hours', 'Hours'), ('days', 'Days'),
('weeks', 'Weeks'), ('months', 'Months')],
string='Unit', default='hours', required=True)
interval_type = fields.Selection([
('after_sub', 'After each registration'),
('before_event', 'Before the event'),
('after_event', 'After the event')],
string='Trigger ', default="before_event", required=True)
scheduled_date = fields.Datetime('Schedule Date', compute='_compute_scheduled_date', store=True)
# contact and status
mail_registration_ids = fields.One2many(
'event.mail.registration', 'scheduler_id',
help='Communication related to event registrations')
mail_done = fields.Boolean("Sent", copy=False, readonly=True)
mail_state = fields.Selection(
[('running', 'Running'), ('scheduled', 'Scheduled'), ('sent', 'Sent')],
string='Global communication Status', compute='_compute_mail_state')
mail_count_done = fields.Integer('# Sent', copy=False, readonly=True)
template_model_id = fields.Many2one('ir.model', string='Template Model', compute='_compute_template_model_id', compute_sudo=True)
template_ref = fields.Reference(string='Template', selection='_selection_template_model', required=True)
@api.depends('notification_type')
def _compute_template_model_id(self):
mail_model = self.env['ir.model']._get('mail.template')
for mail in self:
mail.template_model_id = mail_model if mail.notification_type == 'mail' else False
@api.depends('event_id.date_begin', 'event_id.date_end', 'interval_type', 'interval_unit', 'interval_nbr')
def _compute_scheduled_date(self):
for scheduler in self:
if scheduler.interval_type == 'after_sub':
date, sign = scheduler.event_id.create_date, 1
elif scheduler.interval_type == 'before_event':
date, sign = scheduler.event_id.date_begin, -1
else:
date, sign = scheduler.event_id.date_end, 1
scheduler.scheduled_date = date + _INTERVALS[scheduler.interval_unit](sign * scheduler.interval_nbr) if date else False
@api.depends('interval_type', 'scheduled_date', 'mail_done')
def _compute_mail_state(self):
for scheduler in self:
# registrations based
if scheduler.interval_type == 'after_sub':
scheduler.mail_state = 'running'
# global event based
elif scheduler.mail_done:
scheduler.mail_state = 'sent'
elif scheduler.scheduled_date:
scheduler.mail_state = 'scheduled'
else:
scheduler.mail_state = 'running'
@api.constrains('notification_type', 'template_ref')
def _check_template_ref_model(self):
model_map = self._selection_template_model_get_mapping()
for record in self.filtered('template_ref'):
model = model_map[record.notification_type]
if record.template_ref._name != model:
raise ValidationError(_('The template which is referenced should be coming from %(model_name)s model.', model_name=model))
def execute(self):
for scheduler in self:
now = fields.Datetime.now()
if scheduler.interval_type == 'after_sub':
new_registrations = scheduler.event_id.registration_ids.filtered_domain(
[('state', 'not in', ('cancel', 'draft'))]
) - scheduler.mail_registration_ids.registration_id
scheduler._create_missing_mail_registrations(new_registrations)
# execute scheduler on registrations
scheduler.mail_registration_ids.execute()
total_sent = len(scheduler.mail_registration_ids.filtered(lambda reg: reg.mail_sent))
scheduler.update({
'mail_done': total_sent >= (scheduler.event_id.seats_reserved + scheduler.event_id.seats_used),
'mail_count_done': total_sent,
})
else:
# before or after event -> one shot email
if scheduler.mail_done or scheduler.notification_type != 'mail':
continue
# no template -> ill configured, skip and avoid crash
if not scheduler.template_ref:
continue
# do not send emails if the mailing was scheduled before the event but the event is over
if scheduler.scheduled_date <= now and (scheduler.interval_type != 'before_event' or scheduler.event_id.date_end > now):
scheduler.event_id.mail_attendees(scheduler.template_ref.id)
scheduler.update({
'mail_done': True,
'mail_count_done': scheduler.event_id.seats_reserved + scheduler.event_id.seats_used,
})
return True
def _create_missing_mail_registrations(self, registrations):
new = []
for scheduler in self:
new += [{
'registration_id': registration.id,
'scheduler_id': scheduler.id,
} for registration in registrations]
if new:
return self.env['event.mail.registration'].create(new)
return self.env['event.mail.registration']
@api.model
def _warn_template_error(self, scheduler, exception):
# We warn ~ once by hour ~ instead of every 10 min if the interval unit is more than 'hours'.
if random.random() < 0.1666 or scheduler.interval_unit in ('now', 'hours'):
ex_s = exception_to_unicode(exception)
try:
event, template = scheduler.event_id, scheduler.template_ref
emails = list(set([event.organizer_id.email, event.user_id.email, template.write_uid.email]))
subject = _("WARNING: Event Scheduler Error for event: %s", event.name)
body = _("""Event Scheduler for:
- Event: %(event_name)s (%(event_id)s)
- Scheduled: %(date)s
- Template: %(template_name)s (%(template_id)s)
Failed with error:
- %(error)s
You receive this email because you are:
- the organizer of the event,
- or the responsible of the event,
- or the last writer of the template.
""",
event_name=event.name,
event_id=event.id,
date=scheduler.scheduled_date,
template_name=template.name,
template_id=template.id,
error=ex_s)
email = self.env['ir.mail_server'].build_email(
email_from=self.env.user.email,
email_to=emails,
subject=subject, body=body,
)
self.env['ir.mail_server'].send_email(email)
except Exception as e:
_logger.error("Exception while sending traceback by email: %s.\n Original Traceback:\n%s", e, exception)
pass
@api.model
def run(self, autocommit=False):
""" Backward compatible method, notably if crons are not updated when
migrating for some reason. """
return self.schedule_communications(autocommit=autocommit)
@api.model
def schedule_communications(self, autocommit=False):
schedulers = self.search([
('mail_done', '=', False),
('scheduled_date', '<=', fields.Datetime.now())
])
for scheduler in schedulers:
try:
# Prevent a mega prefetch of the registration ids of all the events of all the schedulers
self.browse(scheduler.id).execute()
except Exception as e:
_logger.exception(e)
self.invalidate_cache()
self._warn_template_error(scheduler, e)
else:
if autocommit and not getattr(threading.current_thread(), 'testing', False):
self.env.cr.commit()
return True
class EventMailRegistration(models.Model):
_name = 'event.mail.registration'
_description = 'Registration Mail Scheduler'
_rec_name = 'scheduler_id'
_order = 'scheduled_date DESC'
scheduler_id = fields.Many2one('event.mail', 'Mail Scheduler', required=True, ondelete='cascade')
registration_id = fields.Many2one('event.registration', 'Attendee', required=True, ondelete='cascade')
scheduled_date = fields.Datetime('Scheduled Time', compute='_compute_scheduled_date', store=True)
mail_sent = fields.Boolean('Mail Sent')
def execute(self):
now = fields.Datetime.now()
todo = self.filtered(lambda reg_mail:
not reg_mail.mail_sent and \
reg_mail.registration_id.state in ['open', 'done'] and \
(reg_mail.scheduled_date and reg_mail.scheduled_date <= now) and \
reg_mail.scheduler_id.notification_type == 'mail'
)
for reg_mail in todo:
organizer = reg_mail.scheduler_id.event_id.organizer_id
company = self.env.company
author = self.env.ref('base.user_root')
if organizer.email:
author = organizer
elif company.email:
author = company.partner_id
elif self.env.user.email:
author = self.env.user
email_values = {
'author_id': author.id,
}
if not reg_mail.scheduler_id.template_ref.email_from:
email_values['email_from'] = author.email_formatted
reg_mail.scheduler_id.template_ref.send_mail(reg_mail.registration_id.id, email_values=email_values)
todo.write({'mail_sent': True})
@api.depends('registration_id', 'scheduler_id.interval_unit', 'scheduler_id.interval_type')
def _compute_scheduled_date(self):
for mail in self:
if mail.registration_id:
date_open = mail.registration_id.date_open
date_open_datetime = date_open or fields.Datetime.now()
mail.scheduled_date = date_open_datetime + _INTERVALS[mail.scheduler_id.interval_unit](mail.scheduler_id.interval_nbr)
else:
mail.scheduled_date = False
| 45.52381
| 14,340
|
1,440
|
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 EventStage(models.Model):
_name = 'event.stage'
_description = 'Event Stage'
_order = 'sequence, name'
name = fields.Char(string='Stage Name', required=True, translate=True)
description = fields.Text(string='Stage description', translate=True)
sequence = fields.Integer('Sequence', default=1)
fold = fields.Boolean(string='Folded in Kanban', default=False)
pipe_end = fields.Boolean(
string='End Stage', default=False,
help='Events will automatically be moved into this stage when they are finished. The event moved into this stage will automatically be set as green.')
legend_blocked = fields.Char(
'Red Kanban Label', default=lambda s: _('Blocked'), translate=True, required=True,
help='Override the default value displayed for the blocked state for kanban selection.')
legend_done = fields.Char(
'Green Kanban Label', default=lambda s: _('Ready for Next Stage'), translate=True, required=True,
help='Override the default value displayed for the done state for kanban selection.')
legend_normal = fields.Char(
'Grey Kanban Label', default=lambda s: _('In Progress'), translate=True, required=True,
help='Override the default value displayed for the normal state for kanban selection.')
| 53.333333
| 1,440
|
16,102
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models, SUPERUSER_ID
from odoo.tools import format_datetime
from odoo.exceptions import AccessError, ValidationError
class EventRegistration(models.Model):
_name = 'event.registration'
_description = 'Event Registration'
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = 'id desc'
# event
event_id = fields.Many2one(
'event.event', string='Event', required=True,
readonly=True, states={'draft': [('readonly', False)]})
event_ticket_id = fields.Many2one(
'event.event.ticket', string='Event Ticket', readonly=True, ondelete='restrict',
states={'draft': [('readonly', False)]})
active = fields.Boolean(default=True)
# utm informations
utm_campaign_id = fields.Many2one('utm.campaign', 'Campaign', index=True, ondelete='set null')
utm_source_id = fields.Many2one('utm.source', 'Source', index=True, ondelete='set null')
utm_medium_id = fields.Many2one('utm.medium', 'Medium', index=True, ondelete='set null')
# attendee
partner_id = fields.Many2one(
'res.partner', string='Booked by',
states={'done': [('readonly', True)]})
name = fields.Char(
string='Attendee Name', index=True,
compute='_compute_name', readonly=False, store=True, tracking=10)
email = fields.Char(string='Email', compute='_compute_email', readonly=False, store=True, tracking=11)
phone = fields.Char(string='Phone', compute='_compute_phone', readonly=False, store=True, tracking=12)
mobile = fields.Char(string='Mobile', compute='_compute_mobile', readonly=False, store=True, tracking=13)
# organization
date_open = fields.Datetime(string='Registration Date', readonly=True, default=lambda self: fields.Datetime.now()) # weird crash is directly now
date_closed = fields.Datetime(
string='Attended Date', compute='_compute_date_closed',
readonly=False, store=True)
event_begin_date = fields.Datetime(string="Event Start Date", related='event_id.date_begin', readonly=True)
event_end_date = fields.Datetime(string="Event End Date", related='event_id.date_end', readonly=True)
company_id = fields.Many2one(
'res.company', string='Company', related='event_id.company_id',
store=True, readonly=True, states={'draft': [('readonly', False)]})
state = fields.Selection([
('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
('open', 'Confirmed'), ('done', 'Attended')],
string='Status', default='draft', readonly=True, copy=False, tracking=True)
@api.onchange('partner_id')
def _onchange_partner_id(self):
""" Keep an explicit onchange on partner_id. Rationale : if user explicitly
changes the partner in interface, he want to update the whole customer
information. If partner_id is updated in code (e.g. updating your personal
information after having registered in website_event_sale) fields with a
value should not be reset as we don't know which one is the right one.
In other words
* computed fields based on partner_id should only update missing
information. Indeed automated code cannot decide which information
is more accurate;
* interface should allow to update all customer related information
at once. We consider event users really want to update all fields
related to the partner;
"""
for registration in self:
if registration.partner_id:
registration.update(registration._synchronize_partner_values(registration.partner_id))
@api.depends('partner_id')
def _compute_name(self):
for registration in self:
if not registration.name and registration.partner_id:
registration.name = registration._synchronize_partner_values(
registration.partner_id,
fnames=['name']
).get('name') or False
@api.depends('partner_id')
def _compute_email(self):
for registration in self:
if not registration.email and registration.partner_id:
registration.email = registration._synchronize_partner_values(
registration.partner_id,
fnames=['email']
).get('email') or False
@api.depends('partner_id')
def _compute_phone(self):
for registration in self:
if not registration.phone and registration.partner_id:
registration.phone = registration._synchronize_partner_values(
registration.partner_id,
fnames=['phone']
).get('phone') or False
@api.depends('partner_id')
def _compute_mobile(self):
for registration in self:
if not registration.mobile and registration.partner_id:
registration.mobile = registration._synchronize_partner_values(
registration.partner_id,
fnames=['mobile']
).get('mobile') or False
@api.depends('state')
def _compute_date_closed(self):
for registration in self:
if not registration.date_closed:
if registration.state == 'done':
registration.date_closed = fields.Datetime.now()
else:
registration.date_closed = False
@api.constrains('event_id', 'state')
def _check_seats_limit(self):
for registration in self:
if registration.event_id.seats_limited and registration.event_id.seats_max and registration.event_id.seats_available < (1 if registration.state == 'draft' else 0):
raise ValidationError(_('No more seats available for this event.'))
@api.constrains('event_ticket_id', 'state')
def _check_ticket_seats_limit(self):
for record in self:
if record.event_ticket_id.seats_max and record.event_ticket_id.seats_available < 0:
raise ValidationError(_('No more available seats for this ticket'))
@api.constrains('event_id', 'event_ticket_id')
def _check_event_ticket(self):
if any(registration.event_id != registration.event_ticket_id.event_id for registration in self if registration.event_ticket_id):
raise ValidationError(_('Invalid event / ticket choice'))
def _synchronize_partner_values(self, partner, fnames=None):
if fnames is None:
fnames = ['name', 'email', 'phone', 'mobile']
if partner:
contact_id = partner.address_get().get('contact', False)
if contact_id:
contact = self.env['res.partner'].browse(contact_id)
return dict((fname, contact[fname]) for fname in fnames if contact[fname])
return {}
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
registrations = super(EventRegistration, self).create(vals_list)
# auto_confirm if possible; if not automatically confirmed, call mail schedulers in case
# some were created already open
if registrations._check_auto_confirmation():
registrations.sudo().action_confirm()
elif not self.env.context.get('install_mode', False):
# running the scheduler for demo data can cause an issue where wkhtmltopdf runs during
# server start and hangs indefinitely, leading to serious crashes
# we currently avoid this by not running the scheduler, would be best to find the actual
# reason for this issue and fix it so we can remove this check
registrations._update_mail_schedulers()
return registrations
def write(self, vals):
pre_draft = self.env['event.registration']
if vals.get('state') == 'open':
pre_draft = self.filtered(lambda registration: registration.state == 'draft')
ret = super(EventRegistration, self).write(vals)
if vals.get('state') == 'open' and not self.env.context.get('install_mode', False):
# running the scheduler for demo data can cause an issue where wkhtmltopdf runs during
# server start and hangs indefinitely, leading to serious crashes
# we currently avoid this by not running the scheduler, would be best to find the actual
# reason for this issue and fix it so we can remove this check
pre_draft._update_mail_schedulers()
return ret
def name_get(self):
""" Custom name_get implementation to better differentiate registrations
linked to a given partner but with different name (one partner buying
several registrations)
* name, partner_id has no name -> take name
* partner_id has name, name void or same -> take partner name
* both have name: partner + name
"""
ret_list = []
for registration in self:
if registration.partner_id.name:
if registration.name and registration.name != registration.partner_id.name:
name = '%s, %s' % (registration.partner_id.name, registration.name)
else:
name = registration.partner_id.name
else:
name = registration.name
ret_list.append((registration.id, name))
return ret_list
def _check_auto_confirmation(self):
if any(not registration.event_id.auto_confirm or
(not registration.event_id.seats_available and registration.event_id.seats_limited) for registration in self):
return False
return True
# ------------------------------------------------------------
# ACTIONS / BUSINESS
# ------------------------------------------------------------
def action_set_draft(self):
self.write({'state': 'draft'})
def action_confirm(self):
self.write({'state': 'open'})
def action_set_done(self):
""" Close Registration """
self.write({'state': 'done'})
def action_cancel(self):
self.write({'state': 'cancel'})
def action_send_badge_email(self):
""" Open a window to compose an email, with the template - 'event_badge'
message loaded by default
"""
self.ensure_one()
template = self.env.ref('event.event_registration_mail_template_badge', raise_if_not_found=False)
compose_form = self.env.ref('mail.email_compose_message_wizard_form')
ctx = dict(
default_model='event.registration',
default_res_id=self.id,
default_use_template=bool(template),
default_template_id=template and template.id,
default_composition_mode='comment',
custom_layout="mail.mail_notification_light",
)
return {
'name': _('Compose Email'),
'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': ctx,
}
def _update_mail_schedulers(self):
""" Update schedulers to set them as running again, and cron to be called
as soon as possible. """
open_registrations = self.filtered(lambda registration: registration.state == 'open')
if not open_registrations:
return
onsubscribe_schedulers = self.env['event.mail'].sudo().search([
('event_id', 'in', open_registrations.event_id.ids),
('interval_type', '=', 'after_sub')
])
if not onsubscribe_schedulers:
return
onsubscribe_schedulers.update({'mail_done': False})
# we could simply call _create_missing_mail_registrations and let cron do their job
# but it currently leads to several delays. We therefore call execute until
# cron triggers are correctly used
onsubscribe_schedulers.with_user(SUPERUSER_ID).execute()
# ------------------------------------------------------------
# MAILING / GATEWAY
# ------------------------------------------------------------
def _message_get_suggested_recipients(self):
recipients = super(EventRegistration, self)._message_get_suggested_recipients()
public_users = self.env['res.users'].sudo()
public_groups = self.env.ref("base.group_public", raise_if_not_found=False)
if public_groups:
public_users = public_groups.sudo().with_context(active_test=False).mapped("users")
try:
for attendee in self:
is_public = attendee.sudo().with_context(active_test=False).partner_id.user_ids in public_users if public_users else False
if attendee.partner_id and not is_public:
attendee._message_add_suggested_recipient(recipients, partner=attendee.partner_id, reason=_('Customer'))
elif attendee.email:
attendee._message_add_suggested_recipient(recipients, email=attendee.email, reason=_('Customer Email'))
except AccessError: # no read access rights -> ignore suggested recipients
pass
return recipients
def _message_get_default_recipients(self):
# Prioritize registration email over partner_id, which may be shared when a single
# partner booked multiple seats
return {r.id: {
'partner_ids': [],
'email_to': r.email,
'email_cc': False}
for r in self}
def _message_post_after_hook(self, message, msg_vals):
if self.email and not self.partner_id:
# we consider that posting a message with a specified recipient (not a follower, a specific one)
# on a document without customer means that it was created through the chatter using
# suggested recipients. This heuristic allows to avoid ugly hacks in JS.
new_partner = message.partner_ids.filtered(lambda partner: partner.email == self.email)
if new_partner:
self.search([
('partner_id', '=', False),
('email', '=', new_partner.email),
('state', 'not in', ['cancel']),
]).write({'partner_id': new_partner.id})
return super(EventRegistration, self)._message_post_after_hook(message, msg_vals)
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
def get_date_range_str(self):
self.ensure_one()
today = fields.Datetime.now()
event_date = self.event_begin_date
diff = (event_date.date() - today.date())
if diff.days <= 0:
return _('today')
elif diff.days == 1:
return _('tomorrow')
elif (diff.days < 7):
return _('in %d days') % (diff.days, )
elif (diff.days < 14):
return _('next week')
elif event_date.month == (today + relativedelta(months=+1)).month:
return _('next month')
else:
return _('on %(date)s', date=format_datetime(self.env, self.event_begin_date, tz=self.event_id.date_tz, dt_format='medium'))
def _get_registration_summary(self):
self.ensure_one()
return {
'id': self.id,
'name': self.name,
'partner_id': self.partner_id.id,
'ticket_name': self.event_ticket_id.name or _('None'),
'event_id': self.event_id.id,
'event_display_name': self.event_id.display_name,
'company_name': self.event_id.company_id and self.event_id.company_id.name or False,
}
| 46.137536
| 16,102
|
1,003
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
from odoo.osv import expression
class MailTemplate(models.Model):
_inherit = 'mail.template'
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
"""Context-based hack to filter reference field in a m2o search box to emulate a domain the ORM currently does not support.
As we can not specify a domain on a reference field, we added a context
key `filter_template_on_event` on the template reference field. If this
key is set, we add our domain in the `args` in the `_name_search`
method to filtrate the mail templates.
"""
if self.env.context.get('filter_template_on_event'):
args = expression.AND([[('model', '=', 'event.registration')], args])
return super(MailTemplate, self)._name_search(name, args, operator, limit, name_get_uid)
| 45.590909
| 1,003
|
29,959
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pytz
from odoo import _, api, Command, fields, models
from odoo.addons.base.models.res_partner import _tz_get
from odoo.tools import format_datetime, is_html_empty
from odoo.exceptions import ValidationError
from odoo.tools.translate import html_translate
_logger = logging.getLogger(__name__)
try:
import vobject
except ImportError:
_logger.warning("`vobject` Python module not found, iCal file generation disabled. Consider installing this module if you want to generate iCal files")
vobject = None
class EventType(models.Model):
_name = 'event.type'
_description = 'Event Template'
_order = 'sequence, id'
def _default_event_mail_type_ids(self):
return [(0, 0,
{'notification_type': 'mail',
'interval_nbr': 0,
'interval_unit': 'now',
'interval_type': 'after_sub',
'template_ref': 'mail.template, %i' % self.env.ref('event.event_subscription').id,
}),
(0, 0,
{'notification_type': 'mail',
'interval_nbr': 1,
'interval_unit': 'hours',
'interval_type': 'before_event',
'template_ref': 'mail.template, %i' % self.env.ref('event.event_reminder').id,
}),
(0, 0,
{'notification_type': 'mail',
'interval_nbr': 3,
'interval_unit': 'days',
'interval_type': 'before_event',
'template_ref': 'mail.template, %i' % self.env.ref('event.event_reminder').id,
})]
name = fields.Char('Event Template', required=True, translate=True)
note = fields.Html(string='Note')
sequence = fields.Integer()
# tickets
event_type_ticket_ids = fields.One2many('event.type.ticket', 'event_type_id', string='Tickets')
tag_ids = fields.Many2many('event.tag', string="Tags")
# registration
has_seats_limitation = fields.Boolean('Limited Seats')
seats_max = fields.Integer(
'Maximum Registrations', compute='_compute_default_registration',
readonly=False, store=True,
help="It will select this default maximum value when you choose this event")
auto_confirm = fields.Boolean(
'Automatically Confirm Registrations', default=True,
help="Events and registrations will automatically be confirmed "
"upon creation, easing the flow for simple events.")
default_timezone = fields.Selection(
_tz_get, string='Timezone', default=lambda self: self.env.user.tz or 'UTC')
# communication
event_type_mail_ids = fields.One2many(
'event.type.mail', 'event_type_id', string='Mail Schedule',
default=_default_event_mail_type_ids)
# ticket reports
ticket_instructions = fields.Html('Ticket Instructions', translate=True,
help="This information will be printed on your tickets.")
@api.depends('has_seats_limitation')
def _compute_default_registration(self):
for template in self:
if not template.has_seats_limitation:
template.seats_max = 0
class EventEvent(models.Model):
"""Event"""
_name = 'event.event'
_description = 'Event'
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = 'date_begin'
def _get_default_stage_id(self):
return self.env['event.stage'].search([], limit=1)
def _default_description(self):
# avoid template branding with rendering_bundle=True
return self.env['ir.ui.view'].with_context(rendering_bundle=True) \
._render_template('event.event_default_descripton')
def _default_event_mail_ids(self):
return self.env['event.type']._default_event_mail_type_ids()
name = fields.Char(string='Event', translate=True, required=True)
note = fields.Html(string='Note', store=True, compute="_compute_note", readonly=False)
description = fields.Html(string='Description', translate=html_translate, sanitize_attributes=False, sanitize_form=False, default=_default_description)
active = fields.Boolean(default=True)
user_id = fields.Many2one(
'res.users', string='Responsible', tracking=True,
default=lambda self: self.env.user)
company_id = fields.Many2one(
'res.company', string='Company', change_default=True,
default=lambda self: self.env.company,
required=False)
organizer_id = fields.Many2one(
'res.partner', string='Organizer', tracking=True,
default=lambda self: self.env.company.partner_id,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
event_type_id = fields.Many2one('event.type', string='Template', ondelete='set null')
event_mail_ids = fields.One2many(
'event.mail', 'event_id', string='Mail Schedule', copy=True,
compute='_compute_event_mail_ids', readonly=False, store=True)
tag_ids = fields.Many2many(
'event.tag', string="Tags", readonly=False,
store=True, compute="_compute_tag_ids")
# Kanban fields
kanban_state = fields.Selection([('normal', 'In Progress'), ('done', 'Done'), ('blocked', 'Blocked')], default='normal', copy=False)
kanban_state_label = fields.Char(
string='Kanban State Label', compute='_compute_kanban_state_label',
store=True, tracking=True)
stage_id = fields.Many2one(
'event.stage', ondelete='restrict', default=_get_default_stage_id,
group_expand='_read_group_stage_ids', tracking=True, copy=False)
legend_blocked = fields.Char(related='stage_id.legend_blocked', string='Kanban Blocked Explanation', readonly=True)
legend_done = fields.Char(related='stage_id.legend_done', string='Kanban Valid Explanation', readonly=True)
legend_normal = fields.Char(related='stage_id.legend_normal', string='Kanban Ongoing Explanation', readonly=True)
# Seats and computation
seats_max = fields.Integer(
string='Maximum Attendees Number',
compute='_compute_seats_max', readonly=False, store=True,
help="For each event you can define a maximum registration of seats(number of attendees), above this numbers the registrations are not accepted.")
seats_limited = fields.Boolean('Maximum Attendees', required=True, compute='_compute_seats_limited',
readonly=False, store=True)
seats_reserved = fields.Integer(
string='Reserved Seats',
store=True, readonly=True, compute='_compute_seats')
seats_available = fields.Integer(
string='Available Seats',
store=True, readonly=True, compute='_compute_seats')
seats_unconfirmed = fields.Integer(
string='Unconfirmed Seat Reservations',
store=True, readonly=True, compute='_compute_seats')
seats_used = fields.Integer(
string='Number of Participants',
store=True, readonly=True, compute='_compute_seats')
seats_expected = fields.Integer(
string='Number of Expected Attendees',
compute_sudo=True, readonly=True, compute='_compute_seats_expected')
# Registration fields
auto_confirm = fields.Boolean(
string='Autoconfirmation', compute='_compute_auto_confirm', readonly=False, store=True,
help='Autoconfirm Registrations. Registrations will automatically be confirmed upon creation.')
registration_ids = fields.One2many('event.registration', 'event_id', string='Attendees')
event_ticket_ids = fields.One2many(
'event.event.ticket', 'event_id', string='Event Ticket', copy=True,
compute='_compute_event_ticket_ids', readonly=False, store=True)
event_registrations_started = fields.Boolean(
'Registrations started', compute='_compute_event_registrations_started',
help="registrations have started if the current datetime is after the earliest starting date of tickets."
)
event_registrations_open = fields.Boolean(
'Registration open', compute='_compute_event_registrations_open', compute_sudo=True,
help="Registrations are open if:\n"
"- the event is not ended\n"
"- there are seats available on event\n"
"- the tickets are sellable (if ticketing is used)")
event_registrations_sold_out = fields.Boolean(
'Sold Out', compute='_compute_event_registrations_sold_out', compute_sudo=True,
help='The event is sold out if no more seats are available on event. If ticketing is used and all tickets are sold out, the event will be sold out.')
start_sale_datetime = fields.Datetime(
'Start sale date', compute='_compute_start_sale_date',
help='If ticketing is used, contains the earliest starting sale date of tickets.')
# Date fields
date_tz = fields.Selection(
_tz_get, string='Timezone', required=True,
compute='_compute_date_tz', readonly=False, store=True)
date_begin = fields.Datetime(string='Start Date', required=True, tracking=True)
date_end = fields.Datetime(string='End Date', required=True, tracking=True)
date_begin_located = fields.Char(string='Start Date Located', compute='_compute_date_begin_tz')
date_end_located = fields.Char(string='End Date Located', compute='_compute_date_end_tz')
is_ongoing = fields.Boolean('Is Ongoing', compute='_compute_is_ongoing', search='_search_is_ongoing')
is_one_day = fields.Boolean(compute='_compute_field_is_one_day')
is_finished = fields.Boolean(compute='_compute_is_finished', search='_search_is_finished')
# Location and communication
address_id = fields.Many2one(
'res.partner', string='Venue', default=lambda self: self.env.company.partner_id.id,
tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
country_id = fields.Many2one(
'res.country', 'Country', related='address_id.country_id', readonly=False, store=True)
# ticket reports
ticket_instructions = fields.Html('Ticket Instructions', translate=True,
compute='_compute_ticket_instructions', store=True, readonly=False,
help="This information will be printed on your tickets.")
@api.depends('stage_id', 'kanban_state')
def _compute_kanban_state_label(self):
for event in self:
if event.kanban_state == 'normal':
event.kanban_state_label = event.stage_id.legend_normal
elif event.kanban_state == 'blocked':
event.kanban_state_label = event.stage_id.legend_blocked
else:
event.kanban_state_label = event.stage_id.legend_done
@api.depends('seats_max', 'registration_ids.state')
def _compute_seats(self):
""" Determine reserved, available, reserved but unconfirmed and used seats. """
# initialize fields to 0
for event in self:
event.seats_unconfirmed = event.seats_reserved = event.seats_used = event.seats_available = 0
# aggregate registrations by event and by state
state_field = {
'draft': 'seats_unconfirmed',
'open': 'seats_reserved',
'done': 'seats_used',
}
base_vals = dict((fname, 0) for fname in state_field.values())
results = dict((event_id, dict(base_vals)) for event_id in self.ids)
if self.ids:
query = """ SELECT event_id, state, count(event_id)
FROM event_registration
WHERE event_id IN %s AND state IN ('draft', 'open', 'done')
GROUP BY event_id, state
"""
self.env['event.registration'].flush(['event_id', 'state'])
self._cr.execute(query, (tuple(self.ids),))
res = self._cr.fetchall()
for event_id, state, num in res:
results[event_id][state_field[state]] = num
# compute seats_available
for event in self:
event.update(results.get(event._origin.id or event.id, base_vals))
if event.seats_max > 0:
event.seats_available = event.seats_max - (event.seats_reserved + event.seats_used)
@api.depends('seats_unconfirmed', 'seats_reserved', 'seats_used')
def _compute_seats_expected(self):
for event in self:
event.seats_expected = event.seats_unconfirmed + event.seats_reserved + event.seats_used
@api.depends('date_tz', 'start_sale_datetime')
def _compute_event_registrations_started(self):
for event in self:
event = event._set_tz_context()
if event.start_sale_datetime:
current_datetime = fields.Datetime.context_timestamp(event, fields.Datetime.now())
start_sale_datetime = fields.Datetime.context_timestamp(event, event.start_sale_datetime)
event.event_registrations_started = (current_datetime >= start_sale_datetime)
else:
event.event_registrations_started = True
@api.depends('date_tz', 'event_registrations_started', 'date_end', 'seats_available', 'seats_limited', 'event_ticket_ids.sale_available')
def _compute_event_registrations_open(self):
""" Compute whether people may take registrations for this event
* event.date_end -> if event is done, registrations are not open anymore;
* event.start_sale_datetime -> lowest start date of tickets (if any; start_sale_datetime
is False if no ticket are defined, see _compute_start_sale_date);
* any ticket is available for sale (seats available) if any;
* seats are unlimited or seats are available;
"""
for event in self:
event = event._set_tz_context()
current_datetime = fields.Datetime.context_timestamp(event, fields.Datetime.now())
date_end_tz = event.date_end.astimezone(pytz.timezone(event.date_tz or 'UTC')) if event.date_end else False
event.event_registrations_open = event.event_registrations_started and \
(date_end_tz >= current_datetime if date_end_tz else True) and \
(not event.seats_limited or event.seats_available) and \
(not event.event_ticket_ids or any(ticket.sale_available for ticket in event.event_ticket_ids))
@api.depends('event_ticket_ids.start_sale_datetime')
def _compute_start_sale_date(self):
""" Compute the start sale date of an event. Currently lowest starting sale
date of tickets if they are used, of False. """
for event in self:
start_dates = [ticket.start_sale_datetime for ticket in event.event_ticket_ids if not ticket.is_expired]
event.start_sale_datetime = min(start_dates) if start_dates and all(start_dates) else False
@api.depends('event_ticket_ids.sale_available')
def _compute_event_registrations_sold_out(self):
for event in self:
if event.seats_limited and not event.seats_available:
event.event_registrations_sold_out = True
elif event.event_ticket_ids:
event.event_registrations_sold_out = not any(
ticket.seats_available > 0 if ticket.seats_limited else True for ticket in event.event_ticket_ids
)
else:
event.event_registrations_sold_out = False
@api.depends('date_tz', 'date_begin')
def _compute_date_begin_tz(self):
for event in self:
if event.date_begin:
event.date_begin_located = format_datetime(
self.env, event.date_begin, tz=event.date_tz, dt_format='medium')
else:
event.date_begin_located = False
@api.depends('date_tz', 'date_end')
def _compute_date_end_tz(self):
for event in self:
if event.date_end:
event.date_end_located = format_datetime(
self.env, event.date_end, tz=event.date_tz, dt_format='medium')
else:
event.date_end_located = False
@api.depends('date_begin', 'date_end')
def _compute_is_ongoing(self):
now = fields.Datetime.now()
for event in self:
event.is_ongoing = event.date_begin <= now < event.date_end
def _search_is_ongoing(self, operator, value):
if operator not in ['=', '!=']:
raise ValueError(_('This operator is not supported'))
if not isinstance(value, bool):
raise ValueError(_('Value should be True or False (not %s)'), value)
now = fields.Datetime.now()
if (operator == '=' and value) or (operator == '!=' and not value):
domain = [('date_begin', '<=', now), ('date_end', '>', now)]
else:
domain = ['|', ('date_begin', '>', now), ('date_end', '<=', now)]
event_ids = self.env['event.event']._search(domain)
return [('id', 'in', event_ids)]
@api.depends('date_begin', 'date_end', 'date_tz')
def _compute_field_is_one_day(self):
for event in self:
# Need to localize because it could begin late and finish early in
# another timezone
event = event._set_tz_context()
begin_tz = fields.Datetime.context_timestamp(event, event.date_begin)
end_tz = fields.Datetime.context_timestamp(event, event.date_end)
event.is_one_day = (begin_tz.date() == end_tz.date())
@api.depends('date_end')
def _compute_is_finished(self):
for event in self:
if not event.date_end:
event.is_finished = False
continue
event = event._set_tz_context()
current_datetime = fields.Datetime.context_timestamp(event, fields.Datetime.now())
datetime_end = fields.Datetime.context_timestamp(event, event.date_end)
event.is_finished = datetime_end <= current_datetime
def _search_is_finished(self, operator, value):
if operator not in ['=', '!=']:
raise ValueError(_('This operator is not supported'))
if not isinstance(value, bool):
raise ValueError(_('Value should be True or False (not %s)'), value)
now = fields.Datetime.now()
if (operator == '=' and value) or (operator == '!=' and not value):
domain = [('date_end', '<=', now)]
else:
domain = [('date_end', '>', now)]
event_ids = self.env['event.event']._search(domain)
return [('id', 'in', event_ids)]
@api.depends('event_type_id')
def _compute_date_tz(self):
for event in self:
if event.event_type_id.default_timezone:
event.date_tz = event.event_type_id.default_timezone
if not event.date_tz:
event.date_tz = self.env.user.tz or 'UTC'
# seats
@api.depends('event_type_id')
def _compute_seats_max(self):
""" Update event configuration from its event type. Depends are set only
on event_type_id itself, not its sub fields. Purpose is to emulate an
onchange: if event type is changed, update event configuration. Changing
event type content itself should not trigger this method. """
for event in self:
if not event.event_type_id:
event.seats_max = event.seats_max or 0
else:
event.seats_max = event.event_type_id.seats_max or 0
@api.depends('event_type_id')
def _compute_seats_limited(self):
""" Update event configuration from its event type. Depends are set only
on event_type_id itself, not its sub fields. Purpose is to emulate an
onchange: if event type is changed, update event configuration. Changing
event type content itself should not trigger this method. """
for event in self:
if event.event_type_id.has_seats_limitation != event.seats_limited:
event.seats_limited = event.event_type_id.has_seats_limitation
if not event.seats_limited:
event.seats_limited = False
@api.depends('event_type_id')
def _compute_auto_confirm(self):
""" Update event configuration from its event type. Depends are set only
on event_type_id itself, not its sub fields. Purpose is to emulate an
onchange: if event type is changed, update event configuration. Changing
event type content itself should not trigger this method. """
for event in self:
event.auto_confirm = event.event_type_id.auto_confirm
@api.depends('event_type_id')
def _compute_event_mail_ids(self):
""" Update event configuration from its event type. Depends are set only
on event_type_id itself, not its sub fields. Purpose is to emulate an
onchange: if event type is changed, update event configuration. Changing
event type content itself should not trigger this method.
When synchronizing mails:
* lines that are not sent and have no registrations linked are remove;
* type lines are added;
"""
for event in self:
if not event.event_type_id and not event.event_mail_ids:
event.event_mail_ids = self._default_event_mail_ids()
continue
# lines to keep: those with already sent emails or registrations
mails_to_remove = event.event_mail_ids.filtered(
lambda mail: not(mail._origin.mail_done) and not(mail._origin.mail_registration_ids)
)
command = [Command.unlink(mail.id) for mail in mails_to_remove]
if event.event_type_id.event_type_mail_ids:
command += [
Command.create(line._prepare_event_mail_values())
for line in event.event_type_id.event_type_mail_ids
]
if command:
event.event_mail_ids = command
@api.depends('event_type_id')
def _compute_tag_ids(self):
""" Update event configuration from its event type. Depends are set only
on event_type_id itself, not its sub fields. Purpose is to emulate an
onchange: if event type is changed, update event configuration. Changing
event type content itself should not trigger this method. """
for event in self:
if not event.tag_ids and event.event_type_id.tag_ids:
event.tag_ids = event.event_type_id.tag_ids
@api.depends('event_type_id')
def _compute_event_ticket_ids(self):
""" Update event configuration from its event type. Depends are set only
on event_type_id itself, not its sub fields. Purpose is to emulate an
onchange: if event type is changed, update event configuration. Changing
event type content itself should not trigger this method.
When synchronizing tickets:
* lines that have no registrations linked are remove;
* type lines are added;
Note that updating event_ticket_ids triggers _compute_start_sale_date
(start_sale_datetime computation) so ensure result to avoid cache miss.
"""
for event in self:
if not event.event_type_id and not event.event_ticket_ids:
event.event_ticket_ids = False
continue
# lines to keep: those with existing registrations
tickets_to_remove = event.event_ticket_ids.filtered(lambda ticket: not ticket._origin.registration_ids)
command = [Command.unlink(ticket.id) for ticket in tickets_to_remove]
if event.event_type_id.event_type_ticket_ids:
command += [
Command.create({
attribute_name: line[attribute_name] if not isinstance(line[attribute_name], models.BaseModel) else line[attribute_name].id
for attribute_name in self.env['event.type.ticket']._get_event_ticket_fields_whitelist()
}) for line in event.event_type_id.event_type_ticket_ids
]
event.event_ticket_ids = command
@api.depends('event_type_id')
def _compute_note(self):
for event in self:
if event.event_type_id and not is_html_empty(event.event_type_id.note):
event.note = event.event_type_id.note
@api.depends('event_type_id')
def _compute_ticket_instructions(self):
for event in self:
if is_html_empty(event.ticket_instructions) and not \
is_html_empty(event.event_type_id.ticket_instructions):
event.ticket_instructions = event.event_type_id.ticket_instructions
@api.constrains('seats_max', 'seats_available', 'seats_limited')
def _check_seats_limit(self):
if any(event.seats_limited and event.seats_max and event.seats_available < 0 for event in self):
raise ValidationError(_('No more available seats.'))
@api.constrains('date_begin', 'date_end')
def _check_closing_date(self):
for event in self:
if event.date_end < event.date_begin:
raise ValidationError(_('The closing date cannot be earlier than the beginning date.'))
@api.model
def _read_group_stage_ids(self, stages, domain, order):
return self.env['event.stage'].search([])
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
# Temporary fix for ``seats_limited`` and ``date_tz`` required fields
vals.update(self._sync_required_computed(vals))
events = super(EventEvent, self).create(vals_list)
for res in events:
if res.organizer_id:
res.message_subscribe([res.organizer_id.id])
events.flush()
return events
def write(self, vals):
if 'stage_id' in vals and 'kanban_state' not in vals:
# reset kanban state when changing stage
vals['kanban_state'] = 'normal'
res = super(EventEvent, self).write(vals)
if vals.get('organizer_id'):
self.message_subscribe([vals['organizer_id']])
return res
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
self.ensure_one()
default = dict(default or {}, name=_("%s (copy)") % (self.name))
return super(EventEvent, self).copy(default)
@api.model
def _get_mail_message_access(self, res_ids, operation, model_name=None):
if (
operation == 'create'
and self.env.user.has_group('event.group_event_registration_desk')
and (not model_name or model_name == 'event.event')
):
# allow the registration desk users to post messages on Event
# can not be done with "_mail_post_access" otherwise public user will be
# able to post on published Event (see website_event)
return 'read'
return super(EventEvent, self)._get_mail_message_access(res_ids, operation, model_name)
def _sync_required_computed(self, values):
# TODO: See if the change to seats_limited affects this ?
""" Call compute fields in cache to find missing values for required fields
(seats_limited and date_tz) in case they are not given in values """
missing_fields = list(set(['seats_limited', 'date_tz']).difference(set(values.keys())))
if missing_fields and values:
cache_event = self.new(values)
cache_event._compute_seats_limited()
cache_event._compute_date_tz()
return dict((fname, cache_event[fname]) for fname in missing_fields)
else:
return {}
def _set_tz_context(self):
self.ensure_one()
return self.with_context(tz=self.date_tz or 'UTC')
def action_set_done(self):
"""
Action which will move the events
into the first next (by sequence) stage defined as "Ended"
(if they are not already in an ended stage)
"""
first_ended_stage = self.env['event.stage'].search([('pipe_end', '=', True)], limit=1, order='sequence')
if first_ended_stage:
self.write({'stage_id': first_ended_stage.id})
def mail_attendees(self, template_id, force_send=False, filter_func=lambda self: self.state != 'cancel'):
for event in self:
for attendee in event.registration_ids.filtered(filter_func):
self.env['mail.template'].browse(template_id).send_mail(attendee.id, force_send=force_send)
def _get_ics_file(self):
""" Returns iCalendar file for the event invitation.
:returns a dict of .ics file content for each event
"""
result = {}
if not vobject:
return result
for event in self:
cal = vobject.iCalendar()
cal_event = cal.add('vevent')
cal_event.add('created').value = fields.Datetime.now().replace(tzinfo=pytz.timezone('UTC'))
cal_event.add('dtstart').value = fields.Datetime.from_string(event.date_begin).replace(tzinfo=pytz.timezone('UTC'))
cal_event.add('dtend').value = fields.Datetime.from_string(event.date_end).replace(tzinfo=pytz.timezone('UTC'))
cal_event.add('summary').value = event.name
if event.address_id:
cal_event.add('location').value = event.sudo().address_id.contact_address
result[event.id] = cal.serialize().encode('utf-8')
return result
@api.autovacuum
def _gc_mark_events_done(self):
""" move every ended events in the next 'ended stage' """
ended_events = self.env['event.event'].search([
('date_end', '<', fields.Datetime.now()),
('stage_id.pipe_end', '=', False),
])
if ended_events:
ended_events.action_set_done()
| 48.555916
| 29,959
|
1,384
|
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'
module_event_sale = fields.Boolean("Tickets")
module_website_event_meet = fields.Boolean("Discussion Rooms")
module_website_event_track = fields.Boolean("Tracks and Agenda")
module_website_event_track_live = fields.Boolean("Live Mode")
module_website_event_track_quiz = fields.Boolean("Quiz on Tracks")
module_website_event_exhibitor = fields.Boolean("Advanced Sponsors")
module_website_event_questions = fields.Boolean("Registration Survey")
module_event_barcode = fields.Boolean("Barcode")
module_website_event_sale = fields.Boolean("Online Ticketing")
module_event_booth = fields.Boolean("Booth Management")
@api.onchange('module_website_event_track')
def _onchange_module_website_event_track(self):
""" Reset sub-modules, otherwise you may have track to False but still
have track_live or track_quiz to True, meaning track will come back due
to dependencies of modules. """
for config in self:
if not config.module_website_event_track:
config.module_website_event_track_live = False
config.module_website_event_track_quiz = False
| 47.724138
| 1,384
|
1,129
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from random import randint
from odoo import api, fields, models
class EventTagCategory(models.Model):
_name = "event.tag.category"
_description = "Event Tag Category"
_order = "sequence"
name = fields.Char("Name", required=True, translate=True)
sequence = fields.Integer('Sequence', default=0)
tag_ids = fields.One2many('event.tag', 'category_id', string="Tags")
class EventTag(models.Model):
_name = "event.tag"
_description = "Event Tag"
_order = "sequence"
def _default_color(self):
return randint(1, 11)
name = fields.Char("Name", required=True, translate=True)
sequence = fields.Integer('Sequence', default=0)
category_id = fields.Many2one("event.tag.category", string="Category", required=True, ondelete='cascade')
color = fields.Integer(
string='Color Index', default=lambda self: self._default_color(),
help='Tag color. No color means no display in kanban or front-end, to distinguish internal tags from public categorization tags.')
| 36.419355
| 1,129
|
874
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
event_count = fields.Integer(
'# Events', compute='_compute_event_count', groups='event.group_event_registration_desk',
help='Number of events the partner has participated.')
def _compute_event_count(self):
self.event_count = 0
for partner in self:
partner.event_count = self.env['event.event'].search_count([('registration_ids.partner_id', 'child_of', partner.ids)])
def action_event_view(self):
action = self.env["ir.actions.actions"]._for_xml_id("event.action_event_view")
action['context'] = {}
action['domain'] = [('registration_ids.partner_id', 'child_of', self.ids)]
return action
| 38
| 874
|
7,887
|
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 EventTemplateTicket(models.Model):
_name = 'event.type.ticket'
_description = 'Event Template Ticket'
# description
name = fields.Char(
string='Name', default=lambda self: _('Registration'),
required=True, translate=True)
description = fields.Text(
'Description', translate=True,
help="A description of the ticket that you want to communicate to your customers.")
event_type_id = fields.Many2one(
'event.type', string='Event Category', ondelete='cascade', required=True)
# seats
seats_limited = fields.Boolean(string='Seats Limit', readonly=True, store=True,
compute='_compute_seats_limited')
seats_max = fields.Integer(
string='Maximum Seats',
help="Define the number of available tickets. If you have too many registrations you will "
"not be able to sell tickets anymore. Set 0 to ignore this rule set as unlimited.")
@api.depends('seats_max')
def _compute_seats_limited(self):
for ticket in self:
ticket.seats_limited = ticket.seats_max
@api.model
def _get_event_ticket_fields_whitelist(self):
""" Whitelist of fields that are copied from event_type_ticket_ids to event_ticket_ids when
changing the event_type_id field of event.event """
return ['name', 'description', 'seats_max']
class EventTicket(models.Model):
""" Ticket model allowing to have differnt kind of registrations for a given
event. Ticket are based on ticket type as they share some common fields
and behavior. Those models come from <= v13 Odoo event.event.ticket that
modeled both concept: tickets for event templates, and tickets for events. """
_name = 'event.event.ticket'
_inherit = 'event.type.ticket'
_description = 'Event Ticket'
@api.model
def default_get(self, fields):
res = super(EventTicket, self).default_get(fields)
if 'name' in fields and (not res.get('name') or res['name'] == _('Registration')) and self.env.context.get('default_event_name'):
res['name'] = _('Registration for %s', self.env.context['default_event_name'])
return res
# description
event_type_id = fields.Many2one(ondelete='set null', required=False)
event_id = fields.Many2one(
'event.event', string="Event",
ondelete='cascade', required=True)
company_id = fields.Many2one('res.company', related='event_id.company_id')
# sale
start_sale_datetime = fields.Datetime(string="Registration Start")
end_sale_datetime = fields.Datetime(string="Registration End")
is_expired = fields.Boolean(string='Is Expired', compute='_compute_is_expired')
sale_available = fields.Boolean(string='Is Available', compute='_compute_sale_available', compute_sudo=True)
registration_ids = fields.One2many('event.registration', 'event_ticket_id', string='Registrations')
# seats
seats_reserved = fields.Integer(string='Reserved Seats', compute='_compute_seats', store=True)
seats_available = fields.Integer(string='Available Seats', compute='_compute_seats', store=True)
seats_unconfirmed = fields.Integer(string='Unconfirmed Seats', compute='_compute_seats', store=True)
seats_used = fields.Integer(string='Used Seats', compute='_compute_seats', store=True)
@api.depends('end_sale_datetime', 'event_id.date_tz')
def _compute_is_expired(self):
for ticket in self:
ticket = ticket._set_tz_context()
current_datetime = fields.Datetime.context_timestamp(ticket, fields.Datetime.now())
if ticket.end_sale_datetime:
end_sale_datetime = fields.Datetime.context_timestamp(ticket, ticket.end_sale_datetime)
ticket.is_expired = end_sale_datetime < current_datetime
else:
ticket.is_expired = False
@api.depends('is_expired', 'start_sale_datetime', 'event_id.date_tz', 'seats_available', 'seats_max')
def _compute_sale_available(self):
for ticket in self:
if not ticket.is_launched() or ticket.is_expired or (ticket.seats_max and ticket.seats_available <= 0):
ticket.sale_available = False
else:
ticket.sale_available = True
@api.depends('seats_max', 'registration_ids.state')
def _compute_seats(self):
""" Determine reserved, available, reserved but unconfirmed and used seats. """
# initialize fields to 0 + compute seats availability
for ticket in self:
ticket.seats_unconfirmed = ticket.seats_reserved = ticket.seats_used = ticket.seats_available = 0
# aggregate registrations by ticket and by state
results = {}
if self.ids:
state_field = {
'draft': 'seats_unconfirmed',
'open': 'seats_reserved',
'done': 'seats_used',
}
query = """ SELECT event_ticket_id, state, count(event_id)
FROM event_registration
WHERE event_ticket_id IN %s AND state IN ('draft', 'open', 'done')
GROUP BY event_ticket_id, state
"""
self.env['event.registration'].flush(['event_id', 'event_ticket_id', 'state'])
self.env.cr.execute(query, (tuple(self.ids),))
for event_ticket_id, state, num in self.env.cr.fetchall():
results.setdefault(event_ticket_id, {})[state_field[state]] = num
# compute seats_available
for ticket in self:
ticket.update(results.get(ticket._origin.id or ticket.id, {}))
if ticket.seats_max > 0:
ticket.seats_available = ticket.seats_max - (ticket.seats_reserved + ticket.seats_used)
@api.constrains('start_sale_datetime', 'end_sale_datetime')
def _constrains_dates_coherency(self):
for ticket in self:
if ticket.start_sale_datetime and ticket.end_sale_datetime and ticket.start_sale_datetime > ticket.end_sale_datetime:
raise UserError(_('The stop date cannot be earlier than the start date.'))
@api.constrains('seats_available', 'seats_max')
def _constrains_seats_available(self):
if any(record.seats_max and record.seats_available < 0 for record in self):
raise ValidationError(_('No more available seats for this ticket.'))
def _get_ticket_multiline_description(self):
""" Compute a multiline description of this ticket. It is used when ticket
description are necessary without having to encode it manually, like sales
information. """
return '%s\n%s' % (self.display_name, self.event_id.display_name)
def _set_tz_context(self):
self.ensure_one()
return self.with_context(tz=self.event_id.date_tz or 'UTC')
def is_launched(self):
# TDE FIXME: in master, make a computed field, easier to use
self.ensure_one()
if self.start_sale_datetime:
ticket = self._set_tz_context()
current_datetime = fields.Datetime.context_timestamp(ticket, fields.Datetime.now())
start_sale_datetime = fields.Datetime.context_timestamp(ticket, ticket.start_sale_datetime)
return start_sale_datetime <= current_datetime
else:
return True
@api.ondelete(at_uninstall=False)
def _unlink_except_if_registrations(self):
if self.registration_ids:
raise UserError(_(
"The following tickets cannot be deleted while they have one or more registrations linked to them:\n- %s",
'\n- '.join(self.mapped('name'))))
| 48.987578
| 7,887
|
976
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.exceptions import NotFound
from odoo.http import Controller, request, route, content_disposition
class EventController(Controller):
@route(['''/event/<model("event.event"):event>/ics'''], type='http', auth="public")
def event_ics_file(self, event, **kwargs):
if request.env.user._is_public():
frontend_lang = request.httprequest.cookies.get('frontend_lang')
if frontend_lang:
event = event.with_context(lang=frontend_lang)
files = event._get_ics_file()
if not event.id in files:
return NotFound()
content = files[event.id]
return request.make_response(content, [
('Content-Type', 'application/octet-stream'),
('Content-Length', len(content)),
('Content-Disposition', content_disposition('%s.ics' % event.name))
])
| 39.04
| 976
|
1,716
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "Snail Mail",
'description': """
Allows users to send documents by post
=====================================================
""",
'category': 'Hidden/Tools',
'version': '0.3',
'depends': [
'iap_mail',
'mail'
],
'data': [
'data/snailmail_data.xml',
'views/report_assets.xml',
'views/snailmail_views.xml',
'wizard/snailmail_confirm_views.xml',
'wizard/snailmail_letter_cancel_views.xml',
'wizard/snailmail_letter_format_error_views.xml',
'wizard/snailmail_letter_missing_required_fields_views.xml',
'security/ir.model.access.csv',
],
'auto_install': True,
'assets': {
'mail.assets_discuss_public': [
'snailmail/static/src/components/*/*',
'snailmail/static/src/models/*/*.js',
],
'snailmail.report_assets_snailmail': [
('include', 'web._assets_helpers'),
'web/static/lib/bootstrap/scss/_variables.scss',
'snailmail/static/src/scss/snailmail_external_layout_asset.scss',
'snailmail/static/src/js/snailmail_external_layout.js',
],
'web.assets_backend': [
'snailmail/static/src/components/*/*.js',
'snailmail/static/src/components/*/*.scss',
'snailmail/static/src/models/*/*.js',
],
'web.tests_assets': [
'snailmail/static/tests/**/*',
],
'web.qunit_suite_tests': [
'snailmail/static/src/components/*/tests/*.js',
],
'web.assets_qweb': [
'snailmail/static/src/components/*/*.xml',
],
},
'license': 'LGPL-3',
}
| 33
| 1,716
|
6,184
|
py
|
PYTHON
|
15.0
|
SNAILMAIL_COUNTRIES = {
"AC": "Ascension",
"AD": "Andorra",
"AE": "United Arab Emirates",
"AF": "Afghanistan",
"AG": "Antigua and Barbuda",
"AI": "Anguilla",
"AL": "Albania",
"AM": "Armenia",
"AN": "Netherlands Antilles",
"AO": "Angola",
"AQ": "Antarctica",
"AR": "Argentina",
"AS": "American Samoa",
"AT": "Austria",
"AU": "Australia",
"AW": "Aruba",
"AX": "Aland Islands",
"AZ": "Azerbaijan",
"BA": "Bosnia and Herzegovina",
"BB": "Barbados",
"BD": "Bangladesh",
"BE": "Belgium",
"BF": "Burkina Faso",
"BG": "Bulgaria",
"BH": "Bahrain",
"BI": "Burundi",
"BJ": "Benin",
"BL": "Saint Barth\u00e9lemy",
"BM": "Bermuda",
"BN": "Brunei",
"BO": "Bolivia",
"BQ": "Bonaire Sint Eustatius and Saba",
"BR": "Brazil",
"BS": "Bahamas",
"BT": "Bhutan",
"BV": "Bouvet Island",
"BW": "Botswana",
"BY": "Belarus",
"BZ": "Belize",
"CA": "Canada",
"CC": "Cocos (Keeling) Islands",
"CD": "Congo Democratic Republic",
"CF": "Central African Republic",
"CG": "Congo Republic",
"CH": "Switzerland",
"CI": "C\u00f4te d'Ivoire",
"CK": "Cook Islands",
"CL": "Chile",
"CM": "Cameroon",
"CN": "China",
"CO": "Colombia",
"CR": "Costa Rica",
"CU": "Cuba",
"CV": "Cape Verde",
"CW": "Curacao",
"CX": "Christmas Island",
"CY": "Cyprus",
"CZ": "Czech Republic",
"DE": "Germany",
"DG": "Diego Garcia",
"DJ": "Djibouti",
"DK": "Denmark",
"DM": "Dominica",
"DO": "Dominican Republic",
"DZ": "Algeria",
"EC": "Ecuador",
"EE": "Estonia",
"EG": "Egypt",
"EH": "Western Sahara",
"ER": "Eritrea",
"ES": "Spain",
"ET": "Ethiopia",
"FI": "Finland",
"FJ": "Fiji",
"FK": "Falkland Islands",
"FM": "Micronesia",
"FO": "Faroe Islands",
"FR": "France",
"GA": "Gabon",
"GB": "Great Britain",
"GD": "Grenada",
"GE": "Georgia",
"GF": "French Guiana",
"GG": "Guernsey",
"GH": "Ghana",
"GI": "Gibraltar",
"GL": "Greenland",
"GM": "Gambia",
"GN": "Guinea Republic",
"GP": "Guadeloupe",
"GQ": "Equatorial Guinea",
"GR": "Greece",
"GS": "South Georgia and Sandwich",
"GT": "Guatemala",
"GU": "Guam",
"GW": "Guinea-Bissau",
"GY": "Guyana",
"HK": "Hong Kong",
"HM": "Heard Island And Mcdonald Islands",
"HN": "Honduras",
"HR": "Croatia",
"HT": "Haiti",
"HU": "Hungary",
"IC": "Canary Islands",
"ID": "Indonesia",
"IE": "Ireland",
"IL": "Israel",
"IM": "Isle of Man",
"IN": "India",
"IO": "British Indian Ocean Territory",
"IQ": "Iraq",
"IR": "Iran",
"IS": "Iceland",
"IT": "Italy",
"JE": "Jersey",
"JM": "Jamaica",
"JO": "Jordan",
"JP": "Japan",
"KE": "Kenya",
"KG": "Kyrgyzstan",
"KH": "Cambodia",
"KI": "Kiribati",
"KM": "Comoros",
"KN": "Saint Kitts and Nevis",
"KP": "Korea Dem. Peo. Rep.",
"KR": "Korea (South Korea) Republic",
"KW": "Kuwait",
"KY": "Cayman Islands",
"KZ": "Kazakstan",
"LA": "Laos People's Democratic Republic",
"LB": "Lebanon",
"LC": "Saint Lucia",
"LI": "Liechtenstein",
"LK": "Sri Lanka",
"LR": "Liberia",
"LS": "Lesotho",
"LT": "Lithuania",
"LU": "Luxembourg",
"LV": "Latvia",
"LY": "Libyan",
"MA": "Morocco",
"MC": "Monaco",
"MD": "Moldova",
"ME": "Montenegro",
"MF": "Saint Martin",
"MG": "Madagascar",
"MH": "Marshall Islands",
"MK": "Macedonia",
"ML": "Mali",
"MM": "Myanmar",
"MN": "Mongolia",
"MO": "Macao",
"MP": "Mariana Islands",
"MQ": "Martinique",
"MR": "Mauritania",
"MS": "Montserrat",
"MT": "Malta",
"MU": "Mauritius",
"MV": "Maldives",
"MW": "Malawi",
"MX": "Mexico",
"MY": "Malaysia",
"MZ": "Mozambique",
"NA": "Namibia",
"NC": "New Caledonia",
"NE": "Niger",
"NF": "Norfolk Island",
"NG": "Nigeria",
"NI": "Nicaragua",
"NL": "Netherlands",
"NO": "Norway",
"NP": "Nepal",
"NR": "Nauru",
"NU": "Niue",
"NZ": "New Zealand",
"OM": "Oman",
"PA": "Panama",
"PE": "Peru",
"PF": "French Polynesia",
"PG": "Papua New Guinea",
"PH": "Philippines",
"PK": "Pakistan",
"PL": "Poland",
"PM": "Saint Pierre and Miquelon",
"PN": "Pitcairn Island",
"PR": "Puerto Rico",
"PS": "Palestine",
"PT": "Portugal",
"PW": "Palau",
"PY": "Paraguay",
"QA": "Qatar",
"RE": "R\u00e9union",
"RO": "Romania",
"RS": "Serbia",
"RU": "Russian Federation",
"RW": "Rwanda",
"SA": "Saudi Arabia",
"SB": "Solomon Islands",
"SC": "Seychelles",
"SD": "Sudan",
"SE": "Sweden",
"SG": "Singapore",
"SH": "Ascension StHelena & Tristan",
"SI": "Slovenia",
"SJ": "Svalbard and Jan Mayen",
"SK": "Slovakia",
"SL": "Sierra Leone",
"SM": "San Marino",
"SN": "Senegal",
"SO": "Somalia",
"SR": "Suriname",
"SS": "South Sudan",
"ST": "Sao Tome and Principe",
"SV": "El Salvardor",
"SX": "Sint Maarten",
"SY": "Syria",
"SZ": "Swaziland",
"TA": "Tristan da Cunha",
"TC": "Turks and Caicos",
"TD": "Chad",
"TF": "French Southern Territories",
"TG": "Togo",
"TH": "Thailand",
"TJ": "Tajikistan",
"TK": "Tokelau Islands",
"TL": "Timor-Leste",
"TM": "Turkmenistan",
"TN": "Tunisia",
"TO": "Tonga",
"TR": "Turkey",
"TT": "Trinidad and Tobago",
"TV": "Tuvalu",
"TW": "China Taiwan",
"TZ": "Tanzania",
"UA": "Ukraine",
"UG": "Uganda",
"US": "United States of America",
"UY": "Uruguay",
"UZ": "Uzbekistan",
"VA": "Vatican City State",
"VC": "St. Vincent and Grenadines",
"VE": "Venezuela",
"VG": "Virgin Islands british",
"VI": "Virgin Islands",
"VN": "Vietnam",
"VU": "Vanuatu",
"WF": "Wallis and Futuna Islands",
"WS": "Western Samoa",
"XZ": "Kosovo",
"YE": "Yemen",
"YT": "Mayotte",
"ZA": "South Africa",
"ZM": "Zambia",
"ZW": "Zimbabwe"
}
| 24.15625
| 6,184
|
5,548
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo.exceptions import AccessError
from odoo.tests import TransactionCase
class testAttachmentAccess(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = cls.env['res.users'].create({
'name': "foo",
'login': "foo",
'email': "foo@bar.com",
'groups_id': [(6, 0, [
cls.env.ref('base.group_user').id,
cls.env.ref('base.group_partner_manager').id,
])]
})
cls.letter_defaults = {
'model': cls.user.partner_id._name,
'res_id': cls.user.partner_id.id,
'partner_id': cls.user.partner_id.id,
}
def test_user_letter_attachment_without_res_fields(self):
"""Test an employee can create a letter linked to an attachment without res_model/res_id"""
env_user = self.env(user=self.user)
# As user, create an attachment without res_model/res_id
attachment = env_user['ir.attachment'].create({'name': 'foo', 'datas': base64.b64encode(b'foo')})
# As user, create a snailmail.letter linked to that attachment
letter = env_user['snailmail.letter'].create({'attachment_id': attachment.id, **self.letter_defaults})
# As user, ensure the content of the attachment can be read through the letter
self.assertEqual(base64.b64decode(letter.attachment_datas), b'foo')
# As user, create another attachment without res_model/res_id
attachment_2 = env_user['ir.attachment'].create({'name': 'foo', 'datas': base64.b64encode(b'bar')})
# As user, change the attachment of the letter to this second attachment
letter.write({'attachment_id': attachment_2.id})
# As user, ensure the content of this second attachment can be read through the letter
self.assertEqual(base64.b64decode(letter.attachment_datas), b'bar')
def test_user_letter_attachment_without_res_fields_created_by_admin(self):
"""Test an employee can read the content of the letter's attachment created by another user, the admin,
and the attachment does not have a res_model/res_id
"""
# As admin, create an attachment without res_model/res_id
attachment = self.env['ir.attachment'].create({'name': 'foo', 'datas': base64.b64encode(b'foo')})
# As admin, create a snailmail.letter linked to that attachment
letter = self.env['snailmail.letter'].create({'attachment_id': attachment.id, **self.letter_defaults})
# As user, ensure the attachment itself cannot be read
attachment.invalidate_cache()
with self.assertRaises(AccessError):
attachment.with_user(self.user).datas
# But, as user, the content of the attachment can be read through the letter
self.assertEqual(base64.b64decode(letter.with_user(self.user).attachment_datas), b'foo')
# As admin, create a second attachment without res_model/res_id
attachment = self.env['ir.attachment'].create({'name': 'bar', 'datas': base64.b64encode(b'bar')})
# As admin, link this second attachment to the previously created letter (write instead of create)
letter.write({'attachment_id': attachment.id})
# As user ensure the attachment itself cannot be read
attachment.invalidate_cache()
with self.assertRaises(AccessError):
self.assertEqual(base64.b64decode(attachment.with_user(self.user).datas), b'bar')
# But, as user, the content of the attachment can be read through the letter
self.assertEqual(base64.b64decode(letter.with_user(self.user).attachment_datas), b'bar')
def test_user_read_unallowed_attachment(self):
"""Test a user cannot access an attachment he is not supposed to through a snailmail.letter"""
# As admin, create an attachment for which you require the settings group to access
base_module = self.env.ref('base.module_base')
attachment_forbidden = self.env['ir.attachment'].create({
'name': 'foo', 'datas': base64.b64encode(b'foo'),
'res_model': base_module._name, 'res_id': base_module.id,
})
# As user, make sure this is indeed not possible to access that attachment data directly
attachment_forbidden.invalidate_cache()
with self.assertRaises(AccessError):
attachment_forbidden.with_user(self.user).datas
# As user, create a letter pointing to that attachment
# and make sure it raises an access error
with self.assertRaises(AccessError):
letter = self.env['snailmail.letter'].with_user(self.user).create({
'attachment_id': attachment_forbidden.id,
**self.letter_defaults,
})
letter.attachment_datas
# As user, update the attachment of an existing letter to the unallowed attachment
# and make sure it raises an access error
attachment_tmp = self.env['ir.attachment'].with_user(self.user).create({
'name': 'bar', 'datas': base64.b64encode(b'bar'),
})
letter = self.env['snailmail.letter'].with_user(self.user).create({
'attachment_id': attachment_tmp.id,
**self.letter_defaults,
})
with self.assertRaises(AccessError):
letter.write({'attachment_id': attachment_forbidden.id})
letter.attachment_datas
| 53.346154
| 5,548
|
1,903
|
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models
class SnailmailLetterMissingRequiredFields(models.TransientModel):
_name = 'snailmail.letter.missing.required.fields'
_description = 'Update address of partner'
partner_id = fields.Many2one('res.partner')
letter_id = fields.Many2one('snailmail.letter')
street = fields.Char('Street')
street2 = fields.Char('Street2')
zip = fields.Char('Zip')
city = fields.Char('City')
state_id = fields.Many2one("res.country.state", string='State')
country_id = fields.Many2one('res.country', string='Country')
@api.model
def default_get(self, fields):
defaults = super(SnailmailLetterMissingRequiredFields, self).default_get(fields)
if defaults.get('letter_id'):
letter = self.env['snailmail.letter'].browse(defaults.get('letter_id'))
defaults.update({
'partner_id': letter.partner_id.id,
'street': letter.street,
'street2': letter.street2,
'zip': letter.zip,
'city': letter.city,
'state_id': letter.state_id.id,
'country_id': letter.country_id.id,
})
return defaults
def update_address_cancel(self):
self.letter_id.cancel()
def update_address_save(self):
address_data = {
'street': self.street,
'street2': self.street2,
'zip': self.zip,
'city': self.city,
'state_id': self.state_id.id,
'country_id': self.country_id.id,
}
self.partner_id.write(address_data)
letters_to_resend = self.env['snailmail.letter'].search([
('partner_id', '=', self.partner_id.id),
('error_code', '=', 'MISSING_REQUIRED_FIELDS'),
])
letters_to_resend.write(address_data)
letters_to_resend.snailmail_print()
| 36.596154
| 1,903
|
1,491
|
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 SnailmailConfirm(models.AbstractModel):
_name = 'snailmail.confirm'
_description = 'Snailmail Confirm'
model_name = fields.Char()
@api.model
def show_warning(self):
return not self.env['ir.config_parameter'].sudo().get_param('%s.warning_shown' % self._name, False)
def action_open(self):
view = self.env.ref('snailmail.snailmail_confirm_view')
return {
'name': _('Snailmail'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': self._name,
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'res_id': self.id,
'context': self.env.context
}
def action_confirm(self):
self.env['ir.config_parameter'].sudo().set_param('%s.warning_shown' % self._name, True)
self._confirm()
return self._continue()
def action_cancel(self):
self.env['ir.config_parameter'].sudo().set_param('%s.warning_shown' % self._name, True)
return self._continue()
"""
Called whether the user confirms or cancels posting the letter, e.g. to continue the action
"""
def _continue(self):
pass
"""
Called only when the user confirms sending the letter
"""
def _confirm(self):
pass
| 29.82
| 1,491
|
1,069
|
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models
class SnailmailLetterCancel(models.TransientModel):
_name = 'snailmail.letter.cancel'
_description = 'Dismiss notification for resend by model'
model = fields.Char(string='Model')
help_message = fields.Char(string='Help message', compute='_compute_help_message')
@api.depends('model')
def _compute_help_message(self):
for wizard in self:
wizard.help_message = _("Are you sure you want to discard %s snailmail delivery failures? You won't be able to re-send these letters later!") % (wizard._context.get('unread_counter'))
def cancel_resend_action(self):
author_id = self.env.user.id
for wizard in self:
letters = self.env['snailmail.letter'].search([
('state', 'not in', ['sent', 'canceled', 'pending']),
('user_id', '=', author_id),
('model', '=', wizard.model)
])
for letter in letters:
letter.cancel()
return {'type': 'ir.actions.act_window_close'}
| 41.115385
| 1,069
|
1,056
|
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class SnailmailLetterFormatError(models.TransientModel):
_name = 'snailmail.letter.format.error'
_description = 'Format Error Sending a Snailmail Letter'
message_id = fields.Many2one(
'mail.message',
default=lambda self: self.env.context.get('message_id', None),
)
snailmail_cover = fields.Boolean(
string='Add a Cover Page',
default=lambda self: self.env.company.snailmail_cover,
)
def update_resend_action(self):
self.env.company.write({'snailmail_cover': self.snailmail_cover})
letters_to_resend = self.env['snailmail.letter'].search([
('error_code', '=', 'FORMAT_ERROR'),
])
for letter in letters_to_resend:
old_attachment = letter.attachment_id
letter.attachment_id = False
old_attachment.unlink()
letter.write({'cover': self.snailmail_cover})
letter.snailmail_print()
def cancel_letter_action(self):
self.message_id.cancel_letter()
| 35.2
| 1,056
|
719
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class Notification(models.Model):
_inherit = 'mail.notification'
notification_type = fields.Selection(selection_add=[('snail', 'Snailmail')], ondelete={'snail': 'cascade'})
letter_id = fields.Many2one('snailmail.letter', string="Snailmail Letter", index=True, ondelete='cascade')
failure_type = fields.Selection(selection_add=[
('sn_credit', "Snailmail Credit Error"),
('sn_trial', "Snailmail Trial Error"),
('sn_price', "Snailmail No Price Available"),
('sn_fields', "Snailmail Missing Required Fields"),
('sn_format', "Snailmail Format Error"),
('sn_error', "Snailmail Unknown Error"),
])
| 39.944444
| 719
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.