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
|
---|---|---|---|---|---|---|
504 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class L10nInProductHsnReport(models.Model):
_inherit = "l10n_in.product.hsn.report"
def _from(self):
from_str = super(L10nInProductHsnReport, self)._from()
from_str += """ AND aml.product_id != COALESCE(
(SELECT value from ir_config_parameter where key = 'sale.default_deposit_product_id'), '0')::int
"""
return from_str
| 33.6 | 504 |
918 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class L10nInAccountInvoiceReport(models.Model):
_inherit = "l10n_in.account.invoice.report"
def _from(self):
from_str = super(L10nInAccountInvoiceReport, self)._from()
return from_str.replace(
"LEFT JOIN res_country_state ps ON ps.id = p.state_id",
"""
LEFT JOIN res_partner dp ON dp.id = am.partner_shipping_id
LEFT JOIN res_country_state ps ON ps.id = dp.state_id
"""
)
def _where(self):
where_str = super(L10nInAccountInvoiceReport, self)._where()
where_str += """ AND (aml.product_id IS NULL or aml.product_id != COALESCE(
(SELECT value from ir_config_parameter where key = 'sale.default_deposit_product_id'), '0')::int)
"""
return where_str
| 36.72 | 918 |
908 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Test Full eLearning Flow',
'version': '1.0',
'category': 'Hidden/Tests',
'description': """
This module will test the main certification flow of Odoo.
It will install the e-learning, survey and e-commerce apps and make a complete
certification flow including purchase, certification, failure and success.
""",
'depends': [
'website_sale_product_configurator',
'website_sale_slides',
'website_slides_forum',
'website_slides_survey',
'payment_test'
],
'data': [
'data/res_groups_data.xml',
],
'demo': [
'data/product_demo.xml',
],
'installable': True,
'assets': {
'web.assets_tests': [
'test_website_slides_full/tests/tours/**/*',
],
},
'license': 'LGPL-3',
}
| 28.375 | 908 |
6,951 |
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.fields import Datetime
from odoo import tests
from odoo.addons.website_slides.tests.test_ui_wslides import TestUICommon
@tests.common.tagged('post_install', '-at_install')
class TestUi(TestUICommon):
def test_course_certification_employee(self):
user_demo = self.user_demo
user_demo.flush()
# Avoid Billing/Shipping address page
user_demo.write({
'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id)],
'street': '215 Vine St',
'city': 'Scranton',
'zip': '18503',
'country_id': self.env.ref('base.us').id,
'state_id': self.env.ref('base.state_us_39').id,
'phone': '+1 555-555-5555',
'email': '[email protected]',
})
# Specify Accounting Data
cash_journal = self.env['account.journal'].create({'name': 'Cash - Test', 'type': 'cash', 'code': 'CASH - Test'})
self.env['payment.acquirer'].search([('provider', '=', 'test')]).write({
'journal_id': cash_journal.id,
'state': 'test'
})
a_recv = self.env['account.account'].create({
'code': 'X1012',
'name': 'Debtors - (test)',
'reconcile': True,
'user_type_id': self.env.ref('account.data_account_type_receivable').id,
})
a_pay = self.env['account.account'].create({
'code': 'X1111',
'name': 'Creditors - (test)',
'user_type_id': self.env.ref('account.data_account_type_payable').id,
'reconcile': True,
})
Property = self.env['ir.property']
Property._set_default('property_account_receivable_id', 'res.partner', a_recv, self.env.company)
Property._set_default('property_account_payable_id', 'res.partner', a_pay, self.env.company)
product_course_channel_6 = self.env['product.product'].create({
'name': 'DIY Furniture Course',
'list_price': 100.0,
'type': 'service',
'is_published': True,
})
furniture_survey = self.env['survey.survey'].create({
'title': 'Furniture Creation Certification',
'access_token': '5632a4d7-48cf-aaaa-8c52-2174d58cf50b',
'access_mode': 'public',
'users_can_go_back': True,
'users_login_required': True,
'scoring_type': 'scoring_with_answers',
'certification': True,
'certification_mail_template_id': self.env.ref('survey.mail_template_certification').id,
'is_attempts_limited': True,
'attempts_limit': 3,
'description': "<p>Test your furniture knowledge!</p>",
'question_and_page_ids': [
(0, 0, {
'title': 'Furniture',
'sequence': 1,
'is_page': True,
'description': "<p>Test your furniture knowledge!</p>",
}), (0, 0, {
'title': 'What type of wood is the best for furniture?',
'sequence': 2,
'question_type': 'simple_choice',
'constr_mandatory': True,
'suggested_answer_ids': [
(0, 0, {
'value': 'Fir',
'sequence': 1,
}), (0, 0, {
'value': 'Oak',
'sequence': 2,
'is_correct': True,
'answer_score': 2.0,
}), (0, 0, {
'value': 'Ash',
'sequence': 3,
}), (0, 0, {
'value': 'Beech',
'sequence': 4,
})
]
}), (0, 0, {
'title': 'Select all the furniture shown in the video',
'sequence': 3,
'question_type': 'multiple_choice',
'column_nb': '4',
'suggested_answer_ids': [
(0, 0, {
'value': 'Chair',
'sequence': 1,
'is_correct': True,
'answer_score': 1.0,
}), (0, 0, {
'value': 'Table',
'sequence': 2,
'answer_score': -1.0,
}), (0, 0, {
'value': 'Desk',
'sequence': 3,
'is_correct': True,
'answer_score': 1.0,
}), (0, 0, {
'value': 'Shelve',
'sequence': 4,
'is_correct': True,
'answer_score': 1.0,
}), (0, 0, {
'value': 'Bed',
'sequence': 5,
'answer_score': -1.0,
})
]
}), (0, 0, {
'title': 'What do you think about the content of the course? (not rated)',
'sequence': 4,
'question_type': 'text_box',
})
]
})
slide_channel_demo_6_furn3 = self.env['slide.channel'].create({
'name': 'DIY Furniture - TEST',
'user_id': self.env.ref('base.user_admin').id,
'enroll': 'payment',
'product_id': product_course_channel_6.id,
'channel_type': 'training',
'allow_comment': True,
'promote_strategy': 'most_voted',
'is_published': True,
'description': 'So much amazing certification.',
'create_date': Datetime.now() - relativedelta(days=2),
'slide_ids': [
(0, 0, {
'name': 'DIY Furniture Certification',
'sequence': 1,
'slide_type': 'certification',
'category_id': False,
'is_published': True,
'is_preview': False,
'description': "It's time to test your knowledge!",
'survey_id': furniture_survey.id,
})
]
})
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("certification_member")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.certification_member.ready',
login=user_demo.login)
| 42.127273 | 6,951 |
1,026 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'IBAN Bank Accounts',
'category': 'Hidden/Tools',
'description': """
This module installs the base for IBAN (International Bank Account Number) bank accounts and checks for it's validity.
======================================================================================================================
The ability to extract the correctly represented local accounts from IBAN accounts
with a single statement.
""",
'depends': ['account', 'web'],
'data': [
'views/partner_view.xml',
'views/setup_wizards_view.xml'
],
'demo': ['data/res_partner_bank_demo.xml'],
'assets': {
'web.assets_backend': [
'base_iban/static/src/js/iban_widget.js',
'base_iban/static/src/scss/iban_widget_view.scss',
],
'web.qunit_suite_tests': [
'base_iban/static/src/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 35.37931 | 1,026 |
7,579 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import re
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
def normalize_iban(iban):
return re.sub('[\W_]', '', iban or '')
def pretty_iban(iban):
""" return iban in groups of four characters separated by a single space """
try:
validate_iban(iban)
iban = ' '.join([iban[i:i + 4] for i in range(0, len(iban), 4)])
except ValidationError:
pass
return iban
def get_bban_from_iban(iban):
""" Returns the basic bank account number corresponding to an IBAN.
Note : the BBAN is not the same as the domestic bank account number !
The relation between IBAN, BBAN and domestic can be found here : http://www.ecbs.org/iban.htm
"""
return normalize_iban(iban)[4:]
def validate_iban(iban):
iban = normalize_iban(iban)
if not iban:
raise ValidationError(_("There is no IBAN code."))
country_code = iban[:2].lower()
if country_code not in _map_iban_template:
raise ValidationError(_("The IBAN is invalid, it should begin with the country code"))
iban_template = _map_iban_template[country_code]
if len(iban) != len(iban_template.replace(' ', '')) or not re.fullmatch("[a-zA-Z0-9]+", iban):
raise ValidationError(_("The IBAN does not seem to be correct. You should have entered something like this %s\n"
"Where B = National bank code, S = Branch code, C = Account No, k = Check digit") % iban_template)
check_chars = iban[4:] + iban[:4]
digits = int(''.join(str(int(char, 36)) for char in check_chars)) # BASE 36: 0..9,A..Z -> 0..35
if digits % 97 != 1:
raise ValidationError(_("This IBAN does not pass the validation check, please verify it."))
class ResPartnerBank(models.Model):
_inherit = "res.partner.bank"
@api.model
def _get_supported_account_types(self):
rslt = super(ResPartnerBank, self)._get_supported_account_types()
rslt.append(('iban', _('IBAN')))
return rslt
@api.model
def retrieve_acc_type(self, acc_number):
try:
validate_iban(acc_number)
return 'iban'
except ValidationError:
return super(ResPartnerBank, self).retrieve_acc_type(acc_number)
def get_bban(self):
if self.acc_type != 'iban':
raise UserError(_("Cannot compute the BBAN because the account number is not an IBAN."))
return get_bban_from_iban(self.acc_number)
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if vals.get('acc_number'):
try:
validate_iban(vals['acc_number'])
vals['acc_number'] = pretty_iban(normalize_iban(vals['acc_number']))
except ValidationError:
pass
return super(ResPartnerBank, self).create(vals_list)
def write(self, vals):
if vals.get('acc_number'):
try:
validate_iban(vals['acc_number'])
vals['acc_number'] = pretty_iban(normalize_iban(vals['acc_number']))
except ValidationError:
pass
return super(ResPartnerBank, self).write(vals)
@api.constrains('acc_number')
def _check_iban(self):
for bank in self:
if bank.acc_type == 'iban':
validate_iban(bank.acc_number)
def check_iban(self, iban=''):
try:
validate_iban(iban)
return True
except ValidationError:
return False
# Map ISO 3166-1 -> IBAN template, as described here :
# http://en.wikipedia.org/wiki/International_Bank_Account_Number#IBAN_formats_by_country
_map_iban_template = {
'ad': 'ADkk BBBB SSSS CCCC CCCC CCCC', # Andorra
'ae': 'AEkk BBBC CCCC CCCC CCCC CCC', # United Arab Emirates
'al': 'ALkk BBBS SSSK CCCC CCCC CCCC CCCC', # Albania
'at': 'ATkk BBBB BCCC CCCC CCCC', # Austria
'az': 'AZkk BBBB CCCC CCCC CCCC CCCC CCCC', # Azerbaijan
'ba': 'BAkk BBBS SSCC CCCC CCKK', # Bosnia and Herzegovina
'be': 'BEkk BBBC CCCC CCXX', # Belgium
'bg': 'BGkk BBBB SSSS DDCC CCCC CC', # Bulgaria
'bh': 'BHkk BBBB CCCC CCCC CCCC CC', # Bahrain
'br': 'BRkk BBBB BBBB SSSS SCCC CCCC CCCT N', # Brazil
'by': 'BYkk BBBB AAAA CCCC CCCC CCCC CCCC', # Belarus
'ch': 'CHkk BBBB BCCC CCCC CCCC C', # Switzerland
'cr': 'CRkk BBBC CCCC CCCC CCCC CC', # Costa Rica
'cy': 'CYkk BBBS SSSS CCCC CCCC CCCC CCCC', # Cyprus
'cz': 'CZkk BBBB SSSS SSCC CCCC CCCC', # Czech Republic
'de': 'DEkk BBBB BBBB CCCC CCCC CC', # Germany
'dk': 'DKkk BBBB CCCC CCCC CC', # Denmark
'do': 'DOkk BBBB CCCC CCCC CCCC CCCC CCCC', # Dominican Republic
'ee': 'EEkk BBSS CCCC CCCC CCCK', # Estonia
'es': 'ESkk BBBB SSSS KKCC CCCC CCCC', # Spain
'fi': 'FIkk BBBB BBCC CCCC CK', # Finland
'fo': 'FOkk CCCC CCCC CCCC CC', # Faroe Islands
'fr': 'FRkk BBBB BGGG GGCC CCCC CCCC CKK', # France
'gb': 'GBkk BBBB SSSS SSCC CCCC CC', # United Kingdom
'ge': 'GEkk BBCC CCCC CCCC CCCC CC', # Georgia
'gi': 'GIkk BBBB CCCC CCCC CCCC CCC', # Gibraltar
'gl': 'GLkk BBBB CCCC CCCC CC', # Greenland
'gr': 'GRkk BBBS SSSC CCCC CCCC CCCC CCC', # Greece
'gt': 'GTkk BBBB MMTT CCCC CCCC CCCC CCCC', # Guatemala
'hr': 'HRkk BBBB BBBC CCCC CCCC C', # Croatia
'hu': 'HUkk BBBS SSSC CCCC CCCC CCCC CCCC', # Hungary
'ie': 'IEkk BBBB SSSS SSCC CCCC CC', # Ireland
'il': 'ILkk BBBS SSCC CCCC CCCC CCC', # Israel
'is': 'ISkk BBBB SSCC CCCC XXXX XXXX XX', # Iceland
'it': 'ITkk KBBB BBSS SSSC CCCC CCCC CCC', # Italy
'jo': 'JOkk BBBB NNNN CCCC CCCC CCCC CCCC CC', # Jordan
'kw': 'KWkk BBBB CCCC CCCC CCCC CCCC CCCC CC', # Kuwait
'kz': 'KZkk BBBC CCCC CCCC CCCC', # Kazakhstan
'lb': 'LBkk BBBB CCCC CCCC CCCC CCCC CCCC', # Lebanon
'li': 'LIkk BBBB BCCC CCCC CCCC C', # Liechtenstein
'lt': 'LTkk BBBB BCCC CCCC CCCC', # Lithuania
'lu': 'LUkk BBBC CCCC CCCC CCCC', # Luxembourg
'lv': 'LVkk BBBB CCCC CCCC CCCC C', # Latvia
'mc': 'MCkk BBBB BGGG GGCC CCCC CCCC CKK', # Monaco
'md': 'MDkk BBCC CCCC CCCC CCCC CCCC', # Moldova
'me': 'MEkk BBBC CCCC CCCC CCCC KK', # Montenegro
'mk': 'MKkk BBBC CCCC CCCC CKK', # Macedonia
'mr': 'MRkk BBBB BSSS SSCC CCCC CCCC CKK', # Mauritania
'mt': 'MTkk BBBB SSSS SCCC CCCC CCCC CCCC CCC', # Malta
'mu': 'MUkk BBBB BBSS CCCC CCCC CCCC CCCC CC', # Mauritius
'nl': 'NLkk BBBB CCCC CCCC CC', # Netherlands
'no': 'NOkk BBBB CCCC CCK', # Norway
'pk': 'PKkk BBBB CCCC CCCC CCCC CCCC', # Pakistan
'pl': 'PLkk BBBS SSSK CCCC CCCC CCCC CCCC', # Poland
'ps': 'PSkk BBBB XXXX XXXX XCCC CCCC CCCC C', # Palestinian
'pt': 'PTkk BBBB SSSS CCCC CCCC CCCK K', # Portugal
'qa': 'QAkk BBBB CCCC CCCC CCCC CCCC CCCC C', # Qatar
'ro': 'ROkk BBBB CCCC CCCC CCCC CCCC', # Romania
'rs': 'RSkk BBBC CCCC CCCC CCCC KK', # Serbia
'sa': 'SAkk BBCC CCCC CCCC CCCC CCCC', # Saudi Arabia
'se': 'SEkk BBBB CCCC CCCC CCCC CCCC', # Sweden
'si': 'SIkk BBSS SCCC CCCC CKK', # Slovenia
'sk': 'SKkk BBBB SSSS SSCC CCCC CCCC', # Slovakia
'sm': 'SMkk KBBB BBSS SSSC CCCC CCCC CCC', # San Marino
'tn': 'TNkk BBSS SCCC CCCC CCCC CCCC', # Tunisia
'tr': 'TRkk BBBB BRCC CCCC CCCC CCCC CC', # Turkey
'ua': 'UAkk BBBB BBCC CCCC CCCC CCCC CCCC C', # Ukraine
'vg': 'VGkk BBBB CCCC CCCC CCCC CCCC', # Virgin Islands
'xk': 'XKkk BBBB CCCC CCCC CCCC', # Kosovo
}
| 43.308571 | 7,579 |
1,505 |
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Recruitment',
'version': '1.1',
'category': 'Human Resources/Recruitment',
'sequence': 90,
'summary': 'Track your recruitment pipeline',
'description': "",
'website': 'https://www.odoo.com/app/recruitment',
'depends': [
'hr',
'calendar',
'fetchmail',
'utm',
'attachment_indexation',
'web_tour',
'digest',
],
'data': [
'security/hr_recruitment_security.xml',
'security/ir.model.access.csv',
'data/digest_data.xml',
'data/mail_data.xml',
'data/mail_template_data.xml',
'data/mail_templates.xml',
'data/hr_recruitment_data.xml',
'views/hr_recruitment_views.xml',
'views/res_config_settings_views.xml',
'views/hr_department_views.xml',
'views/hr_job_views.xml',
'views/mail_activity_views.xml',
'views/digest_views.xml',
'wizard/applicant_refuse_reason_views.xml',
],
'demo': [
'data/hr_recruitment_demo.xml',
],
'installable': True,
'auto_install': False,
'application': True,
'assets': {
'web.assets_backend': [
'hr_recruitment/static/src/scss/hr_job.scss',
'hr_recruitment/static/src/js/recruitment.js',
'hr_recruitment/static/src/js/tours/hr_recruitment.js',
],
},
'license': 'LGPL-3',
}
| 29.509804 | 1,505 |
4,647 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
from odoo.addons.hr.tests.common import TestHrCommon
from odoo.modules.module import get_module_resource
class TestRecruitmentProcess(TestHrCommon):
def test_00_recruitment_process(self):
""" Test recruitment process """
self.dep_rd = self.env['hr.department'].create({
'name': 'Research & Development',
})
self.job_developer = self.env['hr.job'].create({
'name': 'Experienced Developer',
'department_id': self.dep_rd.id,
'no_of_recruitment': 5,
})
self.employee_niv = self.env['hr.employee'].create({
'name': 'Sharlene Rhodes',
})
self.job_developer = self.job_developer.with_user(self.res_users_hr_officer.id)
self.employee_niv = self.employee_niv.with_user(self.res_users_hr_officer.id)
# Create a new HR Recruitment Officer
self.res_users_hr_recruitment_officer = self.env['res.users'].create({
'company_id': self.env.ref('base.main_company').id,
'name': 'HR Recruitment Officer',
'login': "hrro",
'email': "[email protected]",
'groups_id': [(6, 0, [self.env.ref('hr_recruitment.group_hr_recruitment_user').id])]
})
# An applicant is interested in the job position. So he sends a resume by email.
# In Order to test process of Recruitment so giving HR officer's rights
with open(get_module_resource('hr_recruitment', 'tests', 'resume.eml'), 'rb') as request_file:
request_message = request_file.read()
self.env['mail.thread'].with_user(self.res_users_hr_recruitment_officer).message_process(
'hr.applicant', request_message, custom_values={"job_id": self.job_developer.id})
# After getting the mail, I check the details of the new applicant.
applicant = self.env['hr.applicant'].search([('email_from', 'ilike', '[email protected]')], limit=1)
self.assertTrue(applicant, "Applicant is not created after getting the mail")
resume_ids = self.env['ir.attachment'].search([
('name', '=', 'resume.pdf'),
('res_model', '=', self.env['hr.applicant']._name),
('res_id', '=', applicant.id)])
self.assertEqual(applicant.name, 'Application for the post of Jr.application Programmer.', 'Applicant name does not match.')
self.assertEqual(applicant.stage_id, self.env.ref('hr_recruitment.stage_job1'),
"Stage should be 'Initial qualification' and is '%s'." % (applicant.stage_id.name))
self.assertTrue(resume_ids, 'Resume is not attached.')
# I assign the Job position to the applicant
applicant.write({'job_id': self.job_developer.id})
# I schedule meeting with applicant for interview.
applicant_meeting = applicant.action_makeMeeting()
self.assertEqual(applicant_meeting['context']['default_name'], 'Application for the post of Jr.application Programmer.',
'Applicant name does not match.')
def test_01_hr_application_notification(self):
new_job_application_mt = self.env.ref(
"hr_recruitment.mt_job_applicant_new"
)
new_application_mt = self.env.ref(
"hr_recruitment.mt_applicant_new"
)
user = self.env["res.users"].with_context(no_reset_password=True).create(
{
"name": "user_1",
"login": "user_1",
"email": "[email protected]",
"groups_id": [
(4, self.env.ref("hr.group_hr_manager").id),
(4, self.env.ref("hr_recruitment.group_hr_recruitment_manager").id),
],
}
)
job = self.env["hr.job"].create({"name": "Test Job for Notification"})
# Make test user follow Test HR Job
self.env["mail.followers"].create(
{
"res_model": "hr.job",
"res_id": job.id,
"partner_id": user.partner_id.id,
"subtype_ids": [(4, new_job_application_mt.id)],
}
)
application = self.env["hr.applicant"].create(
{"name": "Test Job Application for Notification", "job_id": job.id}
)
new_application_message = application.message_ids.filtered(
lambda m: m.subtype_id == new_application_mt
)
self.assertTrue(
user.partner_id in new_application_message.notified_partner_ids
)
| 47.418367 | 4,647 |
2,607 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class ApplicantGetRefuseReason(models.TransientModel):
_name = 'applicant.get.refuse.reason'
_description = 'Get Refuse Reason'
refuse_reason_id = fields.Many2one('hr.applicant.refuse.reason', 'Refuse Reason')
applicant_ids = fields.Many2many('hr.applicant')
send_mail = fields.Boolean("Send Email", compute='_compute_send_mail', store=True, readonly=False)
template_id = fields.Many2one('mail.template', string='Email Template',
compute='_compute_send_mail', store=True, readonly=False,
domain="[('model', '=', 'hr.applicant')]")
applicant_without_email = fields.Text(compute='_compute_applicant_without_email',
string='Applicant(s) not having email')
@api.depends('refuse_reason_id')
def _compute_send_mail(self):
for wizard in self:
template = wizard.refuse_reason_id.template_id
wizard.send_mail = bool(template)
wizard.template_id = template
@api.depends('applicant_ids', 'send_mail')
def _compute_applicant_without_email(self):
for wizard in self:
applicants = wizard.applicant_ids.filtered(lambda x: not x.email_from and not x.partner_id.email)
if applicants and wizard.send_mail:
wizard.applicant_without_email = "%s\n%s" % (
_("The email will not be sent to the following applicant(s) as they don't have email address."),
"\n".join([i.partner_name for i in applicants])
)
else:
wizard.applicant_without_email = False
def action_refuse_reason_apply(self):
if self.send_mail:
if not self.template_id:
raise UserError(_("Email template must be selected to send a mail"))
if not self.applicant_ids.filtered(lambda x: x.email_from or x.partner_id.email):
raise UserError(_("Email of the applicant is not set, email won't be sent."))
self.applicant_ids.write({'refuse_reason_id': self.refuse_reason_id.id, 'active': False})
if self.send_mail:
applicants = self.applicant_ids.filtered(lambda x: x.email_from or x.partner_id.email)
applicants.with_context(active_test=True).message_post_with_template(self.template_id.id, **{
'auto_delete_message': True,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
'email_layout_xmlid': 'mail.mail_notification_light'
})
| 50.134615 | 2,607 |
1,339 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import AccessError
class Digest(models.Model):
_inherit = 'digest.digest'
kpi_hr_recruitment_new_colleagues = fields.Boolean('Employees')
kpi_hr_recruitment_new_colleagues_value = fields.Integer(compute='_compute_kpi_hr_recruitment_new_colleagues_value')
def _compute_kpi_hr_recruitment_new_colleagues_value(self):
if not self.env.user.has_group('hr_recruitment.group_hr_recruitment_user'):
raise AccessError(_("Do not have access, skip this data for user's digest email"))
for record in self:
start, end, company = record._get_kpi_compute_parameters()
new_colleagues = self.env['hr.employee'].search_count([
('create_date', '>=', start),
('create_date', '<', end),
('company_id', '=', company.id)
])
record.kpi_hr_recruitment_new_colleagues_value = new_colleagues
def _compute_kpis_actions(self, company, user):
res = super(Digest, self)._compute_kpis_actions(company, user)
res['kpi_hr_recruitment_new_colleagues'] = 'hr.open_view_employee_list_my&menu_id=%s' % self.env.ref('hr.menu_hr_root').id
return res
| 46.172414 | 1,339 |
1,553 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models
class HrDepartment(models.Model):
_inherit = 'hr.department'
new_applicant_count = fields.Integer(
compute='_compute_new_applicant_count', string='New Applicant')
new_hired_employee = fields.Integer(
compute='_compute_recruitment_stats', string='New Hired Employee')
expected_employee = fields.Integer(
compute='_compute_recruitment_stats', string='Expected Employee')
def _compute_new_applicant_count(self):
applicant_data = self.env['hr.applicant'].read_group(
[('department_id', 'in', self.ids), ('stage_id.sequence', '<=', '1')],
['department_id'], ['department_id'])
result = dict((data['department_id'][0], data['department_id_count']) for data in applicant_data)
for department in self:
department.new_applicant_count = result.get(department.id, 0)
def _compute_recruitment_stats(self):
job_data = self.env['hr.job'].read_group(
[('department_id', 'in', self.ids)],
['no_of_hired_employee', 'no_of_recruitment', 'department_id'], ['department_id'])
new_emp = dict((data['department_id'][0], data['no_of_hired_employee']) for data in job_data)
expected_emp = dict((data['department_id'][0], data['no_of_recruitment']) for data in job_data)
for department in self:
department.new_hired_employee = new_emp.get(department.id, 0)
department.expected_employee = expected_emp.get(department.id, 0)
| 48.53125 | 1,553 |
9,633 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
from odoo import api, fields, models, _
class Job(models.Model):
_name = "hr.job"
_inherit = ["mail.alias.mixin", "hr.job"]
_order = "sequence, state desc, name asc"
@api.model
def _default_address_id(self):
return self.env.company.partner_id
def _get_default_favorite_user_ids(self):
return [(6, 0, [self.env.uid])]
address_id = fields.Many2one(
'res.partner', "Job Location", default=_default_address_id,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
help="Address where employees are working")
application_ids = fields.One2many('hr.applicant', 'job_id', "Job Applications")
application_count = fields.Integer(compute='_compute_application_count', string="Application Count")
all_application_count = fields.Integer(compute='_compute_all_application_count', string="All Application Count")
new_application_count = fields.Integer(
compute='_compute_new_application_count', string="New Application",
help="Number of applications that are new in the flow (typically at first step of the flow)")
old_application_count = fields.Integer(
compute='_compute_old_application_count', string="Old Application")
manager_id = fields.Many2one(
'hr.employee', related='department_id.manager_id', string="Department Manager",
readonly=True, store=True)
user_id = fields.Many2one('res.users', "Recruiter", tracking=True)
hr_responsible_id = fields.Many2one(
'res.users', "HR Responsible", tracking=True,
help="Person responsible of validating the employee's contracts.")
document_ids = fields.One2many('ir.attachment', compute='_compute_document_ids', string="Documents")
documents_count = fields.Integer(compute='_compute_document_ids', string="Document Count")
alias_id = fields.Many2one(
'mail.alias', "Alias", ondelete="restrict", required=True,
help="Email alias for this job position. New emails will automatically create new applicants for this job position.")
color = fields.Integer("Color Index")
is_favorite = fields.Boolean(compute='_compute_is_favorite', inverse='_inverse_is_favorite')
favorite_user_ids = fields.Many2many('res.users', 'job_favorite_user_rel', 'job_id', 'user_id', default=_get_default_favorite_user_ids)
no_of_hired_employee = fields.Integer(compute='_compute_no_of_hired_employee', store=True)
@api.depends('application_ids.date_closed')
def _compute_no_of_hired_employee(self):
for job in self:
job.no_of_hired_employee = len(job.application_ids.filtered(lambda applicant: applicant.date_closed))
def _compute_is_favorite(self):
for job in self:
job.is_favorite = self.env.user in job.favorite_user_ids
def _inverse_is_favorite(self):
unfavorited_jobs = favorited_jobs = self.env['hr.job']
for job in self:
if self.env.user in job.favorite_user_ids:
unfavorited_jobs |= job
else:
favorited_jobs |= job
favorited_jobs.write({'favorite_user_ids': [(4, self.env.uid)]})
unfavorited_jobs.write({'favorite_user_ids': [(3, self.env.uid)]})
def _compute_document_ids(self):
applicants = self.mapped('application_ids').filtered(lambda self: not self.emp_id)
app_to_job = dict((applicant.id, applicant.job_id.id) for applicant in applicants)
attachments = self.env['ir.attachment'].search([
'|',
'&', ('res_model', '=', 'hr.job'), ('res_id', 'in', self.ids),
'&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicants.ids)])
result = dict.fromkeys(self.ids, self.env['ir.attachment'])
for attachment in attachments:
if attachment.res_model == 'hr.applicant':
result[app_to_job[attachment.res_id]] |= attachment
else:
result[attachment.res_id] |= attachment
for job in self:
job.document_ids = result.get(job.id, False)
job.documents_count = len(job.document_ids)
def _compute_all_application_count(self):
read_group_result = self.env['hr.applicant'].with_context(active_test=False).read_group([('job_id', 'in', self.ids)], ['job_id'], ['job_id'])
result = dict((data['job_id'][0], data['job_id_count']) for data in read_group_result)
for job in self:
job.all_application_count = result.get(job.id, 0)
def _compute_application_count(self):
read_group_result = self.env['hr.applicant'].read_group([('job_id', 'in', self.ids)], ['job_id'], ['job_id'])
result = dict((data['job_id'][0], data['job_id_count']) for data in read_group_result)
for job in self:
job.application_count = result.get(job.id, 0)
def _get_first_stage(self):
self.ensure_one()
return self.env['hr.recruitment.stage'].search([
'|',
('job_ids', '=', False),
('job_ids', '=', self.id)], order='sequence asc', limit=1)
def _compute_new_application_count(self):
self.env.cr.execute(
"""
WITH job_stage AS (
SELECT DISTINCT ON (j.id) j.id AS job_id, s.id AS stage_id, s.sequence AS sequence
FROM hr_job j
LEFT JOIN hr_job_hr_recruitment_stage_rel rel
ON rel.hr_job_id = j.id
JOIN hr_recruitment_stage s
ON s.id = rel.hr_recruitment_stage_id
OR s.id NOT IN (
SELECT "hr_recruitment_stage_id"
FROM "hr_job_hr_recruitment_stage_rel"
WHERE "hr_recruitment_stage_id" IS NOT NULL
)
WHERE j.id in %s
ORDER BY 1, 3 asc
)
SELECT s.job_id, COUNT(a.id) AS new_applicant
FROM hr_applicant a
JOIN job_stage s
ON s.job_id = a.job_id
AND a.stage_id = s.stage_id
AND a.active IS TRUE
GROUP BY s.job_id
""", [tuple(self.ids), ]
)
new_applicant_count = dict(self.env.cr.fetchall())
for job in self:
job.new_application_count = new_applicant_count.get(job.id, 0)
@api.depends('application_count', 'new_application_count')
def _compute_old_application_count(self):
for job in self:
job.old_application_count = job.application_count - job.new_application_count
def _alias_get_creation_values(self):
values = super(Job, self)._alias_get_creation_values()
values['alias_model_id'] = self.env['ir.model']._get('hr.applicant').id
if self.id:
values['alias_defaults'] = defaults = ast.literal_eval(self.alias_defaults or "{}")
defaults.update({
'job_id': self.id,
'department_id': self.department_id.id,
'company_id': self.department_id.company_id.id if self.department_id else self.company_id.id,
'user_id': self.user_id.id,
})
return values
@api.model
def create(self, vals):
vals['favorite_user_ids'] = vals.get('favorite_user_ids', []) + [(4, self.env.uid)]
new_job = super(Job, self).create(vals)
utm_linkedin = self.env.ref("utm.utm_source_linkedin", raise_if_not_found=False)
if utm_linkedin:
source_vals = {
'source_id': utm_linkedin.id,
'job_id': new_job.id,
}
self.env['hr.recruitment.source'].create(source_vals)
return new_job
def write(self, vals):
res = super().write(vals)
# Since the alias is created upon record creation, the default values do not reflect the current values unless
# specifically rewritten
# List of fields to keep synched with the alias
alias_fields = {'department_id', 'user_id'}
if any(field for field in alias_fields if field in vals):
for job in self:
alias_default_vals = job._alias_get_creation_values().get('alias_defaults', '{}')
job.alias_defaults = alias_default_vals
return res
def _creation_subtype(self):
return self.env.ref('hr_recruitment.mt_job_new')
def action_get_attachment_tree_view(self):
action = self.env["ir.actions.actions"]._for_xml_id("base.action_attachment")
action['context'] = {
'default_res_model': self._name,
'default_res_id': self.ids[0]
}
action['search_view_id'] = (self.env.ref('hr_recruitment.ir_attachment_view_search_inherit_hr_recruitment').id, )
action['domain'] = ['|', '&', ('res_model', '=', 'hr.job'), ('res_id', 'in', self.ids), '&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', self.mapped('application_ids').ids)]
return action
def close_dialog(self):
return {'type': 'ir.actions.act_window_close'}
def edit_dialog(self):
form_view = self.env.ref('hr.view_hr_job_form')
return {
'name': _('Job'),
'res_model': 'hr.job',
'res_id': self.id,
'views': [(form_view.id, 'form'),],
'type': 'ir.actions.act_window',
'target': 'inline'
}
| 46.990244 | 9,633 |
1,860 |
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 CalendarEvent(models.Model):
""" Model for Calendar Event """
_inherit = 'calendar.event'
@api.model
def default_get(self, fields):
if self.env.context.get('default_applicant_id'):
self = self.with_context(
default_res_model='hr.applicant', #res_model seems to be lost without this
default_res_model_id=self.env.ref('hr_recruitment.model_hr_applicant').id,
default_res_id=self.env.context['default_applicant_id']
)
defaults = super(CalendarEvent, self).default_get(fields)
# sync res_model / res_id to opportunity id (aka creating meeting from lead chatter)
if 'applicant_id' not in defaults:
res_model = defaults.get('res_model', False) or self.env.context.get('default_res_model')
res_model_id = defaults.get('res_model_id', False) or self.env.context.get('default_res_model_id')
if (res_model and res_model == 'hr.applicant') or (res_model_id and self.env['ir.model'].sudo().browse(res_model_id).model == 'hr.applicant'):
defaults['applicant_id'] = defaults.get('res_id', False) or self.env.context.get('default_res_id', False)
return defaults
def _compute_is_highlighted(self):
super(CalendarEvent, self)._compute_is_highlighted()
applicant_id = self.env.context.get('active_id')
if self.env.context.get('active_model') == 'hr.applicant' and applicant_id:
for event in self:
if event.applicant_id.id == applicant_id:
event.is_highlighted = True
applicant_id = fields.Many2one('hr.applicant', string="Applicant", index=True, ondelete='set null')
| 47.692308 | 1,860 |
1,426 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.translate import _
from datetime import timedelta
class HrEmployee(models.Model):
_inherit = "hr.employee"
newly_hired_employee = fields.Boolean('Newly hired employee', compute='_compute_newly_hired_employee',
search='_search_newly_hired_employee')
applicant_id = fields.One2many('hr.applicant', 'emp_id', 'Applicant')
def _compute_newly_hired_employee(self):
now = fields.Datetime.now()
for employee in self:
employee.newly_hired_employee = bool(employee.create_date > (now - timedelta(days=90)))
def _search_newly_hired_employee(self, operator, value):
employees = self.env['hr.employee'].search([
('create_date', '>', fields.Datetime.now() - timedelta(days=90))
])
return [('id', 'in', employees.ids)]
@api.model
def create(self, vals):
new_employee = super(HrEmployee, self).create(vals)
if new_employee.applicant_id:
new_employee.applicant_id.message_post_with_view(
'hr_recruitment.applicant_hired_template',
values={'applicant': new_employee.applicant_id},
subtype_id=self.env.ref("hr_recruitment.mt_applicant_hired").id)
return new_employee
| 41.941176 | 1,426 |
374 |
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']
module_website_hr_recruitment = fields.Boolean(string='Online Posting')
module_hr_recruitment_survey = fields.Boolean(string='Interview Forms')
| 34 | 374 |
29,595 |
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, tools, SUPERUSER_ID
from odoo.tools.translate import _
from odoo.exceptions import UserError
AVAILABLE_PRIORITIES = [
('0', 'Normal'),
('1', 'Good'),
('2', 'Very Good'),
('3', 'Excellent')
]
class RecruitmentSource(models.Model):
_name = "hr.recruitment.source"
_description = "Source of Applicants"
_inherits = {"utm.source": "source_id"}
source_id = fields.Many2one('utm.source', "Source", ondelete='cascade', required=True)
email = fields.Char(related='alias_id.display_name', string="Email", readonly=True)
job_id = fields.Many2one('hr.job', "Job", ondelete='cascade')
alias_id = fields.Many2one('mail.alias', "Alias ID")
def create_alias(self):
campaign = self.env.ref('hr_recruitment.utm_campaign_job')
medium = self.env.ref('utm.utm_medium_email')
for source in self:
vals = {
'alias_parent_thread_id': source.job_id.id,
'alias_model_id': self.env['ir.model']._get('hr.applicant').id,
'alias_parent_model_id': self.env['ir.model']._get('hr.job').id,
'alias_name': "%s+%s" % (source.job_id.alias_name or source.job_id.name, source.name),
'alias_defaults': {
'job_id': source.job_id.id,
'campaign_id': campaign.id,
'medium_id': medium.id,
'source_id': source.source_id.id,
},
}
source.alias_id = self.env['mail.alias'].create(vals)
source.name = source.source_id.name
class RecruitmentStage(models.Model):
_name = "hr.recruitment.stage"
_description = "Recruitment Stages"
_order = 'sequence'
name = fields.Char("Stage Name", required=True, translate=True)
sequence = fields.Integer(
"Sequence", default=10,
help="Gives the sequence order when displaying a list of stages.")
job_ids = fields.Many2many(
'hr.job', string='Job Specific',
help='Specific jobs that uses this stage. Other jobs will not use this stage.')
requirements = fields.Text("Requirements")
template_id = fields.Many2one(
'mail.template', "Email Template",
help="If set, a message is posted on the applicant using the template when the applicant is set to the stage.")
fold = fields.Boolean(
"Folded in Kanban",
help="This stage is folded in the kanban view when there are no records in that stage to display.")
hired_stage = fields.Boolean('Hired Stage',
help="If checked, this stage is used to determine the hire date of an applicant")
legend_blocked = fields.Char(
'Red Kanban Label', default=lambda self: _('Blocked'), translate=True, required=True)
legend_done = fields.Char(
'Green Kanban Label', default=lambda self: _('Ready for Next Stage'), translate=True, required=True)
legend_normal = fields.Char(
'Grey Kanban Label', default=lambda self: _('In Progress'), translate=True, required=True)
is_warning_visible = fields.Boolean(compute='_compute_is_warning_visible')
@api.model
def default_get(self, fields):
if self._context and self._context.get('default_job_id') and not self._context.get('hr_recruitment_stage_mono', False):
context = dict(self._context)
context.pop('default_job_id')
self = self.with_context(context)
return super(RecruitmentStage, self).default_get(fields)
@api.depends('hired_stage')
def _compute_is_warning_visible(self):
applicant_data = self.env['hr.applicant'].read_group([('stage_id', 'in', self.ids)], ['stage_id'], 'stage_id')
applicants = dict((data['stage_id'][0], data['stage_id_count']) for data in applicant_data)
for stage in self:
if stage._origin.hired_stage and not stage.hired_stage and applicants.get(stage._origin.id):
stage.is_warning_visible = True
else:
stage.is_warning_visible = False
class RecruitmentDegree(models.Model):
_name = "hr.recruitment.degree"
_description = "Applicant Degree"
_sql_constraints = [
('name_uniq', 'unique (name)', 'The name of the Degree of Recruitment must be unique!')
]
name = fields.Char("Degree Name", required=True, translate=True)
sequence = fields.Integer("Sequence", default=1, help="Gives the sequence order when displaying a list of degrees.")
class Applicant(models.Model):
_name = "hr.applicant"
_description = "Applicant"
_order = "priority desc, id desc"
_inherit = ['mail.thread.cc', 'mail.activity.mixin', 'utm.mixin']
_mailing_enabled = True
name = fields.Char("Subject / Application Name", required=True, help="Email subject for applications sent via email")
active = fields.Boolean("Active", default=True, help="If the active field is set to false, it will allow you to hide the case without removing it.")
description = fields.Html("Description")
email_from = fields.Char("Email", size=128, help="Applicant email", compute='_compute_partner_phone_email',
inverse='_inverse_partner_email', store=True)
probability = fields.Float("Probability")
partner_id = fields.Many2one('res.partner', "Contact", copy=False)
create_date = fields.Datetime("Creation Date", readonly=True, index=True)
stage_id = fields.Many2one('hr.recruitment.stage', 'Stage', ondelete='restrict', tracking=True,
compute='_compute_stage', store=True, readonly=False,
domain="['|', ('job_ids', '=', False), ('job_ids', '=', job_id)]",
copy=False, index=True,
group_expand='_read_group_stage_ids')
last_stage_id = fields.Many2one('hr.recruitment.stage', "Last Stage",
help="Stage of the applicant before being in the current stage. Used for lost cases analysis.")
categ_ids = fields.Many2many('hr.applicant.category', string="Tags")
company_id = fields.Many2one('res.company', "Company", compute='_compute_company', store=True, readonly=False, tracking=True)
user_id = fields.Many2one(
'res.users', "Recruiter", compute='_compute_user',
tracking=True, store=True, readonly=False)
date_closed = fields.Datetime("Hire Date", compute='_compute_date_closed', store=True, index=True, readonly=False, tracking=True)
date_open = fields.Datetime("Assigned", readonly=True, index=True)
date_last_stage_update = fields.Datetime("Last Stage Update", index=True, default=fields.Datetime.now)
priority = fields.Selection(AVAILABLE_PRIORITIES, "Appreciation", default='0')
job_id = fields.Many2one('hr.job', "Applied Job", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", tracking=True, index=True)
salary_proposed_extra = fields.Char("Proposed Salary Extra", help="Salary Proposed by the Organisation, extra advantages", tracking=True)
salary_expected_extra = fields.Char("Expected Salary Extra", help="Salary Expected by Applicant, extra advantages", tracking=True)
salary_proposed = fields.Float("Proposed Salary", group_operator="avg", help="Salary Proposed by the Organisation", tracking=True)
salary_expected = fields.Float("Expected Salary", group_operator="avg", help="Salary Expected by Applicant", tracking=True)
availability = fields.Date("Availability", help="The date at which the applicant will be available to start working", tracking=True)
partner_name = fields.Char("Applicant's Name")
partner_phone = fields.Char("Phone", size=32, compute='_compute_partner_phone_email',
inverse='_inverse_partner_phone', store=True)
partner_mobile = fields.Char("Mobile", size=32, compute='_compute_partner_phone_email',
inverse='_inverse_partner_mobile', store=True)
type_id = fields.Many2one('hr.recruitment.degree', "Degree")
department_id = fields.Many2one(
'hr.department', "Department", compute='_compute_department', store=True, readonly=False,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", tracking=True)
day_open = fields.Float(compute='_compute_day', string="Days to Open", compute_sudo=True)
day_close = fields.Float(compute='_compute_day', string="Days to Close", compute_sudo=True)
delay_close = fields.Float(compute="_compute_day", string='Delay to Close', readonly=True, group_operator="avg", help="Number of days to close", store=True)
color = fields.Integer("Color Index", default=0)
emp_id = fields.Many2one('hr.employee', string="Employee", help="Employee linked to the applicant.", copy=False)
user_email = fields.Char(related='user_id.email', string="User Email", readonly=True)
attachment_number = fields.Integer(compute='_get_attachment_number', string="Number of Attachments")
employee_name = fields.Char(related='emp_id.name', string="Employee Name", readonly=False, tracking=False)
attachment_ids = fields.One2many('ir.attachment', 'res_id', domain=[('res_model', '=', 'hr.applicant')], string='Attachments')
kanban_state = fields.Selection([
('normal', 'Grey'),
('done', 'Green'),
('blocked', 'Red')], string='Kanban State',
copy=False, default='normal', required=True)
legend_blocked = fields.Char(related='stage_id.legend_blocked', string='Kanban Blocked')
legend_done = fields.Char(related='stage_id.legend_done', string='Kanban Valid')
legend_normal = fields.Char(related='stage_id.legend_normal', string='Kanban Ongoing')
application_count = fields.Integer(compute='_compute_application_count', help='Applications with the same email')
refuse_reason_id = fields.Many2one('hr.applicant.refuse.reason', string='Refuse Reason', tracking=True)
meeting_ids = fields.One2many('calendar.event', 'applicant_id', 'Meetings')
meeting_display_text = fields.Char(compute='_compute_meeting_display')
meeting_display_date = fields.Date(compute='_compute_meeting_display')
@api.depends('date_open', 'date_closed')
def _compute_day(self):
for applicant in self:
if applicant.date_open:
date_create = applicant.create_date
date_open = applicant.date_open
applicant.day_open = (date_open - date_create).total_seconds() / (24.0 * 3600)
else:
applicant.day_open = False
if applicant.date_closed:
date_create = applicant.create_date
date_closed = applicant.date_closed
applicant.day_close = (date_closed - date_create).total_seconds() / (24.0 * 3600)
applicant.delay_close = applicant.day_close - applicant.day_open
else:
applicant.day_close = False
applicant.delay_close = False
@api.depends('email_from')
def _compute_application_count(self):
application_data = self.env['hr.applicant'].with_context(active_test=False).read_group([
('email_from', 'in', list(set(self.mapped('email_from'))))], ['email_from'], ['email_from'])
application_data_mapped = dict((data['email_from'], data['email_from_count']) for data in application_data)
applicants = self.filtered(lambda applicant: applicant.email_from)
for applicant in applicants:
applicant.application_count = application_data_mapped.get(applicant.email_from, 1) - 1
(self - applicants).application_count = False
@api.depends_context('lang')
@api.depends('meeting_ids', 'meeting_ids.start')
def _compute_meeting_display(self):
applicant_with_meetings = self.filtered('meeting_ids')
(self - applicant_with_meetings).update({
'meeting_display_text': _('No Meeting'),
'meeting_display_date': ''
})
today = fields.Date.today()
for applicant in applicant_with_meetings:
count = len(applicant.meeting_ids)
dates = applicant.meeting_ids.mapped('start')
min_date, max_date = min(dates).date(), max(dates).date()
if min_date >= today:
applicant.meeting_display_date = min_date
else:
applicant.meeting_display_date = max_date
if count == 1:
applicant.meeting_display_text = _('1 Meeting')
elif applicant.meeting_display_date >= today:
applicant.meeting_display_text = _('Next Meeting')
else:
applicant.meeting_display_text = _('Last Meeting')
def _get_attachment_number(self):
read_group_res = self.env['ir.attachment'].read_group(
[('res_model', '=', 'hr.applicant'), ('res_id', 'in', self.ids)],
['res_id'], ['res_id'])
attach_data = dict((res['res_id'], res['res_id_count']) for res in read_group_res)
for record in self:
record.attachment_number = attach_data.get(record.id, 0)
@api.model
def _read_group_stage_ids(self, stages, domain, order):
# retrieve job_id from the context and write the domain: ids + contextual columns (job or default)
job_id = self._context.get('default_job_id')
search_domain = [('job_ids', '=', False)]
if job_id:
search_domain = ['|', ('job_ids', '=', job_id)] + search_domain
if stages:
search_domain = ['|', ('id', 'in', stages.ids)] + search_domain
stage_ids = stages._search(search_domain, order=order, access_rights_uid=SUPERUSER_ID)
return stages.browse(stage_ids)
@api.depends('job_id', 'department_id')
def _compute_company(self):
for applicant in self:
company_id = False
if applicant.department_id:
company_id = applicant.department_id.company_id.id
if not company_id and applicant.job_id:
company_id = applicant.job_id.company_id.id
applicant.company_id = company_id or self.env.company.id
@api.depends('job_id')
def _compute_department(self):
for applicant in self:
applicant.department_id = applicant.job_id.department_id.id
@api.depends('job_id')
def _compute_stage(self):
for applicant in self:
if applicant.job_id:
if not applicant.stage_id:
stage_ids = self.env['hr.recruitment.stage'].search([
'|',
('job_ids', '=', False),
('job_ids', '=', applicant.job_id.id),
('fold', '=', False)
], order='sequence asc', limit=1).ids
applicant.stage_id = stage_ids[0] if stage_ids else False
else:
applicant.stage_id = False
@api.depends('job_id')
def _compute_user(self):
for applicant in self:
applicant.user_id = applicant.job_id.user_id.id or self.env.uid
@api.depends('partner_id')
def _compute_partner_phone_email(self):
for applicant in self:
applicant.partner_phone = applicant.partner_id.phone
applicant.partner_mobile = applicant.partner_id.mobile
applicant.email_from = applicant.partner_id.email
def _inverse_partner_email(self):
for applicant in self.filtered(lambda a: a.partner_id and a.email_from and not a.partner_id.email):
applicant.partner_id.email = applicant.email_from
def _inverse_partner_phone(self):
for applicant in self.filtered(lambda a: a.partner_id and a.partner_phone and not a.partner_id.phone):
applicant.partner_id.phone = applicant.partner_phone
def _inverse_partner_mobile(self):
for applicant in self.filtered(lambda a: a.partner_id and a.partner_mobile and not a.partner_id.mobile):
applicant.partner_id.mobile = applicant.partner_mobile
@api.depends('stage_id.hired_stage')
def _compute_date_closed(self):
for applicant in self:
if applicant.stage_id and applicant.stage_id.hired_stage and not applicant.date_closed:
applicant.date_closed = fields.datetime.now()
if not applicant.stage_id.hired_stage:
applicant.date_closed = False
@api.model
def create(self, vals):
if vals.get('department_id') and not self._context.get('default_department_id'):
self = self.with_context(default_department_id=vals.get('department_id'))
if vals.get('user_id'):
vals['date_open'] = fields.Datetime.now()
if vals.get('email_from'):
vals['email_from'] = vals['email_from'].strip()
return super(Applicant, self).create(vals)
def write(self, vals):
# user_id change: update date_open
if vals.get('user_id'):
vals['date_open'] = fields.Datetime.now()
if vals.get('email_from'):
vals['email_from'] = vals['email_from'].strip()
# stage_id: track last stage before update
if 'stage_id' in vals:
vals['date_last_stage_update'] = fields.Datetime.now()
if 'kanban_state' not in vals:
vals['kanban_state'] = 'normal'
for applicant in self:
vals['last_stage_id'] = applicant.stage_id.id
res = super(Applicant, self).write(vals)
else:
res = super(Applicant, self).write(vals)
return res
def get_empty_list_help(self, help):
if 'active_id' in self.env.context and self.env.context.get('active_model') == 'hr.job':
alias_id = self.env['hr.job'].browse(self.env.context['active_id']).alias_id
else:
alias_id = False
nocontent_values = {
'help_title': _('No application yet'),
'para_1': _('Let people apply by email to save time.') ,
'para_2': _('Attachments, like resumes, get indexed automatically.'),
}
nocontent_body = """
<p class="o_view_nocontent_empty_folder">%(help_title)s</p>
<p>%(para_1)s<br/>%(para_2)s</p>"""
if alias_id and alias_id.alias_domain and alias_id.alias_name:
email = alias_id.display_name
email_link = "<a href='mailto:%s'>%s</a>" % (email, email)
nocontent_values['email_link'] = email_link
nocontent_body += """<p class="o_copy_paste_email">%(email_link)s</p>"""
return nocontent_body % nocontent_values
def action_makeMeeting(self):
""" This opens Meeting's calendar view to schedule meeting on current applicant
@return: Dictionary value for created Meeting view
"""
self.ensure_one()
partners = self.partner_id | self.user_id.partner_id | self.department_id.manager_id.user_id.partner_id
category = self.env.ref('hr_recruitment.categ_meet_interview')
res = self.env['ir.actions.act_window']._for_xml_id('calendar.action_calendar_event')
res['context'] = {
'default_applicant_id': self.id,
'default_partner_ids': partners.ids,
'default_user_id': self.env.uid,
'default_name': self.name,
'default_categ_ids': category and [category.id] or False,
}
return res
def action_get_attachment_tree_view(self):
action = self.env['ir.actions.act_window']._for_xml_id('base.action_attachment')
action['context'] = {'default_res_model': self._name, 'default_res_id': self.ids[0]}
action['domain'] = str(['&', ('res_model', '=', self._name), ('res_id', 'in', self.ids)])
action['search_view_id'] = (self.env.ref('hr_recruitment.ir_attachment_view_search_inherit_hr_recruitment').id, )
return action
def action_applications_email(self):
return {
'type': 'ir.actions.act_window',
'name': _('Job Applications'),
'res_model': self._name,
'view_mode': 'kanban,tree,form,pivot,graph,calendar,activity',
'domain': [('email_from', 'in', self.mapped('email_from'))],
'context': {
'active_test': False
},
}
def _track_template(self, changes):
res = super(Applicant, self)._track_template(changes)
applicant = self[0]
if 'stage_id' in changes and applicant.stage_id.template_id:
res['stage_id'] = (applicant.stage_id.template_id, {
'auto_delete_message': True,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
'email_layout_xmlid': 'mail.mail_notification_light'
})
return res
def _creation_subtype(self):
return self.env.ref('hr_recruitment.mt_applicant_new')
def _track_subtype(self, init_values):
record = self[0]
if 'stage_id' in init_values and record.stage_id:
return self.env.ref('hr_recruitment.mt_applicant_stage_changed')
return super(Applicant, self)._track_subtype(init_values)
def _notify_get_reply_to(self, default=None, records=None, company=None, doc_names=None):
""" Override to set alias of applicants to their job definition if any. """
aliases = self.mapped('job_id')._notify_get_reply_to(default=default, records=None, company=company, doc_names=None)
res = {app.id: aliases.get(app.job_id.id) for app in self}
leftover = self.filtered(lambda rec: not rec.job_id)
if leftover:
res.update(super(Applicant, leftover)._notify_get_reply_to(default=default, records=None, company=company, doc_names=doc_names))
return res
def _message_get_suggested_recipients(self):
recipients = super(Applicant, self)._message_get_suggested_recipients()
for applicant in self:
if applicant.partner_id:
applicant._message_add_suggested_recipient(recipients, partner=applicant.partner_id.sudo(), reason=_('Contact'))
elif applicant.email_from:
email_from = applicant.email_from
if applicant.partner_name:
email_from = tools.formataddr((applicant.partner_name, email_from))
applicant._message_add_suggested_recipient(recipients, email=email_from, reason=_('Contact Email'))
return recipients
@api.model
def message_new(self, msg, custom_values=None):
""" Overrides mail_thread message_new that is called by the mailgateway
through message_process.
This override updates the document according to the email.
"""
# remove default author when going through the mail gateway. Indeed we
# do not want to explicitly set user_id to False; however we do not
# want the gateway user to be responsible if no other responsible is
# found.
self = self.with_context(default_user_id=False)
stage = False
if custom_values and 'job_id' in custom_values:
stage = self.env['hr.job'].browse(custom_values['job_id'])._get_first_stage()
val = msg.get('from').split('<')[0]
defaults = {
'name': msg.get('subject') or _("No Subject"),
'partner_name': val,
'email_from': msg.get('from'),
'partner_id': msg.get('author_id', False),
}
if msg.get('priority'):
defaults['priority'] = msg.get('priority')
if stage and stage.id:
defaults['stage_id'] = stage.id
if custom_values:
defaults.update(custom_values)
return super(Applicant, self).message_new(msg, custom_values=defaults)
def _message_post_after_hook(self, message, msg_vals):
if self.email_from 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_from)
if new_partner:
if new_partner.create_date.date() == fields.Date.today():
new_partner.write({
'type': 'private',
'phone': self.partner_phone,
'mobile': self.partner_mobile,
})
self.search([
('partner_id', '=', False),
('email_from', '=', new_partner.email),
('stage_id.fold', '=', False)]).write({'partner_id': new_partner.id})
return super(Applicant, self)._message_post_after_hook(message, msg_vals)
def create_employee_from_applicant(self):
""" Create an hr.employee from the hr.applicants """
employee = False
for applicant in self:
contact_name = False
if applicant.partner_id:
address_id = applicant.partner_id.address_get(['contact'])['contact']
contact_name = applicant.partner_id.display_name
else:
if not applicant.partner_name:
raise UserError(_('You must define a Contact Name for this applicant.'))
new_partner_id = self.env['res.partner'].create({
'is_company': False,
'type': 'private',
'name': applicant.partner_name,
'email': applicant.email_from,
'phone': applicant.partner_phone,
'mobile': applicant.partner_mobile
})
applicant.partner_id = new_partner_id
address_id = new_partner_id.address_get(['contact'])['contact']
if applicant.partner_name or contact_name:
employee_data = {
'default_name': applicant.partner_name or contact_name,
'default_job_id': applicant.job_id.id,
'default_job_title': applicant.job_id.name,
'default_address_home_id': address_id,
'default_department_id': applicant.department_id.id or False,
'default_address_id': applicant.company_id and applicant.company_id.partner_id
and applicant.company_id.partner_id.id or False,
'default_work_email': applicant.department_id and applicant.department_id.company_id
and applicant.department_id.company_id.email or False,
'default_work_phone': applicant.department_id.company_id.phone,
'form_view_initial_mode': 'edit',
'default_applicant_id': applicant.ids,
}
dict_act_window = self.env['ir.actions.act_window']._for_xml_id('hr.open_view_employee_list')
dict_act_window['context'] = employee_data
return dict_act_window
def archive_applicant(self):
return {
'type': 'ir.actions.act_window',
'name': _('Refuse Reason'),
'res_model': 'applicant.get.refuse.reason',
'view_mode': 'form',
'target': 'new',
'context': {'default_applicant_ids': self.ids, 'active_test': False},
'views': [[False, 'form']]
}
def reset_applicant(self):
""" Reinsert the applicant into the recruitment pipe in the first stage"""
default_stage = dict()
for job_id in self.mapped('job_id'):
default_stage[job_id.id] = self.env['hr.recruitment.stage'].search(
['|',
('job_ids', '=', False),
('job_ids', '=', job_id.id),
('fold', '=', False)
], order='sequence asc', limit=1).id
for applicant in self:
applicant.write(
{'stage_id': applicant.job_id.id and default_stage[applicant.job_id.id],
'refuse_reason_id': False})
def toggle_active(self):
res = super(Applicant, self).toggle_active()
applicant_active = self.filtered(lambda applicant: applicant.active)
if applicant_active:
applicant_active.reset_applicant()
applicant_inactive = self.filtered(lambda applicant: not applicant.active)
if applicant_inactive:
return applicant_inactive.archive_applicant()
return res
class ApplicantCategory(models.Model):
_name = "hr.applicant.category"
_description = "Category of applicant"
def _get_default_color(self):
return randint(1, 11)
name = fields.Char("Tag Name", required=True)
color = fields.Integer(string='Color Index', default=_get_default_color)
_sql_constraints = [
('name_uniq', 'unique (name)', "Tag name already exists !"),
]
class ApplicantRefuseReason(models.Model):
_name = "hr.applicant.refuse.reason"
_description = 'Refuse Reason of Applicant'
name = fields.Char('Description', required=True, translate=True)
template_id = fields.Many2one('mail.template', string='Email Template', domain="[('model', '=', 'hr.applicant')]")
active = fields.Boolean('Active', default=True)
| 50.503413 | 29,595 |
529 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "Social Media",
'summary': "Social media connectors for company settings.",
'description': """
The purpose of this technical module is to provide a front for
social media configuration for any other module that might need it.
""",
'author': "Odoo S.A.",
'category': 'Hidden',
'version': '0.1',
'depends': ['base'],
'data': [
'views/res_company_views.xml',
],
'demo': [
'demo/res_company_demo.xml',
],
'license': 'LGPL-3',
}
| 23 | 529 |
516 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class Company(models.Model):
_inherit = "res.company"
social_twitter = fields.Char('Twitter Account')
social_facebook = fields.Char('Facebook Account')
social_github = fields.Char('GitHub Account')
social_linkedin = fields.Char('LinkedIn Account')
social_youtube = fields.Char('Youtube Account')
social_instagram = fields.Char('Instagram Account')
| 34.4 | 516 |
1,839 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Payment Acquirer',
'version': '2.0',
'category': 'Hidden',
'summary': 'Base Module for Payment Acquirers',
'description': """Payment Acquirer Base Module""",
'depends': ['account'],
'data': [
'data/payment_icon_data.xml',
'data/payment_acquirer_data.xml',
'data/payment_cron.xml',
'views/payment_portal_templates.xml',
'views/payment_templates.xml',
'views/account_invoice_views.xml',
'views/account_journal_views.xml',
'views/account_payment_views.xml',
'views/payment_acquirer_views.xml',
'views/payment_icon_views.xml',
'views/payment_transaction_views.xml',
'views/payment_token_views.xml', # Depends on `action_payment_transaction_linked_to_token`
'views/res_partner_views.xml',
'security/ir.model.access.csv',
'security/payment_security.xml',
'wizards/account_payment_register_views.xml',
'wizards/payment_acquirer_onboarding_templates.xml',
'wizards/payment_link_wizard_views.xml',
'wizards/payment_refund_wizard_views.xml',
],
'auto_install': True,
'assets': {
'web.assets_frontend': [
'payment/static/src/scss/portal_payment.scss',
'payment/static/src/scss/payment_form.scss',
'payment/static/lib/jquery.payment/jquery.payment.js',
'payment/static/src/js/checkout_form.js',
'payment/static/src/js/manage_form.js',
'payment/static/src/js/payment_form_mixin.js',
'payment/static/src/js/post_processing.js',
],
'web.assets_backend': [
'payment/static/src/scss/payment_acquirer.scss',
],
},
'license': 'LGPL-3',
}
| 36.058824 | 1,839 |
8,848 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from hashlib import sha1
from odoo import fields
from odoo.http import request
from odoo.tools import consteq, float_round, ustr
from odoo.tools.misc import hmac as hmac_tool
from odoo.addons.payment.const import CURRENCY_MINOR_UNITS
# Access token management
def generate_access_token(*values):
""" Generate an access token based on the provided values.
The token allows to later verify the validity of a request, based on a given set of values.
These will generally include the partner id, amount, currency id, transaction id or transaction
reference.
All values must be convertible to a string.
:param list values: The values to use for the generation of the token
:return: The generated access token
:rtype: str
"""
token_str = '|'.join(str(val) for val in values)
access_token = hmac_tool(request.env(su=True), 'generate_access_token', token_str)
return access_token
def check_access_token(access_token, *values):
""" Check the validity of the access token for the provided values.
The values must be provided in the exact same order as they were to `generate_access_token`.
All values must be convertible to a string.
:param str access_token: The access token used to verify the provided values
:param list values: The values to verify against the token
:return: True if the check is successful
:rtype: bool
"""
authentic_token = generate_access_token(*values)
return access_token and consteq(ustr(access_token), authentic_token)
# Transaction values formatting
def singularize_reference_prefix(prefix='tx', separator='-', max_length=None):
""" Make the prefix more unique by suffixing it with the current datetime.
When the prefix is a placeholder that would be part of a large sequence of references sharing
the same prefix, such as "tx" or "validation", singularizing it allows to make it part of a
single-element sequence of transactions. The computation of the full reference will then execute
faster by failing to find existing references with a matching prefix.
If the `max_length` argument is passed, the end of the prefix can be stripped before
singularizing to ensure that the result accounts for no more than `max_length` characters.
Warning: Generated prefixes are *not* uniques! This function should be used only for making
transaction reference prefixes more distinguishable and *not* for operations that require the
generated value to be unique.
:param str prefix: The custom prefix to singularize
:param str separator: The custom separator used to separate the prefix from the suffix
:param int max_length: The maximum length of the singularized prefix
:return: The singularized prefix
:rtype: str
"""
if prefix is None:
prefix = 'tx'
if max_length:
DATETIME_LENGTH = 14
assert max_length >= 1 + len(separator) + DATETIME_LENGTH # 1 char + separator + datetime
prefix = prefix[:max_length-len(separator)-DATETIME_LENGTH]
return f'{prefix}{separator}{fields.Datetime.now().strftime("%Y%m%d%H%M%S")}'
def to_major_currency_units(minor_amount, currency, arbitrary_decimal_number=None):
""" Return the amount converted to the major units of its currency.
The conversion is done by dividing the amount by 10^k where k is the number of decimals of the
currency as per the ISO 4217 norm.
To force a different number of decimals, set it as the value of the `arbitrary_decimal_number`
argument.
:param float minor_amount: The amount in minor units, to convert in major units
:param recordset currency: The currency of the amount, as a `res.currency` record
:param int arbitrary_decimal_number: The number of decimals to use instead of that of ISO 4217
:return: The amount in major units of its currency
:rtype: int
"""
currency.ensure_one()
if arbitrary_decimal_number is None:
decimal_number = CURRENCY_MINOR_UNITS.get(currency.name, currency.decimal_places)
else:
decimal_number = arbitrary_decimal_number
return float_round(minor_amount, precision_digits=0) / (10**decimal_number)
def to_minor_currency_units(major_amount, currency, arbitrary_decimal_number=None):
""" Return the amount converted to the minor units of its currency.
The conversion is done by multiplying the amount by 10^k where k is the number of decimals of
the currency as per the ISO 4217 norm.
To force a different number of decimals, set it as the value of the `arbitrary_decimal_number`
argument.
Note: currency.ensure_one() if arbitrary_decimal_number is not provided
:param float major_amount: The amount in major units, to convert in minor units
:param recordset currency: The currency of the amount, as a `res.currency` record
:param int arbitrary_decimal_number: The number of decimals to use instead of that of ISO 4217
:return: The amount in minor units of its currency
:rtype: int
"""
if arbitrary_decimal_number is not None:
decimal_number = arbitrary_decimal_number
else:
currency.ensure_one()
decimal_number = CURRENCY_MINOR_UNITS.get(currency.name, currency.decimal_places)
return int(float_round(major_amount * (10**decimal_number), precision_digits=0))
# Token values formatting
def build_token_name(payment_details_short=None, final_length=16):
""" Pad plain payment details with leading X's to build a token name of the desired length.
:param str payment_details_short: The plain part of the payment details (usually last 4 digits)
:param int final_length: The desired final length of the token name (16 for a bank card)
:return: The padded token name
:rtype: str
"""
payment_details_short = payment_details_short or '????'
return f"{'X' * (final_length - len(payment_details_short))}{payment_details_short}"
# Partner values formatting
def format_partner_address(address1="", address2=""):
""" Format a two-parts partner address into a one-line address string.
:param str address1: The first part of the address, usually the `street1` field
:param str address2: The second part of the address, usually the `street2` field
:return: The formatted one-line address
:rtype: str
"""
address1 = address1 or "" # Avoid casting as "False"
address2 = address2 or "" # Avoid casting as "False"
return f"{address1} {address2}".strip()
def split_partner_name(partner_name):
""" Split a single-line partner name in a tuple of first name, last name.
:param str partner_name: The partner name
:return: The splitted first name and last name
:rtype: tuple
"""
return " ".join(partner_name.split()[:-1]), partner_name.split()[-1]
# Security
def get_customer_ip_address():
return request and request.httprequest.remote_addr or ''
def check_rights_on_recordset(recordset):
""" Ensure that the user has the rights to write on the record.
Call this method to check the access rules and rights before doing any operation that is
callable by RPC and that requires to be executed in sudo mode.
:param recordset: The recordset for which the rights should be checked.
:return: None
"""
recordset.check_access_rights('write')
recordset.check_access_rule('write')
# Idempotency
def generate_idempotency_key(tx, scope=None):
""" Generate an idempotency key for the provided transaction and scope.
Idempotency keys are used to prevent API requests from going through twice in a short time: the
API rejects requests made after another one with the same payload and idempotency key if it
succeeded.
The idempotency key is generated based on the transaction reference, database UUID, and scope if
any. This guarantees the key is identical for two API requests with the same transaction
reference, database, and endpoint. Should one of these parameters differ, the key is unique from
one request to another (e.g., after dropping the database, for different endpoints, etc.).
:param recordset tx: The transaction to generate an idempotency key for, as a
`payment.transaction` record.
:param str scope: The scope of the API request to generate an idempotency key for. This should
typically be the API endpoint. It is not necessary to provide the scope if the
API takes care of comparing idempotency keys per endpoint.
:return: The generated idempotency key.
:rtype: str
"""
database_uuid = tx.env['ir.config_parameter'].sudo().get_param('database.uuid')
return sha1(f'{database_uuid}{tx.reference}{scope or ""}'.encode()).hexdigest()
| 42.743961 | 8,848 |
4,041 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# According to https://en.wikipedia.org/wiki/ISO_4217#Minor_unit_fractions
CURRENCY_MINOR_UNITS = {
'ADF': 2,
'ADP': 0,
'AED': 2,
'AFA': 2,
'AFN': 2,
'ALL': 2,
'AMD': 2,
'ANG': 2,
'AOA': 2,
'AOK': 0,
'AON': 0,
'AOR': 0,
'ARA': 2,
'ARL': 2,
'ARP': 2,
'ARS': 2,
'ATS': 2,
'AUD': 2,
'AWG': 2,
'AYM': 0,
'AZM': 2,
'AZN': 2,
'BAD': 2,
'BAM': 2,
'BBD': 2,
'BDS': 2,
'BDT': 2,
'BEF': 2,
'BGL': 2,
'BGN': 2,
'BHD': 3,
'BIF': 0,
'BMD': 2,
'BND': 2,
'BOB': 2,
'BOP': 2,
'BOV': 2,
'BRB': 2,
'BRC': 2,
'BRE': 2,
'BRL': 2,
'BRN': 2,
'BRR': 2,
'BSD': 2,
'BTN': 2,
'BWP': 2,
'BYB': 2,
'BYN': 2,
'BYR': 0,
'BZD': 2,
'CAD': 2,
'CDF': 2,
'CHC': 2,
'CHE': 2,
'CHF': 2,
'CHW': 2,
'CLF': 4,
'CLP': 0,
'CNH': 2,
'CNT': 2,
'CNY': 2,
'COP': 2,
'COU': 2,
'CRC': 2,
'CSD': 2,
'CUC': 2,
'CUP': 2,
'CVE': 2,
'CYP': 2,
'CZK': 2,
'DEM': 2,
'DJF': 0,
'DKK': 2,
'DOP': 2,
'DZD': 2,
'ECS': 0,
'ECV': 2,
'EEK': 2,
'EGP': 2,
'ERN': 2,
'ESP': 0,
'ETB': 2,
'EUR': 2,
'FIM': 2,
'FJD': 2,
'FKP': 2,
'FRF': 2,
'GBP': 2,
'GEK': 0,
'GEL': 2,
'GGP': 2,
'GHC': 2,
'GHP': 2,
'GHS': 2,
'GIP': 2,
'GMD': 2,
'GNF': 0,
'GTQ': 2,
'GWP': 2,
'GYD': 2,
'HKD': 2,
'HNL': 2,
'HRD': 2,
'HRK': 2,
'HTG': 2,
'HUF': 2,
'IDR': 2,
'IEP': 2,
'ILR': 2,
'ILS': 2,
'IMP': 2,
'INR': 2,
'IQD': 3,
'IRR': 2,
'ISJ': 2,
'ISK': 0,
'ITL': 0,
'JEP': 2,
'JMD': 2,
'JOD': 3,
'JPY': 0,
'KES': 2,
'KGS': 2,
'KHR': 2,
'KID': 2,
'KMF': 0,
'KPW': 2,
'KRW': 0,
'KWD': 3,
'KYD': 2,
'KZT': 2,
'LAK': 2,
'LBP': 2,
'LKR': 2,
'LRD': 2,
'LSL': 2,
'LTL': 2,
'LTT': 2,
'LUF': 2,
'LVL': 2,
'LVR': 2,
'LYD': 3,
'MAD': 2,
'MAF': 2,
'MCF': 2,
'MDL': 2,
'MGA': 2,
'MGF': 0,
'MKD': 2,
'MMK': 2,
'MNT': 2,
'MOP': 2,
'MRO': 2,
'MRU': 2,
'MTL': 2,
'MUR': 2,
'MVR': 2,
'MWK': 2,
'MXN': 2,
'MXV': 2,
'MYR': 2,
'MZE': 2,
'MZM': 2,
'MZN': 2,
'NAD': 2,
'NGN': 2,
'NIC': 2,
'NIO': 2,
'NIS': 2,
'NLG': 2,
'NOK': 2,
'NPR': 2,
'NTD': 2,
'NZD': 2,
'OMR': 3,
'PAB': 2,
'PEN': 2,
'PES': 2,
'PGK': 2,
'PHP': 2,
'PKR': 2,
'PLN': 2,
'PLZ': 2,
'PRB': 2,
'PTE': 0,
'PYG': 0,
'QAR': 2,
'RHD': 2,
'RMB': 2,
'ROL': 0,
'RON': 2,
'RSD': 2,
'RUB': 2,
'RUR': 2,
'RWF': 0,
'SAR': 2,
'SBD': 2,
'SCR': 2,
'SDD': 2,
'SDG': 2,
'SEK': 2,
'SGD': 2,
'SHP': 2,
'SIT': 2,
'SKK': 2,
'SLE': 2,
'SLL': 2,
'SLS': 2,
'SML': 0,
'SOS': 2,
'SRD': 2,
'SRG': 2,
'SSP': 2,
'STD': 2,
'STG': 2,
'STN': 2,
'SVC': 2,
'SYP': 2,
'SZL': 2,
'THB': 2,
'TJR': 0,
'TJS': 2,
'TMM': 2,
'TMT': 2,
'TND': 3,
'TOP': 2,
'TPE': 0,
'TRL': 0,
'TRY': 2,
'TTD': 2,
'TVD': 2,
'TWD': 2,
'TZS': 2,
'UAH': 2,
'UAK': 2,
'UGX': 0,
'USD': 2,
'USN': 2,
'USS': 2,
'UYI': 0,
'UYN': 2,
'UYU': 2,
'UYW': 4,
'UZS': 2,
'VAL': 0,
'VEB': 2,
'VED': 2,
'VEF': 2,
'VES': 2,
'VND': 0,
'VUV': 0,
'WST': 2,
'XAF': 0,
'XCD': 2,
'XEU': 0,
'XOF': 0,
'XPF': 0,
'YER': 2,
'YUD': 2,
'YUG': 2,
'YUM': 2,
'YUN': 2,
'YUO': 2,
'YUR': 2,
'ZAL': 2,
'ZAR': 2,
'ZMK': 2,
'ZMW': 2,
'ZRN': 2,
'ZRZ': 2,
'ZWB': 2,
'ZWC': 2,
'ZWD': 2,
'ZWL': 2,
'ZWN': 2,
'ZWR': 2
}
| 14.380783 | 4,041 |
16,217 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from freezegun import freeze_time
from odoo.tests import tagged
from odoo.tools import mute_logger
from odoo.addons.payment.tests.common import PaymentCommon
from odoo.addons.payment.tests.http_common import PaymentHttpCommon
@tagged('post_install', '-at_install')
class TestFlows(PaymentCommon, PaymentHttpCommon):
def _test_flow(self, flow):
""" Simulate the given online payment flow and tests the tx values at each step.
:param str flow: The online payment flow to test ('direct', 'redirect', or 'token')
:return: The transaction created by the payment flow
:rtype: recordset of `payment.transaction`
"""
self.reference = f"Test Transaction ({flow} - {self.partner.name})"
route_values = self._prepare_pay_values()
# /payment/pay
tx_context = self.get_tx_checkout_context(**route_values)
for key, val in tx_context.items():
if key in route_values:
self.assertEqual(val, route_values[key])
self.assertIn(self.acquirer.id, tx_context['acquirer_ids'])
# Route values are taken from tx_context result of /pay route to correctly simulate the flow
route_values = {
k: tx_context[k]
for k in [
'amount',
'currency_id',
'reference_prefix',
'partner_id',
'access_token',
'landing_route',
]
}
route_values.update({
'flow': flow,
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
})
if flow == 'token':
route_values['payment_option_id'] = self.create_token().id
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**route_values)
tx_sudo = self._get_tx(processing_values['reference'])
# Tx values == given values
self.assertEqual(tx_sudo.acquirer_id.id, self.acquirer.id)
self.assertEqual(tx_sudo.amount, self.amount)
self.assertEqual(tx_sudo.currency_id.id, self.currency.id)
self.assertEqual(tx_sudo.partner_id.id, self.partner.id)
self.assertEqual(tx_sudo.reference, self.reference)
# processing_values == given values
self.assertEqual(processing_values['acquirer_id'], self.acquirer.id)
self.assertEqual(processing_values['amount'], self.amount)
self.assertEqual(processing_values['currency_id'], self.currency.id)
self.assertEqual(processing_values['partner_id'], self.partner.id)
self.assertEqual(processing_values['reference'], self.reference)
# Verify computed values not provided, but added during the flow
self.assertIn("tx_id=", tx_sudo.landing_route)
self.assertIn("access_token=", tx_sudo.landing_route)
if flow == 'redirect':
# In redirect flow, we verify the rendering of the dummy test form
redirect_form_info = self._extract_values_from_html_form(
processing_values['redirect_form_html'])
# Test content of rendered dummy redirect form
self.assertEqual(redirect_form_info['action'], 'dummy')
# Public user since we didn't authenticate with a specific user
self.assertEqual(
redirect_form_info['inputs']['user_id'],
str(self.user.id))
self.assertEqual(
redirect_form_info['inputs']['view_id'],
str(self.dummy_acquirer.redirect_form_view_id.id))
return tx_sudo
def test_10_direct_checkout_public(self):
# No authentication needed, automatic fallback on public user
self.user = self.public_user
# Make sure the company considered in payment/pay
# doesn't fall back on the public user main company (not the test one)
self.partner.company_id = self.env.company.id
self._test_flow('direct')
def test_11_direct_checkout_portal(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.user = self.portal_user
self.partner = self.portal_partner
self._test_flow('direct')
def test_12_direct_checkout_internal(self):
self.authenticate(self.internal_user.login, self.internal_user.login)
self.user = self.internal_user
self.partner = self.internal_partner
self._test_flow('direct')
def test_20_redirect_checkout_public(self):
self.user = self.public_user
# Make sure the company considered in payment/pay
# doesn't fall back on the public user main company (not the test one)
self.partner.company_id = self.env.company.id
self._test_flow('redirect')
def test_21_redirect_checkout_portal(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.user = self.portal_user
self.partner = self.portal_partner
self._test_flow('redirect')
def test_22_redirect_checkout_internal(self):
self.authenticate(self.internal_user.login, self.internal_user.login)
self.user = self.internal_user
self.partner = self.internal_partner
self._test_flow('redirect')
# Payment by token #
####################
# NOTE: not tested as public user because a public user cannot save payment details
def test_31_tokenize_portal(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.partner = self.portal_partner
self.user = self.portal_user
self._test_flow('token')
def test_32_tokenize_internal(self):
self.authenticate(self.internal_user.login, self.internal_user.login)
self.partner = self.internal_partner
self.user = self.internal_user
self._test_flow('token')
# VALIDATION #
##############
# NOTE: not tested as public user because the validation flow is only available when logged in
# freeze time for consistent singularize_prefix behavior during the test
@freeze_time("2011-11-02 12:00:21")
def _test_validation(self, flow):
# Fixed with freezegun
expected_reference = 'validation-20111102120021'
validation_amount = self.acquirer._get_validation_amount()
validation_currency = self.acquirer._get_validation_currency()
tx_context = self.get_tx_manage_context()
expected_values = {
'partner_id': self.partner.id,
'access_token': self._generate_test_access_token(self.partner.id, None, None),
'reference_prefix': expected_reference
}
for key, val in tx_context.items():
if key in expected_values:
self.assertEqual(val, expected_values[key])
transaction_values = {
'amount': None,
'currency_id': None,
'partner_id': tx_context['partner_id'],
'access_token': tx_context['access_token'],
'flow': flow,
'payment_option_id': self.acquirer.id,
'tokenization_requested': True,
'reference_prefix': tx_context['reference_prefix'],
'landing_route': tx_context['landing_route'],
'is_validation': True,
}
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**transaction_values)
tx_sudo = self._get_tx(processing_values['reference'])
# Tx values == given values
self.assertEqual(tx_sudo.acquirer_id.id, self.acquirer.id)
self.assertEqual(tx_sudo.amount, validation_amount)
self.assertEqual(tx_sudo.currency_id.id, validation_currency.id)
self.assertEqual(tx_sudo.partner_id.id, self.partner.id)
self.assertEqual(tx_sudo.reference, expected_reference)
# processing_values == given values
self.assertEqual(processing_values['acquirer_id'], self.acquirer.id)
self.assertEqual(processing_values['amount'], validation_amount)
self.assertEqual(processing_values['currency_id'], validation_currency.id)
self.assertEqual(processing_values['partner_id'], self.partner.id)
self.assertEqual(processing_values['reference'], expected_reference)
def test_51_validation_direct_portal(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.partner = self.portal_partner
self._test_validation(flow='direct')
def test_52_validation_direct_internal(self):
self.authenticate(self.internal_user.login, self.internal_user.login)
self.partner = self.internal_partner
self._test_validation(flow='direct')
def test_61_validation_redirect_portal(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.partner = self.portal_partner
self._test_validation(flow='direct')
def test_62_validation_redirect_internal(self):
self.authenticate(self.internal_user.login, self.internal_user.login)
self.partner = self.internal_partner
self._test_validation(flow='direct')
# Specific flows #
##################
def test_pay_redirect_if_no_partner_exist(self):
route_values = self._prepare_pay_values()
route_values.pop('partner_id')
# Pay without a partner specified --> redirection to login page
response = self.portal_pay(**route_values)
self.assertTrue(response.url.startswith(self._build_url('/web/login?redirect=')))
# Pay without a partner specified (but logged) --> pay with the partner of current user.
self.authenticate(self.portal_user.login, self.portal_user.login)
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['partner_id'], self.portal_partner.id)
def test_pay_no_token(self):
route_values = self._prepare_pay_values()
route_values.pop('partner_id')
route_values.pop('access_token')
# Pay without a partner specified --> redirection to login page
response = self.portal_pay(**route_values)
self.assertTrue(response.url.startswith(self._build_url('/web/login?redirect=')))
# Pay without a partner specified (but logged) --> pay with the partner of current user.
self.authenticate(self.portal_user.login, self.portal_user.login)
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['partner_id'], self.portal_partner.id)
def test_pay_wrong_token(self):
route_values = self._prepare_pay_values()
route_values['access_token'] = "abcde"
# Pay with a wrong access token --> Not found (404)
response = self.portal_pay(**route_values)
self.assertEqual(response.status_code, 404)
def test_pay_wrong_currency(self):
# Pay with a wrong currency --> Not found (404)
self.currency = self.env['res.currency'].browse(self.env['res.currency'].search([], order='id desc', limit=1).id + 1000)
route_values = self._prepare_pay_values()
response = self.portal_pay(**route_values)
self.assertEqual(response.status_code, 404)
# Pay with an inactive currency --> Not found (404)
self.currency = self.env['res.currency'].search([('active', '=', False)], limit=1)
route_values = self._prepare_pay_values()
response = self.portal_pay(**route_values)
self.assertEqual(response.status_code, 404)
def test_invoice_payment_flow(self):
"""Test the payment of an invoice through the payment/pay route"""
# Pay for this invoice (no impact even if amounts do not match)
route_values = self._prepare_pay_values()
route_values['invoice_id'] = self.invoice.id
tx_context = self.get_tx_checkout_context(**route_values)
self.assertEqual(tx_context['invoice_id'], self.invoice.id)
# payment/transaction
route_values = {
k: tx_context[k]
for k in [
'amount',
'currency_id',
'reference_prefix',
'partner_id',
'access_token',
'landing_route',
'invoice_id',
]
}
route_values.update({
'flow': 'direct',
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
})
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**route_values)
tx_sudo = self._get_tx(processing_values['reference'])
# Note: strangely, the check
# self.assertEqual(tx_sudo.invoice_ids, invoice)
# doesn't work, and cache invalidation doesn't work either.
self.invoice.invalidate_cache(['transaction_ids'])
self.assertEqual(self.invoice.transaction_ids, tx_sudo)
def test_transaction_wrong_flow(self):
transaction_values = self._prepare_pay_values()
transaction_values.update({
'flow': 'this flow does not exist',
'payment_option_id': self.acquirer.id,
'tokenization_requested': False,
'reference_prefix': 'whatever',
'landing_route': 'whatever',
})
# Transaction step with a wrong flow --> UserError
with mute_logger('odoo.http'):
response = self.portal_transaction(**transaction_values)
self.assertIn(
"odoo.exceptions.UserError: The payment should either be direct, with redirection, or made by a token.",
response.text)
def test_transaction_wrong_token(self):
route_values = self._prepare_pay_values()
route_values['access_token'] = "abcde"
# Transaction step with a wrong access token --> ValidationError
with mute_logger('odoo.http'):
response = self.portal_transaction(**route_values)
self.assertIn(
"odoo.exceptions.ValidationError: The access token is invalid.",
response.text)
@mute_logger('odoo.addons.payment.models.payment_transaction')
def test_direct_payment_triggers_no_payment_request(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.partner = self.portal_partner
self.user = self.portal_user
with patch(
'odoo.addons.payment.models.payment_transaction.PaymentTransaction'
'._send_payment_request'
) as patched:
self.portal_transaction(
**self._prepare_transaction_values(self.acquirer.id, 'direct')
)
self.assertEqual(patched.call_count, 0)
@mute_logger('odoo.addons.payment.models.payment_transaction')
def test_payment_with_redirect_triggers_no_payment_request(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.partner = self.portal_partner
self.user = self.portal_user
with patch(
'odoo.addons.payment.models.payment_transaction.PaymentTransaction'
'._send_payment_request'
) as patched:
self.portal_transaction(
**self._prepare_transaction_values(self.acquirer.id, 'redirect')
)
self.assertEqual(patched.call_count, 0)
@mute_logger('odoo.addons.payment.models.payment_transaction')
def test_payment_by_token_triggers_exactly_one_payment_request(self):
self.authenticate(self.portal_user.login, self.portal_user.login)
self.partner = self.portal_partner
self.user = self.portal_user
with patch(
'odoo.addons.payment.models.payment_transaction.PaymentTransaction'
'._send_payment_request'
) as patched:
self.portal_transaction(
**self._prepare_transaction_values(self.create_token().id, 'token')
)
self.assertEqual(patched.call_count, 1)
| 42.902116 | 16,217 |
6,134 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.tests import tagged
from odoo.addons.payment.tests.common import PaymentCommon
@tagged('-at_install', 'post_install')
class TestPayments(PaymentCommon):
def test_no_amount_available_for_refund_when_not_supported(self):
self.acquirer.support_refund = False
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
self.assertEqual(
tx.payment_id.amount_available_for_refund,
0,
msg="The value of `amount_available_for_refund` should be 0 when the acquirer doesn't "
"support refunds."
)
def test_full_amount_available_for_refund_when_not_yet_refunded(self):
self.acquirer.support_refund = 'full_only' # Should simply not be False
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
self.assertAlmostEqual(
tx.payment_id.amount_available_for_refund,
tx.amount,
places=2,
msg="The value of `amount_available_for_refund` should be that of `total` when there "
"are no linked refunds."
)
def test_full_amount_available_for_refund_when_refunds_are_pending(self):
self.acquirer.write({
'support_refund': 'full_only', # Should simply not be False
'support_authorization': True, # To create transaction in the 'authorized' state
})
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
for reference_index, state in enumerate(('draft', 'pending', 'authorized')):
self.create_transaction(
'dummy',
amount=-tx.amount,
reference=f'R-{tx.reference}-{reference_index + 1}',
state=state,
operation='refund', # Override the computed flow
source_transaction_id=tx.id,
)
self.assertAlmostEqual(
tx.payment_id.amount_available_for_refund,
tx.payment_id.amount,
places=2,
msg="The value of `amount_available_for_refund` should be that of `total` when all the "
"linked refunds are pending (not in the state 'done')."
)
def test_no_amount_available_for_refund_when_fully_refunded(self):
self.acquirer.support_refund = 'full_only' # Should simply not be False
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
self.create_transaction(
'dummy',
amount=-tx.amount,
reference=f'R-{tx.reference}',
state='done',
operation='refund', # Override the computed flow
source_transaction_id=tx.id,
)._reconcile_after_done()
self.assertEqual(
tx.payment_id.amount_available_for_refund,
0,
msg="The value of `amount_available_for_refund` should be 0 when there is a linked "
"refund of the full amount that is confirmed (state 'done')."
)
def test_no_full_amount_available_for_refund_when_partially_refunded(self):
self.acquirer.support_refund = 'partial'
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
self.create_transaction(
'dummy',
amount=-(tx.amount / 10),
reference=f'R-{tx.reference}',
state='done',
operation='refund', # Override the computed flow
source_transaction_id=tx.id,
)._reconcile_after_done()
self.assertAlmostEqual(
tx.payment_id.amount_available_for_refund,
tx.payment_id.amount - (tx.amount / 10),
places=2,
msg="The value of `amount_available_for_refund` should be equal to the total amount "
"minus the sum of the absolute amount of the refunds that are confirmed (state "
"'done')."
)
def test_refunds_count(self):
self.acquirer.support_refund = 'full_only' # Should simply not be False
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
for reference_index, operation in enumerate(
('online_redirect', 'online_direct', 'online_token', 'validation', 'refund')
):
self.create_transaction(
'dummy',
reference=f'R-{tx.reference}-{reference_index + 1}',
state='done',
operation=operation, # Override the computed flow
source_transaction_id=tx.id,
)._reconcile_after_done()
self.assertEqual(
tx.payment_id.refunds_count,
1,
msg="The refunds count should only consider transactions with operation 'refund'."
)
def test_action_post_calls_send_payment_request_only_once(self):
payment_token = self.create_token()
payment_without_token = self.env['account.payment'].create({
'payment_type': 'inbound',
'partner_type': 'customer',
'amount': 2000.0,
'date': '2019-01-01',
'currency_id': self.currency.id,
'partner_id': self.partner.id,
'journal_id': self.acquirer.journal_id.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
})
payment_with_token = payment_without_token.copy()
payment_with_token.payment_token_id = payment_token.id
with patch(
'odoo.addons.payment.models.payment_transaction.PaymentTransaction'
'._send_payment_request'
) as patched:
payment_without_token.action_post()
patched.assert_not_called()
payment_with_token.action_post()
patched.assert_called_once()
| 42.895105 | 6,134 |
3,646 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged
from odoo.addons.payment.tests.common import PaymentCommon
@tagged('-at_install', 'post_install')
class TestTransactions(PaymentCommon):
def test_refunds_count(self):
self.acquirer.support_refund = 'full_only' # Should simply not be False
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
for reference_index, operation in enumerate(
('online_redirect', 'online_direct', 'online_token', 'validation', 'refund')
):
self.create_transaction(
'dummy',
reference=f'R-{tx.reference}-{reference_index + 1}',
state='done',
operation=operation, # Override the computed flow
source_transaction_id=tx.id,
)._reconcile_after_done()
self.assertEqual(
tx.refunds_count,
1,
msg="The refunds count should only consider transactions with operation 'refund'."
)
def test_refund_transaction_values(self):
self.acquirer.support_refund = 'partial'
tx = self.create_transaction('redirect', state='done')
tx._reconcile_after_done() # Create the payment
# Test the default values of a full refund transaction
refund_tx = tx._create_refund_transaction()
self.assertEqual(
refund_tx.reference,
f'R-{tx.reference}',
msg="The reference of the refund transaction should be the prefixed reference of the "
"source transaction."
)
self.assertLess(
refund_tx.amount, 0, msg="The amount of a refund transaction should always be negative."
)
self.assertAlmostEqual(
refund_tx.amount,
-tx.amount,
places=2,
msg="The amount of the refund transaction should be taken from the amount of the "
"source transaction."
)
self.assertEqual(
refund_tx.currency_id,
tx.currency_id,
msg="The currency of the refund transaction should that of the source transaction."
)
self.assertEqual(
refund_tx.operation,
'refund',
msg="The operation of the refund transaction should be 'refund'."
)
self.assertEqual(
tx,
refund_tx.source_transaction_id,
msg="The refund transaction should be linked to the source transaction."
)
self.assertEqual(
refund_tx.partner_id,
tx.partner_id,
msg="The partner of the refund transaction should that of the source transaction."
)
# Test the values of a partial refund transaction with custom refund amount
partial_refund_tx = tx._create_refund_transaction(amount_to_refund=11.11)
self.assertAlmostEqual(
partial_refund_tx.amount,
-11.11,
places=2,
msg="The amount of the refund transaction should be the negative value of the amount "
"to refund."
)
def test_no_payment_for_validations(self):
tx = self.create_transaction(flow='dummy', operation='validation') # Overwrite the flow
tx._reconcile_after_done()
payment_count = self.env['account.payment'].search_count(
[('payment_transaction_id', '=', tx.id)]
)
self.assertEqual(payment_count, 0, msg="validation transactions should not create payments")
| 39.630435 | 3,646 |
8,699 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from unittest.mock import patch
from odoo.addons.account.models.account_payment_method import AccountPaymentMethod
from odoo.fields import Command
from odoo.addons.payment.tests.utils import PaymentTestUtils
_logger = logging.getLogger(__name__)
class PaymentCommon(PaymentTestUtils):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
Method_get_payment_method_information = AccountPaymentMethod._get_payment_method_information
def _get_payment_method_information(self):
res = Method_get_payment_method_information(self)
res['none'] = {'mode': 'multi', 'domain': [('type', '=', 'bank')]}
return res
cls.currency_euro = cls._prepare_currency('EUR')
cls.currency_usd = cls._prepare_currency('USD')
cls.country_belgium = cls.env.ref('base.be')
cls.country_france = cls.env.ref('base.fr')
cls.europe = cls.env.ref('base.europe')
cls.group_user = cls.env.ref('base.group_user')
cls.group_portal = cls.env.ref('base.group_portal')
cls.group_public = cls.env.ref('base.group_public')
cls.admin_user = cls.env.ref('base.user_admin')
cls.internal_user = cls.env['res.users'].create({
'name': 'Internal User (Test)',
'login': 'internal',
'password': 'internal',
'groups_id': [Command.link(cls.group_user.id)]
})
cls.portal_user = cls.env['res.users'].create({
'name': 'Portal User (Test)',
'login': 'payment_portal',
'password': 'payment_portal',
'groups_id': [Command.link(cls.group_portal.id)]
})
cls.public_user = cls.env.ref('base.public_user')
cls.admin_partner = cls.admin_user.partner_id
cls.internal_partner = cls.internal_user.partner_id
cls.portal_partner = cls.portal_user.partner_id
cls.default_partner = cls.env['res.partner'].create({
'name': 'Norbert Buyer',
'lang': 'en_US',
'email': '[email protected]',
'street': 'Huge Street',
'street2': '2/543',
'phone': '0032 12 34 56 78',
'city': 'Sin City',
'zip': '1000',
'country_id': cls.country_belgium.id,
})
# Create a dummy acquirer to allow basic tests without any specific acquirer implementation
arch = """
<form action="dummy" method="post">
<input type="hidden" name="view_id" t-att-value="viewid"/>
<input type="hidden" name="user_id" t-att-value="user_id.id"/>
</form>
""" # We exploit the default values `viewid` and `user_id` from QWeb's rendering context
redirect_form = cls.env['ir.ui.view'].create({
'name': "Dummy Redirect Form",
'type': 'qweb',
'arch': arch,
})
with patch.object(AccountPaymentMethod, '_get_payment_method_information', _get_payment_method_information):
cls.env['account.payment.method'].sudo().create({
'name': 'Dummy method',
'code': 'none',
'payment_type': 'inbound'
})
cls.dummy_acquirer = cls.env['payment.acquirer'].create({
'name': "Dummy Acquirer",
'provider': 'none',
'state': 'test',
'allow_tokenization': True,
'redirect_form_view_id': redirect_form.id,
'journal_id': cls.company_data['default_journal_bank'].id,
})
cls.acquirer = cls.dummy_acquirer
cls.amount = 1111.11
cls.company = cls.env.company
cls.currency = cls.currency_euro
cls.partner = cls.default_partner
cls.reference = "Test Transaction"
cls.account = cls.company.account_journal_payment_credit_account_id
cls.invoice = cls.env['account.move'].create({
'move_type': 'entry',
'date': '2019-01-01',
'line_ids': [
(0, 0, {
'account_id': cls.account.id,
'currency_id': cls.currency_euro.id,
'debit': 100.0,
'credit': 0.0,
'amount_currency': 200.0,
}),
(0, 0, {
'account_id': cls.account.id,
'currency_id': cls.currency_euro.id,
'debit': 0.0,
'credit': 100.0,
'amount_currency': -200.0,
}),
],
})
#=== Utils ===#
@classmethod
def _prepare_currency(cls, currency_code):
currency = cls.env['res.currency'].with_context(active_test=False).search(
[('name', '=', currency_code.upper())]
)
currency.action_unarchive()
return currency
@classmethod
def _prepare_acquirer(cls, provider='none', company=None, update_values=None):
""" Prepare and return the first acquirer matching the given provider and company.
If no acquirer is found in the given company, we duplicate the one from the base company.
All other acquirers belonging to the same company are disabled to avoid any interferences.
:param str provider: The provider of the acquirer to prepare
:param recordset company: The company of the acquirer to prepare, as a `res.company` record
:param dict update_values: The values used to update the acquirer
:return: The acquirer to prepare, if found
:rtype: recordset of `payment.acquirer`
"""
company = company or cls.env.company
update_values = update_values or {}
acquirer = cls.env['payment.acquirer'].sudo().search(
[('provider', '=', provider), ('company_id', '=', company.id)], limit=1
)
if not acquirer:
base_acquirer = cls.env['payment.acquirer'].sudo().search(
[('provider', '=', provider)], limit=1
)
if not base_acquirer:
_logger.error("no payment.acquirer found for provider %s", provider)
return cls.env['payment.acquirer']
else:
acquirer = base_acquirer.copy({'company_id': company.id})
acquirer.write(update_values)
if not acquirer.journal_id:
acquirer.journal_id = cls.env['account.journal'].search([
('company_id', '=', company.id),
('type', '=', 'bank')
], limit=1)
acquirer.state = 'test'
return acquirer
def create_transaction(self, flow, sudo=True, **values):
default_values = {
'amount': self.amount,
'currency_id': self.currency.id,
'acquirer_id': self.acquirer.id,
'reference': self.reference,
'operation': f'online_{flow}',
'partner_id': self.partner.id,
}
return self.env['payment.transaction'].sudo(sudo).create(dict(default_values, **values))
def create_token(self, sudo=True, **values):
default_values = {
'name': "XXXXXXXXXXXXXXX-2565 (TEST)",
'acquirer_id': self.acquirer.id,
'partner_id': self.partner.id,
'acquirer_ref': "Acquirer Ref (TEST)",
}
return self.env['payment.token'].sudo(sudo).create(dict(default_values, **values))
def _get_tx(self, reference):
return self.env['payment.transaction'].sudo().search([
('reference', '=', reference),
])
def _prepare_transaction_values(self, payment_option_id, flow):
""" Prepare the basic payment/transaction route values.
:param int payment_option_id: The payment option handling the transaction, as a
`payment.acquirer` id or a `payment.token` id
:param str flow: The payment flow
:return: The route values
:rtype: dict
"""
return {
'amount': self.amount,
'currency_id': self.currency.id,
'partner_id': self.partner.id,
'access_token': self._generate_test_access_token(
self.partner.id, self.amount, self.currency.id
),
'payment_option_id': payment_option_id,
'reference_prefix': 'test',
'tokenization_requested': True,
'landing_route': 'Test',
'is_validation': False,
'invoice_id': self.invoice.id,
'flow': flow,
}
| 39.540909 | 8,699 |
1,965 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from lxml import objectify
from werkzeug import urls
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tools.misc import hmac as hmac_tool
_logger = logging.getLogger(__name__)
class PaymentTestUtils(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.base_url = cls.env['ir.config_parameter'].get_param('web.base.url')
def _generate_test_access_token(self, *values):
""" Generate an access token based on the provided values for testing purposes.
This methods returns a token identical to that generated by
payment.utils.generate_access_token but uses the test class environment rather than the
environment of odoo.http.request.
See payment.utils.generate_access_token for additional details.
:param list values: The values to use for the generation of the token
:return: The generated access token
:rtype: str
"""
token_str = '|'.join(str(val) for val in values)
access_token = hmac_tool(self.env(su=True), 'generate_access_token', token_str)
return access_token
def _build_url(self, route):
return urls.url_join(self.base_url, route)
def _extract_values_from_html_form(self, html_form):
""" Extract the transaction rendering values from an HTML form.
:param str html_form: The HTML form
:return: The extracted information (action & inputs)
:rtype: dict[str:str]
"""
html_tree = objectify.fromstring(html_form)
action = html_tree.get('action')
inputs = {form_input.get('name'): form_input.get('value') for form_input in html_tree.input}
return {
'action': action,
'inputs': inputs,
}
| 35.727273 | 1,965 |
1,410 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo.fields import Command
from odoo.addons.payment.tests.common import PaymentCommon
_logger = logging.getLogger(__name__)
class PaymentMultiCompanyCommon(PaymentCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.company_a = cls.company_data['company']
cls.company_b = cls.company_data_2['company']
cls.user_company_a = cls.internal_user
cls.user_company_b = cls.env['res.users'].create({
'name': f"{cls.company_b.name} User (TEST)",
'login': 'user_company_b',
'password': 'user_company_b',
'company_id': cls.company_b.id,
'company_ids': [Command.set(cls.company_b.ids)],
'groups_id': [Command.link(cls.group_user.id)],
})
cls.user_multi_company = cls.env['res.users'].create({
'name': "Multi Company User (TEST)",
'login': 'user_multi_company',
'password': 'user_multi_company',
'company_id': cls.company_a.id,
'company_ids': [Command.set([cls.company_a.id, cls.company_b.id])],
'groups_id': [Command.link(cls.group_user.id)],
})
cls.acquirer_company_b = cls._prepare_acquirer(company=cls.company_b)
| 36.153846 | 1,410 |
3,985 |
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 odoo.addons.payment.tests.http_common import PaymentHttpCommon
from odoo.addons.payment.tests.multicompany_common import PaymentMultiCompanyCommon
@tagged('post_install', '-at_install')
class TestMultiCompanyFlows(PaymentMultiCompanyCommon, PaymentHttpCommon):
def test_pay_logged_in_another_company(self):
"""User pays for an amount in another company."""
# for another res.partner than the user's one
route_values = self._prepare_pay_values(partner=self.user_company_b.partner_id)
# Log in as user from Company A
self.authenticate(self.user_company_a.login, self.user_company_a.login)
# Pay in company B
route_values['company_id'] = self.company_b.id
tx_context = self.get_tx_checkout_context(**route_values)
for key, val in tx_context.items():
if key in route_values:
if key == 'access_token':
continue # access_token was modified due to the change of partner.
elif key == 'partner_id':
# The partner is replaced by the partner of the user paying.
self.assertEqual(val, self.user_company_a.partner_id.id)
else:
self.assertEqual(val, route_values[key])
available_acquirers = self.env['payment.acquirer'].sudo().browse(tx_context['acquirer_ids'])
self.assertIn(self.acquirer_company_b, available_acquirers)
self.assertEqual(available_acquirers.company_id, self.company_b)
validation_values = {
k: tx_context[k]
for k in [
'amount',
'currency_id',
'reference_prefix',
'partner_id',
'access_token',
'landing_route',
]
}
validation_values.update({
'flow': 'direct',
'payment_option_id': self.acquirer_company_b.id,
'tokenization_requested': False,
})
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = self.get_processing_values(**validation_values)
tx_sudo = self._get_tx(processing_values['reference'])
# Tx values == given values
self.assertEqual(tx_sudo.acquirer_id.id, self.acquirer_company_b.id)
self.assertEqual(tx_sudo.amount, self.amount)
self.assertEqual(tx_sudo.currency_id.id, self.currency.id)
self.assertEqual(tx_sudo.partner_id.id, self.user_company_a.partner_id.id)
self.assertEqual(tx_sudo.reference, self.reference)
self.assertEqual(tx_sudo.company_id, self.company_b)
# processing_values == given values
self.assertEqual(processing_values['acquirer_id'], self.acquirer_company_b.id)
self.assertEqual(processing_values['amount'], self.amount)
self.assertEqual(processing_values['currency_id'], self.currency.id)
self.assertEqual(processing_values['partner_id'], self.user_company_a.partner_id.id)
self.assertEqual(processing_values['reference'], self.reference)
def test_archive_token_logged_in_another_company(self):
"""User archives his token from another company."""
# get user's token from company A
token = self.create_token(partner_id=self.portal_partner.id)
# assign user to another company
company_b = self.env['res.company'].create({'name': 'Company B'})
self.portal_user.write({'company_ids': [company_b.id], 'company_id': company_b.id})
# Log in as portal user
self.authenticate(self.portal_user.login, self.portal_user.login)
# Archive token in company A
url = self._build_url('/payment/archive_token')
self._make_json_request(url, {'token_id': token.id})
self.assertFalse(token.active)
| 44.775281 | 3,985 |
6,267 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from uuid import uuid4
from lxml import etree, objectify
from odoo import http
from odoo.tests import HttpCase
from odoo.addons.payment.tests.utils import PaymentTestUtils
class PaymentHttpCommon(PaymentTestUtils, HttpCase):
""" HttpCase common to build and simulate requests going through payment controllers.
Only use if you effectively want to test controllers.
If you only want to test 'models' code, the PaymentCommon should be sufficient.
Note: This Common is expected to be used in parallel with the main PaymentCommon.
"""
# Helpers #
###########
def _build_jsonrpc_payload(self, params):
"""Helper to properly build jsonrpc payload"""
if not getattr(self, 'session', None):
# We need to create a session (public if no login & passwd)
# before generating a csrf token
self.authenticate('', '')
params['csrf_token'] = http.WebRequest.csrf_token(self)
return {
"jsonrpc": "2.0",
"method": "call",
"id": str(uuid4()),
"params": params,
}
def _make_http_get_request(self, url, params):
formatted_data = dict()
for k, v in params.items():
if isinstance(v, float):
formatted_data[k] = str(v)
else:
formatted_data[k] = v
return self.opener.get(url, params=formatted_data)
def _make_json_request(self, url, params):
data = self._build_jsonrpc_payload(params)
return self.opener.post(url, json=data)
def _get_tx_context(self, response, form_name):
"""Extracts txContext & other form info (acquirer & token ids)
from a payment response (with manage/checkout html form)
:param response: http Response, with a payment form as text
:param str form_name: o_payment_manage / o_payment_checkout
:return: Transaction context (+ acquirer_ids & token_ids)
:rtype: dict
"""
# Need to specify an HTML parser as parser
# Otherwise void elements (<img>, <link> without a closing / tag)
# are considered wrong and trigger a lxml.etree.XMLSyntaxError
html_tree = objectify.fromstring(
response.text,
parser=etree.HTMLParser(),
)
checkout_form = html_tree.xpath(f"//form[@name='{form_name}']")[0]
values = {}
for key, val in checkout_form.items():
if key.startswith("data-"):
formatted_key = key[5:].replace('-', '_')
if formatted_key.endswith('_id'):
formatted_val = int(val)
elif formatted_key == 'amount':
formatted_val = float(val)
else:
formatted_val = val
values[formatted_key] = formatted_val
payment_options_inputs = html_tree.xpath("//input[@name='o_payment_radio']")
acquirer_ids = []
token_ids = []
for p_o_input in payment_options_inputs:
data = dict()
for key, val in p_o_input.items():
if key.startswith('data-'):
data[key[5:]] = val
if data['payment-option-type'] == 'acquirer':
acquirer_ids.append(int(data['payment-option-id']))
else:
token_ids.append(int(data['payment-option-id']))
values.update({
'acquirer_ids': acquirer_ids,
'token_ids': token_ids,
})
return values
# payment/pay #
###############
def _prepare_pay_values(self, amount=0.0, currency=None, reference='', partner=None):
"""Prepare basic payment/pay route values
NOTE: needs PaymentCommon to enable fallback values.
:rtype: dict
"""
amount = amount or self.amount
currency = currency or self.currency
reference = reference or self.reference
partner = partner or self.partner
return {
'amount': amount,
'currency_id': currency.id,
'reference': reference,
'partner_id': partner.id,
'access_token': self._generate_test_access_token(partner.id, amount, currency.id),
}
def portal_pay(self, **route_kwargs):
"""/payment/pay txContext feedback
NOTE: must be authenticated before calling method.
Or an access_token should be specified in route_kwargs
"""
uri = '/payment/pay'
url = self._build_url(uri)
return self._make_http_get_request(url, route_kwargs)
def get_tx_checkout_context(self, **route_kwargs):
response = self.portal_pay(**route_kwargs)
self.assertEqual(response.status_code, 200)
return self._get_tx_context(response, 'o_payment_checkout')
# /my/payment_method #
######################
def portal_payment_method(self):
"""/my/payment_method txContext feedback
NOTE: must be authenticated before calling method
validation flow is restricted to logged users
"""
uri = '/my/payment_method'
url = self._build_url(uri)
return self._make_http_get_request(url, {})
def get_tx_manage_context(self, **route_kwargs):
response = self.portal_payment_method(**route_kwargs)
self.assertEqual(response.status_code, 200)
return self._get_tx_context(response, 'o_payment_manage')
# payment/transaction #
#######################
def portal_transaction(self, **route_kwargs):
"""/payment/transaction feedback
:return: The response to the json request
"""
uri = '/payment/transaction'
url = self._build_url(uri)
response = self._make_json_request(url, route_kwargs)
self.assertEqual(response.status_code, 200) # Check the request went through.
return response
def get_processing_values(self, **route_kwargs):
response = self.portal_transaction(**route_kwargs)
self.assertEqual(response.status_code, 200)
resp_content = json.loads(response.content)
return resp_content['result']
| 34.624309 | 6,267 |
2,701 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.addons.payment import utils as payment_utils
class AccountMove(models.Model):
_inherit = 'account.move'
transaction_ids = fields.Many2many(
string="Transactions", comodel_name='payment.transaction',
relation='account_invoice_transaction_rel', column1='invoice_id', column2='transaction_id',
readonly=True, copy=False)
authorized_transaction_ids = fields.Many2many(
string="Authorized Transactions", comodel_name='payment.transaction',
compute='_compute_authorized_transaction_ids', readonly=True, copy=False)
amount_paid = fields.Monetary(
string="Amount paid",
help="The amount already paid for this invoice.",
compute='_compute_amount_paid'
)
@api.depends('transaction_ids')
def _compute_authorized_transaction_ids(self):
for invoice in self:
invoice.authorized_transaction_ids = invoice.transaction_ids.filtered(
lambda tx: tx.state == 'authorized'
)
@api.depends('transaction_ids')
def _compute_amount_paid(self):
""" Sum all the transaction amount for which state is in 'authorized' or 'done'
"""
for invoice in self:
invoice.amount_paid = sum(
invoice.transaction_ids.filtered(
lambda tx: tx.state in ('authorized', 'done')
).mapped('amount')
)
def get_portal_last_transaction(self):
self.ensure_one()
return self.with_context(active_test=False).transaction_ids._get_last()
def payment_action_capture(self):
""" Capture all transactions linked to this invoice. """
payment_utils.check_rights_on_recordset(self)
# In sudo mode because we need to be able to read on acquirer fields.
self.authorized_transaction_ids.sudo().action_capture()
def payment_action_void(self):
""" Void all transactions linked to this invoice. """
payment_utils.check_rights_on_recordset(self)
# In sudo mode because we need to be able to read on acquirer fields.
self.authorized_transaction_ids.sudo().action_void()
def action_view_payment_transactions(self):
action = self.env['ir.actions.act_window']._for_xml_id('payment.action_payment_transaction')
if len(self.transaction_ids) == 1:
action['view_mode'] = 'form'
action['res_id'] = self.transaction_ids.id
action['views'] = []
else:
action['domain'] = [('id', 'in', self.transaction_ids.ids)]
return action
| 39.720588 | 2,701 |
49,570 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
import re
import unicodedata
from datetime import datetime
import psycopg2
from dateutil import relativedelta
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.tools import consteq, format_amount, ustr
from odoo.tools.misc import hmac as hmac_tool
from odoo.addons.payment import utils as payment_utils
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_name = 'payment.transaction'
_description = 'Payment Transaction'
_order = 'id desc'
_rec_name = 'reference'
@api.model
def _lang_get(self):
return self.env['res.lang'].get_installed()
acquirer_id = fields.Many2one(
string="Acquirer", comodel_name='payment.acquirer', readonly=True, required=True)
provider = fields.Selection(related='acquirer_id.provider')
company_id = fields.Many2one( # Indexed to speed-up ORM searches (from ir_rule or others)
related='acquirer_id.company_id', store=True, index=True)
reference = fields.Char(
string="Reference", help="The internal reference of the transaction", readonly=True,
required=True) # Already has an index from the UNIQUE SQL constraint
acquirer_reference = fields.Char(
string="Acquirer Reference", help="The acquirer reference of the transaction",
readonly=True) # This is not the same thing as the acquirer reference of the token
amount = fields.Monetary(
string="Amount", currency_field='currency_id', readonly=True, required=True)
currency_id = fields.Many2one(
string="Currency", comodel_name='res.currency', readonly=True, required=True)
fees = fields.Monetary(
string="Fees", currency_field='currency_id',
help="The fees amount; set by the system as it depends on the acquirer", readonly=True)
token_id = fields.Many2one(
string="Payment Token", comodel_name='payment.token', readonly=True,
domain='[("acquirer_id", "=", "acquirer_id")]', ondelete='restrict')
state = fields.Selection(
string="Status",
selection=[('draft', "Draft"), ('pending', "Pending"), ('authorized', "Authorized"),
('done', "Confirmed"), ('cancel', "Canceled"), ('error', "Error")],
default='draft', readonly=True, required=True, copy=False, index=True)
state_message = fields.Text(
string="Message", help="The complementary information message about the state",
readonly=True)
last_state_change = fields.Datetime(
string="Last State Change Date", readonly=True, default=fields.Datetime.now)
# Fields used for traceability
operation = fields.Selection( # This should not be trusted if the state is 'draft' or 'pending'
string="Operation",
selection=[
('online_redirect', "Online payment with redirection"),
('online_direct', "Online direct payment"),
('online_token', "Online payment by token"),
('validation', "Validation of the payment method"),
('offline', "Offline payment by token"),
('refund', "Refund")
],
readonly=True,
index=True,
)
payment_id = fields.Many2one(string="Payment", comodel_name='account.payment', readonly=True)
source_transaction_id = fields.Many2one(
string="Source Transaction",
comodel_name='payment.transaction',
help="The source transaction of related refund transactions",
readonly=True
)
refunds_count = fields.Integer(string="Refunds Count", compute='_compute_refunds_count')
invoice_ids = fields.Many2many(
string="Invoices", comodel_name='account.move', relation='account_invoice_transaction_rel',
column1='transaction_id', column2='invoice_id', readonly=True, copy=False,
domain=[('move_type', 'in', ('out_invoice', 'out_refund', 'in_invoice', 'in_refund'))])
invoices_count = fields.Integer(string="Invoices Count", compute='_compute_invoices_count')
# Fields used for user redirection & payment post-processing
is_post_processed = fields.Boolean(
string="Is Post-processed", help="Has the payment been post-processed")
tokenize = fields.Boolean(
string="Create Token",
help="Whether a payment token should be created when post-processing the transaction")
landing_route = fields.Char(
string="Landing Route",
help="The route the user is redirected to after the transaction")
callback_model_id = fields.Many2one(
string="Callback Document Model", comodel_name='ir.model', groups='base.group_system')
callback_res_id = fields.Integer(string="Callback Record ID", groups='base.group_system')
callback_method = fields.Char(string="Callback Method", groups='base.group_system')
# Hash for additional security on top of the callback fields' group in case a bug exposes a sudo
callback_hash = fields.Char(string="Callback Hash", groups='base.group_system')
callback_is_done = fields.Boolean(
string="Callback Done", help="Whether the callback has already been executed",
groups="base.group_system", readonly=True)
# Duplicated partner values allowing to keep a record of them, should they be later updated
partner_id = fields.Many2one(
string="Customer", comodel_name='res.partner', readonly=True, required=True,
ondelete='restrict')
partner_name = fields.Char(string="Partner Name")
partner_lang = fields.Selection(string="Language", selection=_lang_get)
partner_email = fields.Char(string="Email")
partner_address = fields.Char(string="Address")
partner_zip = fields.Char(string="Zip")
partner_city = fields.Char(string="City")
partner_state_id = fields.Many2one(string="State", comodel_name='res.country.state')
partner_country_id = fields.Many2one(string="Country", comodel_name='res.country')
partner_phone = fields.Char(string="Phone")
_sql_constraints = [
('reference_uniq', 'unique(reference)', "Reference must be unique!"),
]
#=== COMPUTE METHODS ===#
@api.depends('invoice_ids')
def _compute_invoices_count(self):
self.env.cr.execute(
'''
SELECT transaction_id, count(invoice_id)
FROM account_invoice_transaction_rel
WHERE transaction_id IN %s
GROUP BY transaction_id
''',
[tuple(self.ids)]
)
tx_data = dict(self.env.cr.fetchall()) # {id: count}
for tx in self:
tx.invoices_count = tx_data.get(tx.id, 0)
def _compute_refunds_count(self):
rg_data = self.env['payment.transaction'].read_group(
domain=[('source_transaction_id', 'in', self.ids), ('operation', '=', 'refund')],
fields=['source_transaction_id'],
groupby=['source_transaction_id'],
)
data = {x['source_transaction_id'][0]: x['source_transaction_id_count'] for x in rg_data}
for record in self:
record.refunds_count = data.get(record.id, 0)
#=== CONSTRAINT METHODS ===#
@api.constrains('state')
def _check_state_authorized_supported(self):
""" Check that authorization is supported for a transaction in the 'authorized' state. """
illegal_authorize_state_txs = self.filtered(
lambda tx: tx.state == 'authorized' and not tx.acquirer_id.support_authorization
)
if illegal_authorize_state_txs:
raise ValidationError(_(
"Transaction authorization is not supported by the following payment acquirers: %s",
', '.join(set(illegal_authorize_state_txs.mapped('acquirer_id.name')))
))
#=== CRUD METHODS ===#
@api.model_create_multi
def create(self, values_list):
for values in values_list:
acquirer = self.env['payment.acquirer'].browse(values['acquirer_id'])
if not values.get('reference'):
values['reference'] = self._compute_reference(acquirer.provider, **values)
# Duplicate partner values
partner = self.env['res.partner'].browse(values['partner_id'])
values.update({
# Use the parent partner as fallback if the invoicing address has no name.
'partner_name': partner.name or partner.parent_id.name,
'partner_lang': partner.lang,
'partner_email': partner.email,
'partner_address': payment_utils.format_partner_address(
partner.street, partner.street2
),
'partner_zip': partner.zip,
'partner_city': partner.city,
'partner_state_id': partner.state_id.id,
'partner_country_id': partner.country_id.id,
'partner_phone': partner.phone,
})
# Compute fees, for validation transactions fees are zero
if values.get('operation') == 'validation':
values['fees'] = 0
else:
currency = self.env['res.currency'].browse(values.get('currency_id')).exists()
values['fees'] = acquirer._compute_fees(
values.get('amount', 0), currency, partner.country_id,
)
# Include acquirer-specific create values
values.update(self._get_specific_create_values(acquirer.provider, values))
# Generate the hash for the callback if one has be configured on the tx
values['callback_hash'] = self._generate_callback_hash(
values.get('callback_model_id'),
values.get('callback_res_id'),
values.get('callback_method'),
)
txs = super().create(values_list)
# Monetary fields are rounded with the currency at creation time by the ORM. Sometimes, this
# can lead to inconsistent string representation of the amounts sent to the providers.
# E.g., tx.create(amount=1111.11) -> tx.amount == 1111.1100000000001
# To ensure a proper string representation, we invalidate this request's cache values of the
# `amount` and `fees` fields for the created transactions. This forces the ORM to read the
# values from the DB where there were stored using `float_repr`, which produces a result
# consistent with the format expected by providers.
# E.g., tx.create(amount=1111.11) ; tx.invalidate_cache() -> tx.amount == 1111.11
txs.invalidate_cache(['amount', 'fees'])
return txs
@api.model
def _get_specific_create_values(self, provider, values):
""" Complete the values of the `create` method with acquirer-specific values.
For an acquirer to add its own create values, it must overwrite this method and return a
dict of values. Acquirer-specific values take precedence over those of the dict of generic
create values.
:param str provider: The provider of the acquirer that handled the transaction
:param dict values: The original create values
:return: The dict of acquirer-specific create values
:rtype: dict
"""
return dict()
#=== ACTION METHODS ===#
def action_view_invoices(self):
""" Return the action for the views of the invoices linked to the transaction.
Note: self.ensure_one()
:return: The action
:rtype: dict
"""
self.ensure_one()
action = {
'name': _("Invoices"),
'type': 'ir.actions.act_window',
'res_model': 'account.move',
'target': 'current',
}
invoice_ids = self.invoice_ids.ids
if len(invoice_ids) == 1:
invoice = invoice_ids[0]
action['res_id'] = invoice
action['view_mode'] = 'form'
action['views'] = [(self.env.ref('account.view_move_form').id, 'form')]
else:
action['view_mode'] = 'tree,form'
action['domain'] = [('id', 'in', invoice_ids)]
return action
def action_view_refunds(self):
""" Return the action for the views of the refund transactions linked to the transaction.
Note: self.ensure_one()
:return: The action
:rtype: dict
"""
self.ensure_one()
action = {
'name': _("Refund"),
'res_model': 'payment.transaction',
'type': 'ir.actions.act_window',
}
if self.refunds_count == 1:
refund_tx = self.env['payment.transaction'].search([
('source_transaction_id', '=', self.id),
])[0]
action['res_id'] = refund_tx.id
action['view_mode'] = 'form'
else:
action['view_mode'] = 'tree,form'
action['domain'] = [('source_transaction_id', '=', self.id)]
return action
def action_capture(self):
""" Check the state of the transactions and request their capture. """
if any(tx.state != 'authorized' for tx in self):
raise ValidationError(_("Only authorized transactions can be captured."))
payment_utils.check_rights_on_recordset(self)
for tx in self:
# In sudo mode because we need to be able to read on acquirer fields.
tx.sudo()._send_capture_request()
def action_void(self):
""" Check the state of the transaction and request to have them voided. """
if any(tx.state != 'authorized' for tx in self):
raise ValidationError(_("Only authorized transactions can be voided."))
payment_utils.check_rights_on_recordset(self)
for tx in self:
# In sudo mode because we need to be able to read on acquirer fields.
tx.sudo()._send_void_request()
def action_refund(self, amount_to_refund=None):
""" Check the state of the transactions and request their refund.
:param float amount_to_refund: The amount to be refunded
:return: None
"""
if any(tx.state != 'done' for tx in self):
raise ValidationError(_("Only confirmed transactions can be refunded."))
for tx in self:
tx._send_refund_request(amount_to_refund)
#=== BUSINESS METHODS - PAYMENT FLOW ===#
@api.model
def _compute_reference(self, provider, prefix=None, separator='-', **kwargs):
""" Compute a unique reference for the transaction.
The reference either corresponds to the prefix if no other transaction with that prefix
already exists, or follows the pattern `{computed_prefix}{separator}{sequence_number}` where
- {computed_prefix} is:
- The provided custom prefix, if any.
- The computation result of `_compute_reference_prefix` if the custom prefix is not
filled but the kwargs are.
- 'tx-{datetime}', if neither the custom prefix nor the kwargs are filled.
- {separator} is a custom string also used in `_compute_reference_prefix`.
- {sequence_number} is the next integer in the sequence of references sharing the exact
same prefix, '1' if there is only one matching reference (hence without sequence number)
Examples:
- Given the custom prefix 'example' which has no match with an existing reference, the
full reference will be 'example'.
- Given the custom prefix 'example' which matches the existing reference 'example', and
the custom separator '-', the full reference will be 'example-1'.
- Given the kwargs {'invoice_ids': [1, 2]}, the custom separator '-' and no custom prefix,
the full reference will be 'INV1-INV2' (or similar) if no existing reference has the
same prefix, or 'INV1-INV2-n' if n existing references have the same prefix.
:param str provider: The provider of the acquirer handling the transaction
:param str prefix: The custom prefix used to compute the full reference
:param str separator: The custom separator used to separate the prefix from the suffix, and
passed to `_compute_reference_prefix` if it is called
:param dict kwargs: Optional values passed to `_compute_reference_prefix` if no custom
prefix is provided
:return: The unique reference for the transaction
:rtype: str
"""
# Compute the prefix
if prefix:
# Replace special characters by their ASCII alternative (é -> e ; ä -> a ; ...)
prefix = unicodedata.normalize('NFKD', prefix).encode('ascii', 'ignore').decode('utf-8')
if not prefix: # Prefix not provided or voided above, compute it based on the kwargs
prefix = self.sudo()._compute_reference_prefix(provider, separator, **kwargs)
if not prefix: # Prefix not computed from the kwargs, fallback on time-based value
prefix = payment_utils.singularize_reference_prefix()
# Compute the sequence number
reference = prefix # The first reference of a sequence has no sequence number
if self.sudo().search([('reference', '=', prefix)]): # The reference already has a match
# We now execute a second search on `payment.transaction` to fetch all the references
# starting with the given prefix. The load of these two searches is mitigated by the
# index on `reference`. Although not ideal, this solution allows for quickly knowing
# whether the sequence for a given prefix is already started or not, usually not. An SQL
# query wouldn't help either as the selector is arbitrary and doing that would be an
# open-door to SQL injections.
same_prefix_references = self.sudo().search(
[('reference', 'like', f'{prefix}{separator}%')]
).with_context(prefetch_fields=False).mapped('reference')
# A final regex search is necessary to figure out the next sequence number. The previous
# search could not rely on alphabetically sorting the reference to infer the largest
# sequence number because both the prefix and the separator are arbitrary. A given
# prefix could happen to be a substring of the reference from a different sequence.
# For instance, the prefix 'example' is a valid match for the existing references
# 'example', 'example-1' and 'example-ref', in that order. Trusting the order to infer
# the sequence number would lead to a collision with 'example-1'.
search_pattern = re.compile(rf'^{re.escape(prefix)}{separator}(\d+)$')
max_sequence_number = 0 # If no match is found, start the sequence with this reference
for existing_reference in same_prefix_references:
search_result = re.search(search_pattern, existing_reference)
if search_result: # The reference has the same prefix and is from the same sequence
# Find the largest sequence number, if any
current_sequence = int(search_result.group(1))
if current_sequence > max_sequence_number:
max_sequence_number = current_sequence
# Compute the full reference
reference = f'{prefix}{separator}{max_sequence_number + 1}'
return reference
@api.model
def _compute_reference_prefix(self, provider, separator, **values):
""" Compute the reference prefix from the transaction values.
If the `values` parameter has an entry with 'invoice_ids' as key and a list of (4, id, O) or
(6, 0, ids) X2M command as value, the prefix is computed based on the invoice name(s).
Otherwise, an empty string is returned.
Note: This method should be called in sudo mode to give access to documents (INV, SO, ...).
:param str provider: The provider of the acquirer handling the transaction
:param str separator: The custom separator used to separate data references
:param dict values: The transaction values used to compute the reference prefix. It should
have the structure {'invoice_ids': [(X2M command), ...], ...}.
:return: The computed reference prefix if invoice ids are found, an empty string otherwise
:rtype: str
"""
command_list = values.get('invoice_ids')
if command_list:
# Extract invoice id(s) from the X2M commands
invoice_ids = self._fields['invoice_ids'].convert_to_cache(command_list, self)
invoices = self.env['account.move'].browse(invoice_ids).exists()
if len(invoices) == len(invoice_ids): # All ids are valid
return separator.join(invoices.mapped('name'))
return ''
@api.model
def _generate_callback_hash(self, callback_model_id, callback_res_id, callback_method):
""" Return the hash for the callback on the transaction.
:param int callback_model_id: The model on which the callback method is defined, as a
`res.model` id
:param int callback_res_id: The record on which the callback method must be called, as an id
of the callback model
:param str callback_method: The name of the callback method
:return: The callback hash
:rtype: str
"""
if callback_model_id and callback_res_id and callback_method:
model_name = self.env['ir.model'].sudo().browse(callback_model_id).model
token = f'{model_name}|{callback_res_id}|{callback_method}'
callback_hash = hmac_tool(self.env(su=True), 'generate_callback_hash', token)
return callback_hash
return None
def _get_processing_values(self):
""" Return a dict of values used to process the transaction.
The returned dict contains the following entries:
- tx_id: The transaction, as a `payment.transaction` id
- acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id
- provider: The provider of the acquirer
- reference: The reference of the transaction
- amount: The rounded amount of the transaction
- currency_id: The currency of the transaction, as a res.currency id
- partner_id: The partner making the transaction, as a res.partner id
- Additional acquirer-specific entries
Note: self.ensure_one()
:return: The dict of processing values
:rtype: dict
"""
self.ensure_one()
processing_values = {
'acquirer_id': self.acquirer_id.id,
'provider': self.provider,
'reference': self.reference,
'amount': self.amount,
'currency_id': self.currency_id.id,
'partner_id': self.partner_id.id,
}
# Complete generic processing values with acquirer-specific values
processing_values.update(self._get_specific_processing_values(processing_values))
_logger.info(
"generic and acquirer-specific processing values for transaction with id %s:\n%s",
self.id, pprint.pformat(processing_values)
)
# Render the html form for the redirect flow if available
if self.operation in ('online_redirect', 'validation'):
redirect_form_view = self.acquirer_id._get_redirect_form_view(
is_validation=self.operation == 'validation'
)
if redirect_form_view: # Some acquirer don't need a redirect form
rendering_values = self._get_specific_rendering_values(processing_values)
_logger.info(
"acquirer-specific rendering values for transaction with id %s:\n%s",
self.id, pprint.pformat(rendering_values)
)
redirect_form_html = redirect_form_view._render(rendering_values, engine='ir.qweb')
processing_values.update(redirect_form_html=redirect_form_html)
return processing_values
def _get_specific_processing_values(self, processing_values):
""" Return a dict of acquirer-specific values used to process the transaction.
For an acquirer to add its own processing values, it must overwrite this method and return a
dict of acquirer-specific values based on the generic values returned by this method.
Acquirer-specific values take precedence over those of the dict of generic processing
values.
:param dict processing_values: The generic processing values of the transaction
:return: The dict of acquirer-specific processing values
:rtype: dict
"""
return dict()
def _get_specific_rendering_values(self, processing_values):
""" Return a dict of acquirer-specific values used to render the redirect form.
For an acquirer to add its own rendering values, it must overwrite this method and return a
dict of acquirer-specific values based on the processing values (acquirer-specific
processing values included).
:param dict processing_values: The processing values of the transaction
:return: The dict of acquirer-specific rendering values
:rtype: dict
"""
return dict()
def _send_payment_request(self):
""" Request the provider of the acquirer handling the transaction to execute the payment.
For an acquirer to support tokenization, it must override this method and call it to log the
'sent' message, then request a money transfer to its provider.
Note: self.ensure_one()
:return: None
"""
self.ensure_one()
self._log_sent_message()
def _send_refund_request(self, amount_to_refund=None, create_refund_transaction=True):
""" Request the provider of the acquirer handling the transaction to refund it.
For an acquirer to support refunds, it must override this method and request a refund
to its provider.
Note: self.ensure_one()
:param float amount_to_refund: The amount to be refunded
:param bool create_refund_transaction: Whether a refund transaction should be created
:return: The refund transaction if any
:rtype: recordset of `payment.transaction`
"""
self.ensure_one()
if create_refund_transaction:
refund_tx = self._create_refund_transaction(amount_to_refund=amount_to_refund)
refund_tx._log_sent_message()
return refund_tx
else:
return self.env['payment.transaction']
def _send_capture_request(self):
""" Request the provider of the acquirer handling the transaction to capture it.
For an acquirer to support authorization, it must override this method and request a capture
to its provider.
Note: self.ensure_one()
:return: None
"""
self.ensure_one()
def _send_void_request(self):
""" Request the provider of the acquirer handling the transaction to void it.
For an acquirer to support authorization, it must override this method and request the
transaction to be voided to its provider.
Note: self.ensure_one()
:return: None
"""
self.ensure_one()
def _create_refund_transaction(self, amount_to_refund=None, **custom_create_values):
""" Create a new transaction with operation 'refund' and link it to the current transaction.
:param float amount_to_refund: The strictly positive amount to refund, in the same currency
as the source transaction
:return: The refund transaction
:rtype: recordset of `payment.transaction`
"""
self.ensure_one()
return self.create({
'acquirer_id': self.acquirer_id.id,
'reference': self._compute_reference(self.provider, prefix=f'R-{self.reference}'),
'amount': -(amount_to_refund or self.amount),
'currency_id': self.currency_id.id,
'token_id': self.token_id.id,
'operation': 'refund',
'source_transaction_id': self.id,
'partner_id': self.partner_id.id,
**custom_create_values,
})
@api.model
def _handle_feedback_data(self, provider, data):
""" Match the transaction with the feedback data, update its state and return it.
: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
:rtype: recordset of `payment.transaction`
"""
tx = self._get_tx_from_feedback_data(provider, data)
tx._process_feedback_data(data)
tx._execute_callback()
return tx
@api.model
def _get_tx_from_feedback_data(self, provider, data):
""" Find the transaction based on the feedback data.
For an acquirer to handle transaction post-processing, it must overwrite this method and
return the transaction matching the data.
:param str provider: The provider of the acquirer that handled the transaction
:param dict data: The feedback data sent by the acquirer
:return: The transaction if found
:rtype: recordset of `payment.transaction`
"""
return self
def _process_feedback_data(self, data):
""" Update the transaction state and the acquirer reference based on the feedback data.
For an acquirer to handle transaction post-processing, it must overwrite this method and
process the feedback data.
Note: self.ensure_one()
:param dict data: The feedback data sent by the acquirer
:return: None
"""
self.ensure_one()
def _set_pending(self, state_message=None):
""" Update the transactions' state to 'pending'.
:param str state_message: The reason for which the transaction is set in 'pending' state
:return: None
"""
allowed_states = ('draft',)
target_state = 'pending'
txs_to_process = self._update_state(allowed_states, target_state, state_message)
txs_to_process._log_received_message()
def _set_authorized(self, state_message=None):
""" Update the transactions' state to 'authorized'.
:param str state_message: The reason for which the transaction is set in 'authorized' state
:return: None
"""
allowed_states = ('draft', 'pending')
target_state = 'authorized'
txs_to_process = self._update_state(allowed_states, target_state, state_message)
txs_to_process._log_received_message()
def _set_done(self, state_message=None):
""" Update the transactions' state to 'done'.
:return: None
"""
allowed_states = ('draft', 'pending', 'authorized', 'error', 'cancel') # 'cancel' for Payulatam
target_state = 'done'
txs_to_process = self._update_state(allowed_states, target_state, state_message)
txs_to_process._log_received_message()
def _set_canceled(self, state_message=None):
""" Update the transactions' state to 'cancel'.
:param str state_message: The reason for which the transaction is set in 'cancel' state
:return: None
"""
allowed_states = ('draft', 'pending', 'authorized')
target_state = 'cancel'
txs_to_process = self._update_state(allowed_states, target_state, state_message)
# Cancel the existing payments
txs_to_process.mapped('payment_id').action_cancel()
txs_to_process._log_received_message()
def _set_error(self, state_message):
""" Update the transactions' state to 'error'.
:param str state_message: The reason for which the transaction is set in 'error' state
:return: None
"""
allowed_states = ('draft', 'pending', 'authorized')
target_state = 'error'
txs_to_process = self._update_state(allowed_states, target_state, state_message)
txs_to_process._log_received_message()
def _update_state(self, allowed_states, target_state, state_message):
""" Update the transactions' state to the target state if the current state allows it.
If the current state is the same as the target state, the transaction is skipped.
:param tuple[str] allowed_states: The allowed source states for the target state
:param str target_state: The target state
:param str state_message: The message to set as `state_message`
:return: The recordset of transactions whose state was correctly updated
:rtype: recordset of `payment.transaction`
"""
def _classify_by_state(_transactions):
"""Classify the transactions according to their current state.
For each transaction of the current recordset, if:
- The state is an allowed state: the transaction is flagged as 'to process'.
- The state is equal to the target state: the transaction is flagged as 'processed'.
- The state matches none of above: the transaction is flagged as 'in wrong state'.
:param recordset _transactions: The transactions to classify, as a `payment.transaction`
recordset
:return: A 3-items tuple of recordsets of classified transactions, in this order:
transactions 'to process', 'processed', and 'in wrong state'
:rtype: tuple(recordset)
"""
_txs_to_process = _transactions.filtered(lambda _tx: _tx.state in allowed_states)
_txs_already_processed = _transactions.filtered(lambda _tx: _tx.state == target_state)
_txs_wrong_state = _transactions - _txs_to_process - _txs_already_processed
return _txs_to_process, _txs_already_processed, _txs_wrong_state
txs_to_process, txs_already_processed, txs_wrong_state = _classify_by_state(self)
for tx in txs_already_processed:
_logger.info(
"tried to write tx state with same value (ref: %s, state: %s)",
tx.reference, tx.state
)
for tx in txs_wrong_state:
logging_values = {
'reference': tx.reference,
'tx_state': tx.state,
'target_state': target_state,
'allowed_states': allowed_states,
}
_logger.warning(
"tried to write tx state with illegal value (ref: %(reference)s, previous state "
"%(tx_state)s, target state: %(target_state)s, expected previous state to be in: "
"%(allowed_states)s)", logging_values
)
txs_to_process.write({
'state': target_state,
'state_message': state_message,
'last_state_change': fields.Datetime.now(),
})
return txs_to_process
def _execute_callback(self):
""" Execute the callbacks defined on the transactions.
Callbacks that have already been executed are silently ignored. This case can happen when a
transaction is first authorized before being confirmed, for instance. In this case, both
status updates try to execute the callback.
Only successful callbacks are marked as done. This allows callbacks to reschedule themselves
should the conditions not be met in the present call.
:return: None
"""
for tx in self.filtered(lambda t: not t.sudo().callback_is_done):
# Only use sudo to check, not to execute
tx_sudo = tx.sudo()
model_sudo = tx_sudo.callback_model_id
res_id = tx_sudo.callback_res_id
method = tx_sudo.callback_method
callback_hash = tx_sudo.callback_hash
if not (model_sudo and res_id and method):
continue # Skip transactions with unset (or not properly defined) callbacks
valid_callback_hash = self._generate_callback_hash(model_sudo.id, res_id, method)
if not consteq(ustr(valid_callback_hash), callback_hash):
_logger.warning("invalid callback signature for transaction with id %s", tx.id)
continue # Ignore tampered callbacks
record = self.env[model_sudo.model].browse(res_id).exists()
if not record:
logging_values = {
'model': model_sudo.model,
'record_id': res_id,
'tx_id': tx.id,
}
_logger.warning(
"invalid callback record %(model)s.%(record_id)s for transaction with id "
"%(tx_id)s", logging_values
)
continue # Ignore invalidated callbacks
success = getattr(record, method)(tx) # Execute the callback
tx_sudo.callback_is_done = success or success is None # Missing returns are successful
#=== BUSINESS METHODS - POST-PROCESSING ===#
def _get_post_processing_values(self):
""" Return a dict of values used to display the status of the transaction.
For an acquirer to handle transaction status display, it must override this method and
return a dict of values. Acquirer-specific values take precedence over those of the dict of
generic post-processing values.
The returned dict contains the following entries:
- provider: The provider of the acquirer
- reference: The reference of the transaction
- amount: The rounded amount of the transaction
- currency_id: The currency of the transaction, as a res.currency id
- state: The transaction state: draft, pending, authorized, done, cancel or error
- state_message: The information message about the state
- is_post_processed: Whether the transaction has already been post-processed
- landing_route: The route the user is redirected to after the transaction
- Additional acquirer-specific entries
Note: self.ensure_one()
:return: The dict of processing values
:rtype: dict
"""
self.ensure_one()
post_processing_values = {
'provider': self.provider,
'reference': self.reference,
'amount': self.amount,
'currency_code': self.currency_id.name,
'state': self.state,
'state_message': self.state_message,
'is_post_processed': self.is_post_processed,
'landing_route': self.landing_route,
}
_logger.debug(
"post-processing values for acquirer with id %s:\n%s",
self.acquirer_id.id, pprint.pformat(post_processing_values)
) # DEBUG level because this can get spammy with transactions in non-final states
return post_processing_values
def _finalize_post_processing(self):
""" Trigger the final post-processing tasks and mark the transactions as post-processed.
:return: None
"""
self._reconcile_after_done()
self._log_received_message() # 2nd call to link the created account.payment in the chatter
self.is_post_processed = True
def _cron_finalize_post_processing(self):
""" Finalize the post-processing of recently done transactions not handled by the client.
:return: None
"""
txs_to_post_process = self
if not txs_to_post_process:
# Let the client post-process transactions so that they remain available in the portal
client_handling_limit_date = datetime.now() - relativedelta.relativedelta(minutes=10)
# Don't try forever to post-process a transaction that doesn't go through. Set the limit
# to 4 days because some providers (PayPal) need that much for the payment verification.
retry_limit_date = datetime.now() - relativedelta.relativedelta(days=4)
# Retrieve all transactions matching the criteria for post-processing
txs_to_post_process = self.search([
('state', '=', 'done'),
('is_post_processed', '=', False),
'|', ('last_state_change', '<=', client_handling_limit_date),
('operation', '=', 'refund'),
('last_state_change', '>=', retry_limit_date),
])
for tx in txs_to_post_process:
try:
tx._finalize_post_processing()
self.env.cr.commit()
except psycopg2.OperationalError: # A collision of accounting sequences occurred
self.env.cr.rollback() # Rollback and try later
except Exception as e:
_logger.exception(
"encountered an error while post-processing transaction with id %s:\n%s",
tx.id, e
)
self.env.cr.rollback()
def _reconcile_after_done(self):
""" Post relevant fiscal documents and create missing payments.
As there is nothing to reconcile for validation transactions, no payment is created for
them. This is also true for validations with a validity check (transfer of a small amount
with immediate refund) because validation amounts are not included in payouts.
:return: None
"""
# Validate invoices automatically once the transaction is confirmed
self.invoice_ids.filtered(lambda inv: inv.state == 'draft').action_post()
# Create and post missing payments for transactions requiring reconciliation
for tx in self.filtered(lambda t: t.operation != 'validation' and not t.payment_id):
tx._create_payment()
def _create_payment(self, **extra_create_values):
"""Create an `account.payment` record for the current transaction.
If the transaction is linked to some invoices, their reconciliation is done automatically.
Note: self.ensure_one()
:param dict extra_create_values: Optional extra create values
:return: The created payment
:rtype: recordset of `account.payment`
"""
self.ensure_one()
payment_method_line = self.acquirer_id.journal_id.inbound_payment_method_line_ids\
.filtered(lambda l: l.code == self.provider)
payment_values = {
'amount': abs(self.amount), # A tx may have a negative amount, but a payment must >= 0
'payment_type': 'inbound' if self.amount > 0 else 'outbound',
'currency_id': self.currency_id.id,
'partner_id': self.partner_id.commercial_partner_id.id,
'partner_type': 'customer',
'journal_id': self.acquirer_id.journal_id.id,
'company_id': self.acquirer_id.company_id.id,
'payment_method_line_id': payment_method_line.id,
'payment_token_id': self.token_id.id,
'payment_transaction_id': self.id,
'ref': self.reference,
**extra_create_values,
}
payment = self.env['account.payment'].create(payment_values)
payment.action_post()
# Track the payment to make a one2one.
self.payment_id = payment
if self.invoice_ids:
self.invoice_ids.filtered(lambda inv: inv.state == 'draft').action_post()
(payment.line_ids + self.invoice_ids.line_ids).filtered(
lambda line: line.account_id == payment.destination_account_id
and not line.reconciled
).reconcile()
return payment
#=== BUSINESS METHODS - LOGGING ===#
def _log_sent_message(self):
""" Log in the chatter of relevant documents that the transactions have been initiated.
:return: None
"""
for tx in self:
message = tx._get_sent_message()
tx._log_message_on_linked_documents(message)
def _log_received_message(self):
""" Log in the chatter of relevant documents that the transactions have been received.
A transaction is 'received' when a response is received from the provider of the acquirer
handling the transaction.
:return: None
"""
for tx in self:
message = tx._get_received_message()
tx._log_message_on_linked_documents(message)
def _log_message_on_linked_documents(self, message):
""" Log a message on the payment and the invoices linked to the transaction.
For a module to implement payments and link documents to a transaction, it must override
this method and call super, then log the message on documents linked to the transaction.
Note: self.ensure_one()
:param str message: The message to be logged
:return: None
"""
self.ensure_one()
if self.source_transaction_id.payment_id:
self.source_transaction_id.payment_id.message_post(body=message)
for invoice in self.source_transaction_id.invoice_ids:
invoice.message_post(body=message)
for invoice in self.invoice_ids:
invoice.message_post(body=message)
#=== BUSINESS METHODS - GETTERS ===#
def _get_sent_message(self):
""" Return the message stating that the transaction has been requested.
Note: self.ensure_one()
:return: The 'transaction sent' message
:rtype: str
"""
self.ensure_one()
# Choose the message based on the payment flow
if self.operation in ('online_redirect', 'online_direct'):
message = _(
"A transaction with reference %(ref)s has been initiated (%(acq_name)s).",
ref=self.reference, acq_name=self.acquirer_id.name
)
elif self.operation == 'refund':
formatted_amount = format_amount(self.env, -self.amount, self.currency_id)
message = _(
"A refund request of %(amount)s has been sent. The payment will be created soon. "
"Refund transaction reference: %(ref)s (%(acq_name)s).",
amount=formatted_amount, ref=self.reference, acq_name=self.acquirer_id.name
)
else: # 'online_token'
message = _(
"A transaction with reference %(ref)s has been initiated using the payment method "
"%(token_name)s (%(acq_name)s).",
ref=self.reference, token_name=self.token_id.name, acq_name=self.acquirer_id.name
)
return message
def _get_received_message(self):
""" Return the message stating that the transaction has been received by the provider.
Note: self.ensure_one()
"""
self.ensure_one()
formatted_amount = format_amount(self.env, self.amount, self.currency_id)
if self.state == 'pending':
message = _(
"The transaction with reference %(ref)s for %(amount)s is pending (%(acq_name)s).",
ref=self.reference, amount=formatted_amount, acq_name=self.acquirer_id.name
)
elif self.state == 'authorized':
message = _(
"The transaction with reference %(ref)s for %(amount)s has been authorized "
"(%(acq_name)s).", ref=self.reference, amount=formatted_amount,
acq_name=self.acquirer_id.name
)
elif self.state == 'done':
message = _(
"The transaction with reference %(ref)s for %(amount)s has been confirmed "
"(%(acq_name)s).", ref=self.reference, amount=formatted_amount,
acq_name=self.acquirer_id.name
)
if self.payment_id:
message += "<br />" + _(
"The related payment is posted: %s",
self.payment_id._get_payment_chatter_link()
)
elif self.state == 'error':
message = _(
"The transaction with reference %(ref)s for %(amount)s encountered an error"
" (%(acq_name)s).",
ref=self.reference, amount=formatted_amount, acq_name=self.acquirer_id.name
)
if self.state_message:
message += "<br />" + _("Error: %s", self.state_message)
else:
message = _(
"The transaction with reference %(ref)s for %(amount)s is canceled (%(acq_name)s).",
ref=self.reference, amount=formatted_amount, acq_name=self.acquirer_id.name
)
if self.state_message:
message += "<br />" + _("Reason: %s", self.state_message)
return message
def _get_last(self):
""" Return the last transaction of the recordset.
:return: The last transaction of the recordset, sorted by id
:rtype: recordset of `payment.transaction`
"""
return self.filtered(lambda t: t.state != 'draft').sorted()[:1]
| 45.642726 | 49,568 |
343 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
@classmethod
def _get_translation_frontend_modules_name(cls):
mods = super(IrHttp, cls)._get_translation_frontend_modules_name()
return mods + ['payment']
| 28.583333 | 343 |
3,913 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, Command, models
from odoo.exceptions import UserError
class AccountJournal(models.Model):
_inherit = "account.journal"
@api.constrains('inbound_payment_method_line_ids')
def _check_inbound_payment_method_line_ids(self):
"""
Check and ensure that the user do not remove a apml that is linked to an acquirer in the test or enabled state.
"""
if not self.company_id:
return
self.env['account.payment.method'].flush(['code', 'payment_type'])
self.env['account.payment.method.line'].flush(['payment_method_id'])
self.env['payment.acquirer'].flush(['provider', 'state'])
self._cr.execute('''
SELECT acquirer.id
FROM payment_acquirer acquirer
JOIN account_payment_method apm ON apm.code = acquirer.provider
LEFT JOIN account_payment_method_line apml ON apm.id = apml.payment_method_id AND apml.journal_id IS NOT NULL
WHERE acquirer.state IN ('enabled', 'test') AND apm.payment_type = 'inbound'
AND apml.id IS NULL
AND acquirer.company_id IN %(company_ids)s
''', {'company_ids': tuple(self.company_id.ids)})
ids = [r[0] for r in self._cr.fetchall()]
if ids:
acquirers = self.env['payment.acquirer'].sudo().browse(ids)
raise UserError(_("You can't delete a payment method that is linked to an acquirer in the enabled or test state.\n"
"Linked acquirer(s): %s", ', '.join(a.display_name for a in acquirers)))
def _get_available_payment_method_lines(self, payment_type):
lines = super()._get_available_payment_method_lines(payment_type)
return lines.filtered(lambda l: l.payment_acquirer_state != 'disabled')
@api.depends('outbound_payment_method_line_ids', 'inbound_payment_method_line_ids')
def _compute_available_payment_method_ids(self):
super()._compute_available_payment_method_ids()
installed_acquirers = self.env['payment.acquirer'].sudo().search([])
method_information = self.env['account.payment.method']._get_payment_method_information()
pay_methods = self.env['account.payment.method'].search([('code', 'in', list(method_information.keys()))])
pay_method_by_code = {x.code + x.payment_type: x for x in pay_methods}
# On top of the basic filtering, filter to hide unavailable acquirers.
# This avoid allowing payment method lines linked to an acquirer that has no record.
for code, vals in method_information.items():
payment_method = pay_method_by_code.get(code + 'inbound')
if not payment_method:
continue
for journal in self:
to_remove = []
available_providers = installed_acquirers.filtered(
lambda a: a.company_id == journal.company_id
).mapped('provider')
available = payment_method.code in available_providers
if vals['mode'] == 'unique' and not available:
to_remove.append(payment_method.id)
journal.available_payment_method_ids = [Command.unlink(payment_method) for payment_method in to_remove]
@api.ondelete(at_uninstall=False)
def _unlink_except_linked_to_payment_acquirer(self):
linked_acquirers = self.env['payment.acquirer'].sudo().search([]).filtered(
lambda acq: acq.journal_id.id in self.ids and acq.state != 'disabled'
)
if linked_acquirers:
raise UserError(_(
"You must first deactivate a payment acquirer before deleting its journal.\n"
"Linked acquirer(s): %s", ', '.join(acq.display_name for acq in linked_acquirers)
))
| 47.719512 | 3,913 |
5,187 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class PaymentToken(models.Model):
_name = 'payment.token'
_order = 'partner_id, id desc'
_description = 'Payment Token'
acquirer_id = fields.Many2one(
string="Acquirer Account", comodel_name='payment.acquirer', required=True)
provider = fields.Selection(related='acquirer_id.provider')
name = fields.Char(
string="Name", help="The anonymized acquirer reference of the payment method",
required=True)
partner_id = fields.Many2one(string="Partner", comodel_name='res.partner', required=True)
company_id = fields.Many2one( # Indexed to speed-up ORM searches (from ir_rule or others)
related='acquirer_id.company_id', store=True, index=True)
acquirer_ref = fields.Char(
string="Acquirer Reference", help="The acquirer reference of the token of the transaction",
required=True) # This is not the same thing as the acquirer reference of the transaction
transaction_ids = fields.One2many(
string="Payment Transactions", comodel_name='payment.transaction', inverse_name='token_id')
verified = fields.Boolean(string="Verified")
active = fields.Boolean(string="Active", default=True)
#=== CRUD METHODS ===#
@api.model_create_multi
def create(self, values_list):
for values in values_list:
if 'acquirer_id' in values:
acquirer = self.env['payment.acquirer'].browse(values['acquirer_id'])
# Include acquirer-specific create values
values.update(self._get_specific_create_values(acquirer.provider, values))
else:
pass # Let psycopg warn about the missing required field
return super().create(values_list)
@api.model
def _get_specific_create_values(self, provider, values):
""" Complete the values of the `create` method with acquirer-specific values.
For an acquirer to add its own create values, it must overwrite this method and return a
dict of values. Acquirer-specific values take precedence over those of the dict of generic
create values.
:param str provider: The provider of the acquirer managing the token
:param dict values: The original create values
:return: The dict of acquirer-specific create values
:rtype: dict
"""
return dict()
def write(self, values):
""" Delegate the handling of active state switch to dedicated methods.
Unless an exception is raised in the handling methods, the toggling proceeds no matter what.
This is because allowing users to hide their saved payment methods comes before making sure
that the recorded payment details effectively get deleted.
:return: The result of the write
:rtype: bool
"""
# Let acquirers handle activation/deactivation requests
if 'active' in values:
for token in self:
# Call handlers in sudo mode because this method might have been called by RPC
if values['active'] and not token.active:
token.sudo()._handle_reactivation_request()
elif not values['active'] and token.active:
token.sudo()._handle_deactivation_request()
# Proceed with the toggling of the active state
return super().write(values)
#=== BUSINESS METHODS ===#
def _handle_deactivation_request(self):
""" Handle the request for deactivation of the token.
For an acquirer to support deactivation of tokens, or perform additional operations when a
token is deactivated, it must overwrite this method and raise an UserError if the token
cannot be deactivated.
Note: self.ensure_one()
:return: None
"""
self.ensure_one()
def _handle_reactivation_request(self):
""" Handle the request for reactivation of the token.
For an acquirer to support reactivation of tokens, or perform additional operations when a
token is reactivated, it must overwrite this method and raise an UserError if the token
cannot be reactivated.
Note: self.ensure_one()
:return: None
"""
self.ensure_one()
def get_linked_records_info(self):
""" Return a list of information about records linked to the current token.
For a module to implement payments and link documents to a token, it must override this
method and add information about linked records to the returned list.
The information must be structured as a dict with the following keys:
- description: The description of the record's model (e.g. "Subscription")
- id: The id of the record
- name: The name of the record
- url: The url to access the record.
Note: self.ensure_one()
:return: The list of information about linked documents
:rtype: list
"""
self.ensure_one()
return []
| 39.9 | 5,187 |
2,259 |
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.osv import expression
class AccountPaymentMethodLine(models.Model):
_inherit = "account.payment.method.line"
payment_acquirer_id = fields.Many2one(
comodel_name='payment.acquirer',
compute='_compute_payment_acquirer_id',
store=True
)
payment_acquirer_state = fields.Selection(
related='payment_acquirer_id.state'
)
@api.depends('payment_method_id')
def _compute_payment_acquirer_id(self):
acquirers = self.env['payment.acquirer'].sudo().search([
('provider', 'in', self.mapped('code')),
('company_id', 'in', self.journal_id.company_id.ids),
])
# Make sure to pick the active acquirer, if any.
acquirers_map = dict()
for acquirer in acquirers:
current_value = acquirers_map.get((acquirer.provider, acquirer.company_id), False)
if current_value and current_value.state != 'disabled':
continue
acquirers_map[(acquirer.provider, acquirer.company_id)] = acquirer
for line in self:
code = line.payment_method_id.code
company = line.journal_id.company_id
line.payment_acquirer_id = acquirers_map.get((code, company), False)
def _get_payment_method_domain(self):
# OVERRIDE
domain = super()._get_payment_method_domain()
information = self._get_payment_method_information().get(self.code)
unique = information.get('mode') == 'unique'
if unique:
company_ids = self.env['payment.acquirer'].sudo().search([('provider', '=', self.code)]).mapped('company_id')
if company_ids:
domain = expression.AND([domain, [('company_id', 'in', company_ids.ids)]])
return domain
def action_open_acquirer_form(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': _('Acquirer'),
'view_mode': 'form',
'res_model': 'payment.acquirer',
'target': 'current',
'res_id': self.payment_acquirer_id.id
}
| 35.857143 | 2,259 |
19,772 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import _, api, fields, models, SUPERUSER_ID
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
_logger = logging.getLogger(__name__)
class PaymentAcquirer(models.Model):
_name = 'payment.acquirer'
_description = 'Payment Acquirer'
_order = 'module_state, state desc, sequence, name'
def _valid_field_parameter(self, field, name):
return name == 'required_if_provider' or super()._valid_field_parameter(field, name)
# Configuration fields
name = fields.Char(string="Name", required=True, translate=True)
sequence = fields.Integer(string="Sequence", help="Define the display order")
provider = fields.Selection(
string="Provider", help="The Payment Service Provider to use with this acquirer",
selection=[('none', "No Provider Set")], default='none', required=True)
state = fields.Selection(
string="State",
help="In test mode, a fake payment is processed through a test payment interface.\n"
"This mode is advised when setting up the acquirer.",
selection=[('disabled', "Disabled"), ('enabled', "Enabled"), ('test', "Test Mode")],
default='disabled', required=True, copy=False)
company_id = fields.Many2one( # Indexed to speed-up ORM searches (from ir_rule or others)
string="Company", comodel_name='res.company', default=lambda self: self.env.company.id,
required=True, index=True)
payment_icon_ids = fields.Many2many(
string="Supported Payment Icons", comodel_name='payment.icon')
allow_tokenization = fields.Boolean(
string="Allow Saving Payment Methods",
help="This controls whether customers can save their payment methods as payment tokens.\n"
"A payment token is an anonymous link to the payment method details saved in the\n"
"acquirer's database, allowing the customer to reuse it for a next purchase.")
capture_manually = fields.Boolean(
string="Capture Amount Manually",
help="Capture the amount from Odoo, when the delivery is completed.\n"
"Use this if you want to charge your customers cards only when\n"
"you are sure you can ship the goods to them.")
redirect_form_view_id = fields.Many2one(
string="Redirect Form Template", comodel_name='ir.ui.view',
help="The template rendering a form submitted to redirect the user when making a payment",
domain=[('type', '=', 'qweb')])
inline_form_view_id = fields.Many2one(
string="Inline Form Template", comodel_name='ir.ui.view',
help="The template rendering the inline payment form when making a direct payment",
domain=[('type', '=', 'qweb')])
country_ids = fields.Many2many(
string="Countries", comodel_name='res.country', relation='payment_country_rel',
column1='payment_id', column2='country_id',
help="The countries for which this payment acquirer is available.\n"
"If none is set, it is available for all countries.")
journal_id = fields.Many2one(
string="Payment Journal", comodel_name='account.journal',
compute='_compute_journal_id', inverse='_inverse_journal_id',
help="The journal in which the successful transactions are posted",
domain="[('type', '=', 'bank'), ('company_id', '=', company_id)]")
# Fees fields
fees_active = fields.Boolean(string="Add Extra Fees")
fees_dom_fixed = fields.Float(string="Fixed domestic fees")
fees_dom_var = fields.Float(string="Variable domestic fees (in percents)")
fees_int_fixed = fields.Float(string="Fixed international fees")
fees_int_var = fields.Float(string="Variable international fees (in percents)")
# Message fields
display_as = fields.Char(
string="Displayed as", help="Description of the acquirer for customers",
translate=True)
pre_msg = fields.Html(
string="Help Message", help="The message displayed to explain and help the payment process",
translate=True)
pending_msg = fields.Html(
string="Pending Message",
help="The message displayed if the order pending after the payment process",
default=lambda self: _(
"Your payment has been successfully processed but is waiting for approval."
), translate=True)
auth_msg = fields.Html(
string="Authorize Message", help="The message displayed if payment is authorized",
default=lambda self: _("Your payment has been authorized."), translate=True)
done_msg = fields.Html(
string="Done Message",
help="The message displayed if the order is successfully done after the payment process",
default=lambda self: _("Your payment has been successfully processed. Thank you!"),
translate=True)
cancel_msg = fields.Html(
string="Canceled Message",
help="The message displayed if the order is canceled during the payment process",
default=lambda self: _("Your payment has been cancelled."), translate=True)
# Feature support fields
support_authorization = fields.Boolean(string="Authorize Mechanism Supported")
support_fees_computation = fields.Boolean(string="Fees Computation Supported")
support_tokenization = fields.Boolean(string="Tokenization Supported")
support_refund = fields.Selection(
string="Type of Refund Supported",
selection=[('full_only', "Full Only"), ('partial', "Partial")],
)
# Kanban view fields
description = fields.Html(
string="Description", help="The description shown in the card in kanban view ")
image_128 = fields.Image(string="Image", max_width=128, max_height=128)
color = fields.Integer(
string="Color", help="The color of the card in kanban view", compute='_compute_color',
store=True)
# Module-related fields
module_id = fields.Many2one(string="Corresponding Module", comodel_name='ir.module.module')
module_state = fields.Selection(
string="Installation State", related='module_id.state', store=True) # Stored for sorting
module_to_buy = fields.Boolean(string="Odoo Enterprise Module", related='module_id.to_buy')
# View configuration fields
show_credentials_page = fields.Boolean(compute='_compute_view_configuration_fields')
show_allow_tokenization = fields.Boolean(compute='_compute_view_configuration_fields')
show_payment_icon_ids = fields.Boolean(compute='_compute_view_configuration_fields')
show_pre_msg = fields.Boolean(compute='_compute_view_configuration_fields')
show_pending_msg = fields.Boolean(compute='_compute_view_configuration_fields')
show_auth_msg = fields.Boolean(compute='_compute_view_configuration_fields')
show_done_msg = fields.Boolean(compute='_compute_view_configuration_fields')
show_cancel_msg = fields.Boolean(compute='_compute_view_configuration_fields')
#=== COMPUTE METHODS ===#
@api.depends('state', 'module_state')
def _compute_color(self):
""" Update the color of the kanban card based on the state of the acquirer.
:return: None
"""
for acquirer in self:
if acquirer.module_id and not acquirer.module_state == 'installed':
acquirer.color = 4 # blue
elif acquirer.state == 'disabled':
acquirer.color = 3 # yellow
elif acquirer.state == 'test':
acquirer.color = 2 # orange
elif acquirer.state == 'enabled':
acquirer.color = 7 # green
@api.depends('provider')
def _compute_view_configuration_fields(self):
""" Compute view configuration fields based on the provider.
By default, all fields are set to `True`.
For an acquirer to hide generic elements (pages, fields) in a view, it must override this
method and set their corresponding view configuration field to `False`.
:return: None
"""
self.update({
'show_credentials_page': True,
'show_allow_tokenization': True,
'show_payment_icon_ids': True,
'show_pre_msg': True,
'show_pending_msg': True,
'show_auth_msg': True,
'show_done_msg': True,
'show_cancel_msg': True,
})
def _compute_journal_id(self):
for acquirer in self:
payment_method = self.env['account.payment.method.line'].search([
('journal_id.company_id', '=', acquirer.company_id.id),
('code', '=', acquirer.provider)
], limit=1)
if payment_method:
acquirer.journal_id = payment_method.journal_id
else:
acquirer.journal_id = False
def _inverse_journal_id(self):
for acquirer in self:
payment_method_line = self.env['account.payment.method.line'].search([
('journal_id.company_id', '=', acquirer.company_id.id),
('code', '=', acquirer.provider)
], limit=1)
if acquirer.journal_id:
if not payment_method_line:
default_payment_method_id = acquirer._get_default_payment_method_id()
existing_payment_method_line = self.env['account.payment.method.line'].search([
('payment_method_id', '=', default_payment_method_id),
('journal_id', '=', acquirer.journal_id.id)
], limit=1)
if not existing_payment_method_line:
self.env['account.payment.method.line'].create({
'payment_method_id': default_payment_method_id,
'journal_id': acquirer.journal_id.id,
})
else:
payment_method_line.journal_id = acquirer.journal_id
elif payment_method_line:
payment_method_line.unlink()
def _get_default_payment_method_id(self):
self.ensure_one()
return self.env.ref('account.account_payment_method_manual_in').id
#=== CONSTRAINT METHODS ===#
@api.constrains('fees_dom_var', 'fees_int_var')
def _check_fee_var_within_boundaries(self):
""" Check that variable fees are within realistic boundaries.
Variable fees values should always be positive and below 100% to respectively avoid negative
and infinite (division by zero) fees amount.
:return None
"""
for acquirer in self:
if any(not 0 <= fee < 100 for fee in (acquirer.fees_dom_var, acquirer.fees_int_var)):
raise ValidationError(_("Variable fees must always be positive and below 100%."))
#=== CRUD METHODS ===#
@api.model_create_multi
def create(self, values_list):
acquirers = super().create(values_list)
acquirers._check_required_if_provider()
return acquirers
def write(self, values):
result = super().write(values)
self._check_required_if_provider()
return result
def _check_required_if_provider(self):
""" Check that acquirer-specific required fields have been filled.
The fields that have the `required_if_provider="<provider>"` attribute are made required
for all payment.acquirer records with the `provider` field equal to <provider> and with the
`state` field equal to 'enabled' or 'test'.
Acquirer-specific views should make the form fields required under the same conditions.
:return: None
:raise ValidationError: if an acquirer-specific required field is empty
"""
field_names = []
enabled_acquirers = self.filtered(lambda acq: acq.state in ['enabled', 'test'])
for name, field in self._fields.items():
required_provider = getattr(field, 'required_if_provider', None)
if required_provider and any(
required_provider == acquirer.provider and not acquirer[name]
for acquirer in enabled_acquirers
):
ir_field = self.env['ir.model.fields']._get(self._name, name)
field_names.append(ir_field.field_description)
if field_names:
raise ValidationError(
_("The following fields must be filled: %s", ", ".join(field_names))
)
@api.ondelete(at_uninstall=False)
def _unlink_except_master_data(self):
""" Prevent the deletion of the payment acquirer if it has an xmlid. """
external_ids = self.get_external_id()
for acquirer in self:
external_id = external_ids[acquirer.id]
if external_id and not external_id.startswith('__export__'):
raise UserError(
_("You cannot delete the payment acquirer %s; archive it instead.", acquirer.name)
)
#=== ACTION METHODS ===#
def button_immediate_install(self):
""" Install the acquirer's module and reload the page.
Note: self.ensure_one()
:return: The action to reload the page
:rtype: dict
"""
if self.module_id and self.module_state != 'installed':
self.module_id.button_immediate_install()
return {
'type': 'ir.actions.client',
'tag': 'reload',
}
#=== BUSINESS METHODS ===#
@api.model
def _get_compatible_acquirers(
self, company_id, partner_id, currency_id=None, force_tokenization=False,
is_validation=False, **kwargs
):
""" Select and return the acquirers matching the criteria.
The base criteria are that acquirers must not be disabled, be in the company that is
provided, and support the country of the partner if it exists.
:param int company_id: The company to which acquirers must belong, as a `res.company` id
:param int partner_id: The partner making the payment, as a `res.partner` id
:param int currency_id: The payment currency if known beforehand, as a `res.currency` id
:param bool force_tokenization: Whether only acquirers allowing tokenization can be matched
:param bool is_validation: Whether the operation is a validation
:param dict kwargs: Optional data. This parameter is not used here
:return: The compatible acquirers
:rtype: recordset of `payment.acquirer`
"""
# Compute the base domain for compatible acquirers
domain = ['&', ('state', 'in', ['enabled', 'test']), ('company_id', '=', company_id)]
# Handle partner country
partner = self.env['res.partner'].browse(partner_id)
if partner.country_id: # The partner country must either not be set or be supported
domain = expression.AND([
domain,
['|', ('country_ids', '=', False), ('country_ids', 'in', [partner.country_id.id])]
])
# Handle tokenization support requirements
if force_tokenization or self._is_tokenization_required(**kwargs):
domain = expression.AND([domain, [('allow_tokenization', '=', True)]])
compatible_acquirers = self.env['payment.acquirer'].search(domain)
return compatible_acquirers
@api.model
def _is_tokenization_required(self, provider=None, **kwargs):
""" Return whether tokenizing the transaction is required given its context.
For a module to make the tokenization required based on the transaction context, it must
override this method and return whether it is required.
:param str provider: The provider of the acquirer handling the transaction
:param dict kwargs: The transaction context. This parameter is not used here
:return: Whether tokenizing the transaction is required
:rtype: bool
"""
return False
def _should_build_inline_form(self, is_validation=False):
""" Return whether the inline form should be instantiated if it exists.
For an acquirer to handle both direct payments and payment with redirection, it should
override this method and return whether the inline form should be instantiated (i.e. if the
payment should be direct) based on the operation (online payment or validation).
:param bool is_validation: Whether the operation is a validation
:return: Whether the inline form should be instantiated
:rtype: bool
"""
return True
def _compute_fees(self, amount, currency, country):
""" Compute the transaction fees.
The computation is based on the generic fields `fees_dom_fixed`, `fees_dom_var`,
`fees_int_fixed` and `fees_int_var` and is done according to the following formula:
`fees = (amount * variable / 100.0 + fixed) / (1 - variable / 100.0)` where the value
of `fixed` and `variable` is taken either from the domestic (dom) or international (int)
field depending on whether the country matches the company's country.
For an acquirer to base the computation on different variables, or to use a different
formula, it must override this method and return the resulting fees as a float.
:param float amount: The amount to pay for the transaction
:param recordset currency: The currency of the transaction, as a `res.currency` record
:param recordset country: The customer country, as a `res.country` record
:return: The computed fees
:rtype: float
"""
self.ensure_one()
fees = 0.0
if self.fees_active:
if country == self.company_id.country_id:
fixed = self.fees_dom_fixed
variable = self.fees_dom_var
else:
fixed = self.fees_int_fixed
variable = self.fees_int_var
fees = (amount * variable / 100.0 + fixed) / (1 - variable / 100.0)
return fees
def _get_validation_amount(self):
""" Get the amount to transfer in a payment method validation operation.
For an acquirer to support tokenization, it must override this method and return the amount
to be transferred in a payment method validation operation *if the validation amount is not
null*.
Note: self.ensure_one()
:return: The validation amount
:rtype: float
"""
self.ensure_one()
return 0.0
def _get_validation_currency(self):
""" Get the currency of the transfer in a payment method validation operation.
For an acquirer to support tokenization, it must override this method and return the
currency to be used in a payment method validation operation *if the validation amount is
not null*.
Note: self.ensure_one()
:return: The validation currency
:rtype: recordset of `res.currency`
"""
self.ensure_one()
return self.journal_id.currency_id or self.company_id.currency_id
def _get_redirect_form_view(self, is_validation=False):
""" Return the view of the template used to render the redirect form.
For an acquirer to return a different view depending on whether the operation is a
validation, it must override this method and return the appropriate view.
Note: self.ensure_one()
:param bool is_validation: Whether the operation is a validation
:return: The redirect form template
:rtype: record of `ir.ui.view`
"""
self.ensure_one()
return self.redirect_form_view_id
| 45.768519 | 19,772 |
9,315 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, Command, fields, models
from odoo.exceptions import ValidationError
class AccountPayment(models.Model):
_inherit = 'account.payment'
# == Business fields ==
payment_transaction_id = fields.Many2one(
string="Payment Transaction",
comodel_name='payment.transaction',
readonly=True,
auto_join=True, # No access rule bypass since access to payments means access to txs too
)
payment_token_id = fields.Many2one(
string="Saved Payment Token", comodel_name='payment.token', domain="""[
('id', 'in', suitable_payment_token_ids),
]""",
help="Note that only tokens from acquirers allowing to capture the amount are available.")
amount_available_for_refund = fields.Monetary(compute='_compute_amount_available_for_refund')
# == Display purpose fields ==
suitable_payment_token_ids = fields.Many2many(
comodel_name='payment.token',
compute='_compute_suitable_payment_token_ids',
compute_sudo=True,
)
use_electronic_payment_method = fields.Boolean(
compute='_compute_use_electronic_payment_method',
help='Technical field used to hide or show the payment_token_id if needed.'
)
# == Fields used for traceability ==
source_payment_id = fields.Many2one(
string="Source Payment",
comodel_name='account.payment',
help="The source payment of related refund payments",
related='payment_transaction_id.source_transaction_id.payment_id',
readonly=True,
store=True, # Stored for the group by in `_compute_refunds_count`
)
refunds_count = fields.Integer(string="Refunds Count", compute='_compute_refunds_count')
def _compute_amount_available_for_refund(self):
for payment in self:
tx_sudo = payment.payment_transaction_id.sudo()
if tx_sudo.acquirer_id.support_refund and tx_sudo.operation != 'refund':
# Only consider refund transactions that are confirmed by summing the amounts of
# payments linked to such refund transactions. Indeed, should a refund transaction
# be stuck forever in a transient state (due to webhook failure, for example), the
# user would never be allowed to refund the source transaction again.
refund_payments = self.search([('source_payment_id', '=', self.id)])
refunded_amount = abs(sum(refund_payments.mapped('amount')))
payment.amount_available_for_refund = payment.amount - refunded_amount
else:
payment.amount_available_for_refund = 0
@api.depends('payment_method_line_id')
def _compute_suitable_payment_token_ids(self):
for payment in self:
related_partner_ids = (
payment.partner_id
| payment.partner_id.commercial_partner_id
| payment.partner_id.commercial_partner_id.child_ids
)._origin
if payment.use_electronic_payment_method:
payment.suitable_payment_token_ids = self.env['payment.token'].sudo().search([
('company_id', '=', payment.company_id.id),
('acquirer_id.capture_manually', '=', False),
('partner_id', 'in', related_partner_ids.ids),
('acquirer_id', '=', payment.payment_method_line_id.payment_acquirer_id.id),
])
else:
payment.suitable_payment_token_ids = [Command.clear()]
@api.depends('payment_method_line_id')
def _compute_use_electronic_payment_method(self):
for payment in self:
# Get a list of all electronic payment method codes.
# These codes are comprised of 'electronic' and the providers of each payment acquirer.
codes = [key for key in dict(self.env['payment.acquirer']._fields['provider']._description_selection(self.env))]
payment.use_electronic_payment_method = payment.payment_method_code in codes
def _compute_refunds_count(self):
rg_data = self.env['account.payment'].read_group(
domain=[
('source_payment_id', 'in', self.ids),
('payment_transaction_id.operation', '=', 'refund')
],
fields=['source_payment_id'],
groupby=['source_payment_id']
)
data = {x['source_payment_id'][0]: x['source_payment_id_count'] for x in rg_data}
for payment in self:
payment.refunds_count = data.get(payment.id, 0)
@api.onchange('partner_id', 'payment_method_line_id', 'journal_id')
def _onchange_set_payment_token_id(self):
codes = [key for key in dict(self.env['payment.acquirer']._fields['provider']._description_selection(self.env))]
if not (self.payment_method_code in codes and self.partner_id and self.journal_id):
self.payment_token_id = False
return
related_partner_ids = (
self.partner_id
| self.partner_id.commercial_partner_id
| self.partner_id.commercial_partner_id.child_ids
)._origin
self.payment_token_id = self.env['payment.token'].sudo().search([
('company_id', '=', self.company_id.id),
('partner_id', 'in', related_partner_ids.ids),
('acquirer_id.capture_manually', '=', False),
('acquirer_id', '=', self.payment_method_line_id.payment_acquirer_id.id),
], limit=1)
def action_post(self):
# Post the payments "normally" if no transactions are needed.
# If not, let the acquirer update the state.
payments_need_tx = self.filtered(
lambda p: p.payment_token_id and not p.payment_transaction_id
)
# creating the transaction require to access data on payment acquirers, not always accessible to users
# able to create payments
transactions = payments_need_tx.sudo()._create_payment_transaction()
res = super(AccountPayment, self - payments_need_tx).action_post()
for tx in transactions: # Process the transactions with a payment by token
tx._send_payment_request()
# Post payments for issued transactions
transactions._finalize_post_processing()
payments_tx_done = payments_need_tx.filtered(
lambda p: p.payment_transaction_id.state == 'done'
)
super(AccountPayment, payments_tx_done).action_post()
payments_tx_not_done = payments_need_tx.filtered(
lambda p: p.payment_transaction_id.state != 'done'
)
payments_tx_not_done.action_cancel()
return res
def action_refund_wizard(self):
self.ensure_one()
return {
'name': _("Refund"),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'payment.refund.wizard',
'target': 'new',
}
def action_view_refunds(self):
self.ensure_one()
action = {
'name': _("Refund"),
'res_model': 'account.payment',
'type': 'ir.actions.act_window',
}
if self.refunds_count == 1:
refund_tx = self.env['account.payment'].search([
('source_payment_id', '=', self.id)
], limit=1)
action['res_id'] = refund_tx.id
action['view_mode'] = 'form'
else:
action['view_mode'] = 'tree,form'
action['domain'] = [('source_payment_id', '=', self.id)]
return action
def _get_payment_chatter_link(self):
self.ensure_one()
return f'<a href=# data-oe-model=account.payment data-oe-id={self.id}>{self.name}</a>'
def _create_payment_transaction(self, **extra_create_values):
for payment in self:
if payment.payment_transaction_id:
raise ValidationError(_(
"A payment transaction with reference %s already exists.",
payment.payment_transaction_id.reference
))
elif not payment.payment_token_id:
raise ValidationError(_("A token is required to create a new payment transaction."))
transactions = self.env['payment.transaction']
for payment in self:
transaction_vals = payment._prepare_payment_transaction_vals(**extra_create_values)
transaction = self.env['payment.transaction'].create(transaction_vals)
transactions += transaction
payment.payment_transaction_id = transaction # Link the transaction to the payment
return transactions
def _prepare_payment_transaction_vals(self, **extra_create_values):
self.ensure_one()
return {
'acquirer_id': self.payment_token_id.acquirer_id.id,
'reference': self.ref,
'amount': self.amount,
'currency_id': self.currency_id.id,
'partner_id': self.partner_id.id,
'token_id': self.payment_token_id.id,
'operation': 'offline',
'payment_id': self.id,
**extra_create_values,
}
| 44.146919 | 9,315 |
714 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, models
from odoo.exceptions import UserError
class IrUiView(models.Model):
_inherit = 'ir.ui.view'
@api.ondelete(at_uninstall=False)
def _unlink_if_not_referenced_by_acquirer(self):
referencing_acquirers_sudo = self.env['payment.acquirer'].sudo().search([
'|', ('redirect_form_view_id', 'in', self.ids), ('inline_form_view_id', 'in', self.ids)
]) # In sudo mode to allow non-admin users (e.g., Website designers) to read the view ids.
if referencing_acquirers_sudo:
raise UserError(_("You cannot delete a view that is used by a payment acquirer."))
| 44.625 | 714 |
3,701 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResCompany(models.Model):
_inherit = 'res.company'
payment_acquirer_onboarding_state = fields.Selection(
string="State of the onboarding payment acquirer step",
selection=[('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done")],
default='not_done')
payment_onboarding_payment_method = fields.Selection(
string="Selected onboarding payment method",
selection=[
('paypal', "PayPal"),
('stripe', "Stripe"),
('manual', "Manual"),
('other', "Other"),
])
@api.model
def action_open_payment_onboarding_payment_acquirer(self):
""" Called by onboarding panel above the customer invoice list. """
# TODO remove me in master.
# This action is never used anywhere because the onboarding step's method is overridden in
# website_sale to call action_open_website_sale_onboarding_payment_acquirer instead.
# Fail if there are no existing accounts
self.env.company.get_chart_of_accounts_or_fail()
action = self.env['ir.actions.actions']._for_xml_id(
'payment.action_open_payment_onboarding_payment_acquirer_wizard'
)
return action
def _run_payment_onboarding_step(self, menu_id):
""" Install the suggested payment modules and configure the acquirers.
It's checked that the current company has a Chart of Account.
:param int menu_id: The menu from which the user started the onboarding step, as an
`ir.ui.menu` id
:return: The action returned by `action_stripe_connect_account`
:rtype: dict
"""
self.env.company.get_chart_of_accounts_or_fail()
self._install_modules(['payment_stripe', 'account_payment'])
# Create a new env including the freshly installed module(s)
new_env = api.Environment(self.env.cr, self.env.uid, self.env.context)
# Configure Stripe
default_journal = new_env['account.journal'].search(
[('type', '=', 'bank'), ('company_id', '=', new_env.company.id)], limit=1
)
stripe_acquirer = new_env['payment.acquirer'].search(
[('company_id', '=', self.env.company.id), ('name', '=', 'Stripe')], limit=1
)
if not stripe_acquirer:
base_acquirer = self.env.ref('payment.payment_acquirer_stripe')
# Use sudo to access payment acquirer record that can be in different company.
stripe_acquirer = base_acquirer.sudo().copy(default={'company_id': self.env.company.id})
stripe_acquirer.company_id = self.env.company.id
stripe_acquirer.journal_id = stripe_acquirer.journal_id or default_journal
return stripe_acquirer.action_stripe_connect_account(menu_id=menu_id)
def _install_modules(self, module_names):
modules_sudo = self.env['ir.module.module'].sudo().search([('name', 'in', module_names)])
STATES = ['installed', 'to install', 'to upgrade']
modules_sudo.filtered(lambda m: m.state not in STATES).button_immediate_install()
def _mark_payment_onboarding_step_as_done(self):
""" Mark the payment onboarding step as done.
:return: None
"""
self.set_onboarding_step_done('payment_acquirer_onboarding_state')
def get_account_invoice_onboarding_steps_states_names(self):
""" Override of account. """
steps = super().get_account_invoice_onboarding_steps_states_names()
return steps + ['payment_acquirer_onboarding_state']
| 43.541176 | 3,701 |
913 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
payment_token_ids = fields.One2many(
string="Payment Tokens", comodel_name='payment.token', inverse_name='partner_id')
payment_token_count = fields.Integer(
string="Payment Token Count", compute='_compute_payment_token_count')
@api.depends('payment_token_ids')
def _compute_payment_token_count(self):
payments_data = self.env['payment.token'].read_group(
[('partner_id', 'in', self.ids)], ['partner_id'], ['partner_id']
)
partners_data = {payment_data['partner_id'][0]: payment_data['partner_id_count']
for payment_data in payments_data}
for partner in self:
partner.payment_token_count = partners_data.get(partner.id, 0)
| 41.5 | 913 |
820 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class PaymentIcon(models.Model):
_name = 'payment.icon'
_description = 'Payment Icon'
_order = 'sequence, name'
name = fields.Char(string="Name")
acquirer_ids = fields.Many2many(
string="Acquirers", comodel_name='payment.acquirer',
help="The list of acquirers supporting this payment icon")
image = fields.Image(
string="Image", max_width=64, max_height=64,
help="This field holds the image used for this payment icon, limited to 64x64 px")
image_payment_form = fields.Image(
string="Image displayed on the payment form", related='image', store=True, max_width=45,
max_height=30)
sequence = fields.Integer('Sequence', default=1)
| 39.047619 | 820 |
4,279 |
py
|
PYTHON
|
15.0
|
from odoo import api, Command, fields, models
class AccountPaymentRegister(models.TransientModel):
_inherit = 'account.payment.register'
# == Business fields ==
payment_token_id = fields.Many2one(
comodel_name='payment.token',
string="Saved payment token",
store=True, readonly=False,
compute='_compute_payment_token_id',
domain='''[
('id', 'in', suitable_payment_token_ids),
]''',
help="Note that tokens from acquirers set to only authorize transactions (instead of capturing the amount) are "
"not available.")
# == Display purpose fields ==
suitable_payment_token_ids = fields.Many2many(
comodel_name='payment.token',
compute='_compute_suitable_payment_token_ids'
)
use_electronic_payment_method = fields.Boolean(
compute='_compute_use_electronic_payment_method',
help='Technical field used to hide or show the payment_token_id if needed.'
)
payment_method_code = fields.Char(
related='payment_method_line_id.code')
# -------------------------------------------------------------------------
# COMPUTE METHODS
# -------------------------------------------------------------------------
@api.depends('payment_method_line_id')
def _compute_suitable_payment_token_ids(self):
for wizard in self:
if wizard.can_edit_wizard and wizard.use_electronic_payment_method:
related_partner_ids = (
wizard.partner_id
| wizard.partner_id.commercial_partner_id
| wizard.partner_id.commercial_partner_id.child_ids
)._origin
wizard.suitable_payment_token_ids = self.env['payment.token'].sudo().search([
('company_id', '=', wizard.company_id.id),
('acquirer_id.capture_manually', '=', False),
('partner_id', 'in', related_partner_ids.ids),
('acquirer_id', '=', wizard.payment_method_line_id.payment_acquirer_id.id),
])
else:
wizard.suitable_payment_token_ids = [Command.clear()]
@api.depends('payment_method_line_id')
def _compute_use_electronic_payment_method(self):
for wizard in self:
# Get a list of all electronic payment method codes.
# These codes are comprised of the providers of each payment acquirer.
codes = [key for key in dict(self.env['payment.acquirer']._fields['provider']._description_selection(self.env))]
wizard.use_electronic_payment_method = wizard.payment_method_code in codes
@api.onchange('can_edit_wizard', 'payment_method_line_id', 'journal_id')
def _compute_payment_token_id(self):
codes = [key for key in dict(self.env['payment.acquirer']._fields['provider']._description_selection(self.env))]
for wizard in self:
related_partner_ids = (
wizard.partner_id
| wizard.partner_id.commercial_partner_id
| wizard.partner_id.commercial_partner_id.child_ids
)._origin
if wizard.can_edit_wizard \
and wizard.payment_method_line_id.code in codes \
and wizard.journal_id \
and related_partner_ids:
wizard.payment_token_id = self.env['payment.token'].sudo().search([
('company_id', '=', wizard.company_id.id),
('partner_id', 'in', related_partner_ids.ids),
('acquirer_id.capture_manually', '=', False),
('acquirer_id', '=', wizard.payment_method_line_id.payment_acquirer_id.id),
], limit=1)
else:
wizard.payment_token_id = False
# -------------------------------------------------------------------------
# BUSINESS METHODS
# -------------------------------------------------------------------------
def _create_payment_vals_from_wizard(self):
# OVERRIDE
payment_vals = super()._create_payment_vals_from_wizard()
payment_vals['payment_token_id'] = self.payment_token_id.id
return payment_vals
| 46.010753 | 4,279 |
9,820 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import etree
from werkzeug import urls
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.tools import float_compare
from odoo.addons.payment import utils as payment_utils
class PaymentLinkWizard(models.TransientModel):
_name = "payment.link.wizard"
_description = "Generate Payment Link"
@api.model
def default_get(self, fields):
res = super(PaymentLinkWizard, self).default_get(fields)
res_id = self._context.get('active_id')
res_model = self._context.get('active_model')
res.update({'res_id': res_id, 'res_model': res_model})
amount_field = 'amount_residual' if res_model == 'account.move' else 'amount_total'
if res_id and res_model == 'account.move':
record = self.env[res_model].browse(res_id)
res.update({
'description': record.payment_reference,
'amount': record[amount_field],
'currency_id': record.currency_id.id,
'partner_id': record.partner_id.id,
'amount_max': record[amount_field],
})
return res
@api.model
def fields_view_get(self, *args, **kwargs):
""" Overrides orm fields_view_get
Using a Many2One field, when a user opens this wizard and tries to select a preferred
payment acquirer, he will get an AccessError telling that he is not allowed to access
'payment.acquirer' records. This error is thrown because the Many2One field is filled
by the name_get() function and users don't have clearance to read 'payment.acquirer' records.
This override allows replacing the Many2One with a selection field, that is prefilled in the
backend with the name of available acquirers. Therefore, Users will be able to select their
preferred acquirer.
:return: composition of the requested view (including inherited views and extensions)
:rtype: dict
"""
res = super().fields_view_get(*args, **kwargs)
if res['type'] == 'form':
doc = etree.XML(res['arch'])
# Replace acquirer_id with payment_acquirer_selection in the view
acq = doc.xpath("//field[@name='acquirer_id']")[0]
acq.attrib['name'] = 'payment_acquirer_selection'
acq.attrib['widget'] = 'selection'
acq.attrib['string'] = _('Force Payment Acquirer')
del acq.attrib['options']
del acq.attrib['placeholder']
# Replace acquirer_id with payment_acquirer_selection in the fields list
xarch, xfields = self.env['ir.ui.view'].postprocess_and_fields(doc, model=self._name)
res['arch'] = xarch
res['fields'] = xfields
return res
res_model = fields.Char('Related Document Model', required=True)
res_id = fields.Integer('Related Document ID', required=True)
amount = fields.Monetary(currency_field='currency_id', required=True)
amount_max = fields.Monetary(currency_field='currency_id')
currency_id = fields.Many2one('res.currency')
partner_id = fields.Many2one('res.partner')
partner_email = fields.Char(related='partner_id.email')
link = fields.Char(string='Payment Link', compute='_compute_values')
description = fields.Char('Payment Ref')
access_token = fields.Char(compute='_compute_values')
company_id = fields.Many2one('res.company', compute='_compute_company')
available_acquirer_ids = fields.Many2many(
comodel_name='payment.acquirer',
string="Payment Acquirers Available",
compute='_compute_available_acquirer_ids',
compute_sudo=True,
)
acquirer_id = fields.Many2one(
comodel_name='payment.acquirer',
string="Force Payment Acquirer",
domain="[('id', 'in', available_acquirer_ids)]",
help="Force the customer to pay via the specified payment acquirer. Leave empty to allow the customer to choose among all acquirers."
)
has_multiple_acquirers = fields.Boolean(
string="Has Multiple Acquirers",
compute='_compute_has_multiple_acquirers',
)
payment_acquirer_selection = fields.Selection(
string="Payment acquirer selected",
selection='_selection_payment_acquirer_selection',
default='all',
compute='_compute_payment_acquirer_selection',
inverse='_inverse_payment_acquirer_selection',
required=True,
)
@api.onchange('amount', 'description')
def _onchange_amount(self):
if float_compare(self.amount_max, self.amount, precision_rounding=self.currency_id.rounding or 0.01) == -1:
raise ValidationError(_("Please set an amount smaller than %s.") % (self.amount_max))
if self.amount <= 0:
raise ValidationError(_("The value of the payment amount must be positive."))
@api.depends('amount', 'description', 'partner_id', 'currency_id', 'payment_acquirer_selection')
def _compute_values(self):
for payment_link in self:
payment_link.access_token = payment_utils.generate_access_token(
payment_link.partner_id.id, payment_link.amount, payment_link.currency_id.id
)
# must be called after token generation, obvsly - the link needs an up-to-date token
self._generate_link()
@api.depends('res_model', 'res_id')
def _compute_company(self):
for link in self:
record = self.env[link.res_model].browse(link.res_id)
link.company_id = record.company_id if 'company_id' in record else False
@api.depends('company_id', 'partner_id', 'currency_id')
def _compute_available_acquirer_ids(self):
for link in self:
link.available_acquirer_ids = link._get_payment_acquirer_available()
@api.depends('acquirer_id')
def _compute_payment_acquirer_selection(self):
for link in self:
link.payment_acquirer_selection = link.acquirer_id.id if link.acquirer_id else 'all'
def _inverse_payment_acquirer_selection(self):
for link in self:
link.acquirer_id = link.payment_acquirer_selection if link.payment_acquirer_selection != 'all' else False
def _selection_payment_acquirer_selection(self):
""" Specify available acquirers in the selection field.
:return: The selection list of available acquirers.
:rtype: list[tuple]
"""
defaults = self.default_get(['res_model', 'res_id'])
selection = [('all', "All")]
res_model, res_id = defaults['res_model'], defaults['res_id']
if res_id and res_model in ['account.move', "sale.order"]:
# At module install, the selection method is called
# but the document context isn't specified.
related_document = self.env[res_model].browse(res_id)
company_id = related_document.company_id
partner_id = related_document.partner_id
currency_id = related_document.currency_id
if res_model == "sale.order":
# If the Order contains a recurring product but is not already linked to a
# subscription, the payment acquirer must support tokenization. The res_id allows
# the overrides of sale_subscription to check this condition.
selection.extend(
self._get_payment_acquirer_available(
company_id.id, partner_id.id, currency_id.id, res_id,
).name_get()
)
else:
selection.extend(
self._get_payment_acquirer_available(
company_id.id, partner_id.id, currency_id.id,
).name_get()
)
return selection
def _get_payment_acquirer_available(self, company_id=None, partner_id=None, currency_id=None):
""" Select and return the acquirers matching the criteria.
:param int company_id: The company to which acquirers must belong, as a `res.company` id
:param int partner_id: The partner making the payment, as a `res.partner` id
:param int currency_id: The payment currency if known beforehand, as a `res.currency` id
:return: The compatible acquirers
:rtype: recordset of `payment.acquirer`
"""
return self.env['payment.acquirer'].sudo()._get_compatible_acquirers(
company_id=company_id or self.company_id.id,
partner_id=partner_id or self.partner_id.id,
currency_id=currency_id or self.currency_id.id
)
@api.depends('available_acquirer_ids')
def _compute_has_multiple_acquirers(self):
for link in self:
link.has_multiple_acquirers = len(link.available_acquirer_ids) > 1
def _generate_link(self):
for payment_link in self:
related_document = self.env[payment_link.res_model].browse(payment_link.res_id)
base_url = related_document.get_base_url() # Don't generate links for the wrong website
payment_link.link = f'{base_url}/payment/pay' \
f'?reference={urls.url_quote(payment_link.description)}' \
f'&amount={payment_link.amount}' \
f'¤cy_id={payment_link.currency_id.id}' \
f'&partner_id={payment_link.partner_id.id}' \
f'&company_id={payment_link.company_id.id}' \
f'&invoice_id={payment_link.res_id}' \
f'{"&acquirer_id=" + str(payment_link.payment_acquirer_selection) if payment_link.payment_acquirer_selection != "all" else "" }' \
f'&access_token={payment_link.access_token}'
| 47.902439 | 9,820 |
9,414 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class PaymentWizard(models.TransientModel):
_name = 'payment.acquirer.onboarding.wizard'
_description = 'Payment acquire onboarding wizard'
payment_method = fields.Selection([
('paypal', "PayPal"),
('stripe', "Credit card (via Stripe)"),
('other', "Other payment acquirer"),
('manual', "Custom payment instructions"),
], string="Payment Method", default=lambda self: self._get_default_payment_acquirer_onboarding_value('payment_method'))
paypal_user_type = fields.Selection([
('new_user', "I don't have a Paypal account"),
('existing_user', 'I have a Paypal account')], string="Paypal User Type", default='new_user')
paypal_email_account = fields.Char("Email", default=lambda self: self._get_default_payment_acquirer_onboarding_value('paypal_email_account'))
paypal_seller_account = fields.Char("Merchant Account ID")
paypal_pdt_token = fields.Char("PDT Identity Token", default=lambda self: self._get_default_payment_acquirer_onboarding_value('paypal_pdt_token'))
stripe_secret_key = fields.Char(default=lambda self: self._get_default_payment_acquirer_onboarding_value('stripe_secret_key'))
stripe_publishable_key = fields.Char(default=lambda self: self._get_default_payment_acquirer_onboarding_value('stripe_publishable_key'))
manual_name = fields.Char("Method", default=lambda self: self._get_default_payment_acquirer_onboarding_value('manual_name'))
journal_name = fields.Char("Bank Name", default=lambda self: self._get_default_payment_acquirer_onboarding_value('journal_name'))
acc_number = fields.Char("Account Number", default=lambda self: self._get_default_payment_acquirer_onboarding_value('acc_number'))
manual_post_msg = fields.Html("Payment Instructions")
_data_fetched = fields.Boolean(store=False)
@api.onchange('journal_name', 'acc_number')
def _set_manual_post_msg_value(self):
self.manual_post_msg = _(
'<h3>Please make a payment to: </h3><ul><li>Bank: %s</li><li>Account Number: %s</li><li>Account Holder: %s</li></ul>',
self.journal_name or _("Bank"),
self.acc_number or _("Account"),
self.env.company.name
)
_payment_acquirer_onboarding_cache = {}
def _get_manual_payment_acquirer(self, env=None):
if env is None:
env = self.env
module_id = env.ref('base.module_payment_transfer').id
return env['payment.acquirer'].search([('module_id', '=', module_id),
('company_id', '=', env.company.id)], limit=1)
def _get_default_payment_acquirer_onboarding_value(self, key):
if not self.env.is_admin():
raise UserError(_("Only administrators can access this data."))
if self._data_fetched:
return self._payment_acquirer_onboarding_cache.get(key, '')
self._data_fetched = True
self._payment_acquirer_onboarding_cache['payment_method'] = self.env.company.payment_onboarding_payment_method
installed_modules = self.env['ir.module.module'].sudo().search([
('name', 'in', ('payment_paypal', 'payment_stripe')),
('state', '=', 'installed'),
]).mapped('name')
if 'payment_paypal' in installed_modules:
acquirer = self.env['payment.acquirer'].search(
[('company_id', '=', self.env.company.id), ('name', '=', 'PayPal')], limit=1
)
self._payment_acquirer_onboarding_cache['paypal_email_account'] = acquirer['paypal_email_account'] or self.env.user.email or ''
self._payment_acquirer_onboarding_cache['paypal_pdt_token'] = acquirer['paypal_pdt_token']
if 'payment_stripe' in installed_modules:
acquirer = self.env['payment.acquirer'].search(
[('company_id', '=', self.env.company.id), ('name', '=', 'Stripe')], limit=1
)
self._payment_acquirer_onboarding_cache['stripe_secret_key'] = acquirer['stripe_secret_key']
self._payment_acquirer_onboarding_cache['stripe_publishable_key'] = acquirer['stripe_publishable_key']
manual_payment = self._get_manual_payment_acquirer()
journal = manual_payment.journal_id
self._payment_acquirer_onboarding_cache['manual_name'] = manual_payment['name']
self._payment_acquirer_onboarding_cache['manual_post_msg'] = manual_payment['pending_msg']
self._payment_acquirer_onboarding_cache['journal_name'] = journal.name if journal.name != "Bank" else ""
self._payment_acquirer_onboarding_cache['acc_number'] = journal.bank_acc_number
return self._payment_acquirer_onboarding_cache.get(key, '')
def _install_module(self, module_name):
module = self.env['ir.module.module'].sudo().search([('name', '=', module_name)])
if module.state not in ('installed', 'to install', 'to upgrade'):
module.button_immediate_install()
def _on_save_payment_acquirer(self):
self._install_module('account_payment')
def add_payment_methods(self):
""" Install required payment acquiers, configure them and mark the
onboarding step as done."""
if self.payment_method == 'stripe' and not self.stripe_publishable_key:
self.env.company.payment_onboarding_payment_method = self.payment_method
return self._start_stripe_onboarding()
if self.payment_method == 'paypal':
self._install_module('payment_paypal')
if self.payment_method == 'stripe':
self._install_module('payment_stripe')
if self.payment_method in ('paypal', 'stripe', 'manual', 'other'):
self._on_save_payment_acquirer()
self.env.company.payment_onboarding_payment_method = self.payment_method
# create a new env including the freshly installed module(s)
new_env = api.Environment(self.env.cr, self.env.uid, self.env.context)
if self.payment_method == 'paypal':
acquirer = new_env['payment.acquirer'].search(
[('name', '=', 'PayPal'), ('company_id', '=', self.env.company.id)], limit=1
)
if not acquirer:
base_acquirer = self.env.ref('payment.payment_acquirer_paypal')
# Use sudo to access payment acquirer record that can be in different company.
acquirer = base_acquirer.sudo().copy(
default={'company_id': self.env.company.id}
)
acquirer.company_id = self.env.company.id
default_journal = new_env['account.journal'].search(
[('type', '=', 'bank'), ('company_id', '=', new_env.company.id)], limit=1
)
acquirer.write({
'paypal_email_account': self.paypal_email_account,
'paypal_seller_account': self.paypal_seller_account,
'paypal_pdt_token': self.paypal_pdt_token,
'state': 'enabled',
'journal_id': acquirer.journal_id or default_journal
})
if self.payment_method == 'stripe':
new_env['payment.acquirer'].search(
[('name', '=', 'Stripe'), ('company_id', '=', self.env.company.id)], limit=1
).write({
'stripe_secret_key': self.stripe_secret_key,
'stripe_publishable_key': self.stripe_publishable_key,
'state': 'enabled',
})
if self.payment_method == 'manual':
manual_acquirer = self._get_manual_payment_acquirer(new_env)
if not manual_acquirer:
raise UserError(_(
'No manual payment method could be found for this company. '
'Please create one from the Payment Acquirer menu.'
))
manual_acquirer.name = self.manual_name
manual_acquirer.pending_msg = self.manual_post_msg
manual_acquirer.state = 'enabled'
journal = manual_acquirer.journal_id
if journal:
journal.name = self.journal_name
journal.bank_acc_number = self.acc_number
# delete wizard data immediately to get rid of residual credentials
self.sudo().unlink()
# the user clicked `apply` and not cancel so we can assume this step is done.
self._set_payment_acquirer_onboarding_step_done()
return {'type': 'ir.actions.act_window_close'}
def _set_payment_acquirer_onboarding_step_done(self):
self.env.company.sudo().set_onboarding_step_done('payment_acquirer_onboarding_state')
def action_onboarding_other_payment_acquirer(self):
self._set_payment_acquirer_onboarding_step_done()
action = self.env["ir.actions.actions"]._for_xml_id("payment.action_payment_acquirer")
return action
def _start_stripe_onboarding(self):
""" Start Stripe Connect onboarding. """
menu_id = self.env.ref('payment.payment_acquirer_menu').id
return self.env.company._run_payment_onboarding_step(menu_id)
| 50.886486 | 9,414 |
2,965 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class PaymentRefundWizard(models.TransientModel):
_name = 'payment.refund.wizard'
_description = "Payment Refund Wizard"
payment_id = fields.Many2one(
string="Payment",
comodel_name='account.payment',
readonly=True,
default=lambda self: self.env.context.get('active_id'),
)
transaction_id = fields.Many2one(
string="Payment Transaction", related='payment_id.payment_transaction_id'
)
payment_amount = fields.Monetary(string="Payment Amount", related='payment_id.amount')
refunded_amount = fields.Monetary(string="Refunded Amount", compute='_compute_refunded_amount')
amount_available_for_refund = fields.Monetary(
string="Maximum Refund Allowed", related='payment_id.amount_available_for_refund'
)
amount_to_refund = fields.Monetary(
string="Refund Amount", compute='_compute_amount_to_refund', store=True, readonly=False
)
currency_id = fields.Many2one(string="Currency", related='transaction_id.currency_id')
support_refund = fields.Selection(related='transaction_id.acquirer_id.support_refund')
has_pending_refund = fields.Boolean(
string="Has a pending refund", compute='_compute_has_pending_refund'
)
@api.constrains('amount_to_refund')
def _check_amount_to_refund_within_boundaries(self):
for wizard in self:
if not 0 < wizard.amount_to_refund <= wizard.amount_available_for_refund:
raise ValidationError(_(
"The amount to be refunded must be positive and cannot be superior to %s.",
wizard.amount_available_for_refund
))
@api.depends('amount_available_for_refund')
def _compute_refunded_amount(self):
for wizard in self:
wizard.refunded_amount = wizard.payment_amount - wizard.amount_available_for_refund
@api.depends('amount_available_for_refund')
def _compute_amount_to_refund(self):
""" Set the default amount to refund to the amount available for refund. """
for wizard in self:
wizard.amount_to_refund = wizard.amount_available_for_refund
@api.depends('payment_id') # To always trigger the compute
def _compute_has_pending_refund(self):
for wizard in self:
pending_refunds_count = self.env['payment.transaction'].search_count([
('source_transaction_id', '=', wizard.payment_id.payment_transaction_id.id),
('operation', '=', 'refund'),
('state', 'in', ['draft', 'pending', 'authorized']),
])
wizard.has_pending_refund = pending_refunds_count > 0
def action_refund(self):
for wizard in self:
wizard.transaction_id.action_refund(amount_to_refund=wizard.amount_to_refund)
| 44.924242 | 2,965 |
22,894 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import urllib.parse
import werkzeug
from odoo import _, http
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.fields import Command
from odoo.http import request
from odoo.addons.payment import utils as payment_utils
from odoo.addons.payment.controllers.post_processing import PaymentPostProcessing
from odoo.addons.portal.controllers import portal
class PaymentPortal(portal.CustomerPortal):
""" This controller contains the foundations for online payments through the portal.
It allows to complete a full payment flow without the need of going though a document-based flow
made available by another module's controller.
Such controllers should extend this one to gain access to the _create_transaction static method
that implements the creation of a transaction before its processing, or to override specific
routes and change their behavior globally (e.g. make the /pay route handle sale orders).
The following routes are exposed:
- `/payment/pay` allows for arbitrary payments.
- `/my/payment_method` allows the user to create and delete tokens. It's its own `landing_route`
- `/payment/transaction` is the `transaction_route` for the standard payment flow. It creates a
draft transaction, and return the processing values necessary for the completion of the
transaction.
- `/payment/confirmation` is the `landing_route` for the standard payment flow. It displays the
payment confirmation page to the user when the transaction is validated.
"""
@http.route(
'/payment/pay', type='http', methods=['GET'], auth='public', website=True, sitemap=False,
)
def payment_pay(
self, reference=None, amount=None, currency_id=None, partner_id=None, company_id=None,
acquirer_id=None, access_token=None, invoice_id=None, **kwargs
):
""" Display the payment form with optional filtering of payment options.
The filtering takes place on the basis of provided parameters, if any. If a parameter is
incorrect or malformed, it is skipped to avoid preventing the user from making the payment.
In addition to the desired filtering, a second one ensures that none of the following
rules is broken:
- Public users are not allowed to save their payment method as a token.
- Payments made by public users should either *not* be made on behalf of a specific
partner or have an access token validating the partner, amount and currency.
We let access rights and security rules do their job for logged in users.
:param str reference: The custom prefix to compute the full reference
:param str amount: The amount to pay
:param str currency_id: The desired currency, as a `res.currency` id
:param str partner_id: The partner making the payment, as a `res.partner` id
:param str company_id: The related company, as a `res.company` id
:param str acquirer_id: The desired acquirer, as a `payment.acquirer` id
:param str access_token: The access token used to authenticate the partner
:param str invoice_id: The account move for which a payment id made, as a `account.move` id
:param dict kwargs: Optional data. This parameter is not used here
:return: The rendered checkout form
:rtype: str
:raise: werkzeug.exceptions.NotFound if the access token is invalid
"""
# Cast numeric parameters as int or float and void them if their str value is malformed
currency_id, acquirer_id, partner_id, company_id, invoice_id = tuple(map(
self._cast_as_int, (currency_id, acquirer_id, partner_id, company_id, invoice_id)
))
amount = self._cast_as_float(amount)
# Raise an HTTP 404 if a partner is provided with an invalid access token
if partner_id:
if not payment_utils.check_access_token(access_token, partner_id, amount, currency_id):
raise werkzeug.exceptions.NotFound # Don't leak info about the existence of an id
user_sudo = request.env.user
logged_in = not user_sudo._is_public()
# If the user is logged in, take their partner rather than the partner set in the params.
# This is something that we want, since security rules are based on the partner, and created
# tokens should not be assigned to the public user. This should have no impact on the
# transaction itself besides making reconciliation possibly more difficult (e.g. The
# transaction and invoice partners are different).
partner_is_different = False
if logged_in:
partner_is_different = partner_id and partner_id != user_sudo.partner_id.id
partner_sudo = user_sudo.partner_id
else:
partner_sudo = request.env['res.partner'].sudo().browse(partner_id).exists()
if not partner_sudo:
return request.redirect(
# Escape special characters to avoid loosing original params when redirected
f'/web/login?redirect={urllib.parse.quote(request.httprequest.full_path)}'
)
# Instantiate transaction values to their default if not set in parameters
reference = reference or payment_utils.singularize_reference_prefix(prefix='tx')
amount = amount or 0.0 # If the amount is invalid, set it to 0 to stop the payment flow
company_id = company_id or partner_sudo.company_id.id or user_sudo.company_id.id
company = request.env['res.company'].sudo().browse(company_id)
currency_id = currency_id or company.currency_id.id
# Make sure that the currency exists and is active
currency = request.env['res.currency'].browse(currency_id).exists()
if not currency or not currency.active:
raise werkzeug.exceptions.NotFound # The currency must exist and be active
# Select all acquirers and tokens that match the constraints
acquirers_sudo = request.env['payment.acquirer'].sudo()._get_compatible_acquirers(
company_id, partner_sudo.id, currency_id=currency.id, **kwargs
) # In sudo mode to read the fields of acquirers and partner (if not logged in)
if acquirer_id in acquirers_sudo.ids: # Only keep the desired acquirer if it's suitable
acquirers_sudo = acquirers_sudo.browse(acquirer_id)
payment_tokens = request.env['payment.token'].search(
[('acquirer_id', 'in', acquirers_sudo.ids), ('partner_id', '=', partner_sudo.id)]
) if logged_in else request.env['payment.token']
# Make sure that the partner's company matches the company passed as parameter.
if not PaymentPortal._can_partner_pay_in_company(partner_sudo, company):
acquirers_sudo = request.env['payment.acquirer'].sudo()
payment_tokens = request.env['payment.token']
# Compute the fees taken by acquirers supporting the feature
fees_by_acquirer = {
acq_sudo: acq_sudo._compute_fees(amount, currency, partner_sudo.country_id)
for acq_sudo in acquirers_sudo.filtered('fees_active')
}
# Generate a new access token in case the partner id or the currency id was updated
access_token = payment_utils.generate_access_token(partner_sudo.id, amount, currency.id)
rendering_context = {
'acquirers': acquirers_sudo,
'tokens': payment_tokens,
'fees_by_acquirer': fees_by_acquirer,
'show_tokenize_input': logged_in, # Prevent public partner from saving payment methods
'reference_prefix': reference,
'amount': amount,
'currency': currency,
'partner_id': partner_sudo.id,
'access_token': access_token,
'transaction_route': '/payment/transaction',
'landing_route': '/payment/confirmation',
'res_company': company, # Display the correct logo in a multi-company environment
'partner_is_different': partner_is_different,
'invoice_id': invoice_id,
**self._get_custom_rendering_context_values(**kwargs),
}
return request.render(self._get_payment_page_template_xmlid(**kwargs), rendering_context)
def _get_payment_page_template_xmlid(self, **kwargs):
return 'payment.pay'
@http.route('/my/payment_method', type='http', methods=['GET'], auth='user', website=True)
def payment_method(self, **kwargs):
""" Display the form to manage payment methods.
:param dict kwargs: Optional data. This parameter is not used here
:return: The rendered manage form
:rtype: str
"""
partner = request.env.user.partner_id
acquirers_sudo = request.env['payment.acquirer'].sudo()._get_compatible_acquirers(
request.env.company.id, partner.id, force_tokenization=True, is_validation=True
)
tokens = set(partner.payment_token_ids).union(
partner.commercial_partner_id.sudo().payment_token_ids
) # Show all partner's tokens, regardless of which acquirer is available
access_token = payment_utils.generate_access_token(partner.id, None, None)
rendering_context = {
'acquirers': acquirers_sudo,
'tokens': tokens,
'reference_prefix': payment_utils.singularize_reference_prefix(prefix='validation'),
'partner_id': partner.id,
'access_token': access_token,
'transaction_route': '/payment/transaction',
'landing_route': '/my/payment_method',
**self._get_custom_rendering_context_values(**kwargs),
}
return request.render('payment.payment_methods', rendering_context)
def _get_custom_rendering_context_values(self, **kwargs):
""" Return a dict of additional rendering context values.
:param dict kwargs: Optional data. This parameter is not used here
:return: The dict of additional rendering context values
:rtype: dict
"""
return {}
@http.route('/payment/transaction', type='json', auth='public')
def payment_transaction(self, amount, currency_id, partner_id, access_token, **kwargs):
""" Create a draft transaction and return its processing values.
:param float|None amount: The amount to pay in the given currency.
None if in a payment method validation operation
:param int|None currency_id: The currency of the transaction, as a `res.currency` id.
None if in a payment method validation operation
:param int partner_id: The partner making the payment, as a `res.partner` id
:param str access_token: The access token used to authenticate the partner
:param dict kwargs: Locally unused data passed to `_create_transaction`
:return: The mandatory values for the processing of the transaction
:rtype: dict
:raise: ValidationError if the access token is invalid
"""
# Check the access token against the transaction values
amount = amount and float(amount) # Cast as float in case the JS stripped the '.0'
if not payment_utils.check_access_token(access_token, partner_id, amount, currency_id):
raise ValidationError(_("The access token is invalid."))
kwargs.pop('custom_create_values', None) # Don't allow passing arbitrary create values
tx_sudo = self._create_transaction(
amount=amount, currency_id=currency_id, partner_id=partner_id, **kwargs
)
self._update_landing_route(tx_sudo, access_token) # Add the required parameters to the route
return tx_sudo._get_processing_values()
def _create_transaction(
self, payment_option_id, reference_prefix, amount, currency_id, partner_id, flow,
tokenization_requested, landing_route, is_validation=False, invoice_id=None,
custom_create_values=None, **kwargs
):
""" Create a draft transaction based on the payment context and return it.
:param int payment_option_id: The payment option handling the transaction, as a
`payment.acquirer` id or a `payment.token` id
:param str reference_prefix: The custom prefix to compute the full reference
:param float|None amount: The amount to pay in the given currency.
None if in a payment method validation operation
:param int|None currency_id: The currency of the transaction, as a `res.currency` id.
None if in a payment method validation operation
:param int partner_id: The partner making the payment, as a `res.partner` id
:param str flow: The online payment flow of the transaction: 'redirect', 'direct' or 'token'
:param bool tokenization_requested: Whether the user requested that a token is created
:param str landing_route: The route the user is redirected to after the transaction
:param bool is_validation: Whether the operation is a validation
:param int invoice_id: The account move for which a payment id made, as an `account.move` id
:param dict custom_create_values: Additional create values overwriting the default ones
:param dict kwargs: Locally unused data passed to `_is_tokenization_required` and
`_compute_reference`
:return: The sudoed transaction that was created
:rtype: recordset of `payment.transaction`
:raise: UserError if the flow is invalid
"""
# Prepare create values
if flow in ['redirect', 'direct']: # Direct payment or payment with redirection
acquirer_sudo = request.env['payment.acquirer'].sudo().browse(payment_option_id)
token_id = None
tokenization_required_or_requested = acquirer_sudo._is_tokenization_required(
provider=acquirer_sudo.provider, **kwargs
) or tokenization_requested
tokenize = bool(
# Don't tokenize if the user tried to force it through the browser's developer tools
acquirer_sudo.allow_tokenization
# Token is only created if required by the flow or requested by the user
and tokenization_required_or_requested
)
elif flow == 'token': # Payment by token
token_sudo = request.env['payment.token'].sudo().browse(payment_option_id)
# Prevent from paying with a token that doesn't belong to the current partner (either
# the current user's partner if logged in, or the partner on behalf of whom the payment
# is being made).
partner_sudo = request.env['res.partner'].sudo().browse(partner_id)
if partner_sudo.commercial_partner_id != token_sudo.partner_id.commercial_partner_id:
raise AccessError(_("You do not have access to this payment token."))
acquirer_sudo = token_sudo.acquirer_id
token_id = payment_option_id
tokenize = False
else:
raise UserError(
_("The payment should either be direct, with redirection, or made by a token.")
)
if invoice_id:
if custom_create_values is None:
custom_create_values = {}
custom_create_values['invoice_ids'] = [Command.set([int(invoice_id)])]
reference = request.env['payment.transaction']._compute_reference(
acquirer_sudo.provider,
prefix=reference_prefix,
**(custom_create_values or {}),
**kwargs
)
if is_validation: # Acquirers determine the amount and currency in validation operations
amount = acquirer_sudo._get_validation_amount()
currency_id = acquirer_sudo._get_validation_currency().id
# Create the transaction
tx_sudo = request.env['payment.transaction'].sudo().create({
'acquirer_id': acquirer_sudo.id,
'reference': reference,
'amount': amount,
'currency_id': currency_id,
'partner_id': partner_id,
'token_id': token_id,
'operation': f'online_{flow}' if not is_validation else 'validation',
'tokenize': tokenize,
'landing_route': landing_route,
**(custom_create_values or {}),
}) # In sudo mode to allow writing on callback fields
if flow == 'token':
tx_sudo._send_payment_request() # Payments by token process transactions immediately
else:
tx_sudo._log_sent_message()
# Monitor the transaction to make it available in the portal
PaymentPostProcessing.monitor_transactions(tx_sudo)
return tx_sudo
@staticmethod
def _update_landing_route(tx_sudo, access_token):
""" Add the mandatory parameters to the route and recompute the access token if needed.
The generic landing route requires the tx id and access token to be provided since there is
no document to rely on. The access token is recomputed in case we are dealing with a
validation transaction (acquirer-specific amount and currency).
:param recordset tx_sudo: The transaction whose landing routes to update, as a
`payment.transaction` record.
:param str access_token: The access token used to authenticate the partner
:return: None
"""
if tx_sudo.operation == 'validation':
access_token = payment_utils.generate_access_token(
tx_sudo.partner_id.id, tx_sudo.amount, tx_sudo.currency_id.id
)
tx_sudo.landing_route = f'{tx_sudo.landing_route}' \
f'?tx_id={tx_sudo.id}&access_token={access_token}'
@http.route('/payment/confirmation', type='http', methods=['GET'], auth='public', website=True)
def payment_confirm(self, tx_id, access_token, **kwargs):
""" Display the payment confirmation page with the appropriate status message to the user.
:param str tx_id: The transaction to confirm, as a `payment.transaction` id
:param str access_token: The access token used to verify the user
:param dict kwargs: Optional data. This parameter is not used here
:raise: werkzeug.exceptions.NotFound if the access token is invalid
"""
tx_id = self._cast_as_int(tx_id)
if tx_id:
tx_sudo = request.env['payment.transaction'].sudo().browse(tx_id)
# Raise an HTTP 404 if the access token is invalid
if not payment_utils.check_access_token(
access_token, tx_sudo.partner_id.id, tx_sudo.amount, tx_sudo.currency_id.id
):
raise werkzeug.exceptions.NotFound # Don't leak info about existence of an id
# Fetch the appropriate status message configured on the acquirer
if tx_sudo.state == 'draft':
status = 'info'
message = tx_sudo.state_message \
or _("This payment has not been processed yet.")
elif tx_sudo.state == 'pending':
status = 'warning'
message = tx_sudo.acquirer_id.pending_msg
elif tx_sudo.state in ('authorized', 'done'):
status = 'success'
message = tx_sudo.acquirer_id.done_msg
elif tx_sudo.state == 'cancel':
status = 'danger'
message = tx_sudo.acquirer_id.cancel_msg
else:
status = 'danger'
message = tx_sudo.state_message \
or _("An error occurred during the processing of this payment.")
# Display the payment confirmation page to the user
PaymentPostProcessing.remove_transactions(tx_sudo)
render_values = {
'tx': tx_sudo,
'status': status,
'message': message
}
return request.render('payment.confirm', render_values)
else:
# Display the portal homepage to the user
return request.redirect('/my/home')
@http.route('/payment/archive_token', type='json', auth='user')
def archive_token(self, token_id):
""" Check that a user has write access on a token and archive the token if so.
:param int token_id: The token to archive, as a `payment.token` id
:return: None
"""
partner_sudo = request.env.user.partner_id
token_sudo = request.env['payment.token'].sudo().search([
('id', '=', token_id),
# Check that the user owns the token before letting them archive anything
('partner_id', 'in', [partner_sudo.id, partner_sudo.commercial_partner_id.id])
])
if token_sudo:
token_sudo.active = False
@staticmethod
def _cast_as_int(str_value):
""" Cast a string as an `int` and return it.
If the conversion fails, `None` is returned instead.
:param str str_value: The value to cast as an `int`
:return: The casted value, possibly replaced by None if incompatible
:rtype: int|None
"""
try:
return int(str_value)
except (TypeError, ValueError, OverflowError):
return None
@staticmethod
def _cast_as_float(str_value):
""" Cast a string as a `float` and return it.
If the conversion fails, `None` is returned instead.
:param str str_value: The value to cast as a `float`
:return: The casted value, possibly replaced by None if incompatible
:rtype: float|None
"""
try:
return float(str_value)
except (TypeError, ValueError, OverflowError):
return None
@staticmethod
def _can_partner_pay_in_company(partner, document_company):
""" Return whether the provided partner can pay in the provided company.
The payment is allowed either if the partner's company is not set or if the companies match.
:param recordset partner: The partner on behalf on which the payment is made, as a
`res.partner` record.
:param recordset document_company: The company of the document being paid, as a
`res.company` record.
:return: Whether the payment is allowed.
:rtype: str
"""
return not partner.company_id or partner.company_id == document_company
| 51.217002 | 22,894 |
5,406 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import timedelta
import psycopg2
from odoo import fields, http
from odoo.http import request
_logger = logging.getLogger(__name__)
class PaymentPostProcessing(http.Controller):
"""
This controller is responsible for the monitoring and finalization of the post-processing of
transactions.
It exposes the route `/payment/status`: All payment flows must go through this route at some
point to allow the user checking on the transactions' status, and to trigger the finalization of
their post-processing.
"""
MONITORED_TX_IDS_KEY = '__payment_monitored_tx_ids__'
@http.route('/payment/status', type='http', auth='public', website=True, sitemap=False)
def display_status(self, **kwargs):
""" Display the payment status page.
:param dict kwargs: Optional data. This parameter is not used here
:return: The rendered status page
:rtype: str
"""
return request.render('payment.payment_status')
@http.route('/payment/status/poll', type='json', auth='public')
def poll_status(self):
""" Fetch the transactions to display on the status page and finalize their post-processing.
:return: The post-processing values of the transactions
:rtype: dict
"""
# Retrieve recent user's transactions from the session
limit_date = fields.Datetime.now() - timedelta(days=1)
monitored_txs = request.env['payment.transaction'].sudo().search([
('id', 'in', self.get_monitored_transaction_ids()),
('last_state_change', '>=', limit_date)
])
if not monitored_txs: # The transaction was not correctly created
return {
'success': False,
'error': 'no_tx_found',
}
# Build the list of display values with the display message and post-processing values
display_values_list = []
for tx in monitored_txs:
display_message = None
if tx.state == 'pending':
display_message = tx.acquirer_id.pending_msg
elif tx.state == 'done':
display_message = tx.acquirer_id.done_msg
elif tx.state == 'cancel':
display_message = tx.acquirer_id.cancel_msg
display_values_list.append({
'display_message': display_message,
**tx._get_post_processing_values(),
})
# Stop monitoring already post-processed transactions
post_processed_txs = monitored_txs.filtered('is_post_processed')
self.remove_transactions(post_processed_txs)
# Finalize post-processing of transactions before displaying them to the user
txs_to_post_process = (monitored_txs - post_processed_txs).filtered(
lambda t: t.state == 'done'
)
success, error = True, None
try:
txs_to_post_process._finalize_post_processing()
except psycopg2.OperationalError: # A collision of accounting sequences occurred
request.env.cr.rollback() # Rollback and try later
success = False
error = 'tx_process_retry'
except Exception as e:
request.env.cr.rollback()
success = False
error = str(e)
_logger.exception(
"encountered an error while post-processing transactions with ids %s:\n%s",
', '.join([str(tx_id) for tx_id in txs_to_post_process.ids]), e
)
return {
'success': success,
'error': error,
'display_values_list': display_values_list,
}
@classmethod
def monitor_transactions(cls, transactions):
""" Add the ids of the provided transactions to the list of monitored transaction ids.
:param recordset transactions: The transactions to monitor, as a `payment.transaction`
recordset
:return: None
"""
if transactions:
monitored_tx_ids = request.session.get(cls.MONITORED_TX_IDS_KEY, [])
request.session[cls.MONITORED_TX_IDS_KEY] = list(
set(monitored_tx_ids).union(transactions.ids)
)
@classmethod
def get_monitored_transaction_ids(cls):
""" Return the ids of transactions being monitored.
Only the ids and not the recordset itself is returned to allow the caller browsing the
recordset with sudo privileges, and using the ids in a custom query.
:return: The ids of transactions being monitored
:rtype: list
"""
return request.session.get(cls.MONITORED_TX_IDS_KEY, [])
@classmethod
def remove_transactions(cls, transactions):
""" Remove the ids of the provided transactions from the list of monitored transaction ids.
:param recordset transactions: The transactions to remove, as a `payment.transaction`
recordset
:return: None
"""
if transactions:
monitored_tx_ids = request.session.get(cls.MONITORED_TX_IDS_KEY, [])
request.session[cls.MONITORED_TX_IDS_KEY] = [
tx_id for tx_id in monitored_tx_ids if tx_id not in transactions.ids
]
| 38.892086 | 5,406 |
737 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Product Images',
'version': '1.0',
'description': """
Automatically set product images based on the barcode
=====================================================
This module integrates with the Google Custom Search API to set images on products based on the
barcode.
""",
'license': 'LGPL-3',
'category': 'Technical',
'depends': ['product'],
'data': [
'data/ir_cron_data.xml',
'security/product_security.xml',
'security/ir.model.access.csv',
'views/res_config_settings_views.xml',
'wizard/product_fetch_image_wizard_views.xml',
],
'uninstall_hook': 'uninstall_hook',
}
| 30.708333 | 737 |
15,511 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import logging
from datetime import timedelta
import requests
from requests.exceptions import ConnectionError as RequestConnectionError
from odoo import _, api, fields, models
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
class ProductFetchImageWizard(models.TransientModel):
_name = 'product.fetch.image.wizard'
_description = "Fetch product images from Google Images based on the product's barcode number."
_session = requests.Session()
@api.model
def default_get(self, fields_list):
# Check that the cron has not been deleted and raise an error if so
ir_cron_fetch_image = self.env.ref(
'product_images.ir_cron_fetch_image', raise_if_not_found=False
)
if not ir_cron_fetch_image:
raise UserError(_(
"The scheduled action \"Product Images: Get product images from Google\" has "
"been deleted. Please contact your administrator to have the action restored "
"or to reinstall the module \"product_images\"."
))
# Check that the cron is not already triggered and raise an error if so
cron_triggers_count = self.env['ir.cron.trigger'].search_count(
[('cron_id', '=', ir_cron_fetch_image.id)]
)
if cron_triggers_count > 0:
raise UserError(_(
"A task to process products in the background is already running. Please try again"
"later."
))
# Check if API keys are set without retrieving the values to avoid leaking them
ICP = self.env['ir.config_parameter']
google_pse_id_is_set = bool(ICP.get_param('google.pse.id'))
google_custom_search_key_is_set = bool(ICP.get_param('google.custom_search.key'))
if not (google_pse_id_is_set and google_custom_search_key_is_set):
raise UserError(_(
"The API Key and Search Engine ID must be set in the General Settings."
))
# Compute default values
if self._context.get('active_model') == 'product.template':
product_ids = self.env['product.template'].browse(
self._context.get('active_ids')
).product_variant_ids
else:
product_ids = self.env['product.product'].browse(
self._context.get('active_ids')
)
nb_products_selected = len(product_ids)
products_to_process = product_ids.filtered(lambda p: not p.image_1920 and p.barcode)
nb_products_to_process = len(products_to_process)
nb_products_unable_to_process = nb_products_selected - nb_products_to_process
defaults = super().default_get(fields_list)
defaults.update(
products_to_process=products_to_process,
nb_products_selected=nb_products_selected,
nb_products_to_process=nb_products_to_process,
nb_products_unable_to_process=nb_products_unable_to_process,
)
return defaults
nb_products_selected = fields.Integer(string="Number of selected products", readonly=True)
products_to_process = fields.Many2many(
comodel_name='product.product',
help="The list of selected products that meet the criteria (have a barcode and no image)",
)
nb_products_to_process = fields.Integer(string="Number of products to process", readonly=True)
nb_products_unable_to_process = fields.Integer(
string="Number of product unprocessable", readonly=True
)
def action_fetch_image(self):
""" Fetch the images of the first ten products and delegate the remaining to the cron.
The first ten images are immediately fetched to improve the user experience. This way, they
can immediately browse the processed products and be assured that the task is running well.
Also, if any error occurs, it can be thrown to the user. Then, a cron job is triggered to be
run as soon as possible, unless the daily request limit has been reached. In that case, the
cron job is scheduled to run a day later.
:return: A notification to inform the user about the outcome of the action
:rtype: dict
"""
self.products_to_process.image_fetch_pending = True # Flag products to process for the cron
# Process the first 10 products immediately
matching_images_count = self._process_products(self._get_products_to_process(10))
if self._get_products_to_process(1): # Delegate remaining products to the cron
# Check that the cron has not been deleted and raise an error if so
ir_cron_fetch_image = self.env.ref(
'product_images.ir_cron_fetch_image', raise_if_not_found=False
)
if not ir_cron_fetch_image:
raise UserError(_(
"The scheduled action \"Product Images: Get product images from Google\" has "
"been deleted. Please contact your administrator to have the action restored "
"or to reinstall the module \"product_images\"."
))
# Check that the cron is not already triggered and create a new trigger if not
cron_triggers_count = self.env['ir.cron.trigger'].search_count(
[('cron_id', '=', ir_cron_fetch_image.id)]
)
if cron_triggers_count == 0:
self.with_context(automatically_triggered=False)._trigger_fetch_images_cron()
message = _(
"Products are processed in the background. Images will be updated progressively."
)
warning_type = 'success'
else:
message = _(
"%(matching_images_count)s matching images have been found for %(product_count)s "
"products.",
matching_images_count=matching_images_count,
product_count=len(self.products_to_process)
)
warning_type = 'success' if matching_images_count > 0 else 'warning'
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _("Product images"),
'type': warning_type,
'message': message,
'next': {'type': 'ir.actions.act_window_close'},
}
}
def _cron_fetch_image(self):
""" Fetch images of a list of products using their barcode.
This method is called from a cron job. If the daily request limit is reached, the cron job
is scheduled to run again a day later.
:return: None
"""
# Retrieve 100 products at a time to limit the run time and avoid reaching Google's default
# rate limit.
self._process_products(self._get_products_to_process(100))
if self._get_products_to_process(1):
self.with_context(automatically_triggered=True)._trigger_fetch_images_cron(
fields.Datetime.now() + timedelta(minutes=1.0)
)
def _get_products_to_process(self, limit=10000):
""" Get the products that need to be processed and meet the criteria.
The criteria are to have a barcode and no image. If `products_to_process` is not populated,
the DB is searched to find matching product records.
:param int limit: The maximum number of records to return, defaulting to 10000 to match
Google's API default rate limit
:return: The products that meet the criteria
:rtype: recordset of `product.product`
"""
products_to_process = self.products_to_process or self.env['product.product'].search(
[('image_fetch_pending', '=', True)], limit=limit
)
return products_to_process.filtered(
# p.image_fetch_pending needed for self.products_to_process's records that might already
# have been processed but not yet removed from the list when called from
# action_fetch_image.
lambda p: not p.image_1920 and p.barcode and p.image_fetch_pending
)[:limit] # Apply the limit after the filter with self.products_to_process for more results
def _process_products(self, products_to_process):
""" Fetch an image from the Google Custom Search API for each product.
We fetch the 10 first image URLs and save the first valid image.
:param recordset products_to_process: The products for which an image must be fetched, as a
`product.product` recordset
:return: The number of products for which a matching image was found
:rtype: int
:raises UserError: If the project is misconfigured on Google's side
:raises UserError: If the API Key or Search Engine ID is incorrect
"""
if not products_to_process:
return 0
nb_service_unavailable_codes = 0
nb_timeouts = 0
for product in products_to_process:
# Fetch image URLs and handle eventual errors
try:
response = self._fetch_image_urls_from_google(product.barcode)
if response.status_code == requests.codes.forbidden:
raise UserError(_(
"The Custom Search API is not enabled in your Google project. Please visit "
"your Google Cloud Platform project page and enable it, then retry. If you "
"enabled this API recently, please wait a few minutes and retry."
))
elif response.status_code == requests.codes.service_unavailable:
nb_service_unavailable_codes += 1
if nb_service_unavailable_codes <= 3: # Temporary loss of service
continue # Let the image of this product be fetched by the next cron run
# The service has not responded more han 3 times, stop trying for now and wait
# for the next cron run.
self.with_context(automatically_triggered=True)._trigger_fetch_images_cron(
fields.Datetime.now() + timedelta(hours=1.0)
)
_logger.warning(
"received too many service_unavailable responses. delegating remaining "
"images to next cron run."
)
break
elif response.status_code == requests.codes.too_many_requests:
self.with_context(automatically_triggered=True)._trigger_fetch_images_cron(
fields.Datetime.now() + timedelta(days=1.0)
)
_logger.warning(
"search quota exceeded. delegating remaining images to next cron run."
)
break
elif response.status_code == requests.codes.bad_request:
raise UserError(_(
"Your API Key or your Search Engine ID is incorrect."
))
except (RequestConnectionError):
nb_timeouts += 1
if nb_timeouts <= 3: # Temporary loss of service
continue # Let the image of this product be fetched by the next cron run
# The service has not responded more han 3 times, stop trying for now and wait for
# the next cron run.
self.with_context(automatically_triggered=True)._trigger_fetch_images_cron(
fields.Datetime.now() + timedelta(hours=1.0)
)
_logger.warning(
"encountered too many timeouts. delegating remaining images to next cron run."
)
break
# Fetch image and handle possible error
response_content = response.json()
if int(response_content['searchInformation']['totalResults']) > 0:
for item in response_content['items']: # Only populated if totalResults > 0
try:
image = self._get_image_from_url(item['link'])
if image:
product.image_1920 = image
break # Stop at the first valid image
except (
RequestConnectionError,
UserError, # Raised when the image couldn't be decoded as base64
):
pass # Move on to the next image
product.image_fetch_pending = False
self.env.cr.commit() # Commit every image in case the cron is killed
return len(products_to_process.filtered('image_1920'))
def _fetch_image_urls_from_google(self, barcode):
""" Fetch the first 10 image URLs from the Google Custom Search API.
:param string barcode: A product's barcode
:return: A response or None
:rtype: Response
"""
if not barcode:
return
ICP = self.env['ir.config_parameter']
return self._session.get(
url='https://customsearch.googleapis.com/customsearch/v1',
params={
'cx': ICP.get_param('google.pse.id').strip(),
'safe': 'active',
'searchType': 'image',
'key': ICP.get_param('google.custom_search.key').strip(),
'rights': 'cc_publicdomain,cc_attribute,cc_sharealike',
'imgSize': 'large',
'imgType': 'photo',
'fields': 'searchInformation/totalResults,items(link)',
'q': barcode,
}
)
def _get_image_from_url(self, url):
""" Retrieve an image from the URL.
If the url contains 'x-raw-image:///', the request failed or the response header
'Content-Type' does not contain 'image/', return None
:param string url: url of an image
:return: The retrieved image or None
:rtype: bytes
"""
image = None
if 'x-raw-image:///' not in url: # Ignore images with incorrect link
response = self._session.get(url, timeout=5)
if response.status_code == requests.codes.ok \
and 'image/' in response.headers['Content-Type']: # Ignore non-image results
image = base64.b64encode(response.content)
return image
def _trigger_fetch_images_cron(self, at=None):
""" Create a trigger for the con `ir_cron_fetch_image`.
By default the cron is scheduled to be executed as soon as possible but
the optional `at` argument may be given to delay the execution later
with a precision down to 1 minute.
:param Optional[datetime.datetime] at:
When to execute the cron, at one moments in time instead of as soon as possible.
"""
self.env.ref('product_images.ir_cron_fetch_image')._trigger(at)
# If two `ir_cron_fetch_image` are triggered automatically, and the first one is not
# committed, the constrains will return a ValidationError and roll back to the last commit,
# leaving no `ir_cron_fetch_image` in the schedule.
self.env.cr.commit()
| 47.289634 | 15,511 |
314 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ProductProduct(models.Model):
_inherit = "product.product"
image_fetch_pending = fields.Boolean(
help="Whether an image must be fetched for this product. Handled by a cron.",
)
| 28.545455 | 314 |
501 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
google_custom_search_key = fields.Char(
string="Google Custom Search API Key",
config_parameter='google.custom_search.key',
)
google_pse_id = fields.Char(
string="The identifier of the Google Programmable Search Engine",
config_parameter='google.pse.id',
)
| 31.3125 | 501 |
2,168 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, models
from odoo.exceptions import ValidationError
class IrCronTrigger(models.Model):
_inherit = 'ir.cron.trigger'
@api.constrains('cron_id')
def _check_image_cron_is_not_already_triggered(self):
""" Ensure that there is a maximum of one trigger at a time for `ir_cron_fetch_image`.
This cron is triggered in an optimal way to retrieve fastly the images without blocking a
worker for a long amount of time. It fetches images in multiples batches to allow other
crons to run in between. The cron also schedules itself if there are remaining products to
be processed or if it encounters errors like a rate limit reached, a ConnectionTimeout, or
service unavailable. Multiple triggers at the same will trouble the rate limit management
and/or errors handling. More information in `product_fetch_image_wizard.py`.
:return: None
:raise ValidationError: If the maximum number of coexisting triggers for
`ir_cron_fetch_image` is reached
"""
ir_cron_fetch_image = self.env.ref(
'product_images.ir_cron_fetch_image', raise_if_not_found=False
)
if ir_cron_fetch_image and self.cron_id.id != ir_cron_fetch_image.id:
return
cron_triggers_count = self.env['ir.cron.trigger'].search_count(
[('cron_id', '=', ir_cron_fetch_image.id)]
)
# When the cron is automatically triggered, we must allow two triggers to exists at the same
# time: the one that triggered the cron and the one that will schedule another cron run. We
# check whether the cron was automatically triggered rather than manually triggered to cover
# the case where the admin would create an ir.cron.trigger manually.
max_coexisting_cron_triggers = 2 if self.env.context.get('automatically_triggered') else 1
if cron_triggers_count > max_coexisting_cron_triggers:
raise ValidationError(_("This action is already scheduled. Please try again later."))
| 52.878049 | 2,168 |
1,075 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Check Printing Base',
'version': '1.0',
'category': 'Accounting/Accounting',
'summary': 'Check printing basic features',
'description': """
This module offers the basic functionalities to make payments by printing checks.
It must be used as a dependency for modules that provide country-specific check templates.
The check settings are located in the accounting journals configuration page.
""",
'depends': ['account'],
'data': [
'security/ir.model.access.csv',
'data/account_check_printing_data.xml',
'views/account_journal_views.xml',
'views/account_move_views.xml',
'views/account_payment_views.xml',
'views/res_config_settings_views.xml',
'views/res_partner_views.xml',
'wizard/print_prenumbered_checks_views.xml'
],
'installable': True,
'auto_install': False,
'post_init_hook': 'create_check_sequence_on_bank_journals',
'license': 'LGPL-3',
}
| 37.068966 | 1,075 |
7,839 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.addons.account_check_printing.models.account_payment import INV_LINES_PER_STUB
from odoo.tests import tagged
from odoo.tools.misc import NON_BREAKING_SPACE
import math
@tagged('post_install', '-at_install')
class TestPrintCheck(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
bank_journal = cls.company_data['default_journal_bank']
cls.payment_method_line_check = bank_journal.outbound_payment_method_line_ids\
.filtered(lambda l: l.code == 'check_printing')
def test_in_invoice_check_manual_sequencing(self):
''' Test the check generation for vendor bills. '''
nb_invoices_to_test = INV_LINES_PER_STUB + 1
self.company_data['default_journal_bank'].write({
'check_manual_sequencing': True,
'check_next_number': '00042',
})
# Create 10 customer invoices.
in_invoices = self.env['account.move'].create([{
'move_type': 'in_invoice',
'partner_id': self.partner_a.id,
'date': '2017-01-01',
'invoice_date': '2017-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 100.0})]
} for i in range(nb_invoices_to_test)])
in_invoices.action_post()
# Create a single payment.
payment = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=in_invoices.ids).create({
'group_payment': True,
'payment_method_line_id': self.payment_method_line_check.id,
})._create_payments()
# Check created payment.
self.assertRecordValues(payment, [{
'payment_method_line_id': self.payment_method_line_check.id,
'check_amount_in_words': payment.currency_id.amount_to_text(100.0 * nb_invoices_to_test),
'check_number': '00042',
}])
# Check pages.
self.company_data['company'].account_check_printing_multi_stub = True
report_pages = payment._check_get_pages()
self.assertEqual(len(report_pages), int(math.ceil(len(in_invoices) / INV_LINES_PER_STUB)))
self.company_data['company'].account_check_printing_multi_stub = False
report_pages = payment._check_get_pages()
self.assertEqual(len(report_pages), 1)
def test_out_refund_check_manual_sequencing(self):
''' Test the check generation for refunds. '''
nb_invoices_to_test = INV_LINES_PER_STUB + 1
self.company_data['default_journal_bank'].write({
'check_manual_sequencing': True,
'check_next_number': '00042',
})
# Create 10 refunds.
out_refunds = self.env['account.move'].create([{
'move_type': 'out_refund',
'partner_id': self.partner_a.id,
'date': '2017-01-01',
'invoice_date': '2017-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 100.0})]
} for i in range(nb_invoices_to_test)])
out_refunds.action_post()
# Create a single payment.
payment = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=out_refunds.ids).create({
'group_payment': True,
'payment_method_line_id': self.payment_method_line_check.id,
})._create_payments()
# Check created payment.
self.assertRecordValues(payment, [{
'payment_method_line_id': self.payment_method_line_check.id,
'check_amount_in_words': payment.currency_id.amount_to_text(100.0 * nb_invoices_to_test),
'check_number': '00042',
}])
# Check pages.
self.company_data['company'].account_check_printing_multi_stub = True
report_pages = payment._check_get_pages()
self.assertEqual(len(report_pages), int(math.ceil(len(out_refunds) / INV_LINES_PER_STUB)))
self.company_data['company'].account_check_printing_multi_stub = False
report_pages = payment._check_get_pages()
self.assertEqual(len(report_pages), 1)
def test_multi_currency_stub_lines(self):
# Invoice in company's currency: 100$
invoice = self.env['account.move'].create({
'move_type': 'in_invoice',
'partner_id': self.partner_a.id,
'date': '2016-01-01',
'invoice_date': '2016-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 100.0})]
})
invoice.action_post()
# Partial payment in foreign currency: 100Gol = 33.33$.
payment = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({
'payment_method_line_id': self.payment_method_line_check.id,
'currency_id': self.currency_data['currency'].id,
'amount': 100.0,
'payment_date': '2017-01-01',
})._create_payments()
stub_pages = payment._check_make_stub_pages()
self.assertEqual(stub_pages, [[{
'due_date': '01/01/2016',
'number': invoice.name,
'amount_total': f'${NON_BREAKING_SPACE}100.00',
'amount_residual': f'${NON_BREAKING_SPACE}50.00',
'amount_paid': f'150.000{NON_BREAKING_SPACE}☺',
'currency': invoice.currency_id,
}]])
def test_in_invoice_check_manual_sequencing_with_multiple_payments(self):
"""
Test the check generation for vendor bills with multiple payments.
"""
nb_invoices_to_test = INV_LINES_PER_STUB + 1
self.company_data['default_journal_bank'].write({
'check_manual_sequencing': True,
'check_next_number': '11111',
})
in_invoices = self.env['account.move'].create([{
'move_type': 'in_invoice',
'partner_id': self.partner_a.id,
'date': '2017-01-01',
'invoice_date': '2017-01-01',
'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 100.0})]
} for i in range(nb_invoices_to_test)])
in_invoices.action_post()
payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=in_invoices.ids).create({
'group_payment': False,
'payment_method_line_id': self.payment_method_line_check.id,
})._create_payments()
self.assertEqual(set(payments.mapped('check_number')), {str(x) for x in range(11111, 11111 + nb_invoices_to_test)})
def test_print_great_pre_number_check(self):
"""
Make sure we can use integer of more than 2147483647 in check sequence
limit of `integer` type in psql: https://www.postgresql.org/docs/current/datatype-numeric.html
"""
vals = {
'payment_type': 'outbound',
'partner_type': 'supplier',
'amount': 100.0,
'journal_id': self.company_data['default_journal_bank'].id,
'payment_method_line_id': self.payment_method_line_check.id,
}
payment = self.env['account.payment'].create(vals)
payment.action_post()
self.assertTrue(payment.write({'check_number': '2147483647'}))
self.assertTrue(payment.write({'check_number': '2147483648'}))
payment_2 = self.env['account.payment'].create(vals)
payment_2.action_post()
action_window = payment_2.print_checks()
self.assertEqual(action_window['context']['default_next_check_number'], '2147483649', "Check number should have been incremented without error.")
| 43.298343 | 7,837 |
1,288 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class PrintPreNumberedChecks(models.TransientModel):
_name = 'print.prenumbered.checks'
_description = 'Print Pre-numbered Checks'
next_check_number = fields.Char('Next Check Number', required=True)
@api.constrains('next_check_number')
def _check_next_check_number(self):
for check in self:
if check.next_check_number and not re.match(r'^[0-9]+$', check.next_check_number):
raise ValidationError(_('Next Check Number should only contains numbers.'))
def print_checks(self):
check_number = int(self.next_check_number)
number_len = len(self.next_check_number or "")
payments = self.env['account.payment'].browse(self.env.context['payment_ids'])
payments.filtered(lambda r: r.state == 'draft').action_post()
payments.filtered(lambda r: r.state == 'posted' and not r.is_move_sent).write({'is_move_sent': True})
for payment in payments:
payment.check_number = '%0{}d'.format(number_len) % check_number
check_number += 1
return payments.do_print_checks()
| 42.933333 | 1,288 |
1,303 |
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.tools.sql import column_exists, create_column
class AccountMove(models.Model):
_inherit = 'account.move'
preferred_payment_method_id = fields.Many2one(
string="Preferred Payment Method",
comodel_name='account.payment.method',
compute='_compute_preferred_payment_method_idd',
store=True,
)
def _auto_init(self):
""" Create column for `preferred_payment_method_id` to avoid having it
computed by the ORM on installation. Since `property_payment_method_id` is
introduced in this module, there is no need for UPDATE
"""
if not column_exists(self.env.cr, "account_move", "preferred_payment_method_id"):
create_column(self.env.cr, "account_move", "preferred_payment_method_id", "int4")
return super()._auto_init()
@api.depends('partner_id')
def _compute_preferred_payment_method_idd(self):
for move in self:
partner = move.partner_id
# take the payment method corresponding to the move's company
move.preferred_payment_method_id = partner.with_company(move.company_id).property_payment_method_id
| 39.484848 | 1,303 |
4,208 |
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
class AccountJournal(models.Model):
_inherit = "account.journal"
def _default_outbound_payment_methods(self):
res = super()._default_outbound_payment_methods()
if self._is_payment_method_available('check_printing'):
res |= self.env.ref('account_check_printing.account_payment_method_check')
return res
check_manual_sequencing = fields.Boolean(
string='Manual Numbering',
default=False,
help="Check this option if your pre-printed checks are not numbered.",
)
check_sequence_id = fields.Many2one(
comodel_name='ir.sequence',
string='Check Sequence',
readonly=True,
copy=False,
help="Checks numbering sequence.",
)
check_next_number = fields.Char(
string='Next Check Number',
compute='_compute_check_next_number',
inverse='_inverse_check_next_number',
help="Sequence number of the next printed check.",
)
@api.depends('check_manual_sequencing')
def _compute_check_next_number(self):
for journal in self:
sequence = journal.check_sequence_id
if sequence:
journal.check_next_number = sequence.get_next_char(sequence.number_next_actual)
else:
journal.check_next_number = 1
def _inverse_check_next_number(self):
for journal in self:
if journal.check_next_number and not re.match(r'^[0-9]+$', journal.check_next_number):
raise ValidationError(_('Next Check Number should only contains numbers.'))
if int(journal.check_next_number) < journal.check_sequence_id.number_next_actual:
raise ValidationError(_(
"The last check number was %s. In order to avoid a check being rejected "
"by the bank, you can only use a greater number.",
journal.check_sequence_id.number_next_actual
))
if journal.check_sequence_id:
journal.check_sequence_id.sudo().number_next_actual = int(journal.check_next_number)
journal.check_sequence_id.sudo().padding = len(journal.check_next_number)
@api.model
def create(self, vals):
rec = super(AccountJournal, self).create(vals)
if not rec.check_sequence_id:
rec._create_check_sequence()
return rec
def _create_check_sequence(self):
""" Create a check sequence for the journal """
for journal in self:
journal.check_sequence_id = self.env['ir.sequence'].sudo().create({
'name': journal.name + _(" : Check Number Sequence"),
'implementation': 'no_gap',
'padding': 5,
'number_increment': 1,
'company_id': journal.company_id.id,
})
def get_journal_dashboard_datas(self):
domain_checks_to_print = [
('journal_id', '=', self.id),
('payment_method_line_id.code', '=', 'check_printing'),
('state', '=', 'posted'),
('is_move_sent','=', False),
]
return dict(
super(AccountJournal, self).get_journal_dashboard_datas(),
num_checks_to_print=self.env['account.payment'].search_count(domain_checks_to_print),
)
def action_checks_to_print(self):
payment_method_line = self.outbound_payment_method_line_ids.filtered(lambda l: l.code == 'check_printing')
return {
'name': _('Checks to Print'),
'type': 'ir.actions.act_window',
'view_mode': 'list,form,graph',
'res_model': 'account.payment',
'context': dict(
self.env.context,
search_default_checks_to_send=1,
journal_id=self.id,
default_journal_id=self.id,
default_payment_type='outbound',
default_payment_method_line_id=payment_method_line.id,
),
}
| 40.07619 | 4,208 |
436 |
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['check_printing'] = {'mode': 'multi', 'domain': [('type', '=', 'bank')]}
return res
| 31.142857 | 436 |
14,621 |
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 UserError, ValidationError, RedirectWarning
from odoo.tools.misc import formatLang, format_date
INV_LINES_PER_STUB = 9
class AccountPaymentRegister(models.TransientModel):
_inherit = "account.payment.register"
@api.depends('payment_type', 'journal_id', 'partner_id')
def _compute_payment_method_line_id(self):
super()._compute_payment_method_line_id()
for record in self:
preferred = record.partner_id.with_company(record.company_id).property_payment_method_id
method_line = record.journal_id.outbound_payment_method_line_ids.filtered(
lambda l: l.payment_method_id == preferred
)
if record.payment_type == 'outbound' and method_line:
record.payment_method_line_id = method_line[0]
class AccountPayment(models.Model):
_inherit = "account.payment"
check_amount_in_words = fields.Char(
string="Amount in Words",
store=True,
compute='_compute_check_amount_in_words',
)
check_manual_sequencing = fields.Boolean(related='journal_id.check_manual_sequencing')
check_number = fields.Char(
string="Check Number",
store=True,
readonly=True,
copy=False,
compute='_compute_check_number',
inverse='_inverse_check_number',
help="The selected journal is configured to print check numbers. If your pre-printed check paper already has numbers "
"or if the current numbering is wrong, you can change it in the journal configuration page.",
)
payment_method_line_id = fields.Many2one(index=True)
@api.constrains('check_number', 'journal_id')
def _constrains_check_number(self):
payment_checks = self.filtered('check_number')
if not payment_checks:
return
for payment_check in payment_checks:
if not payment_check.check_number.isdecimal():
raise ValidationError(_('Check numbers can only consist of digits'))
self.flush()
self.env.cr.execute("""
SELECT payment.check_number, move.journal_id
FROM account_payment payment
JOIN account_move move ON move.id = payment.move_id
JOIN account_journal journal ON journal.id = move.journal_id,
account_payment other_payment
JOIN account_move other_move ON other_move.id = other_payment.move_id
WHERE payment.check_number::BIGINT = other_payment.check_number::BIGINT
AND move.journal_id = other_move.journal_id
AND payment.id != other_payment.id
AND payment.id IN %(ids)s
AND move.state = 'posted'
AND other_move.state = 'posted'
AND payment.check_number IS NOT NULL
AND other_payment.check_number IS NOT NULL
""", {
'ids': tuple(payment_checks.ids),
})
res = self.env.cr.dictfetchall()
if res:
raise ValidationError(_(
'The following numbers are already used:\n%s',
'\n'.join(_(
'%(number)s in journal %(journal)s',
number=r['check_number'],
journal=self.env['account.journal'].browse(r['journal_id']).display_name,
) for r in res)
))
@api.depends('payment_method_line_id', 'currency_id', 'amount')
def _compute_check_amount_in_words(self):
for pay in self:
if pay.currency_id:
pay.check_amount_in_words = pay.currency_id.amount_to_text(pay.amount)
else:
pay.check_amount_in_words = False
@api.depends('journal_id', 'payment_method_code')
def _compute_check_number(self):
for pay in self:
if pay.journal_id.check_manual_sequencing and pay.payment_method_code == 'check_printing':
sequence = pay.journal_id.check_sequence_id
pay.check_number = sequence.get_next_char(sequence.number_next_actual)
else:
pay.check_number = False
def _inverse_check_number(self):
for payment in self:
if payment.check_number:
sequence = payment.journal_id.check_sequence_id.sudo()
sequence.padding = len(payment.check_number)
@api.depends('payment_type', 'journal_id', 'partner_id')
def _compute_payment_method_line_id(self):
super()._compute_payment_method_line_id()
for record in self:
preferred = record.partner_id.with_company(record.company_id).property_payment_method_id
method_line = record.journal_id.outbound_payment_method_line_ids\
.filtered(lambda l: l.payment_method_id == preferred)
if record.payment_type == 'outbound' and method_line:
record.payment_method_line_id = method_line[0]
def action_post(self):
payment_method_check = self.env.ref('account_check_printing.account_payment_method_check')
for payment in self.filtered(lambda p: p.payment_method_id == payment_method_check and p.check_manual_sequencing):
sequence = payment.journal_id.check_sequence_id
payment.check_number = sequence.next_by_id()
return super(AccountPayment, self).action_post()
def print_checks(self):
""" Check that the recordset is valid, set the payments state to sent and call print_checks() """
# Since this method can be called via a client_action_multi, we need to make sure the received records are what we expect
self = self.filtered(lambda r: r.payment_method_line_id.code == 'check_printing' and r.state != 'reconciled')
if len(self) == 0:
raise UserError(_("Payments to print as a checks must have 'Check' selected as payment method and "
"not have already been reconciled"))
if any(payment.journal_id != self[0].journal_id for payment in self):
raise UserError(_("In order to print multiple checks at once, they must belong to the same bank journal."))
if not self[0].journal_id.check_manual_sequencing:
# The wizard asks for the number printed on the first pre-printed check
# so payments are attributed the number of the check the'll be printed on.
self.env.cr.execute("""
SELECT payment.id
FROM account_payment payment
JOIN account_move move ON movE.id = payment.move_id
WHERE journal_id = %(journal_id)s
AND payment.check_number IS NOT NULL
ORDER BY payment.check_number::BIGINT DESC
LIMIT 1
""", {
'journal_id': self.journal_id.id,
})
last_printed_check = self.browse(self.env.cr.fetchone())
number_len = len(last_printed_check.check_number or "")
next_check_number = '%0{}d'.format(number_len) % (int(last_printed_check.check_number) + 1)
return {
'name': _('Print Pre-numbered Checks'),
'type': 'ir.actions.act_window',
'res_model': 'print.prenumbered.checks',
'view_mode': 'form',
'target': 'new',
'context': {
'payment_ids': self.ids,
'default_next_check_number': next_check_number,
}
}
else:
self.filtered(lambda r: r.state == 'draft').action_post()
return self.do_print_checks()
def action_unmark_sent(self):
self.write({'is_move_sent': False})
def action_void_check(self):
self.action_draft()
self.action_cancel()
def do_print_checks(self):
check_layout = self.company_id.account_check_printing_layout
redirect_action = self.env.ref('account.action_account_config')
if not check_layout or check_layout == 'disabled':
msg = _("You have to choose a check layout. For this, go in Invoicing/Accounting Settings, search for 'Checks layout' and set one.")
raise RedirectWarning(msg, redirect_action.id, _('Go to the configuration panel'))
report_action = self.env.ref(check_layout, False)
if not report_action:
msg = _("Something went wrong with Check Layout, please select another layout in Invoicing/Accounting Settings and try again.")
raise RedirectWarning(msg, redirect_action.id, _('Go to the configuration panel'))
self.write({'is_move_sent': True})
return report_action.report_action(self)
#######################
#CHECK PRINTING METHODS
#######################
def _check_fill_line(self, amount_str):
return amount_str and (amount_str + ' ').ljust(200, '*') or ''
def _check_build_page_info(self, i, p):
multi_stub = self.company_id.account_check_printing_multi_stub
return {
'sequence_number': self.check_number,
'manual_sequencing': self.journal_id.check_manual_sequencing,
'date': format_date(self.env, self.date),
'partner_id': self.partner_id,
'partner_name': self.partner_id.name,
'currency': self.currency_id,
'state': self.state,
'amount': formatLang(self.env, self.amount, currency_obj=self.currency_id) if i == 0 else 'VOID',
'amount_in_word': self._check_fill_line(self.check_amount_in_words) if i == 0 else 'VOID',
'memo': self.ref,
'stub_cropped': not multi_stub and len(self.move_id._get_reconciled_invoices()) > INV_LINES_PER_STUB,
# If the payment does not reference an invoice, there is no stub line to display
'stub_lines': p,
}
def _check_get_pages(self):
""" Returns the data structure used by the template : a list of dicts containing what to print on pages.
"""
stub_pages = self._check_make_stub_pages() or [False]
pages = []
for i, p in enumerate(stub_pages):
pages.append(self._check_build_page_info(i, p))
return pages
def _check_make_stub_pages(self):
""" The stub is the summary of paid invoices. It may spill on several pages, in which case only the check on
first page is valid. This function returns a list of stub lines per page.
"""
self.ensure_one()
def prepare_vals(invoice, partials):
number = ' - '.join([invoice.name, invoice.ref] if invoice.ref else [invoice.name])
if invoice.is_outbound() or invoice.move_type == 'entry':
invoice_sign = 1
partial_field = 'debit_amount_currency'
else:
invoice_sign = -1
partial_field = 'credit_amount_currency'
if invoice.currency_id.is_zero(invoice.amount_residual):
amount_residual_str = '-'
else:
amount_residual_str = formatLang(self.env, invoice_sign * invoice.amount_residual, currency_obj=invoice.currency_id)
return {
'due_date': format_date(self.env, invoice.invoice_date_due),
'number': number,
'amount_total': formatLang(self.env, invoice_sign * invoice.amount_total, currency_obj=invoice.currency_id),
'amount_residual': amount_residual_str,
'amount_paid': formatLang(self.env, invoice_sign * sum(partials.mapped(partial_field)), currency_obj=self.currency_id),
'currency': invoice.currency_id,
}
# Decode the reconciliation to keep only bills.
term_lines = self.line_ids.filtered(lambda line: line.account_id.internal_type in ('receivable', 'payable'))
invoices = (term_lines.matched_debit_ids.debit_move_id.move_id + term_lines.matched_credit_ids.credit_move_id.move_id) \
.filtered(lambda move: move.is_outbound() or move.move_type == 'entry')
invoices = invoices.sorted(lambda x: x.invoice_date_due or x.date)
# Group partials by invoices.
invoice_map = {invoice: self.env['account.partial.reconcile'] for invoice in invoices}
for partial in term_lines.matched_debit_ids:
invoice = partial.debit_move_id.move_id
if invoice in invoice_map:
invoice_map[invoice] |= partial
for partial in term_lines.matched_credit_ids:
invoice = partial.credit_move_id.move_id
if invoice in invoice_map:
invoice_map[invoice] |= partial
# Prepare stub_lines.
if 'out_refund' in invoices.mapped('move_type'):
stub_lines = [{'header': True, 'name': "Bills"}]
stub_lines += [prepare_vals(invoice, partials)
for invoice, partials in invoice_map.items()
if invoice.move_type == 'in_invoice']
stub_lines += [{'header': True, 'name': "Refunds"}]
stub_lines += [prepare_vals(invoice, partials)
for invoice, partials in invoice_map.items()
if invoice.move_type == 'out_refund']
else:
stub_lines = [prepare_vals(invoice, partials)
for invoice, partials in invoice_map.items()
if invoice.move_type in ('in_invoice', 'entry')]
# Crop the stub lines or split them on multiple pages
if not self.company_id.account_check_printing_multi_stub:
# If we need to crop the stub, leave place for an ellipsis line
num_stub_lines = len(stub_lines) > INV_LINES_PER_STUB and INV_LINES_PER_STUB - 1 or INV_LINES_PER_STUB
stub_pages = [stub_lines[:num_stub_lines]]
else:
stub_pages = []
i = 0
while i < len(stub_lines):
# Make sure we don't start the credit section at the end of a page
if len(stub_lines) >= i + INV_LINES_PER_STUB and stub_lines[i + INV_LINES_PER_STUB - 1].get('header'):
num_stub_lines = INV_LINES_PER_STUB - 1 or INV_LINES_PER_STUB
else:
num_stub_lines = INV_LINES_PER_STUB
stub_pages.append(stub_lines[i:i + num_stub_lines])
i += num_stub_lines
return stub_pages
| 48.413907 | 14,621 |
1,862 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, fields
class res_company(models.Model):
_inherit = "res.company"
# This field needs to be overridden with `selection_add` in the modules which intends to add report layouts.
# The xmlID of all the report actions which are actually Check Layouts has to be kept as key of the selection.
account_check_printing_layout = fields.Selection(
string="Check Layout",
selection=[
('disabled', 'None'),
],
default='disabled',
help="Select the format corresponding to the check paper you will be printing your checks on.\n"
"In order to disable the printing feature, select 'None'.",
)
account_check_printing_date_label = fields.Boolean(
string='Print Date Label',
default=True,
help="This option allows you to print the date label on the check as per CPA.\n"
"Disable this if your pre-printed check includes the date label.",
)
account_check_printing_multi_stub = fields.Boolean(
string='Multi-Pages Check Stub',
help="This option allows you to print check details (stub) on multiple pages if they don't fit on a single page.",
)
account_check_printing_margin_top = fields.Float(
string='Check Top Margin',
default=0.25,
help="Adjust the margins of generated checks to make it fit your printer's settings.",
)
account_check_printing_margin_left = fields.Float(
string='Check Left Margin',
default=0.25,
help="Adjust the margins of generated checks to make it fit your printer's settings.",
)
account_check_printing_margin_right = fields.Float(
string='Right Margin',
default=0.25,
help="Adjust the margins of generated checks to make it fit your printer's settings.",
)
| 42.318182 | 1,862 |
2,078 |
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'
account_check_printing_layout = fields.Selection(
related='company_id.account_check_printing_layout',
string="Check Layout",
readonly=False,
help="Select the format corresponding to the check paper you will be printing your checks on.\n"
"In order to disable the printing feature, select 'None'."
)
account_check_printing_date_label = fields.Boolean(
related='company_id.account_check_printing_date_label',
string="Print Date Label",
readonly=False,
help="This option allows you to print the date label on the check as per CPA.\n"
"Disable this if your pre-printed check includes the date label."
)
account_check_printing_multi_stub = fields.Boolean(
related='company_id.account_check_printing_multi_stub',
string='Multi-Pages Check Stub',
readonly=False,
help="This option allows you to print check details (stub) on multiple pages if they don't fit on a single page."
)
account_check_printing_margin_top = fields.Float(
related='company_id.account_check_printing_margin_top',
string='Check Top Margin',
readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings."
)
account_check_printing_margin_left = fields.Float(
related='company_id.account_check_printing_margin_left',
string='Check Left Margin',
readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings."
)
account_check_printing_margin_right = fields.Float(
related='company_id.account_check_printing_margin_right',
string='Check Right Margin',
readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings."
)
| 44.212766 | 2,078 |
669 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class ResPartner(models.Model):
_inherit = 'res.partner'
property_payment_method_id = fields.Many2one(
comodel_name='account.payment.method',
string='Payment Method',
company_dependent=True,
domain="[('payment_type', '=', 'outbound')]",
help="Preferred payment method when paying this vendor. This is used to filter vendor bills"
" by preferred payment method to register payments in mass. Use cases: create bank"
" files for batch wires, check runs.",
)
| 35.210526 | 669 |
1,345 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "l10n_it_stock_ddt",
'icon': '/l10n_it/static/description/icon.png',
'website': 'https://www.odoo.com',
'category': 'Accounting/Localizations/EDI',
'version': '0.1',
'description': """
Documento di Trasporto (DDT)
Whenever goods are transferred between A and B, the DDT serves
as a legitimation e.g. when the police would stop you.
When you want to print an outgoing picking in an Italian company,
it will print you the DDT instead. It is like the delivery
slip, but it also contains the value of the product,
the transportation reason, the carrier, ... which make it a DDT.
We also use a separate sequence for the DDT as the number should not
have any gaps and should only be applied at the moment the goods are sent.
When invoices are related to their sale order and the sale order with the
delivery, the system will automatically calculate the linked DDTs for every
invoice line to export in the FatturaPA XML.
""",
'depends': ['l10n_it_edi', 'delivery', 'stock_account'],
'data': [
'report/l10n_it_ddt_report.xml',
'views/stock_picking_views.xml',
'views/account_invoice_views.xml',
'data/l10n_it_ddt_template.xml',
],
'auto_install': True,
'post_init_hook': '_create_picking_seq',
'license': 'LGPL-3',
}
| 37.361111 | 1,345 |
6,312 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale.tests.common import TestSaleCommon
from odoo.tests import tagged, Form
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestDDT(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_it.l10n_it_chart_template_generic'):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.company_data['company'].write({
'vat':"IT12345670017",
'country_id': cls.env.ref('base.it').id,
'l10n_it_codice_fiscale': '01234560157',
'l10n_it_tax_system': 'RF01',
'street': 'Via Giovanni Maria Platina 66',
'zip': '26100',
'city': 'Cremona',
})
cls.env['res.partner.bank'].create({
'acc_number': 'IT60X0542811101000000123456',
'partner_id': cls.company_data['company'].partner_id.id,
})
cls.partner_a.write({
'street': 'Piazza Guglielmo Marconi 5',
'zip': '26100',
'city': 'Cremona',
'country_id': cls.env.ref('base.it').id,
'vat': 'IT12345670124'
})
settings = cls.env['res.config.settings'].create({})
if hasattr(settings, 'button_create_proxy_user'):
# Needed when `l10n_it_edi_sdiscoop` is installed
settings.button_create_proxy_user()
def test_ddt_flow(self):
"""
We confirm a sale order and handle its delivery partially.
This should have created a DDT number and when we generate and the invoice,
the delivery should be linked to it as DDT.
"""
self.so = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'partner_invoice_id': self.partner_a.id,
'partner_shipping_id': self.partner_a.id,
'order_line': [(0, 0, {'name': p.name,
'product_id': p.id,
'product_uom_qty': 5,
'product_uom': p.uom_id.id,
'price_unit': p.list_price,
'tax_id': self.company_data['default_tax_sale']})
for p in (
self.company_data['product_order_no'],
self.company_data['product_service_delivery'],
self.company_data['product_service_order'],
self.company_data['product_delivery_no'],
)],
'pricelist_id': self.company_data['default_pricelist'].id,
'picking_policy': 'direct',
})
self.so.action_confirm()
# deliver partially
pick = self.so.picking_ids
pick.move_lines.write({'quantity_done': 1})
wiz_act = pick.button_validate()
wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save()
wiz.process()
self.assertTrue(pick.l10n_it_ddt_number, 'The outgoing picking should have a DDT number')
self.inv1 = self.so._create_invoices()
self.inv1.action_post()
self.assertEqual(self.inv1.l10n_it_ddt_ids.ids, pick.ids, 'DDT should be linked to the invoice')
# deliver partially
pickx1 = self.so.picking_ids.filtered(lambda p: p.state != 'done')
pickx1.move_lines.write({'quantity_done': 1})
wiz_act = pickx1.button_validate()
wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save()
wiz.process()
# and again
pickx2 = self.so.picking_ids.filtered(lambda p: p.state != 'done')
pickx2.move_lines.write({'quantity_done': 2})
wiz_act = pickx2.button_validate()
wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save()
wiz.process()
self.inv2 = self.so._create_invoices()
self.inv2.action_post()
self.assertEqual(self.inv2.l10n_it_ddt_ids.ids, (pickx1 | pickx2).ids, 'DDTs should be linked to the invoice')
def test_ddt_flow_2(self):
"""
Test that the link between the invoice lines and the deliveries linked to the invoice
through the link with the sale order is calculated correctly.
"""
so = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [(0, 0, {
'product_id': self.product_a.id,
'product_uom_qty': 3,
'product_uom': self.product_a.uom_id.id,
'price_unit': self.product_a.list_price,
'tax_id': self.company_data['default_tax_sale']
}
)],
'pricelist_id': self.company_data['default_pricelist'].id,
'picking_policy': 'direct',
})
so.action_confirm()
# deliver partially
picking_1 = so.picking_ids
picking_1.move_lines.write({'quantity_done': 1})
wiz_act = picking_1.button_validate()
wiz = Form(self.env[wiz_act['res_model']].with_context(wiz_act['context'])).save()
wiz.process()
invoice_1 = so._create_invoices()
invoice_form = Form(invoice_1)
with invoice_form.invoice_line_ids.edit(0) as line:
line.quantity = 1.0
invoice_1 = invoice_form.save()
invoice_1.action_post()
picking_2 = so.picking_ids.filtered(lambda p: p.state != 'done')
picking_2.move_lines.write({'quantity_done': 2})
picking_2.button_validate()
invoice_2 = so._create_invoices()
invoice_2.action_post()
# Invalidate the cache to ensure the lines will be fetched in the right order.
picking_2.invalidate_cache()
self.assertEqual(invoice_1.l10n_it_ddt_ids.ids, picking_1.ids, 'DDT picking_1 should be linked to the invoice_1')
self.assertEqual(invoice_2.l10n_it_ddt_ids.ids, picking_2.ids, 'DDT picking_2 should be linked to the invoice_2')
| 44.765957 | 6,312 |
4,700 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, fields, _
from odoo.tools.float_utils import float_compare
class AccountMove(models.Model):
_inherit = 'account.move'
l10n_it_ddt_ids = fields.Many2many('stock.picking', compute="_compute_ddt_ids")
l10n_it_ddt_count = fields.Integer(compute="_compute_ddt_ids")
def _get_ddt_values(self):
"""
We calculate the link between the invoice lines and the deliveries related to the invoice through the
links with the sale order(s). We assume that the first picking was invoiced first. (FIFO)
:return: a dictionary with as key the picking and value the invoice line numbers (by counting)
"""
self.ensure_one()
# We don't consider returns/credit notes as we suppose they will lead to more deliveries/invoices as well
if self.move_type != "out_invoice" or self.state != 'posted':
return {}
line_count = 0
invoice_line_pickings = {}
for line in self.invoice_line_ids.filtered(lambda l: not l.display_type):
line_count += 1
done_moves_related = line.sale_line_ids.mapped('move_ids').filtered(lambda m: m.state == 'done' and m.location_dest_id.usage == 'customer')
if len(done_moves_related) <= 1:
if done_moves_related and line_count not in invoice_line_pickings.get(done_moves_related.picking_id, []):
invoice_line_pickings.setdefault(done_moves_related.picking_id, []).append(line_count)
else:
total_invoices = done_moves_related.mapped('sale_line_id.invoice_lines').filtered(
lambda l: l.move_id.state == 'posted' and l.move_id.move_type == 'out_invoice').sorted(lambda l: (l.move_id.invoice_date, l.move_id.id))
total_invs = [(i.product_uom_id._compute_quantity(i.quantity, i.product_id.uom_id), i) for i in total_invoices]
inv = total_invs.pop(0)
# Match all moves and related invoice lines FIFO looking for when the matched invoice_line matches line
for move in done_moves_related.sorted(lambda m: (m.date, m.id)):
rounding = move.product_uom.rounding
move_qty = move.product_qty
while (float_compare(move_qty, 0, precision_rounding=rounding) > 0):
if float_compare(inv[0], move_qty, precision_rounding=rounding) > 0:
inv = (inv[0] - move_qty, inv[1])
invoice_line = inv[1]
move_qty = 0
if float_compare(inv[0], move_qty, precision_rounding=rounding) <= 0:
move_qty -= inv[0]
invoice_line = inv[1]
if total_invs:
inv = total_invs.pop(0)
else:
move_qty = 0 #abort when not enough matched invoices
# If in our FIFO iteration we stumble upon the line we were checking
if invoice_line == line and line_count not in invoice_line_pickings.get(move.picking_id, []):
invoice_line_pickings.setdefault(move.picking_id, []).append(line_count)
return invoice_line_pickings
@api.depends('invoice_line_ids', 'invoice_line_ids.sale_line_ids')
def _compute_ddt_ids(self):
it_out_invoices = self.filtered(lambda i: i.move_type == 'out_invoice' and i.company_id.account_fiscal_country_id.code == 'IT')
for invoice in it_out_invoices:
invoice_line_pickings = invoice._get_ddt_values()
pickings = self.env['stock.picking']
for picking in invoice_line_pickings:
pickings |= picking
invoice.l10n_it_ddt_ids = pickings
invoice.l10n_it_ddt_count = len(pickings)
for invoice in self - it_out_invoices:
invoice.l10n_it_ddt_ids = self.env['stock.picking']
invoice.l10n_it_ddt_count = 0
def get_linked_ddts(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'view_mode': 'tree,form',
'name': _("Linked deliveries"),
'res_model': 'stock.picking',
'domain': [('id', 'in', self.l10n_it_ddt_ids.ids)],
}
def _prepare_fatturapa_export_values(self):
template_values = super()._prepare_fatturapa_export_values()
template_values['ddt_dict'] = self._get_ddt_values()
return template_values
| 55.294118 | 4,700 |
4,899 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
class StockPicking(models.Model):
_inherit = "stock.picking"
l10n_it_transport_reason = fields.Selection([('sale', 'Sale'),
('outsourcing', 'Outsourcing'),
('evaluation', 'Evaluation'),
('gift', 'Gift'),
('transfer', 'Transfer'),
('substitution', 'Substitution'),
('attemped_sale', 'Attempted Sale'),
('loaned_use', 'Loaned for Use'),
('repair', 'Repair')], default="sale", tracking=True, string='Transport Reason')
l10n_it_transport_method = fields.Selection([('sender', 'Sender'), ('recipient', 'Recipient'), ('courier', 'Courier service')],
default="sender", string='Transport Method')
l10n_it_transport_method_details = fields.Char('Transport Note')
l10n_it_parcels = fields.Integer(string="Parcels", default=1)
l10n_it_ddt_number = fields.Char('DDT Number', readonly=True)
l10n_it_show_print_ddt_button = fields.Boolean(compute="_compute_l10n_it_show_print_ddt_button")
@api.depends('country_code',
'picking_type_code',
'state',
'is_locked',
'move_ids_without_package',
'move_ids_without_package.partner_id',
'location_id',
'location_dest_id')
def _compute_l10n_it_show_print_ddt_button(self):
# Enable printing the DDT for done outgoing shipments
# or dropshipping (picking going from supplier to customer)
for picking in self:
picking.l10n_it_show_print_ddt_button = (
picking.country_code == 'IT'
and picking.state == 'done'
and picking.is_locked
and (picking.picking_type_code == 'outgoing'
or (
picking.move_ids_without_package
and picking.move_ids_without_package[0].partner_id
and picking.location_id.usage == 'supplier'
and picking.location_dest_id.usage == 'customer'
)
)
)
def _action_done(self):
super(StockPicking, self)._action_done()
for picking in self.filtered(lambda p: p.picking_type_id.l10n_it_ddt_sequence_id):
picking.l10n_it_ddt_number = picking.picking_type_id.l10n_it_ddt_sequence_id.next_by_id()
class StockPickingType(models.Model):
_inherit = 'stock.picking.type'
l10n_it_ddt_sequence_id = fields.Many2one('ir.sequence')
def _get_dtt_ir_seq_vals(self, warehouse_id, sequence_code):
if warehouse_id:
wh = self.env['stock.warehouse'].browse(warehouse_id)
ir_seq_name = wh.name + ' ' + _('Sequence') + ' ' + sequence_code
ir_seq_prefix = wh.code + '/' + sequence_code + '/DDT'
else:
ir_seq_name = _('Sequence') + ' ' + sequence_code
ir_seq_prefix = sequence_code + '/DDT'
return ir_seq_name, ir_seq_prefix
@api.model
def create(self, vals):
company = self.env['res.company'].browse(vals.get('company_id', False)) or self.env.company
if 'l10n_it_ddt_sequence_id' not in vals or not vals['l10n_it_ddt_sequence_id'] and vals['code'] == 'outgoing' \
and company.country_id.code == 'IT':
ir_seq_name, ir_seq_prefix = self._get_dtt_ir_seq_vals(vals.get('warehouse_id'), vals['sequence_code'])
vals['l10n_it_ddt_sequence_id'] = self.env['ir.sequence'].create({
'name': ir_seq_name,
'prefix': ir_seq_prefix,
'padding': 5,
'company_id': company.id,
'implementation': 'no_gap',
}).id
return super(StockPickingType, self).create(vals)
def write(self, vals):
if 'sequence_code' in vals:
for picking_type in self.filtered(lambda p: p.l10n_it_ddt_sequence_id):
warehouse = picking_type.warehouse_id.id if 'warehouse_id' not in vals else vals['warehouse_ids']
ir_seq_name, ir_seq_prefix = self._get_dtt_ir_seq_vals(warehouse, vals['sequence_code'])
picking_type.l10n_it_ddt_sequence_id.write({
'name': ir_seq_name,
'prefix': ir_seq_prefix,
})
return super(StockPickingType, self).write(vals)
| 50.505155 | 4,899 |
4,996 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'eLearning',
'version': '2.4',
'sequence': 125,
'summary': 'Manage and publish an eLearning platform',
'website': 'https://www.odoo.com/app/elearning',
'category': 'Website/eLearning',
'description': """
Create Online Courses
=====================
Featuring
* Integrated course and lesson management
* Fullscreen navigation
* Support Youtube videos, Google documents, PDF, images, web pages
* Test knowledge with quizzes
* Filter and Tag
* Statistics
""",
'depends': [
'portal_rating',
'website',
'website_mail',
'website_profile',
],
'data': [
'security/website_slides_security.xml',
'security/ir.model.access.csv',
'views/res_config_settings_views.xml',
'views/res_partner_views.xml',
'views/rating_rating_views.xml',
'views/slide_question_views.xml',
'views/slide_slide_views.xml',
'views/slide_channel_partner_views.xml',
'views/slide_channel_views.xml',
'views/slide_channel_tag_views.xml',
'views/slide_snippets.xml',
'views/website_slides_menu_views.xml',
'views/website_slides_templates_homepage.xml',
'views/website_slides_templates_course.xml',
'views/website_slides_templates_lesson.xml',
'views/website_slides_templates_lesson_fullscreen.xml',
'views/website_slides_templates_lesson_embed.xml',
'views/website_slides_templates_profile.xml',
'views/website_slides_templates_utils.xml',
'wizard/slide_channel_invite_views.xml',
'data/gamification_data.xml',
'data/mail_data.xml',
'data/mail_template_data.xml',
'data/mail_templates.xml',
'data/slide_data.xml',
'data/website_data.xml',
],
'demo': [
'data/res_users_demo.xml',
'data/slide_channel_tag_demo.xml',
'data/slide_channel_demo.xml',
'data/slide_slide_demo.xml',
'data/slide_user_demo.xml',
],
'installable': True,
'application': True,
'assets': {
'web.assets_backend': [
'website_slides/static/src/scss/rating_rating_views.scss',
'website_slides/static/src/scss/slide_views.scss',
'website_slides/static/src/components/activity/activity.js',
'website_slides/static/src/js/slide_category_one2many.js',
'website_slides/static/src/js/rating_field_backend.js',
],
'web.assets_frontend': [
'website_slides/static/src/scss/website_slides.scss',
'website_slides/static/src/scss/website_slides_profile.scss',
'website_slides/static/src/scss/slides_slide_fullscreen.scss',
'website_slides/static/src/js/slides.js',
'website_slides/static/src/js/slides_share.js',
'website_slides/static/src/js/slides_upload.js',
'website_slides/static/src/js/slides_category_add.js',
'website_slides/static/src/js/slides_category_delete.js',
'website_slides/static/src/js/slides_slide_archive.js',
'website_slides/static/src/js/slides_slide_toggle_is_preview.js',
'website_slides/static/src/js/slides_slide_like.js',
'website_slides/static/src/js/slides_course_slides_list.js',
'website_slides/static/src/js/slides_course_fullscreen_player.js',
'website_slides/static/src/js/slides_course_join.js',
'website_slides/static/src/js/slides_course_enroll_email.js',
'website_slides/static/src/js/slides_course_quiz.js',
'website_slides/static/src/js/slides_course_quiz_question_form.js',
'website_slides/static/src/js/slides_course_quiz_finish.js',
'website_slides/static/src/js/slides_course_tag_add.js',
'website_slides/static/src/js/slides_course_unsubscribe.js',
'website_slides/static/src/js/tours/slides_tour.js',
'website_slides/static/src/js/portal_chatter.js',
],
'web.assets_tests': [
'website_slides/static/src/tests/**/*',
],
'website.assets_editor': [
'website_slides/static/src/js/website_slides.editor.js',
],
'website_slides.slide_embed_assets': [
('include', 'web._assets_helpers'),
'web/static/lib/bootstrap/scss/_variables.scss',
('include', 'web._assets_bootstrap'),
'website_slides/static/src/scss/website_slides.scss',
('include', 'web.pdf_js_lib'),
'website_slides/static/lib/pdfslidesviewer/PDFSlidesViewer.js',
'website_slides/static/src/js/slides_embed.js',
],
'web.qunit_suite_tests': [
'website_slides/static/src/components/activity/activity_tests.js',
],
'web.assets_qweb': [
'website_slides/static/src/components/activity/activity.xml',
],
},
'license': 'LGPL-3',
}
| 41.633333 | 4,996 |
16,478 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.website_slides.tests import common
from odoo.exceptions import AccessError
from odoo.tests import tagged
from odoo.tools import mute_logger
@tagged('security')
class TestAccess(common.SlidesCase):
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_access_channel_invite(self):
""" Invite channels don't give enroll if not member """
self.channel.write({'enroll': 'invite'})
self.channel.with_user(self.user_officer).read(['name'])
self.channel.with_user(self.user_manager).read(['name'])
self.channel.with_user(self.user_emp).read(['name'])
self.channel.with_user(self.user_portal).read(['name'])
self.channel.with_user(self.user_public).read(['name'])
self.slide.with_user(self.user_officer).read(['name'])
self.slide.with_user(self.user_manager).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_portal).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_portal).read(['name'])
# if member -> can read
membership = self.env['slide.channel.partner'].create({
'channel_id': self.channel.id,
'partner_id': self.user_emp.partner_id.id,
})
self.channel.with_user(self.user_emp).read(['name'])
self.slide.with_user(self.user_emp).read(['name'])
# not member anymore -> cannot read
membership.unlink()
self.channel.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_emp).read(['name'])
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_access_channel_public(self):
""" Public channels don't give enroll if not member """
self.channel.write({'enroll': 'public'})
self.channel.with_user(self.user_officer).read(['name'])
self.channel.with_user(self.user_manager).read(['name'])
self.channel.with_user(self.user_emp).read(['name'])
self.channel.with_user(self.user_portal).read(['name'])
self.channel.with_user(self.user_public).read(['name'])
self.slide.with_user(self.user_officer).read(['name'])
self.slide.with_user(self.user_manager).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_portal).read(['name'])
with self.assertRaises(AccessError):
self.slide.with_user(self.user_public).read(['name'])
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_access_channel_publish(self):
""" Unpublished channels and their content are visible only to eLearning people """
self.channel.write({'is_published': False, 'enroll': 'public'})
self.channel.flush(['is_published', 'website_published', 'enroll'])
# channel available only to eLearning
self.channel.invalidate_cache(['name'])
self.channel.with_user(self.user_officer).read(['name'])
self.channel.invalidate_cache(['name'])
self.channel.with_user(self.user_manager).read(['name'])
with self.assertRaises(AccessError):
self.channel.invalidate_cache(['name'])
self.channel.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.channel.invalidate_cache(['name'])
self.channel.with_user(self.user_portal).read(['name'])
with self.assertRaises(AccessError):
self.channel.invalidate_cache(['name'])
self.channel.with_user(self.user_public).read(['name'])
# slide available only to eLearning
self.channel.invalidate_cache(['name'])
self.slide.with_user(self.user_officer).read(['name'])
self.channel.invalidate_cache(['name'])
self.slide.with_user(self.user_manager).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_portal).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_public).read(['name'])
# even members cannot see unpublished content
self.env['slide.channel.partner'].create({
'channel_id': self.channel.id,
'partner_id': self.user_emp.partner_id.id,
})
with self.assertRaises(AccessError):
self.channel.invalidate_cache(['name'])
self.channel.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_emp).read(['name'])
# publish channel but content unpublished (even if can be previewed) still unavailable
self.channel.write({'is_published': True})
self.slide.write({
'is_preview': True,
'is_published': False,
})
self.channel.flush(['website_published'])
self.slide.flush(['is_preview', 'website_published'])
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_officer).read(['name'])
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_manager).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_emp).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_portal).read(['name'])
with self.assertRaises(AccessError):
self.slide.invalidate_cache(['name'])
self.slide.with_user(self.user_public).read(['name'])
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_access_slide_preview(self):
""" Slides with preview flag are always visible even to non members if published """
self.channel.write({'enroll': 'invite'})
self.slide.write({'is_preview': True})
self.slide.flush(['is_preview'])
self.slide.with_user(self.user_officer).read(['name'])
self.slide.with_user(self.user_manager).read(['name'])
self.slide.with_user(self.user_emp).read(['name'])
self.slide.with_user(self.user_portal).read(['name'])
self.slide.with_user(self.user_public).read(['name'])
@tagged('functional', 'security')
class TestRemoveMembership(common.SlidesCase):
def setUp(self):
super(TestRemoveMembership, self).setUp()
self.channel_partner = self.env['slide.channel.partner'].create({
'channel_id': self.channel.id,
'partner_id': self.customer.id,
})
self.slide_partner = self.env['slide.slide.partner'].create({
'slide_id': self.slide.id,
'channel_id': self.channel.id,
'partner_id': self.customer.id
})
def test_security_unlink(self):
# Only the publisher can unlink channel_partner (and slide_partner by extension)
with self.assertRaises(AccessError):
self.channel_partner.with_user(self.user_public).unlink()
with self.assertRaises(AccessError):
self.channel_partner.with_user(self.user_portal).unlink()
with self.assertRaises(AccessError):
self.channel_partner.with_user(self.user_emp).unlink()
def test_slide_partner_remove(self):
id_slide_partner = self.slide_partner.id
id_channel_partner = self.channel_partner.id
self.channel_partner.with_user(self.user_officer).unlink()
self.assertFalse(self.env['slide.channel.partner'].search([('id', '=', '%d' % id_channel_partner)]))
# Slide(s) related to the channel and the partner is unlink too.
self.assertFalse(self.env['slide.slide.partner'].search([('id', '=', '%d' % id_slide_partner)]))
@tagged('functional')
class TestAccessFeatures(common.SlidesCase):
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_channel_auto_subscription(self):
user_employees = self.env['res.users'].search([('groups_id', 'in', self.ref('base.group_user'))])
channel = self.env['slide.channel'].with_user(self.user_officer).create({
'name': 'Test',
'enroll': 'invite',
'is_published': True,
'enroll_group_ids': [(4, self.ref('base.group_user'))]
})
channel.invalidate_cache(['partner_ids'])
self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id'))
new_user = self.env['res.users'].create({
'name': 'NewUser',
'login': 'NewUser',
'groups_id': [(6, 0, [self.ref('base.group_user')])]
})
channel.invalidate_cache()
self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id)
new_user_2 = self.env['res.users'].create({
'name': 'NewUser2',
'login': 'NewUser2',
'groups_id': [(5, 0)]
})
channel.invalidate_cache()
self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id)
new_user_2.write({'groups_id': [(4, self.ref('base.group_user'))]})
channel.invalidate_cache()
self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id | new_user_2.partner_id)
new_user_3 = self.env['res.users'].create({
'name': 'NewUser3',
'login': 'NewUser3',
'groups_id': [(5, 0)]
})
channel.invalidate_cache()
self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id | new_user_2.partner_id)
self.env.ref('base.group_user').write({'users': [(4, new_user_3.id)]})
channel.invalidate_cache()
self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id | new_user_2.partner_id | new_user_3.partner_id)
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_channel_access_fields_employee(self):
channel_manager = self.channel.with_user(self.user_manager)
channel_emp = self.channel.with_user(self.user_emp)
channel_portal = self.channel.with_user(self.user_portal)
self.assertFalse(channel_emp.can_upload)
self.assertFalse(channel_emp.can_publish)
self.assertFalse(channel_portal.can_upload)
self.assertFalse(channel_portal.can_publish)
# allow employees to upload
channel_manager.write({'upload_group_ids': [(4, self.ref('base.group_user'))]})
self.assertTrue(channel_emp.can_upload)
self.assertFalse(channel_emp.can_publish)
self.assertFalse(channel_portal.can_upload)
self.assertFalse(channel_portal.can_publish)
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_channel_access_fields_officer(self):
self.assertEqual(self.channel.user_id, self.user_officer)
channel_officer = self.channel.with_user(self.user_officer)
self.assertTrue(channel_officer.can_upload)
self.assertTrue(channel_officer.can_publish)
channel_officer.write({'upload_group_ids': [(4, self.ref('base.group_system'))]})
self.assertTrue(channel_officer.can_upload)
self.assertTrue(channel_officer.can_publish)
channel_manager = self.channel.with_user(self.user_manager)
channel_manager.write({
'upload_group_ids': [(5, 0)],
'user_id': self.user_manager.id
})
self.assertFalse(channel_officer.can_upload)
self.assertFalse(channel_officer.can_publish)
self.assertTrue(channel_manager.can_upload)
self.assertTrue(channel_manager.can_publish)
@mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule')
def test_channel_access_fields_manager(self):
channel_manager = self.channel.with_user(self.user_manager)
self.assertTrue(channel_manager.can_upload)
self.assertTrue(channel_manager.can_publish)
# test upload group limitation: member of group_system OR responsible OR manager
channel_manager.write({'upload_group_ids': [(4, self.ref('base.group_system'))]})
self.assertFalse(channel_manager.can_upload)
self.assertFalse(channel_manager.can_publish)
channel_manager.write({'user_id': self.user_manager.id})
self.assertTrue(channel_manager.can_upload)
self.assertTrue(channel_manager.can_publish)
# Needs the manager to write on channel as user_officer is not the responsible anymore
channel_manager.write({'upload_group_ids': [(5, 0)]})
self.assertTrue(channel_manager.can_upload)
self.assertTrue(channel_manager.can_publish)
channel_manager.write({'user_id': self.user_officer.id})
self.assertTrue(channel_manager.can_upload)
self.assertTrue(channel_manager.can_publish)
# superuser should always be able to publish even if he's not the responsible
channel_superuser = self.channel.sudo()
channel_superuser.invalidate_cache(['can_upload', 'can_publish'])
self.assertTrue(channel_superuser.can_upload)
self.assertTrue(channel_superuser.can_publish)
@mute_logger('odoo.models.unlink', 'odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model')
def test_resource_access(self):
resource_values = {
'name': 'Image',
'slide_id': self.slide_3.id,
'data': base64.b64encode(b'Some content')
}
resource1, resource2 = self.env['slide.slide.resource'].with_user(self.user_officer).create(
[resource_values for _ in range(2)])
# No public access
with self.assertRaises(AccessError):
resource1.with_user(self.user_public).read(['name'])
with self.assertRaises(AccessError):
resource1.with_user(self.user_public).write({'name': 'other name'})
# No random portal access
with self.assertRaises(AccessError):
resource1.with_user(self.user_portal).read(['name'])
# Members can only read
self.env['slide.channel.partner'].create({
'channel_id': self.channel.id,
'partner_id': self.user_portal.partner_id.id,
})
resource1.with_user(self.user_portal).read(['name'])
with self.assertRaises(AccessError):
resource1.with_user(self.user_portal).write({'name': 'other name'})
# Other officers can only read
user_officer_other = mail_new_test_user(
self.env, name='Ornella Officer', login='user_officer_2', email='[email protected]',
groups='base.group_user,website_slides.group_website_slides_officer'
)
resource1.with_user(user_officer_other).read(['name'])
with self.assertRaises(AccessError):
resource1.with_user(user_officer_other).write({'name': 'Another name'})
with self.assertRaises(AccessError):
self.env['slide.slide.resource'].with_user(user_officer_other).create(resource_values)
with self.assertRaises(AccessError):
resource1.with_user(user_officer_other).unlink()
# Responsible officer can do anything on their own channels
resource1.with_user(self.user_officer).write({'name': 'other name'})
resource1.with_user(self.user_officer).unlink()
# Managers can do anything on all channels
resource2.with_user(self.user_manager).write({'name': 'Another name'})
resource2.with_user(self.user_manager).unlink()
self.env['slide.slide.resource'].with_user(self.user_manager).create(resource_values)
| 46.679887 | 16,478 |
10,836 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import math
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.addons.website_slides.tests import common
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.tools import mute_logger, float_compare
@tagged('functional')
class TestChannelStatistics(common.SlidesCase):
@mute_logger('odoo.models')
def test_channel_new_content(self):
(self.slide | self.slide_2).write({'date_published': fields.Datetime.now() + relativedelta(days=-6)})
self.slide_3.write({'date_published': fields.Datetime.now() + relativedelta(days=-8)})
self.assertTrue(all(slide.is_new_slide for slide in (self.slide | self.slide_2)))
self.assertFalse(self.slide_3.is_new_slide)
channel_aspublisher = self.channel.with_user(self.user_officer)
self.assertTrue(channel_aspublisher.partner_has_new_content)
(self.slide | self.slide_2).with_user(self.user_officer).action_set_completed()
self.assertFalse(channel_aspublisher.partner_has_new_content)
channel_aspublisher._action_add_members(self.user_portal.partner_id)
channel_asportal = self.channel.with_user(self.user_portal)
self.assertTrue(channel_asportal.partner_has_new_content)
(self.slide | self.slide_2).write({'date_published': fields.Datetime.now() + relativedelta(days=-8)})
channel_asportal.invalidate_cache(['partner_has_new_content'])
self.assertFalse(channel_asportal.partner_has_new_content)
@mute_logger('odoo.models')
def test_channel_statistics(self):
channel_publisher = self.channel.with_user(self.user_officer)
# slide type computation
self.assertEqual(channel_publisher.total_slides, len(channel_publisher.slide_content_ids))
self.assertEqual(channel_publisher.nbr_infographic, len(channel_publisher.slide_content_ids.filtered(lambda s: s.slide_type == 'infographic')))
self.assertEqual(channel_publisher.nbr_presentation, len(channel_publisher.slide_content_ids.filtered(lambda s: s.slide_type == 'presentation')))
self.assertEqual(channel_publisher.nbr_document, len(channel_publisher.slide_content_ids.filtered(lambda s: s.slide_type == 'document')))
self.assertEqual(channel_publisher.nbr_video, len(channel_publisher.slide_content_ids.filtered(lambda s: s.slide_type == 'video')))
# slide statistics computation
self.assertEqual(float_compare(channel_publisher.total_time, sum(s.completion_time for s in channel_publisher.slide_content_ids), 3), 0)
# members computation
self.assertEqual(channel_publisher.members_count, 1)
channel_publisher.action_add_member()
self.assertEqual(channel_publisher.members_count, 1)
channel_publisher._action_add_members(self.user_emp.partner_id)
channel_publisher.invalidate_cache(['partner_ids'])
self.assertEqual(channel_publisher.members_count, 2)
self.assertEqual(channel_publisher.partner_ids, self.user_officer.partner_id | self.user_emp.partner_id)
@mute_logger('odoo.models')
def test_channel_user_statistics(self):
channel_publisher = self.channel.with_user(self.user_officer)
channel_publisher.write({
'enroll': 'invite',
})
channel_publisher._action_add_members(self.user_emp.partner_id)
channel_emp = self.channel.with_user(self.user_emp)
members = self.env['slide.channel.partner'].search([('channel_id', '=', self.channel.id)])
member_emp = members.filtered(lambda m: m.partner_id == self.user_emp.partner_id)
member_publisher = members.filtered(lambda m: m.partner_id == self.user_officer.partner_id)
slides_emp = (self.slide | self.slide_2).with_user(self.user_emp)
slides_emp.action_set_viewed()
self.assertEqual(member_emp.completion, 0)
self.assertEqual(channel_emp.completion, 0)
slides_emp.action_set_completed()
channel_emp.invalidate_cache()
self.assertEqual(
channel_emp.completion,
math.ceil(100.0 * len(slides_emp) / len(channel_publisher.slide_content_ids)))
self.assertFalse(channel_emp.completed)
self.slide_3.with_user(self.user_emp).action_set_completed()
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertTrue(channel_emp.completed)
# The following tests should not update the completion for users that has already completed the course
self.slide_3.is_published = False
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertTrue(channel_emp.completed)
self.slide_3.is_published = True
self.slide_3.active = False
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertTrue(channel_emp.completed)
self.assertEqual(member_publisher.completion, 0)
self.assertEqual(channel_publisher.completion, 0)
self.slide.with_user(self.user_officer).action_set_completed()
self.assertEqual(member_publisher.completion, 50)
self.assertEqual(channel_publisher.completion, 50)
# Should update completion when slide is (un)archived
self.slide_3.active = True
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertEqual(member_publisher.completion, 33)
self.assertEqual(channel_publisher.completion, 33)
# Should update completion when a new published slide is created
self.slide_4 = self.slide_3.copy({'is_published': True})
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertEqual(member_publisher.completion, 25)
self.assertEqual(channel_publisher.completion, 25)
# Should update completion when slide is (un)published
self.slide_4.is_published = False
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertEqual(member_publisher.completion, 33)
self.assertEqual(channel_publisher.completion, 33)
# Should update completion when a slide is unlinked
self.slide.with_user(self.user_manager).unlink()
self.assertEqual(member_emp.completion, 100)
self.assertEqual(channel_emp.completion, 100)
self.assertEqual(member_publisher.completion, 0)
self.assertEqual(channel_publisher.completion, 0)
@mute_logger('odoo.models')
def test_channel_user_statistics_complete_check_member(self):
slides = (self.slide | self.slide_2)
slides.write({'is_preview': True})
slides.flush(['is_preview'])
slides_emp = slides.with_user(self.user_emp)
slides_emp.read(['name'])
with self.assertRaises(UserError):
slides_emp.action_set_completed()
@mute_logger('odoo.models')
def test_channel_user_statistics_view_check_member(self):
slides = (self.slide | self.slide_2)
slides.write({'is_preview': True})
slides.flush(['is_preview'])
slides_emp = slides.with_user(self.user_emp)
slides_emp.read(['name'])
with self.assertRaises(UserError):
slides_emp.action_set_viewed()
@tagged('functional')
class TestSlideStatistics(common.SlidesCase):
def test_slide_user_statistics(self):
channel_publisher = self.channel.with_user(self.user_officer)
channel_publisher._action_add_members(self.user_emp.partner_id)
channel_publisher.invalidate_cache(['partner_ids'])
slide_emp = self.slide.with_user(self.user_emp)
self.assertEqual(slide_emp.likes, 0)
self.assertEqual(slide_emp.dislikes, 0)
self.assertEqual(slide_emp.user_vote, 0)
slide_emp.action_like()
self.assertEqual(slide_emp.likes, 1)
self.assertEqual(slide_emp.dislikes, 0)
self.assertEqual(slide_emp.user_vote, 1)
slide_emp.action_dislike()
self.assertEqual(slide_emp.likes, 0)
self.assertEqual(slide_emp.dislikes, 0)
self.assertEqual(slide_emp.user_vote, 0)
slide_emp.action_dislike()
self.assertEqual(slide_emp.likes, 0)
self.assertEqual(slide_emp.dislikes, 1)
self.assertEqual(slide_emp.user_vote, -1)
def test_slide_statistics_views(self):
channel_publisher = self.channel.with_user(self.user_officer)
channel_publisher._action_add_members(self.user_emp.partner_id)
self.assertEqual(self.slide.slide_views, 0)
self.assertEqual(self.slide.public_views, 0)
self.slide.write({'public_views': 4})
self.assertEqual(self.slide.slide_views, 0)
self.assertEqual(self.slide.public_views, 4)
self.assertEqual(self.slide.total_views, 4)
slide_emp = self.slide.with_user(self.user_emp)
slide_emp.action_set_viewed()
self.assertEqual(slide_emp.slide_views, 1)
self.assertEqual(slide_emp.public_views, 4)
self.assertEqual(slide_emp.total_views, 5)
@users('user_officer')
def test_slide_statistics_types(self):
category = self.category.with_user(self.env.user)
self.assertEqual(
category.nbr_presentation,
len(category.channel_id.slide_ids.filtered(lambda s: s.category_id == category and s.slide_type == 'presentation')))
self.assertEqual(
category.nbr_document,
len(category.channel_id.slide_ids.filtered(lambda s: s.category_id == category and s.slide_type == 'document')))
self.assertEqual(self.channel.total_slides, 3, 'The channel should contain 3 slides')
self.assertEqual(category.total_slides, 2, 'The first category should contain 2 slides')
other_category = self.env['slide.slide'].with_user(self.user_officer).create({
'name': 'Other Category',
'channel_id': self.channel.id,
'is_category': True,
'is_published': True,
'sequence': 5,
})
self.assertEqual(other_category.total_slides, 0, 'The other category should not contain any slide yet')
# move one of the slide to the other category
self.slide_3.write({'sequence': 6})
self.assertEqual(category.total_slides, 1, 'The first category should contain 1 slide')
self.assertEqual(other_category.total_slides, 1, 'The other category should contain 1 slide')
self.assertEqual(self.channel.total_slides, 3, 'The channel should still contain 3 slides')
| 47.735683 | 10,836 |
4,777 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_slides.tests import common
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.tools import mute_logger
@tagged('functional')
class TestKarmaGain(common.SlidesCase):
def setUp(self):
super(TestKarmaGain, self).setUp()
self.channel_2 = self.env['slide.channel'].with_user(self.user_officer).create({
'name': 'Test Channel 2',
'channel_type': 'training',
'promote_strategy': 'most_voted',
'enroll': 'public',
'visibility': 'public',
'is_published': True,
'karma_gen_channel_finish': 100,
'karma_gen_slide_vote': 5,
'karma_gen_channel_rank': 10,
})
self.slide_2_0 = self.env['slide.slide'].with_user(self.user_officer).create({
'name': 'How to travel through space and time',
'channel_id': self.channel_2.id,
'slide_type': 'presentation',
'is_published': True,
'completion_time': 2.0,
})
self.slide_2_1 = self.env['slide.slide'].with_user(self.user_officer).create({
'name': 'How to duplicate yourself',
'channel_id': self.channel_2.id,
'slide_type': 'presentation',
'is_published': True,
'completion_time': 2.0,
})
@mute_logger('odoo.models')
@users('user_emp', 'user_portal', 'user_officer')
def test_karma_gain(self):
user = self.env.user
user.write({'karma': 0})
computed_karma = 0
# Add the user to the course
(self.channel | self.channel_2)._action_add_members(user.partner_id)
self.assertEqual(user.karma, 0)
# Finish the Course
self.slide.with_user(user).action_set_completed()
self.assertFalse(self.channel.with_user(user).completed)
self.slide_2.with_user(user).action_set_completed()
# answer a quizz question
self.slide_3.with_user(user).action_set_viewed(quiz_attempts_inc=True)
self.slide_3.with_user(user)._action_set_quiz_done()
self.slide_3.with_user(user).action_set_completed()
computed_karma += self.slide_3.quiz_first_attempt_reward
computed_karma += self.channel.karma_gen_channel_finish
self.assertTrue(self.channel.with_user(user).completed)
self.assertEqual(user.karma, computed_karma)
# Begin then finish the second Course
self.slide_2_0.with_user(user).action_set_completed()
self.assertFalse(self.channel_2.with_user(user).completed)
self.assertEqual(user.karma, computed_karma)
self.slide_2_1.with_user(user).action_set_completed()
self.assertTrue(self.channel_2.with_user(user).completed)
computed_karma += self.channel_2.karma_gen_channel_finish
self.assertEqual(user.karma, computed_karma)
# Vote for a slide
slide_user = self.slide.with_user(user)
slide_user.action_like()
computed_karma += self.channel.karma_gen_slide_vote
self.assertEqual(user.karma, computed_karma)
slide_user.action_like() # re-like something already liked should not add karma again
self.assertEqual(user.karma, computed_karma)
slide_user.action_dislike()
computed_karma -= self.channel.karma_gen_slide_vote
self.assertEqual(user.karma, computed_karma)
slide_user.action_dislike()
computed_karma -= self.channel.karma_gen_slide_vote
self.assertEqual(user.karma, computed_karma)
slide_user.action_dislike() # dislike again something already disliked should not remove karma again
self.assertEqual(user.karma, computed_karma)
# Leave the finished course
self.channel._remove_membership(user.partner_id.ids)
computed_karma -= self.channel.karma_gen_channel_finish
computed_karma -= self.slide_3.quiz_first_attempt_reward
self.assertEqual(user.karma, computed_karma)
@mute_logger('odoo.models')
@users('user_emp', 'user_portal', 'user_officer')
def test_karma_gain_multiple_course(self):
user = self.env.user
user.write({'karma': 0})
computed_karma = 0
# Finish two course at the same time (should not ever happen but hey, we never know)
(self.channel | self.channel_2)._action_add_members(user.partner_id)
computed_karma += self.channel.karma_gen_channel_finish + self.channel_2.karma_gen_channel_finish
(self.slide | self.slide_2 | self.slide_3 | self.slide_2_0 | self.slide_2_1).with_user(user).action_set_completed()
self.assertEqual(user.karma, computed_karma)
| 42.274336 | 4,777 |
3,886 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
from odoo.addons.mail.tests.common import mail_new_test_user, MockEmail
class SlidesCase(common.TransactionCase, MockEmail):
@classmethod
def setUpClass(cls):
super(SlidesCase, cls).setUpClass()
cls.user_officer = mail_new_test_user(
cls.env, name='Ophélie Officer', login='user_officer', email='[email protected]',
groups='base.group_user,website_slides.group_website_slides_officer'
)
cls.user_manager = mail_new_test_user(
cls.env, name='Manuel Manager', login='user_manager', email='[email protected]',
groups='base.group_user,website_slides.group_website_slides_manager'
)
cls.user_emp = mail_new_test_user(
cls.env, name='Eglantine Employee', login='user_emp', email='[email protected]',
groups='base.group_user'
)
cls.user_portal = mail_new_test_user(
cls.env, name='Patrick Portal', login='user_portal', email='[email protected]',
groups='base.group_portal'
)
cls.user_public = mail_new_test_user(
cls.env, name='Pauline Public', login='user_public', email='[email protected]',
groups='base.group_public'
)
cls.customer = cls.env['res.partner'].create({
'name': 'Caroline Customer',
'email': '[email protected]',
})
cls.channel = cls.env['slide.channel'].with_user(cls.user_officer).create({
'name': 'Test Channel',
'channel_type': 'documentation',
'promote_strategy': 'most_voted',
'enroll': 'public',
'visibility': 'public',
'is_published': True,
'karma_gen_channel_finish': 100,
'karma_gen_slide_vote': 5,
'karma_gen_channel_rank': 10,
})
cls.slide = cls.env['slide.slide'].with_user(cls.user_officer).create({
'name': 'How To Cook Humans',
'channel_id': cls.channel.id,
'slide_type': 'presentation',
'is_published': True,
'completion_time': 2.0,
'sequence': 1,
})
cls.category = cls.env['slide.slide'].with_user(cls.user_officer).create({
'name': 'Cooking Tips for Humans',
'channel_id': cls.channel.id,
'is_category': True,
'is_published': True,
'sequence': 2,
})
cls.slide_2 = cls.env['slide.slide'].with_user(cls.user_officer).create({
'name': 'How To Cook For Humans',
'channel_id': cls.channel.id,
'slide_type': 'presentation',
'is_published': True,
'completion_time': 3.0,
'sequence': 3,
})
cls.slide_3 = cls.env['slide.slide'].with_user(cls.user_officer).create({
'name': 'How To Cook Humans For Humans',
'channel_id': cls.channel.id,
'slide_type': 'document',
'is_published': True,
'completion_time': 1.5,
'sequence': 4,
'quiz_first_attempt_reward': 42,
})
cls.question_1 = cls.env['slide.question'].with_user(cls.user_officer).create({
'question': 'How long should be cooked a human?',
'slide_id': cls.slide_3.id,
})
cls.answer_1 = cls.env['slide.answer'].with_user(cls.user_officer).create({
'question_id': cls.question_1.id,
'text_value': "25' at 180°C",
'is_correct': True,
})
cls.answer_2 = cls.env['slide.answer'].with_user(cls.user_officer).create({
'question_id': cls.question_1.id,
'text_value': "Raw",
'is_correct': False,
})
| 38.84 | 3,884 |
8,356 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from dateutil.relativedelta import relativedelta
from odoo import tests
from odoo.fields import Datetime
from odoo.modules.module import get_module_resource
from odoo.addons.base.tests.common import HttpCaseWithUserDemo, HttpCaseWithUserPortal
class TestUICommon(HttpCaseWithUserDemo, HttpCaseWithUserPortal):
def setUp(self):
super(TestUICommon, self).setUp()
# Load pdf and img contents
pdf_path = get_module_resource('website_slides', 'static', 'src', 'img', 'presentation.pdf')
pdf_content = base64.b64encode(open(pdf_path, "rb").read())
img_path = get_module_resource('website_slides', 'static', 'src', 'img', 'slide_demo_gardening_1.jpg')
img_content = base64.b64encode(open(img_path, "rb").read())
self.channel = self.env['slide.channel'].create({
'name': 'Basics of Gardening - Test',
'user_id': self.env.ref('base.user_admin').id,
'enroll': 'public',
'channel_type': 'training',
'allow_comment': True,
'promote_strategy': 'most_voted',
'is_published': True,
'description': 'Learn the basics of gardening !',
'create_date': Datetime.now() - relativedelta(days=8),
'slide_ids': [
(0, 0, {
'name': 'Gardening: The Know-How',
'sequence': 1,
'datas': pdf_content,
'slide_type': 'presentation',
'is_published': True,
'is_preview': True,
}), (0, 0, {
'name': 'Home Gardening',
'sequence': 2,
'image_1920': img_content,
'slide_type': 'infographic',
'is_published': True,
}), (0, 0, {
'name': 'Mighty Carrots',
'sequence': 3,
'image_1920': img_content,
'slide_type': 'infographic',
'is_published': True,
}), (0, 0, {
'name': 'How to Grow and Harvest The Best Strawberries | Basics',
'sequence': 4,
'datas': pdf_content,
'slide_type': 'document',
'is_published': True,
}), (0, 0, {
'name': 'Test your knowledge',
'sequence': 5,
'slide_type': 'quiz',
'is_published': True,
'question_ids': [
(0, 0, {
'question': 'What is a strawberry ?',
'answer_ids': [
(0, 0, {
'text_value': 'A fruit',
'is_correct': True,
'sequence': 1,
}), (0, 0, {
'text_value': 'A vegetable',
'sequence': 2,
}), (0, 0, {
'text_value': 'A table',
'sequence': 3,
})
]
}), (0, 0, {
'question': 'What is the best tool to dig a hole for your plants ?',
'answer_ids': [
(0, 0, {
'text_value': 'A shovel',
'is_correct': True,
'sequence': 1,
}), (0, 0, {
'text_value': 'A spoon',
'sequence': 2,
})
]
})
]
})
]
})
@tests.common.tagged('post_install', '-at_install')
class TestUi(TestUICommon):
def test_course_member_employee(self):
user_demo = self.user_demo
user_demo.flush()
user_demo.write({
'karma': 1,
'groups_id': [(6, 0, self.env.ref('base.group_user').ids)]
})
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("course_member")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.course_member.ready',
login=user_demo.login)
def test_course_member_elearning_officer(self):
user_demo = self.user_demo
user_demo.flush()
user_demo.write({
'karma': 1,
'groups_id': [(6, 0, (self.env.ref('base.group_user') | self.env.ref('website_slides.group_website_slides_officer')).ids)]
})
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("course_member")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.course_member.ready',
login=user_demo.login)
def test_course_member_portal(self):
user_portal = self.user_portal
user_portal.flush()
user_portal.karma = 1
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("course_member")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.course_member.ready',
login=user_portal.login)
def test_full_screen_edition_website_publisher(self):
# group_website_designer
user_demo = self.env.ref('base.user_demo')
user_demo.flush()
user_demo.write({
'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id), (4, self.env.ref('website.group_website_publisher').id)]
})
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("full_screen_web_editor")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.full_screen_web_editor.ready',
login=user_demo.login)
def test_course_reviews_elearning_officer(self):
user_demo = self.user_demo
user_demo.write({
'groups_id': [(6, 0, (self.env.ref('base.group_user') | self.env.ref('website_slides.group_website_slides_officer')).ids)]
})
# The user must be a course member before being able to post a log note.
self.channel._action_add_members(user_demo.partner_id)
self.channel.with_user(user_demo).message_post(
body='Log note', subtype_xmlid='mail.mt_note', message_type='comment')
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("course_reviews")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.course_reviews.ready',
login=user_demo.login)
@tests.common.tagged('external', 'post_install', '-standard', '-at_install')
class TestUiYoutube(HttpCaseWithUserDemo):
def test_course_member_yt_employee(self):
# remove membership because we need to be able to join the course during the tour
user_demo = self.user_demo
user_demo.flush()
user_demo.write({
'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id)]
})
self.env.ref('website_slides.slide_channel_demo_3_furn0')._remove_membership(self.env.ref('base.partner_demo').ids)
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("course_member_youtube")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.course_member_youtube.ready',
login=user_demo.login)
def test_course_publisher_elearning_manager(self):
user_demo = self.user_demo
user_demo.flush()
user_demo.write({
'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id), (4, self.env.ref('website_slides.group_website_slides_manager').id)]
})
self.browser_js(
'/slides',
'odoo.__DEBUG__.services["web_tour.tour"].run("course_publisher")',
'odoo.__DEBUG__.services["web_tour.tour"].tours.course_publisher.ready',
login=user_demo.login)
| 41.572139 | 8,356 |
866 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_slides.tests import common
class TestAttendee(common.SlidesCase):
def test_course_attendee_copy(self):
""" To check members of the channel after duplication of contact """
# Adding attendee
self.channel._action_add_members(self.customer)
self.channel.invalidate_cache()
# Attendee count before copy of contact
attendee_before = self.env['slide.channel.partner'].search_count([])
# Duplicating the contact
self.customer.copy()
# Attendee count after copy of contact
attendee_after = self.env['slide.channel.partner'].search_count([])
self.assertEqual(attendee_before, attendee_after, "Duplicating the contact should not create a new attendee")
| 37.652174 | 866 |
11,099 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_slides.tests import common as slides_common
from odoo.tests.common import users
class TestSlidesManagement(slides_common.SlidesCase):
@users('user_officer')
def test_get_categorized_slides(self):
new_category = self.env['slide.slide'].create({
'name': 'Cooking Tips for Cooking Humans',
'channel_id': self.channel.id,
'is_category': True,
'sequence': 5,
})
order = self.env['slide.slide']._order_by_strategy['sequence']
categorized_slides = self.channel._get_categorized_slides([], order)
self.assertEqual(categorized_slides[0]['category'], False)
self.assertEqual(categorized_slides[1]['category'], self.category)
self.assertEqual(categorized_slides[1]['total_slides'], 2)
self.assertEqual(categorized_slides[2]['total_slides'], 0)
self.assertEqual(categorized_slides[2]['category'], new_category)
@users('user_manager')
def test_archive(self):
self.env['slide.slide.partner'].create({
'slide_id': self.slide.id,
'channel_id': self.channel.id,
'partner_id': self.user_manager.partner_id.id,
'completed': True
})
channel_partner = self.channel._action_add_members(self.user_manager.partner_id)
self.assertTrue(self.channel.active)
self.assertTrue(self.channel.is_published)
self.assertFalse(channel_partner.completed)
for slide in self.channel.slide_ids:
self.assertTrue(slide.active, "All slide should be archived when a channel is archived")
self.assertTrue(slide.is_published, "All slide should be unpublished when a channel is archived")
self.channel.toggle_active()
self.assertFalse(self.channel.active)
self.assertFalse(self.channel.is_published)
# channel_partner should still NOT be marked as completed
self.assertFalse(channel_partner.completed)
for slide in self.channel.slide_ids:
self.assertFalse(slide.active, "All slides should be archived when a channel is archived")
if not slide.is_category:
self.assertFalse(slide.is_published, "All slides should be unpublished when a channel is archived, except categories")
else:
self.assertTrue(slide.is_published, "All slides should be unpublished when a channel is archived, except categories")
def test_mail_completed(self):
""" When the slide.channel is completed, an email is supposed to be sent to people that completed it. """
channel_2 = self.env['slide.channel'].create({
'name': 'Test Course 2',
'slide_ids': [(0, 0, {
'name': 'Test Slide 1'
})]
})
all_users = self.user_officer | self.user_emp | self.user_portal
all_channels = self.channel | channel_2
all_channels.sudo()._action_add_members(all_users.partner_id)
slide_slide_vals = []
for slide in all_channels.slide_content_ids:
for user in self.user_officer | self.user_emp:
slide_slide_vals.append({
'slide_id': slide.id,
'channel_id': self.channel.id,
'partner_id': user.partner_id.id,
'completed': True
})
self.env['slide.slide.partner'].create(slide_slide_vals)
created_mails = self.env['mail.mail'].search([])
# 2 'congratulations' emails are supposed to be sent to user_officer and user_emp
for user in self.user_officer | self.user_emp:
self.assertTrue(
any(mail.model == 'slide.channel.partner' and user.partner_id in mail.recipient_ids
for mail in created_mails)
)
# user_portal has not finished the course, it should not receive anything
self.assertFalse(
any(mail.model == 'slide.channel.partner' and self.user_portal.partner_id in mail.recipient_ids
for mail in created_mails)
)
def test_mail_completed_with_different_templates(self):
""" When the completion email is generated, it must take into account different templates. """
mail_template = self.env['mail.template'].create({
'model_id': self.env['ir.model']._get('slide.channel.partner').id,
'name': 'test template',
'partner_to': '{{ object.partner_id.id }}',
'body_html': '<p>TestBodyTemplate2</p>',
'subject': 'ATestSubject'
})
channel_2 = self.env['slide.channel'].create({
'name': 'Test Course 2',
'slide_ids': [(0, 0, {
'name': 'Test Slide 2'
})],
'completed_template_id': mail_template.id
})
self.channel.completed_template_id.body_html = '<p>TestBodyTemplate</p>'
all_channels = self.channel | channel_2
all_channels.sudo()._action_add_members(self.user_officer.partner_id)
with self.mock_mail_gateway():
self.env['slide.slide.partner'].create([
{'channel_id': self.channel.id,
'completed': True,
'partner_id': self.user_officer.partner_id.id,
'slide_id': slide.id,
}
for slide in all_channels.slide_content_ids
])
slide_created_mails = self._new_mails.filtered(lambda m: m.model == 'slide.channel.partner')
# 2 mails should be generated from two different templates:
# the default template and the new one
self.assertEqual(len(slide_created_mails), 2)
self.assertEqual(
slide_created_mails.mapped('body'),
['<p>TestBodyTemplate</p>', '<p>TestBodyTemplate2</p>']
)
self.assertEqual(
slide_created_mails.mapped('subject'),
['Congratulation! You completed %s' % self.channel.name, 'ATestSubject']
)
class TestSequencing(slides_common.SlidesCase):
@users('user_officer')
def test_category_update(self):
self.assertEqual(self.channel.slide_category_ids, self.category)
self.assertEqual(self.channel.slide_content_ids, self.slide | self.slide_2 | self.slide_3)
self.assertEqual(self.slide.category_id, self.env['slide.slide'])
self.assertEqual(self.slide_2.category_id, self.category)
self.assertEqual(self.slide_3.category_id, self.category)
self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.category.id, self.slide_2.id, self.slide_3.id])
self.slide.write({'sequence': 0})
self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.category.id, self.slide_2.id, self.slide_3.id])
self.assertEqual(self.slide_2.category_id, self.category)
self.slide_2.write({'sequence': 1})
self.channel.invalidate_cache()
self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.slide_2.id, self.category.id, self.slide_3.id])
self.assertEqual(self.slide_2.category_id, self.env['slide.slide'])
channel_2 = self.env['slide.channel'].create({
'name': 'Test2'
})
new_category = self.env['slide.slide'].create({
'name': 'NewCategorySlide',
'channel_id': channel_2.id,
'is_category': True,
'sequence': 1,
})
new_category_2 = self.env['slide.slide'].create({
'name': 'NewCategorySlide2',
'channel_id': channel_2.id,
'is_category': True,
'sequence': 2,
})
new_slide = self.env['slide.slide'].create({
'name': 'NewTestSlide',
'channel_id': channel_2.id,
'sequence': 2,
})
self.assertEqual(new_slide.category_id, new_category_2)
(new_slide | self.slide_3).write({'sequence': 1})
self.assertEqual(new_slide.category_id, new_category)
self.assertEqual(self.slide_3.category_id, self.env['slide.slide'])
(new_slide | self.slide_3).write({'sequence': 0})
self.assertEqual(new_slide.category_id, self.env['slide.slide'])
self.assertEqual(self.slide_3.category_id, self.env['slide.slide'])
@users('user_officer')
def test_resequence(self):
self.assertEqual(self.slide.sequence, 1)
self.category.write({'sequence': 4})
self.slide_2.write({'sequence': 8})
self.slide_3.write({'sequence': 3})
self.channel.invalidate_cache()
self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.slide_3.id, self.category.id, self.slide_2.id])
self.assertEqual(self.slide.sequence, 1)
# insert a new category and check resequence_slides does as expected
new_category = self.env['slide.slide'].create({
'name': 'Sub-cooking Tips Category',
'channel_id': self.channel.id,
'is_category': True,
'is_published': True,
'sequence': 2,
})
new_category.flush()
self.channel.invalidate_cache()
self.channel._resequence_slides(self.slide_3, force_category=new_category)
self.assertEqual(self.slide.sequence, 1)
self.assertEqual(new_category.sequence, 2)
self.assertEqual(self.slide_3.sequence, 3)
self.assertEqual(self.category.sequence, 4)
self.assertEqual(self.slide_2.sequence, 5)
self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, new_category.id, self.slide_3.id, self.category.id, self.slide_2.id])
class TestFromURL(slides_common.SlidesCase):
def test_youtube_urls(self):
urls = {
'W0JQcpGLSFw': [
'https://youtu.be/W0JQcpGLSFw',
'https://www.youtube.com/watch?v=W0JQcpGLSFw',
'https://www.youtube.com/watch?v=W0JQcpGLSFw&list=PL1-aSABtP6ACZuppkBqXFgzpNb2nVctZx',
],
'vmhB-pt7EfA': [ # id starts with v, it is important
'https://youtu.be/vmhB-pt7EfA',
'https://www.youtube.com/watch?feature=youtu.be&v=vmhB-pt7EfA',
'https://www.youtube.com/watch?v=vmhB-pt7EfA&list=PL1-aSABtP6ACZuppkBqXFgzpNb2nVctZx&index=7',
],
'hlhLv0GN1hA': [
'https://www.youtube.com/v/hlhLv0GN1hA',
'https://www.youtube.com/embed/hlhLv0GN1hA',
'https://www.youtube-nocookie.com/embed/hlhLv0GN1hA',
'https://m.youtube.com/watch?v=hlhLv0GN1hA',
],
}
for id, urls in urls.items():
for url in urls:
with self.subTest(url=url, id=id):
document = self.env['slide.slide']._find_document_data_from_url(url)
self.assertEqual(document[0], 'youtube')
self.assertEqual(document[1], id)
| 45.863636 | 11,099 |
5,392 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import re
from odoo import api, fields, models, _
from odoo.exceptions import UserError, AccessError
_logger = logging.getLogger(__name__)
emails_split = re.compile(r"[;,\n\r]+")
class SlideChannelInvite(models.TransientModel):
_name = 'slide.channel.invite'
_inherit = 'mail.composer.mixin'
_description = 'Channel Invitation Wizard'
# composer content
attachment_ids = fields.Many2many('ir.attachment', string='Attachments')
# recipients
partner_ids = fields.Many2many('res.partner', string='Recipients')
# slide channel
channel_id = fields.Many2one('slide.channel', string='Slide channel', required=True)
# Overrides of mail.composer.mixin
@api.depends('channel_id') # fake trigger otherwise not computed in new mode
def _compute_render_model(self):
self.render_model = 'slide.channel.partner'
@api.onchange('partner_ids')
def _onchange_partner_ids(self):
if self.partner_ids:
signup_allowed = self.env['res.users'].sudo()._get_signup_invitation_scope() == 'b2c'
if not signup_allowed:
invalid_partners = self.env['res.partner'].search([
('user_ids', '=', False),
('id', 'in', self.partner_ids.ids)
])
if invalid_partners:
raise UserError(_(
'The following recipients have no user account: %s. You should create user accounts for them or allow external sign up in configuration.',
', '.join(invalid_partners.mapped('name'))
))
@api.model
def create(self, values):
if values.get('template_id') and not (values.get('body') or values.get('subject')):
template = self.env['mail.template'].browse(values['template_id'])
if not values.get('subject'):
values['subject'] = template.subject
if not values.get('body'):
values['body'] = template.body_html
return super(SlideChannelInvite, self).create(values)
def action_invite(self):
""" Process the wizard content and proceed with sending the related
email(s), rendering any template patterns on the fly if needed """
self.ensure_one()
if not self.env.user.email:
raise UserError(_("Unable to post message, please configure the sender's email address."))
if not self.partner_ids:
raise UserError(_("Please select at least one recipient."))
try:
self.channel_id.check_access_rights('write')
self.channel_id.check_access_rule('write')
except AccessError:
raise AccessError(_('You are not allowed to add members to this course. Please contact the course responsible or an administrator.'))
mail_values = []
for partner_id in self.partner_ids:
slide_channel_partner = self.channel_id._action_add_members(partner_id)
if slide_channel_partner:
mail_values.append(self._prepare_mail_values(slide_channel_partner))
self.env['mail.mail'].sudo().create(mail_values)
return {'type': 'ir.actions.act_window_close'}
def _prepare_mail_values(self, slide_channel_partner):
""" Create mail specific for recipient """
subject = self._render_field('subject', slide_channel_partner.ids, options={'render_safe': True})[slide_channel_partner.id]
body = self._render_field('body', slide_channel_partner.ids, post_process=True)[slide_channel_partner.id]
# post the message
mail_values = {
'email_from': self.env.user.email_formatted,
'author_id': self.env.user.partner_id.id,
'model': None,
'res_id': None,
'subject': subject,
'body_html': body,
'attachment_ids': [(4, att.id) for att in self.attachment_ids],
'auto_delete': True,
'recipient_ids': [(4, slide_channel_partner.partner_id.id)]
}
# optional support of notif_layout in context
notif_layout = self.env.context.get('notif_layout', self.env.context.get('custom_layout'))
if notif_layout:
try:
template = self.env.ref(notif_layout, raise_if_not_found=True)
except ValueError:
_logger.warning('QWeb template %s not found when sending slide channel mails. Sending without layouting.' % (notif_layout))
else:
# could be great to use _notify_prepare_template_context someday
template_ctx = {
'message': self.env['mail.message'].sudo().new(dict(body=mail_values['body_html'], record_name=self.channel_id.name)),
'model_description': self.env['ir.model']._get('slide.channel').display_name,
'record': slide_channel_partner,
'company': self.env.company,
'signature': self.channel_id.user_id.signature,
}
body = template._render(template_ctx, engine='ir.qweb', minimal_qcontext=True)
mail_values['body_html'] = self.env['mail.render.mixin']._replace_local_links(body)
return mail_values
| 45.310924 | 5,392 |
346 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class Challenge(models.Model):
_inherit = 'gamification.challenge'
challenge_category = fields.Selection(selection_add=[
('slides', 'Website / Slides')
], ondelete={'slides': 'set default'})
| 28.833333 | 346 |
1,152 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class Http(models.AbstractModel):
_inherit = 'ir.http'
def binary_content(self, xmlid=None, model='ir.attachment', id=None, field='datas',
unique=False, filename=None, filename_field='name', download=False,
mimetype=None, default_mimetype='application/octet-stream',
access_token=None):
obj = None
if xmlid:
obj = self._xmlid_to_obj(self.env, xmlid)
if obj and obj._name != 'slide.slide':
obj = None
elif id and model == 'slide.slide':
obj = self.env[model].browse(int(id))
if obj:
obj.check_access_rights('read')
obj.check_access_rule('read')
return super(Http, self).binary_content(
xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename,
filename_field=filename_field, download=download, mimetype=mimetype,
default_mimetype=default_mimetype, access_token=access_token)
| 42.666667 | 1,152 |
46,293 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import datetime
import io
import re
import requests
import PyPDF2
import json
from dateutil.relativedelta import relativedelta
from PIL import Image
from werkzeug import urls
from odoo import api, fields, models, _
from odoo.addons.http_routing.models.ir_http import slug
from odoo.exceptions import UserError, AccessError
from odoo.http import request
from odoo.addons.http_routing.models.ir_http import url_for
from odoo.tools import html2plaintext, sql
class SlidePartnerRelation(models.Model):
_name = 'slide.slide.partner'
_description = 'Slide / Partner decorated m2m'
_table = 'slide_slide_partner'
slide_id = fields.Many2one('slide.slide', ondelete="cascade", index=True, required=True)
channel_id = fields.Many2one(
'slide.channel', string="Channel",
related="slide_id.channel_id", store=True, index=True, ondelete='cascade')
partner_id = fields.Many2one('res.partner', index=True, required=True, ondelete='cascade')
vote = fields.Integer('Vote', default=0)
completed = fields.Boolean('Completed')
quiz_attempts_count = fields.Integer('Quiz attempts count', default=0)
@api.model_create_multi
def create(self, vals_list):
res = super().create(vals_list)
completed = res.filtered('completed')
if completed:
completed._set_completed_callback()
return res
def write(self, values):
res = super(SlidePartnerRelation, self).write(values)
if values.get('completed'):
self._set_completed_callback()
return res
def _set_completed_callback(self):
self.env['slide.channel.partner'].search([
('channel_id', 'in', self.channel_id.ids),
('partner_id', 'in', self.partner_id.ids),
])._recompute_completion()
class SlideLink(models.Model):
_name = 'slide.slide.link'
_description = "External URL for a particular slide"
slide_id = fields.Many2one('slide.slide', required=True, ondelete='cascade')
name = fields.Char('Title', required=True)
link = fields.Char('Link', required=True)
class SlideResource(models.Model):
_name = 'slide.slide.resource'
_description = "Additional resource for a particular slide"
slide_id = fields.Many2one('slide.slide', required=True, ondelete='cascade')
name = fields.Char('Name', required=True)
data = fields.Binary('Resource')
class EmbeddedSlide(models.Model):
""" Embedding in third party websites. Track view count, generate statistics. """
_name = 'slide.embed'
_description = 'Embedded Slides View Counter'
_rec_name = 'slide_id'
slide_id = fields.Many2one('slide.slide', string="Presentation", required=True, index=True, ondelete='cascade')
url = fields.Char('Third Party Website URL', required=True)
count_views = fields.Integer('# Views', default=1)
def _add_embed_url(self, slide_id, url):
baseurl = urls.url_parse(url).netloc
if not baseurl:
return 0
embeds = self.search([('url', '=', baseurl), ('slide_id', '=', int(slide_id))], limit=1)
if embeds:
embeds.count_views += 1
else:
embeds = self.create({
'slide_id': slide_id,
'url': baseurl,
})
return embeds.count_views
class SlideTag(models.Model):
""" Tag to search slides across channels. """
_name = 'slide.tag'
_description = 'Slide Tag'
name = fields.Char('Name', required=True, translate=True)
_sql_constraints = [
('slide_tag_unique', 'UNIQUE(name)', 'A tag must be unique!'),
]
class Slide(models.Model):
_name = 'slide.slide'
_inherit = [
'mail.thread',
'image.mixin',
'website.seo.metadata',
'website.published.mixin',
'website.searchable.mixin',
]
_description = 'Slides'
_mail_post_access = 'read'
_order_by_strategy = {
'sequence': 'sequence asc, id asc',
'most_viewed': 'total_views desc',
'most_voted': 'likes desc',
'latest': 'date_published desc',
}
_order = 'sequence asc, is_category asc, id asc'
# description
name = fields.Char('Title', required=True, translate=True)
active = fields.Boolean(default=True, tracking=100)
sequence = fields.Integer('Sequence', default=0)
user_id = fields.Many2one('res.users', string='Uploaded by', default=lambda self: self.env.uid)
description = fields.Html('Description', translate=True, sanitize_attributes=False)
channel_id = fields.Many2one('slide.channel', string="Course", required=True)
tag_ids = fields.Many2many('slide.tag', 'rel_slide_tag', 'slide_id', 'tag_id', string='Tags')
is_preview = fields.Boolean('Allow Preview', default=False, help="The course is accessible by anyone : the users don't need to join the channel to access the content of the course.")
is_new_slide = fields.Boolean('Is New Slide', compute='_compute_is_new_slide')
completion_time = fields.Float('Duration', digits=(10, 4), help="The estimated completion time for this slide")
# Categories
is_category = fields.Boolean('Is a category', default=False)
category_id = fields.Many2one('slide.slide', string="Section", compute="_compute_category_id", store=True)
slide_ids = fields.One2many('slide.slide', "category_id", string="Slides")
# subscribers
partner_ids = fields.Many2many('res.partner', 'slide_slide_partner', 'slide_id', 'partner_id',
string='Subscribers', groups='website_slides.group_website_slides_officer', copy=False)
slide_partner_ids = fields.One2many('slide.slide.partner', 'slide_id', string='Subscribers information', groups='website_slides.group_website_slides_officer', copy=False)
user_membership_id = fields.Many2one(
'slide.slide.partner', string="Subscriber information",
compute='_compute_user_membership_id', compute_sudo=False,
help="Subscriber information for the current logged in user")
# Quiz related fields
question_ids = fields.One2many("slide.question", "slide_id", string="Questions")
questions_count = fields.Integer(string="Numbers of Questions", compute='_compute_questions_count')
quiz_first_attempt_reward = fields.Integer("Reward: first attempt", default=10)
quiz_second_attempt_reward = fields.Integer("Reward: second attempt", default=7)
quiz_third_attempt_reward = fields.Integer("Reward: third attempt", default=5,)
quiz_fourth_attempt_reward = fields.Integer("Reward: every attempt after the third try", default=2)
# content
slide_type = fields.Selection([
('infographic', 'Infographic'),
('webpage', 'Web Page'),
('presentation', 'Presentation'),
('document', 'Document'),
('video', 'Video'),
('quiz', "Quiz")],
string='Type', required=True,
default='document',
help="The document type will be set automatically based on the document URL and properties (e.g. height and width for presentation and document).")
datas = fields.Binary('Content', attachment=True)
url = fields.Char('Document URL', help="Youtube or Google Document URL")
document_id = fields.Char('Document ID', help="Youtube or Google Document ID")
link_ids = fields.One2many('slide.slide.link', 'slide_id', string="External URL for this slide")
slide_resource_ids = fields.One2many('slide.slide.resource', 'slide_id', string="Additional Resource for this slide")
slide_resource_downloadable = fields.Boolean('Allow Download', default=True, help="Allow the user to download the content of the slide.")
mime_type = fields.Char('Mime-type')
html_content = fields.Html("HTML Content", help="Custom HTML content for slides of type 'Web Page'.", translate=True, sanitize_attributes=False, sanitize_form=False)
# website
website_id = fields.Many2one(related='channel_id.website_id', readonly=True)
date_published = fields.Datetime('Publish Date', readonly=True, tracking=1)
likes = fields.Integer('Likes', compute='_compute_like_info', store=True, compute_sudo=False)
dislikes = fields.Integer('Dislikes', compute='_compute_like_info', store=True, compute_sudo=False)
user_vote = fields.Integer('User vote', compute='_compute_user_membership_id', compute_sudo=False)
embed_code = fields.Html('Embed Code', readonly=True, compute='_compute_embed_code', sanitize=False)
# views
embedcount_ids = fields.One2many('slide.embed', 'slide_id', string="Embed Count")
slide_views = fields.Integer('# of Website Views', store=True, compute="_compute_slide_views")
public_views = fields.Integer('# of Public Views', copy=False)
total_views = fields.Integer("Views", default="0", compute='_compute_total', store=True)
# comments
comments_count = fields.Integer('Number of comments', compute="_compute_comments_count")
# channel
channel_type = fields.Selection(related="channel_id.channel_type", string="Channel type")
channel_allow_comment = fields.Boolean(related="channel_id.allow_comment", string="Allows comment")
# Statistics in case the slide is a category
nbr_presentation = fields.Integer("Number of Presentations", compute='_compute_slides_statistics', store=True)
nbr_document = fields.Integer("Number of Documents", compute='_compute_slides_statistics', store=True)
nbr_video = fields.Integer("Number of Videos", compute='_compute_slides_statistics', store=True)
nbr_infographic = fields.Integer("Number of Infographics", compute='_compute_slides_statistics', store=True)
nbr_webpage = fields.Integer("Number of Webpages", compute='_compute_slides_statistics', store=True)
nbr_quiz = fields.Integer("Number of Quizs", compute="_compute_slides_statistics", store=True)
total_slides = fields.Integer(compute='_compute_slides_statistics', store=True)
_sql_constraints = [
('exclusion_html_content_and_url', "CHECK(html_content IS NULL OR url IS NULL)", "A slide is either filled with a document url or HTML content. Not both.")
]
@api.depends('date_published', 'is_published')
def _compute_is_new_slide(self):
for slide in self:
slide.is_new_slide = slide.date_published > fields.Datetime.now() - relativedelta(days=7) if slide.is_published else False
@api.depends('channel_id.slide_ids.is_category', 'channel_id.slide_ids.sequence')
def _compute_category_id(self):
""" Will take all the slides of the channel for which the index is higher
than the index of this category and lower than the index of the next category.
Lists are manually sorted because when adding a new browse record order
will not be correct as the added slide would actually end up at the
first place no matter its sequence."""
self.category_id = False # initialize whatever the state
channel_slides = {}
for slide in self:
if slide.channel_id.id not in channel_slides:
channel_slides[slide.channel_id.id] = slide.channel_id.slide_ids
for cid, slides in channel_slides.items():
current_category = self.env['slide.slide']
slide_list = list(slides)
slide_list.sort(key=lambda s: (s.sequence, not s.is_category))
for slide in slide_list:
if slide.is_category:
current_category = slide
elif slide.category_id != current_category:
slide.category_id = current_category.id
@api.depends('question_ids')
def _compute_questions_count(self):
for slide in self:
slide.questions_count = len(slide.question_ids)
def _has_additional_resources(self):
"""Sudo required for public user to know if the course has additional
resources that they will be able to access once a member."""
self.ensure_one()
return bool(self.sudo().slide_resource_ids)
@api.depends('website_message_ids.res_id', 'website_message_ids.model', 'website_message_ids.message_type')
def _compute_comments_count(self):
for slide in self:
slide.comments_count = len(slide.website_message_ids)
@api.depends('slide_views', 'public_views')
def _compute_total(self):
for record in self:
record.total_views = record.slide_views + record.public_views
@api.depends('slide_partner_ids.vote')
def _compute_like_info(self):
if not self.ids:
self.update({'likes': 0, 'dislikes': 0})
return
rg_data_like = self.env['slide.slide.partner'].sudo().read_group(
[('slide_id', 'in', self.ids), ('vote', '=', 1)],
['slide_id'], ['slide_id']
)
rg_data_dislike = self.env['slide.slide.partner'].sudo().read_group(
[('slide_id', 'in', self.ids), ('vote', '=', -1)],
['slide_id'], ['slide_id']
)
mapped_data_like = dict(
(rg_data['slide_id'][0], rg_data['slide_id_count'])
for rg_data in rg_data_like
)
mapped_data_dislike = dict(
(rg_data['slide_id'][0], rg_data['slide_id_count'])
for rg_data in rg_data_dislike
)
for slide in self:
slide.likes = mapped_data_like.get(slide.id, 0)
slide.dislikes = mapped_data_dislike.get(slide.id, 0)
@api.depends('slide_partner_ids.vote')
@api.depends_context('uid')
def _compute_user_info(self):
""" Deprecated. Now computed directly by _compute_user_membership_id
for user_vote and _compute_like_info for likes / dislikes. Remove me in
master. """
default_stats = {'likes': 0, 'dislikes': 0, 'user_vote': False}
if not self.ids:
self.update(default_stats)
return
slide_data = dict.fromkeys(self.ids, default_stats)
slide_partners = self.env['slide.slide.partner'].sudo().search([
('slide_id', 'in', self.ids)
])
for slide_partner in slide_partners:
if slide_partner.vote == 1:
slide_data[slide_partner.slide_id.id]['likes'] += 1
if slide_partner.partner_id == self.env.user.partner_id:
slide_data[slide_partner.slide_id.id]['user_vote'] = 1
elif slide_partner.vote == -1:
slide_data[slide_partner.slide_id.id]['dislikes'] += 1
if slide_partner.partner_id == self.env.user.partner_id:
slide_data[slide_partner.slide_id.id]['user_vote'] = -1
for slide in self:
slide.update(slide_data[slide.id])
@api.depends('slide_partner_ids.slide_id')
def _compute_slide_views(self):
# TODO awa: tried compute_sudo, for some reason it doesn't work in here...
read_group_res = self.env['slide.slide.partner'].sudo().read_group(
[('slide_id', 'in', self.ids)],
['slide_id'],
groupby=['slide_id']
)
mapped_data = dict((res['slide_id'][0], res['slide_id_count']) for res in read_group_res)
for slide in self:
slide.slide_views = mapped_data.get(slide.id, 0)
@api.depends('slide_ids.sequence', 'slide_ids.slide_type', 'slide_ids.is_published', 'slide_ids.is_category')
def _compute_slides_statistics(self):
# Do not use dict.fromkeys(self.ids, dict()) otherwise it will use the same dictionnary for all keys.
# Therefore, when updating the dict of one key, it updates the dict of all keys.
keys = ['nbr_%s' % slide_type for slide_type in self.env['slide.slide']._fields['slide_type'].get_values(self.env)]
default_vals = dict((key, 0) for key in keys + ['total_slides'])
res = self.env['slide.slide'].read_group(
[('is_published', '=', True), ('category_id', 'in', self.ids), ('is_category', '=', False)],
['category_id', 'slide_type'], ['category_id', 'slide_type'],
lazy=False)
type_stats = self._compute_slides_statistics_type(res)
for record in self:
record.update(type_stats.get(record._origin.id, default_vals))
def _compute_slides_statistics_type(self, read_group_res):
""" Compute statistics based on all existing slide types """
slide_types = self.env['slide.slide']._fields['slide_type'].get_values(self.env)
keys = ['nbr_%s' % slide_type for slide_type in slide_types]
result = dict((cid, dict((key, 0) for key in keys + ['total_slides'])) for cid in self.ids)
for res_group in read_group_res:
cid = res_group['category_id'][0]
slide_type = res_group.get('slide_type')
if slide_type:
slide_type_count = res_group.get('__count', 0)
result[cid]['nbr_%s' % slide_type] = slide_type_count
result[cid]['total_slides'] += slide_type_count
return result
@api.depends('slide_partner_ids.partner_id', 'slide_partner_ids.vote')
@api.depends('uid')
def _compute_user_membership_id(self):
slide_partners = self.env['slide.slide.partner'].sudo().search([
('slide_id', 'in', self.ids),
('partner_id', '=', self.env.user.partner_id.id),
])
for record in self:
record.user_membership_id = next(
(slide_partner for slide_partner in slide_partners if slide_partner.slide_id == record),
self.env['slide.slide.partner']
)
record.user_vote = record.user_membership_id.vote
@api.depends('document_id', 'slide_type', 'mime_type')
def _compute_embed_code(self):
base_url = request and request.httprequest.url_root
for record in self:
if not base_url:
base_url = record.get_base_url()
if base_url[-1] == '/':
base_url = base_url[:-1]
if record.datas and (not record.document_id or record.slide_type in ['document', 'presentation']):
slide_url = base_url + url_for('/slides/embed/%s?page=1' % record.id)
record.embed_code = '<iframe src="%s" class="o_wslides_iframe_viewer" allowFullScreen="true" height="%s" width="%s" frameborder="0"></iframe>' % (slide_url, 315, 420)
elif record.slide_type == 'video' and record.document_id:
if not record.mime_type:
# embed youtube video
query = urls.url_parse(record.url).query
query = query + '&theme=light' if query else 'theme=light'
record.embed_code = '<iframe src="//www.youtube-nocookie.com/embed/%s?%s" allowFullScreen="true" frameborder="0"></iframe>' % (record.document_id, query)
else:
# embed google doc video
record.embed_code = '<iframe src="//drive.google.com/file/d/%s/preview" allowFullScreen="true" frameborder="0"></iframe>' % (record.document_id)
else:
record.embed_code = False
@api.onchange('url')
def _on_change_url(self):
self.ensure_one()
if self.url:
res = self._parse_document_url(self.url)
if res.get('error'):
raise UserError(res.get('error'))
values = res['values']
if not values.get('document_id'):
raise UserError(_('Please enter valid Youtube or Google Doc URL'))
for key, value in values.items():
self[key] = value
@api.onchange('datas')
def _on_change_datas(self):
""" For PDFs, we assume that it takes 5 minutes to read a page.
If the selected file is not a PDF, it is an image (You can
only upload PDF or Image file) then the slide_type is changed
into infographic and the uploaded dataS is transfered to the
image field. (It avoids the infinite loading in PDF viewer)"""
if self.datas:
data = base64.b64decode(self.datas)
if data.startswith(b'%PDF-'):
pdf = PyPDF2.PdfFileReader(io.BytesIO(data), overwriteWarnings=False, strict=False)
try:
pdf.getNumPages()
except PyPDF2.utils.PdfReadError:
return
self.completion_time = (5 * len(pdf.pages)) / 60
else:
self.slide_type = 'infographic'
self.image_1920 = self.datas
self.datas = None
@api.depends('name', 'channel_id.website_id.domain')
def _compute_website_url(self):
super(Slide, self)._compute_website_url()
for slide in self:
if slide.id: # avoid to perform a slug on a not yet saved record in case of an onchange.
base_url = slide.channel_id.get_base_url()
slide.website_url = '%s/slides/slide/%s' % (base_url, slug(slide))
@api.depends('channel_id.can_publish')
def _compute_can_publish(self):
for record in self:
record.can_publish = record.channel_id.can_publish
@api.model
def _get_can_publish_error_message(self):
return _("Publishing is restricted to the responsible of training courses or members of the publisher group for documentation courses")
# ---------------------------------------------------------
# ORM Overrides
# ---------------------------------------------------------
@api.model
def create(self, values):
# Do not publish slide if user has not publisher rights
channel = self.env['slide.channel'].browse(values['channel_id'])
if not channel.can_publish:
# 'website_published' is handled by mixin
values['date_published'] = False
if values.get('slide_type') == 'infographic' and not values.get('image_1920'):
values['image_1920'] = values['datas']
if values.get('is_category'):
values['is_preview'] = True
values['is_published'] = True
if values.get('is_published') and not values.get('date_published'):
values['date_published'] = datetime.datetime.now()
if values.get('url') and not values.get('document_id'):
doc_data = self._parse_document_url(values['url']).get('values', dict())
for key, value in doc_data.items():
values.setdefault(key, value)
slide = super(Slide, self).create(values)
if slide.is_published and not slide.is_category:
slide._post_publication()
slide.channel_id.channel_partner_ids._recompute_completion()
return slide
def write(self, values):
if values.get('url') and values['url'] != self.url:
doc_data = self._parse_document_url(values['url']).get('values', dict())
for key, value in doc_data.items():
values.setdefault(key, value)
if values.get('is_category'):
values['is_preview'] = True
values['is_published'] = True
res = super(Slide, self).write(values)
if values.get('is_published'):
self.date_published = datetime.datetime.now()
self._post_publication()
if 'is_published' in values or 'active' in values:
# recompute the completion for all partners of the channel
self.channel_id.channel_partner_ids._recompute_completion()
return res
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
"""Sets the sequence to zero so that it always lands at the beginning
of the newly selected course as an uncategorized slide"""
rec = super(Slide, self).copy(default)
rec.sequence = 0
return rec
@api.ondelete(at_uninstall=False)
def _unlink_except_already_taken(self):
if self.question_ids and self.channel_id.channel_partner_ids:
raise UserError(_("People already took this quiz. To keep course progression it should not be deleted."))
def unlink(self):
for category in self.filtered(lambda slide: slide.is_category):
category.channel_id._move_category_slides(category, False)
channel_partner_ids = self.channel_id.channel_partner_ids
super(Slide, self).unlink()
channel_partner_ids._recompute_completion()
def toggle_active(self):
# archiving/unarchiving a channel does it on its slides, too
to_archive = self.filtered(lambda slide: slide.active)
res = super(Slide, self).toggle_active()
if to_archive:
to_archive.filtered(lambda slide: not slide.is_category).is_published = False
return res
# ---------------------------------------------------------
# Mail/Rating
# ---------------------------------------------------------
@api.returns('mail.message', lambda value: value.id)
def message_post(self, *, message_type='notification', **kwargs):
self.ensure_one()
if message_type == 'comment' and not self.channel_id.can_comment: # user comments have a restriction on karma
raise AccessError(_('Not enough karma to comment'))
return super(Slide, self).message_post(message_type=message_type, **kwargs)
def get_access_action(self, access_uid=None):
""" Instead of the classic form view, redirect to website if it is published. """
self.ensure_one()
if self.website_published:
return {
'type': 'ir.actions.act_url',
'url': '%s' % self.website_url,
'target': 'self',
'target_type': 'public',
'res_id': self.id,
}
return super(Slide, self).get_access_action(access_uid)
def _notify_get_groups(self, msg_vals=None):
""" Add access button to everyone if the document is active. """
groups = super(Slide, self)._notify_get_groups(msg_vals=msg_vals)
if self.website_published:
for group_name, group_method, group_data in groups:
group_data['has_button_access'] = True
return groups
# ---------------------------------------------------------
# Business Methods
# ---------------------------------------------------------
def _post_publication(self):
for slide in self.filtered(lambda slide: slide.website_published and slide.channel_id.publish_template_id):
publish_template = slide.channel_id.publish_template_id
html_body = publish_template.with_context(base_url=slide.get_base_url())._render_field('body_html', slide.ids)[slide.id]
subject = publish_template._render_field('subject', slide.ids)[slide.id]
# We want to use the 'reply_to' of the template if set. However, `mail.message` will check
# if the key 'reply_to' is in the kwargs before calling _get_reply_to. If the value is
# falsy, we don't include it in the 'message_post' call.
kwargs = {}
reply_to = publish_template._render_field('reply_to', slide.ids)[slide.id]
if reply_to:
kwargs['reply_to'] = reply_to
slide.channel_id.with_context(mail_create_nosubscribe=True).message_post(
subject=subject,
body=html_body,
subtype_xmlid='website_slides.mt_channel_slide_published',
email_layout_xmlid='mail.mail_notification_light',
**kwargs,
)
return True
def _generate_signed_token(self, partner_id):
""" Lazy generate the acces_token and return it signed by the given partner_id
:rtype tuple (string, int)
:return (signed_token, partner_id)
"""
if not self.access_token:
self.write({'access_token': self._default_access_token()})
return self._sign_token(partner_id)
def _send_share_email(self, email, fullscreen):
# TDE FIXME: template to check
mail_ids = []
for record in self:
template = record.channel_id.share_template_id.with_context(
user=self.env.user,
email=email,
base_url=record.get_base_url(),
fullscreen=fullscreen
)
email_values = {'email_to': email}
if self.env.user.has_group('base.group_portal'):
template = template.sudo()
email_values['email_from'] = self.env.company.catchall_formatted or self.env.company.email_formatted
mail_ids.append(template.send_mail(record.id, notif_layout='mail.mail_notification_light', email_values=email_values))
return mail_ids
def action_like(self):
self.check_access_rights('read')
self.check_access_rule('read')
return self._action_vote(upvote=True)
def action_dislike(self):
self.check_access_rights('read')
self.check_access_rule('read')
return self._action_vote(upvote=False)
def _action_vote(self, upvote=True):
""" Private implementation of voting. It does not check for any real access
rights; public methods should grant access before calling this method.
:param upvote: if True, is a like; if False, is a dislike
"""
self_sudo = self.sudo()
SlidePartnerSudo = self.env['slide.slide.partner'].sudo()
slide_partners = SlidePartnerSudo.search([
('slide_id', 'in', self.ids),
('partner_id', '=', self.env.user.partner_id.id)
])
slide_id = slide_partners.mapped('slide_id')
new_slides = self_sudo - slide_id
channel = slide_id.channel_id
karma_to_add = 0
for slide_partner in slide_partners:
if upvote:
new_vote = 0 if slide_partner.vote == -1 else 1
if slide_partner.vote != 1:
karma_to_add += channel.karma_gen_slide_vote
else:
new_vote = 0 if slide_partner.vote == 1 else -1
if slide_partner.vote != -1:
karma_to_add -= channel.karma_gen_slide_vote
slide_partner.vote = new_vote
for new_slide in new_slides:
new_vote = 1 if upvote else -1
new_slide.write({
'slide_partner_ids': [(0, 0, {'vote': new_vote, 'partner_id': self.env.user.partner_id.id})]
})
karma_to_add += new_slide.channel_id.karma_gen_slide_vote * (1 if upvote else -1)
if karma_to_add:
self.env.user.add_karma(karma_to_add)
def action_set_viewed(self, quiz_attempts_inc=False):
if any(not slide.channel_id.is_member for slide in self):
raise UserError(_('You cannot mark a slide as viewed if you are not among its members.'))
return bool(self._action_set_viewed(self.env.user.partner_id, quiz_attempts_inc=quiz_attempts_inc))
def _action_set_viewed(self, target_partner, quiz_attempts_inc=False):
self_sudo = self.sudo()
SlidePartnerSudo = self.env['slide.slide.partner'].sudo()
existing_sudo = SlidePartnerSudo.search([
('slide_id', 'in', self.ids),
('partner_id', '=', target_partner.id)
])
if quiz_attempts_inc and existing_sudo:
sql.increment_field_skiplock(existing_sudo, 'quiz_attempts_count')
SlidePartnerSudo.invalidate_cache(fnames=['quiz_attempts_count'], ids=existing_sudo.ids)
new_slides = self_sudo - existing_sudo.mapped('slide_id')
return SlidePartnerSudo.create([{
'slide_id': new_slide.id,
'channel_id': new_slide.channel_id.id,
'partner_id': target_partner.id,
'quiz_attempts_count': 1 if quiz_attempts_inc else 0,
'vote': 0} for new_slide in new_slides])
def action_set_completed(self):
if any(not slide.channel_id.is_member for slide in self):
raise UserError(_('You cannot mark a slide as completed if you are not among its members.'))
return self._action_set_completed(self.env.user.partner_id)
def _action_set_completed(self, target_partner):
self_sudo = self.sudo()
SlidePartnerSudo = self.env['slide.slide.partner'].sudo()
existing_sudo = SlidePartnerSudo.search([
('slide_id', 'in', self.ids),
('partner_id', '=', target_partner.id)
])
existing_sudo.write({'completed': True})
new_slides = self_sudo - existing_sudo.mapped('slide_id')
SlidePartnerSudo.create([{
'slide_id': new_slide.id,
'channel_id': new_slide.channel_id.id,
'partner_id': target_partner.id,
'vote': 0,
'completed': True} for new_slide in new_slides])
return True
def _action_set_quiz_done(self):
if any(not slide.channel_id.is_member for slide in self):
raise UserError(_('You cannot mark a slide quiz as completed if you are not among its members.'))
points = 0
for slide in self:
user_membership_sudo = slide.user_membership_id.sudo()
if not user_membership_sudo or user_membership_sudo.completed or not user_membership_sudo.quiz_attempts_count:
continue
gains = [slide.quiz_first_attempt_reward,
slide.quiz_second_attempt_reward,
slide.quiz_third_attempt_reward,
slide.quiz_fourth_attempt_reward]
points += gains[user_membership_sudo.quiz_attempts_count - 1] if user_membership_sudo.quiz_attempts_count <= len(gains) else gains[-1]
return self.env.user.sudo().add_karma(points)
def _compute_quiz_info(self, target_partner, quiz_done=False):
result = dict.fromkeys(self.ids, False)
slide_partners = self.env['slide.slide.partner'].sudo().search([
('slide_id', 'in', self.ids),
('partner_id', '=', target_partner.id)
])
slide_partners_map = dict((sp.slide_id.id, sp) for sp in slide_partners)
for slide in self:
if not slide.question_ids:
gains = [0]
else:
gains = [slide.quiz_first_attempt_reward,
slide.quiz_second_attempt_reward,
slide.quiz_third_attempt_reward,
slide.quiz_fourth_attempt_reward]
result[slide.id] = {
'quiz_karma_max': gains[0], # what could be gained if succeed at first try
'quiz_karma_gain': gains[0], # what would be gained at next test
'quiz_karma_won': 0, # what has been gained
'quiz_attempts_count': 0, # number of attempts
}
slide_partner = slide_partners_map.get(slide.id)
if slide.question_ids and slide_partner and slide_partner.quiz_attempts_count:
result[slide.id]['quiz_karma_gain'] = gains[slide_partner.quiz_attempts_count] if slide_partner.quiz_attempts_count < len(gains) else gains[-1]
result[slide.id]['quiz_attempts_count'] = slide_partner.quiz_attempts_count
if quiz_done or slide_partner.completed:
result[slide.id]['quiz_karma_won'] = gains[slide_partner.quiz_attempts_count-1] if slide_partner.quiz_attempts_count < len(gains) else gains[-1]
return result
# --------------------------------------------------
# Parsing methods
# --------------------------------------------------
@api.model
def _fetch_data(self, base_url, params, content_type=False):
result = {'values': dict()}
try:
response = requests.get(base_url, timeout=3, params=params)
response.raise_for_status()
if content_type == 'json':
result['values'] = response.json()
elif content_type in ('image', 'pdf'):
result['values'] = base64.b64encode(response.content)
else:
result['values'] = response.content
except requests.exceptions.HTTPError as e:
result['error'] = e.response.content
except requests.exceptions.ConnectionError as e:
result['error'] = str(e)
return result
def _find_document_data_from_url(self, url):
url_obj = urls.url_parse(url)
if url_obj.ascii_host == 'youtu.be':
return ('youtube', url_obj.path[1:] if url_obj.path else False)
elif url_obj.ascii_host in ('youtube.com', 'www.youtube.com', 'm.youtube.com', 'www.youtube-nocookie.com'):
v_query_value = url_obj.decode_query().get('v')
if v_query_value:
return ('youtube', v_query_value)
split_path = url_obj.path.split('/')
if len(split_path) >= 3 and split_path[1] in ('v', 'embed'):
return ('youtube', split_path[2])
expr = re.compile(r'(^https:\/\/docs.google.com|^https:\/\/drive.google.com).*\/d\/([^\/]*)')
arg = expr.match(url)
document_id = arg and arg.group(2) or False
if document_id:
return ('google', document_id)
return (None, False)
def _parse_document_url(self, url, only_preview_fields=False):
document_source, document_id = self._find_document_data_from_url(url)
if document_source and hasattr(self, '_parse_%s_document' % document_source):
return getattr(self, '_parse_%s_document' % document_source)(document_id, only_preview_fields)
return {'error': _('Unknown document')}
def _parse_youtube_document(self, document_id, only_preview_fields):
""" If we receive a duration (YT video), we use it to determine the slide duration.
The received duration is under a special format (e.g: PT1M21S15, meaning 1h 21m 15s). """
key = self.env['website'].get_current_website().website_slide_google_app_key
fetch_res = self._fetch_data('https://www.googleapis.com/youtube/v3/videos', {'id': document_id, 'key': key, 'part': 'snippet,contentDetails', 'fields': 'items(id,snippet,contentDetails)'}, 'json')
if fetch_res.get('error'):
return {'error': self._extract_google_error_message(fetch_res.get('error'))}
values = {'slide_type': 'video', 'document_id': document_id}
items = fetch_res['values'].get('items')
if not items:
return {'error': _('Please enter valid Youtube or Google Doc URL')}
youtube_values = items[0]
youtube_duration = youtube_values.get('contentDetails', {}).get('duration')
if youtube_duration:
parsed_duration = re.search(r'^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$', youtube_duration)
if parsed_duration:
values['completion_time'] = (int(parsed_duration.group(1) or 0)) + \
(int(parsed_duration.group(2) or 0) / 60) + \
(int(parsed_duration.group(3) or 0) / 3600)
if youtube_values.get('snippet'):
snippet = youtube_values['snippet']
if only_preview_fields:
values.update({
'url_src': snippet['thumbnails']['high']['url'],
'title': snippet['title'],
'description': snippet['description']
})
return values
values.update({
'name': snippet['title'],
'image_1920': self._fetch_data(snippet['thumbnails']['high']['url'], {}, 'image')['values'],
'description': snippet['description'],
'mime_type': False,
})
return {'values': values}
def _extract_google_error_message(self, error):
"""
See here for Google error format
https://developers.google.com/drive/api/v3/handle-errors
"""
try:
error = json.loads(error)
error = (error.get('error', {}).get('errors', []) or [{}])[0].get('reason')
except json.decoder.JSONDecodeError:
error = str(error)
if error == 'keyInvalid':
return _('Your Google API key is invalid, please update it in your settings.\nSettings > Website > Features > API Key')
return _('Could not fetch data from url. Document or access right not available:\n%s', error)
@api.model
def _parse_google_document(self, document_id, only_preview_fields):
def get_slide_type(vals):
# TDE FIXME: WTF ??
slide_type = 'presentation'
if vals.get('image_1920'):
image = Image.open(io.BytesIO(base64.b64decode(vals['image_1920'])))
width, height = image.size
if height > width:
return 'document'
return slide_type
# Google drive doesn't use a simple API key to access the data, but requires an access
# token. However, this token is generated in module google_drive, which is not in the
# dependencies of website_slides. We still keep the 'key' parameter just in case, but that
# is probably useless.
params = {}
params['projection'] = 'BASIC'
if 'google.drive.config' in self.env:
access_token = self.env['google.drive.config'].get_access_token()
if access_token:
params['access_token'] = access_token
if not params.get('access_token'):
params['key'] = self.env['website'].get_current_website().website_slide_google_app_key
fetch_res = self._fetch_data('https://www.googleapis.com/drive/v2/files/%s' % document_id, params, "json")
if fetch_res.get('error'):
return {'error': self._extract_google_error_message(fetch_res.get('error'))}
google_values = fetch_res['values']
if only_preview_fields:
return {
'url_src': google_values['thumbnailLink'],
'title': google_values['title'],
}
values = {
'name': google_values['title'],
'image_1920': self._fetch_data(google_values['thumbnailLink'].replace('=s220', ''), {}, 'image')['values'],
'mime_type': google_values['mimeType'],
'document_id': document_id,
}
if google_values['mimeType'].startswith('video/'):
values['slide_type'] = 'video'
elif google_values['mimeType'].startswith('image/'):
values['datas'] = values['image_1920']
values['slide_type'] = 'infographic'
elif google_values['mimeType'].startswith('application/vnd.google-apps'):
values['slide_type'] = get_slide_type(values)
if 'exportLinks' in google_values:
values['datas'] = self._fetch_data(google_values['exportLinks']['application/pdf'], params, 'pdf')['values']
elif google_values['mimeType'] == 'application/pdf':
# TODO: Google Drive PDF document doesn't provide plain text transcript
values['datas'] = self._fetch_data(google_values['webContentLink'], {}, 'pdf')['values']
values['slide_type'] = get_slide_type(values)
return {'values': values}
def _default_website_meta(self):
res = super(Slide, self)._default_website_meta()
res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name
res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = html2plaintext(self.description)
res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = self.env['website'].image_url(self, 'image_1024')
res['default_meta_description'] = html2plaintext(self.description)
return res
# ---------------------------------------------------------
# Data / Misc
# ---------------------------------------------------------
def get_backend_menu_id(self):
return self.env.ref('website_slides.website_slides_menu_root').id
@api.model
def _search_get_detail(self, website, order, options):
with_description = options['displayDescription']
search_fields = ['name']
fetch_fields = ['id', 'name']
mapping = {
'name': {'name': 'name', 'type': 'text', 'match': True},
'website_url': {'name': 'url', 'type': 'text', 'truncate': False},
'extra_link': {'name': 'course', 'type': 'text'},
'extra_link_url': {'name': 'course_url', 'type': 'text', 'truncate': False},
}
if with_description:
search_fields.append('description')
fetch_fields.append('description')
mapping['description'] = {'name': 'description', 'type': 'text', 'html': True, 'match': True}
return {
'model': 'slide.slide',
'base_domain': [website.website_domain()],
'search_fields': search_fields,
'fetch_fields': fetch_fields,
'mapping': mapping,
'icon': 'fa-shopping-cart',
'order': 'name desc, id desc' if 'name desc' in order else 'name asc, id desc',
}
def _search_render_results(self, fetch_fields, mapping, icon, limit):
icon_per_type = {
'infographic': 'fa-file-picture-o',
'webpage': 'fa-file-text',
'presentation': 'fa-file-pdf-o',
'document': 'fa-file-pdf-o',
'video': 'fa-play-circle',
'quiz': 'fa-question-circle',
'link': 'fa-file-code-o', # appears in template "slide_icon"
}
results_data = super()._search_render_results(fetch_fields, mapping, icon, limit)
for slide, data in zip(self, results_data):
data['_fa'] = icon_per_type.get(slide.slide_type, 'fa-file-pdf-o')
data['url'] = slide.website_url
data['course'] = _('Course: %s', slide.channel_id.name)
data['course_url'] = slide.channel_id.website_url
return results_data
| 47.141548 | 46,293 |
46,052 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import uuid
from collections import defaultdict
from dateutil.relativedelta import relativedelta
import ast
from odoo import api, fields, models, tools, _
from odoo.addons.http_routing.models.ir_http import slug, unslug
from odoo.exceptions import AccessError
from odoo.osv import expression
from odoo.tools import is_html_empty
_logger = logging.getLogger(__name__)
class ChannelUsersRelation(models.Model):
_name = 'slide.channel.partner'
_description = 'Channel / Partners (Members)'
_table = 'slide_channel_partner'
channel_id = fields.Many2one('slide.channel', index=True, required=True, ondelete='cascade')
completed = fields.Boolean('Is Completed', help='Channel validated, even if slides / lessons are added once done.')
completion = fields.Integer('% Completed Slides')
completed_slides_count = fields.Integer('# Completed Slides')
partner_id = fields.Many2one('res.partner', index=True, required=True, ondelete='cascade')
partner_email = fields.Char(related='partner_id.email', readonly=True)
# channel-related information (for UX purpose)
channel_user_id = fields.Many2one('res.users', string='Responsible', related='channel_id.user_id')
channel_type = fields.Selection(related='channel_id.channel_type')
channel_visibility = fields.Selection(related='channel_id.visibility')
channel_enroll = fields.Selection(related='channel_id.enroll')
channel_website_id = fields.Many2one('website', string='Website', related='channel_id.website_id')
def _recompute_completion(self):
read_group_res = self.env['slide.slide.partner'].sudo().read_group(
['&', '&', ('channel_id', 'in', self.mapped('channel_id').ids),
('partner_id', 'in', self.mapped('partner_id').ids),
('completed', '=', True),
('slide_id.is_published', '=', True),
('slide_id.active', '=', True)],
['channel_id', 'partner_id'],
groupby=['channel_id', 'partner_id'], lazy=False)
mapped_data = dict()
for item in read_group_res:
mapped_data.setdefault(item['channel_id'][0], dict())
mapped_data[item['channel_id'][0]][item['partner_id'][0]] = item['__count']
completed_records = self.env['slide.channel.partner']
for record in self:
record.completed_slides_count = mapped_data.get(record.channel_id.id, dict()).get(record.partner_id.id, 0)
record.completion = 100.0 if record.completed else round(100.0 * record.completed_slides_count / (record.channel_id.total_slides or 1))
if not record.completed and record.channel_id.active and record.completed_slides_count >= record.channel_id.total_slides:
completed_records += record
if completed_records:
completed_records._set_as_completed()
completed_records._send_completed_mail()
def unlink(self):
"""
Override unlink method :
Remove attendee from a channel, then also remove slide.slide.partner related to.
"""
removed_slide_partner_domain = []
for channel_partner in self:
# find all slide link to the channel and the partner
removed_slide_partner_domain = expression.OR([
removed_slide_partner_domain,
[('partner_id', '=', channel_partner.partner_id.id),
('slide_id', 'in', channel_partner.channel_id.slide_ids.ids)]
])
if removed_slide_partner_domain:
self.env['slide.slide.partner'].search(removed_slide_partner_domain).unlink()
return super(ChannelUsersRelation, self).unlink()
def _set_as_completed(self):
""" Set record as completed and compute karma gains """
partner_karma = dict.fromkeys(self.mapped('partner_id').ids, 0)
for record in self:
record.completed = True
partner_karma[record.partner_id.id] += record.channel_id.karma_gen_channel_finish
partner_karma = {
partner_id: karma_to_add
for partner_id, karma_to_add in partner_karma.items() if karma_to_add > 0
}
if partner_karma:
users = self.env['res.users'].sudo().search([('partner_id', 'in', list(partner_karma.keys()))])
for user in users:
users.add_karma(partner_karma[user.partner_id.id])
def _send_completed_mail(self):
""" Send an email to the attendee when he has successfully completed a course. """
template_to_records = dict()
for record in self:
template = record.channel_id.completed_template_id
if template:
template_to_records.setdefault(template, self.env['slide.channel.partner'])
template_to_records[template] += record
record_email_values = dict()
for template, records in template_to_records.items():
record_email_values.update(template.generate_email(records.ids, ['subject', 'body_html', 'email_from', 'partner_to']))
mail_mail_values = []
for record in self:
email_values = record_email_values.get(record.id)
if not email_values or not email_values.get('partner_ids'):
continue
email_values.update(
author_id=record.channel_id.user_id.partner_id.id or self.env.company.partner_id.id,
auto_delete=True,
recipient_ids=[(4, pid) for pid in email_values['partner_ids']],
)
email_values['body_html'] = template._render_encapsulate(
'mail.mail_notification_light', email_values['body_html'],
add_context={
'message': self.env['mail.message'].sudo().new(dict(body=email_values['body_html'], record_name=record.channel_id.name)),
'model_description': _('Completed Course') # tde fixme: translate into partner lang
}
)
mail_mail_values.append(email_values)
if mail_mail_values:
self.env['mail.mail'].sudo().create(mail_mail_values)
class Channel(models.Model):
""" A channel is a container of slides. """
_name = 'slide.channel'
_description = 'Course'
_inherit = [
'mail.thread', 'rating.mixin',
'mail.activity.mixin',
'image.mixin',
'website.seo.metadata',
'website.published.multi.mixin',
'website.searchable.mixin',
]
_order = 'sequence, id'
def _default_access_token(self):
return str(uuid.uuid4())
def _get_default_enroll_msg(self):
return _('Contact Responsible')
# description
name = fields.Char('Name', translate=True, required=True)
active = fields.Boolean(default=True, tracking=100)
description = fields.Html('Description', translate=True, sanitize_attributes=False, sanitize_form=False, help="The description that is displayed on top of the course page, just below the title")
description_short = fields.Html('Short Description', translate=True, sanitize_attributes=False, sanitize_form=False, help="The description that is displayed on the course card")
description_html = fields.Html('Detailed Description', translate=tools.html_translate, sanitize_attributes=False, sanitize_form=False)
channel_type = fields.Selection([
('training', 'Training'), ('documentation', 'Documentation')],
string="Course type", default="training", required=True)
sequence = fields.Integer(default=10, help='Display order')
user_id = fields.Many2one('res.users', string='Responsible', default=lambda self: self.env.uid)
color = fields.Integer('Color Index', default=0, help='Used to decorate kanban view')
tag_ids = fields.Many2many(
'slide.channel.tag', 'slide_channel_tag_rel', 'channel_id', 'tag_id',
string='Tags', help='Used to categorize and filter displayed channels/courses')
# slides: promote, statistics
slide_ids = fields.One2many('slide.slide', 'channel_id', string="Slides and categories")
slide_content_ids = fields.One2many('slide.slide', string='Slides', compute="_compute_category_and_slide_ids")
slide_category_ids = fields.One2many('slide.slide', string='Categories', compute="_compute_category_and_slide_ids")
slide_last_update = fields.Date('Last Update', compute='_compute_slide_last_update', store=True)
slide_partner_ids = fields.One2many(
'slide.slide.partner', 'channel_id', string="Slide User Data",
copy=False, groups='website_slides.group_website_slides_officer')
promote_strategy = fields.Selection([
('latest', 'Latest Published'),
('most_voted', 'Most Voted'),
('most_viewed', 'Most Viewed'),
('specific', 'Specific'),
('none', 'None')],
string="Promoted Content", default='latest', required=False,
help='Depending the promote strategy, a slide will appear on the top of the course\'s page :\n'
' * Latest Published : the slide created last.\n'
' * Most Voted : the slide which has to most votes.\n'
' * Most Viewed ; the slide which has been viewed the most.\n'
' * Specific : You choose the slide to appear.\n'
' * None : No slides will be shown.\n')
promoted_slide_id = fields.Many2one('slide.slide', string='Promoted Slide')
access_token = fields.Char("Security Token", copy=False, default=_default_access_token)
nbr_presentation = fields.Integer('Presentations', compute='_compute_slides_statistics', store=True)
nbr_document = fields.Integer('Documents', compute='_compute_slides_statistics', store=True)
nbr_video = fields.Integer('Videos', compute='_compute_slides_statistics', store=True)
nbr_infographic = fields.Integer('Infographics', compute='_compute_slides_statistics', store=True)
nbr_webpage = fields.Integer("Webpages", compute='_compute_slides_statistics', store=True)
nbr_quiz = fields.Integer("Number of Quizs", compute='_compute_slides_statistics', store=True)
total_slides = fields.Integer('Content', compute='_compute_slides_statistics', store=True)
total_views = fields.Integer('Visits', compute='_compute_slides_statistics', store=True)
total_votes = fields.Integer('Votes', compute='_compute_slides_statistics', store=True)
total_time = fields.Float('Duration', compute='_compute_slides_statistics', digits=(10, 2), store=True)
rating_avg_stars = fields.Float("Rating Average (Stars)", compute='_compute_rating_stats', digits=(16, 1), compute_sudo=True)
# configuration
allow_comment = fields.Boolean(
"Allow rating on Course", default=True,
help="If checked it allows members to either:\n"
" * like content and post comments on documentation course;\n"
" * post comment and review on training course;")
publish_template_id = fields.Many2one(
'mail.template', string='New Content Email',
help="Email attendees once a new content is published",
default=lambda self: self.env['ir.model.data']._xmlid_to_res_id('website_slides.slide_template_published'))
share_template_id = fields.Many2one(
'mail.template', string='Share Template',
help="Email template used when sharing a slide",
default=lambda self: self.env['ir.model.data']._xmlid_to_res_id('website_slides.slide_template_shared'))
completed_template_id = fields.Many2one(
'mail.template', string='Completion Email', help="Email attendees once they've finished the course",
default=lambda self: self.env['ir.model.data']._xmlid_to_res_id('website_slides.mail_template_channel_completed'))
enroll = fields.Selection([
('public', 'Public'), ('invite', 'On Invitation')],
default='public', string='Enroll Policy', required=True,
help='Condition to enroll: everyone, on invite, on payment (sale bridge).')
enroll_msg = fields.Html(
'Enroll Message', help="Message explaining the enroll process",
default=_get_default_enroll_msg, translate=tools.html_translate, sanitize_attributes=False)
enroll_group_ids = fields.Many2many('res.groups', string='Auto Enroll Groups', help="Members of those groups are automatically added as members of the channel.")
visibility = fields.Selection([
('public', 'Public'), ('members', 'Members Only')],
default='public', string='Visibility', required=True,
help='Applied directly as ACLs. Allow to hide channels and their content for non members.')
partner_ids = fields.Many2many(
'res.partner', 'slide_channel_partner', 'channel_id', 'partner_id',
string='Members', help="All members of the channel.", context={'active_test': False}, copy=False, depends=['channel_partner_ids'])
members_count = fields.Integer('Attendees count', compute='_compute_members_count')
members_done_count = fields.Integer('Attendees Done Count', compute='_compute_members_done_count')
has_requested_access = fields.Boolean(string='Access Requested', compute='_compute_has_requested_access', compute_sudo=False)
is_member = fields.Boolean(string='Is Member', compute='_compute_is_member', compute_sudo=False)
channel_partner_ids = fields.One2many('slide.channel.partner', 'channel_id', string='Members Information', groups='website_slides.group_website_slides_officer', depends=['partner_ids'])
upload_group_ids = fields.Many2many(
'res.groups', 'rel_upload_groups', 'channel_id', 'group_id', string='Upload Groups',
help="Group of users allowed to publish contents on a documentation course.")
# not stored access fields, depending on each user
completed = fields.Boolean('Done', compute='_compute_user_statistics', compute_sudo=False)
completion = fields.Integer('Completion', compute='_compute_user_statistics', compute_sudo=False)
can_upload = fields.Boolean('Can Upload', compute='_compute_can_upload', compute_sudo=False)
partner_has_new_content = fields.Boolean(compute='_compute_partner_has_new_content', compute_sudo=False)
# karma generation
karma_gen_slide_vote = fields.Integer(string='Lesson voted', default=1)
karma_gen_channel_rank = fields.Integer(string='Course ranked', default=5)
karma_gen_channel_finish = fields.Integer(string='Course finished', default=10)
# Karma based actions
karma_review = fields.Integer('Add Review', default=10, help="Karma needed to add a review on the course")
karma_slide_comment = fields.Integer('Add Comment', default=3, help="Karma needed to add a comment on a slide of this course")
karma_slide_vote = fields.Integer('Vote', default=3, help="Karma needed to like/dislike a slide of this course.")
can_review = fields.Boolean('Can Review', compute='_compute_action_rights', compute_sudo=False)
can_comment = fields.Boolean('Can Comment', compute='_compute_action_rights', compute_sudo=False)
can_vote = fields.Boolean('Can Vote', compute='_compute_action_rights', compute_sudo=False)
@api.depends('slide_ids.is_published')
def _compute_slide_last_update(self):
for record in self:
record.slide_last_update = fields.Date.today()
@api.depends('channel_partner_ids.channel_id')
def _compute_members_count(self):
read_group_res = self.env['slide.channel.partner'].sudo().read_group([('channel_id', 'in', self.ids)], ['channel_id'], 'channel_id')
data = dict((res['channel_id'][0], res['channel_id_count']) for res in read_group_res)
for channel in self:
channel.members_count = data.get(channel.id, 0)
@api.depends('channel_partner_ids.channel_id', 'channel_partner_ids.completed')
def _compute_members_done_count(self):
read_group_res = self.env['slide.channel.partner'].sudo().read_group(['&', ('channel_id', 'in', self.ids), ('completed', '=', True)], ['channel_id'], 'channel_id')
data = dict((res['channel_id'][0], res['channel_id_count']) for res in read_group_res)
for channel in self:
channel.members_done_count = data.get(channel.id, 0)
@api.depends('activity_ids.request_partner_id')
@api.depends_context('uid')
@api.model
def _compute_has_requested_access(self):
requested_cids = self.sudo().activity_search(
['website_slides.mail_activity_data_access_request'],
additional_domain=[('request_partner_id', '=', self.env.user.partner_id.id)]
).mapped('res_id')
for channel in self:
channel.has_requested_access = channel.id in requested_cids
@api.depends('channel_partner_ids.partner_id')
@api.depends_context('uid')
@api.model
def _compute_is_member(self):
channel_partners = self.env['slide.channel.partner'].sudo().search([
('channel_id', 'in', self.ids),
])
result = dict()
for cp in channel_partners:
result.setdefault(cp.channel_id.id, []).append(cp.partner_id.id)
for channel in self:
channel.is_member = channel.is_member = self.env.user.partner_id.id in result.get(channel.id, [])
@api.depends('slide_ids.is_category')
def _compute_category_and_slide_ids(self):
for channel in self:
channel.slide_category_ids = channel.slide_ids.filtered(lambda slide: slide.is_category)
channel.slide_content_ids = channel.slide_ids - channel.slide_category_ids
@api.depends('slide_ids.slide_type', 'slide_ids.is_published', 'slide_ids.completion_time',
'slide_ids.likes', 'slide_ids.dislikes', 'slide_ids.total_views', 'slide_ids.is_category', 'slide_ids.active')
def _compute_slides_statistics(self):
default_vals = dict(total_views=0, total_votes=0, total_time=0, total_slides=0)
keys = ['nbr_%s' % slide_type for slide_type in self.env['slide.slide']._fields['slide_type'].get_values(self.env)]
default_vals.update(dict((key, 0) for key in keys))
result = dict((cid, dict(default_vals)) for cid in self.ids)
read_group_res = self.env['slide.slide'].read_group(
[('active', '=', True), ('is_published', '=', True), ('channel_id', 'in', self.ids), ('is_category', '=', False)],
['channel_id', 'slide_type', 'likes', 'dislikes', 'total_views', 'completion_time'],
groupby=['channel_id', 'slide_type'],
lazy=False)
for res_group in read_group_res:
cid = res_group['channel_id'][0]
result[cid]['total_views'] += res_group.get('total_views', 0)
result[cid]['total_votes'] += res_group.get('likes', 0)
result[cid]['total_votes'] -= res_group.get('dislikes', 0)
result[cid]['total_time'] += res_group.get('completion_time', 0)
type_stats = self._compute_slides_statistics_type(read_group_res)
for cid, cdata in type_stats.items():
result[cid].update(cdata)
for record in self:
record.update(result.get(record.id, default_vals))
def _compute_slides_statistics_type(self, read_group_res):
""" Compute statistics based on all existing slide types """
slide_types = self.env['slide.slide']._fields['slide_type'].get_values(self.env)
keys = ['nbr_%s' % slide_type for slide_type in slide_types]
result = dict((cid, dict((key, 0) for key in keys + ['total_slides'])) for cid in self.ids)
for res_group in read_group_res:
cid = res_group['channel_id'][0]
slide_type = res_group.get('slide_type')
if slide_type:
slide_type_count = res_group.get('__count', 0)
result[cid]['nbr_%s' % slide_type] = slide_type_count
result[cid]['total_slides'] += slide_type_count
return result
def _compute_rating_stats(self):
super(Channel, self)._compute_rating_stats()
for record in self:
record.rating_avg_stars = record.rating_avg
@api.depends('slide_partner_ids', 'total_slides')
@api.depends_context('uid')
def _compute_user_statistics(self):
current_user_info = self.env['slide.channel.partner'].sudo().search(
[('channel_id', 'in', self.ids), ('partner_id', '=', self.env.user.partner_id.id)]
)
mapped_data = dict((info.channel_id.id, (info.completed, info.completed_slides_count)) for info in current_user_info)
for record in self:
completed, completed_slides_count = mapped_data.get(record.id, (False, 0))
record.completed = completed
record.completion = 100.0 if completed else round(100.0 * completed_slides_count / (record.total_slides or 1))
@api.depends('upload_group_ids', 'user_id')
@api.depends_context('uid')
def _compute_can_upload(self):
for record in self:
if record.user_id == self.env.user or self.env.is_superuser():
record.can_upload = True
elif record.upload_group_ids:
record.can_upload = bool(record.upload_group_ids & self.env.user.groups_id)
else:
record.can_upload = self.env.user.has_group('website_slides.group_website_slides_manager')
@api.depends('channel_type', 'user_id', 'can_upload')
@api.depends_context('uid')
def _compute_can_publish(self):
""" For channels of type 'training', only the responsible (see user_id field) can publish slides.
The 'sudo' user needs to be handled because he's the one used for uploads done on the front-end when the
logged in user is not publisher but fulfills the upload_group_ids condition. """
for record in self:
if not record.can_upload:
record.can_publish = False
elif record.user_id == self.env.user or self.env.is_superuser():
record.can_publish = True
else:
record.can_publish = self.env.user.has_group('website_slides.group_website_slides_manager')
@api.model
def _get_can_publish_error_message(self):
return _("Publishing is restricted to the responsible of training courses or members of the publisher group for documentation courses")
@api.depends('slide_partner_ids')
@api.depends_context('uid')
def _compute_partner_has_new_content(self):
new_published_slides = self.env['slide.slide'].sudo().search([
('is_published', '=', True),
('date_published', '>', fields.Datetime.now() - relativedelta(days=7)),
('channel_id', 'in', self.ids),
('is_category', '=', False)
])
slide_partner_completed = self.env['slide.slide.partner'].sudo().search([
('channel_id', 'in', self.ids),
('partner_id', '=', self.env.user.partner_id.id),
('slide_id', 'in', new_published_slides.ids),
('completed', '=', True)
]).mapped('slide_id')
for channel in self:
new_slides = new_published_slides.filtered(lambda slide: slide.channel_id == channel)
channel.partner_has_new_content = any(slide not in slide_partner_completed for slide in new_slides)
@api.depends('name', 'website_id.domain')
def _compute_website_url(self):
super(Channel, self)._compute_website_url()
for channel in self:
if channel.id: # avoid to perform a slug on a not yet saved record in case of an onchange.
base_url = channel.get_base_url()
channel.website_url = '%s/slides/%s' % (base_url, slug(channel))
@api.depends('can_publish', 'is_member', 'karma_review', 'karma_slide_comment', 'karma_slide_vote')
@api.depends_context('uid')
def _compute_action_rights(self):
user_karma = self.env.user.karma
for channel in self:
if channel.can_publish:
channel.can_vote = channel.can_comment = channel.can_review = True
elif not channel.is_member:
channel.can_vote = channel.can_comment = channel.can_review = False
else:
channel.can_review = user_karma >= channel.karma_review
channel.can_comment = user_karma >= channel.karma_slide_comment
channel.can_vote = user_karma >= channel.karma_slide_vote
# ---------------------------------------------------------
# ORM Overrides
# ---------------------------------------------------------
def _init_column(self, column_name):
""" Initialize the value of the given column for existing rows.
Overridden here because we need to generate different access tokens
and by default _init_column calls the default method once and applies
it for every record.
"""
if column_name != 'access_token':
super(Channel, self)._init_column(column_name)
else:
query = """
UPDATE %(table_name)s
SET access_token = md5(md5(random()::varchar || id::varchar) || clock_timestamp()::varchar)::uuid::varchar
WHERE access_token IS NULL
""" % {'table_name': self._table}
self.env.cr.execute(query)
@api.model
def create(self, vals):
# Ensure creator is member of its channel it is easier for him to manage it (unless it is odoobot)
if not vals.get('channel_partner_ids') and not self.env.is_superuser():
vals['channel_partner_ids'] = [(0, 0, {
'partner_id': self.env.user.partner_id.id
})]
if not is_html_empty(vals.get('description')) and is_html_empty(vals.get('description_short')):
vals['description_short'] = vals['description']
channel = super(Channel, self.with_context(mail_create_nosubscribe=True)).create(vals)
if channel.user_id:
channel._action_add_members(channel.user_id.partner_id)
if 'enroll_group_ids' in vals:
channel._add_groups_members()
return channel
def write(self, vals):
# If description_short wasn't manually modified, there is an implicit link between this field and description.
if not is_html_empty(vals.get('description')) and is_html_empty(vals.get('description_short')) and self.description == self.description_short:
vals['description_short'] = vals.get('description')
res = super(Channel, self).write(vals)
if vals.get('user_id'):
self._action_add_members(self.env['res.users'].sudo().browse(vals['user_id']).partner_id)
self.activity_reschedule(['website_slides.mail_activity_data_access_request'], new_user_id=vals.get('user_id'))
if 'enroll_group_ids' in vals:
self._add_groups_members()
return res
def toggle_active(self):
""" Archiving/unarchiving a channel does it on its slides, too.
1. When archiving
We want to be archiving the channel FIRST.
So that when slides are archived and the recompute is triggered,
it does not try to mark the channel as "completed".
That happens because it counts slide_done / slide_total, but slide_total
will be 0 since all the slides for the course have been archived as well.
2. When un-archiving
We want to archive the channel LAST.
So that when it recomputes stats for the channel and completion, it correctly
counts the slides_total by counting slides that are already un-archived. """
to_archive = self.filtered(lambda channel: channel.active)
to_activate = self.filtered(lambda channel: not channel.active)
if to_archive:
super(Channel, to_archive).toggle_active()
to_archive.is_published = False
to_archive.mapped('slide_ids').action_archive()
if to_activate:
to_activate.with_context(active_test=False).mapped('slide_ids').action_unarchive()
super(Channel, to_activate).toggle_active()
@api.returns('mail.message', lambda value: value.id)
def message_post(self, *, parent_id=False, subtype_id=False, **kwargs):
""" Temporary workaround to avoid spam. If someone replies on a channel
through the 'Presentation Published' email, it should be considered as a
note as we don't want all channel followers to be notified of this answer. """
self.ensure_one()
if kwargs.get('message_type') == 'comment' and not self.can_review:
raise AccessError(_('Not enough karma to review'))
if parent_id:
parent_message = self.env['mail.message'].sudo().browse(parent_id)
if parent_message.subtype_id and parent_message.subtype_id == self.env.ref('website_slides.mt_channel_slide_published'):
subtype_id = self.env.ref('mail.mt_note').id
return super(Channel, self).message_post(parent_id=parent_id, subtype_id=subtype_id, **kwargs)
# ---------------------------------------------------------
# Business / Actions
# ---------------------------------------------------------
def action_redirect_to_members(self, completed=False):
""" Redirects to attendees of the course. If completed is True, a filter
will be added in action that will display only attendees who have completed
the course. """
action = self.env["ir.actions.actions"]._for_xml_id("website_slides.slide_channel_partner_action")
action_ctx = {'active_test': False}
if completed:
action_ctx['search_default_filter_completed'] = 1
if len(self) == 1:
action['display_name'] = _('Attendees of %s', self.name)
action_ctx['search_default_channel_id'] = self.id
action['context'] = action_ctx
return action
def action_redirect_to_done_members(self):
return self.action_redirect_to_members(completed=True)
def action_channel_invite(self):
self.ensure_one()
template = self.env.ref('website_slides.mail_template_slide_channel_invite', raise_if_not_found=False)
local_context = dict(
self.env.context,
default_channel_id=self.id,
default_use_template=bool(template),
default_template_id=template and template.id or False,
notif_layout='website_slides.mail_notification_channel_invite',
)
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'slide.channel.invite',
'target': 'new',
'context': local_context,
}
def action_add_member(self, **member_values):
""" Adds the logged in user in the channel members.
(see '_action_add_members' for more info)
Returns True if added successfully, False otherwise."""
return bool(self._action_add_members(self.env.user.partner_id, **member_values))
def _action_add_members(self, target_partners, **member_values):
""" Add the target_partner as a member of the channel (to its slide.channel.partner).
This will make the content (slides) of the channel available to that partner.
Returns the added 'slide.channel.partner's (! as sudo !)
"""
to_join = self._filter_add_members(target_partners, **member_values)
if to_join:
existing = self.env['slide.channel.partner'].sudo().search([
('channel_id', 'in', self.ids),
('partner_id', 'in', target_partners.ids)
])
existing_map = dict((cid, list()) for cid in self.ids)
for item in existing:
existing_map[item.channel_id.id].append(item.partner_id.id)
to_create_values = [
dict(channel_id=channel.id, partner_id=partner.id, **member_values)
for channel in to_join
for partner in target_partners if partner.id not in existing_map[channel.id]
]
slide_partners_sudo = self.env['slide.channel.partner'].sudo().create(to_create_values)
to_join.message_subscribe(partner_ids=target_partners.ids, subtype_ids=[self.env.ref('website_slides.mt_channel_slide_published').id])
return slide_partners_sudo
return self.env['slide.channel.partner'].sudo()
def _filter_add_members(self, target_partners, **member_values):
allowed = self.filtered(lambda channel: channel.enroll == 'public')
on_invite = self.filtered(lambda channel: channel.enroll == 'invite')
if on_invite:
try:
on_invite.check_access_rights('write')
on_invite.check_access_rule('write')
except:
pass
else:
allowed |= on_invite
return allowed
def _add_groups_members(self):
for channel in self:
channel._action_add_members(channel.mapped('enroll_group_ids.users.partner_id'))
def _get_earned_karma(self, partner_ids):
""" Compute the number of karma earned by partners on a channel
Warning: this count will not be accurate if the configuration has been
modified after the completion of a course!
"""
total_karma = defaultdict(int)
slide_completed = self.env['slide.slide.partner'].sudo().search([
('partner_id', 'in', partner_ids),
('channel_id', 'in', self.ids),
('completed', '=', True),
('quiz_attempts_count', '>', 0)
])
for partner_slide in slide_completed:
slide = partner_slide.slide_id
if not slide.question_ids:
continue
gains = [slide.quiz_first_attempt_reward,
slide.quiz_second_attempt_reward,
slide.quiz_third_attempt_reward,
slide.quiz_fourth_attempt_reward]
attempts = min(partner_slide.quiz_attempts_count - 1, 3)
total_karma[partner_slide.partner_id.id] += gains[attempts]
channel_completed = self.env['slide.channel.partner'].sudo().search([
('partner_id', 'in', partner_ids),
('channel_id', 'in', self.ids),
('completed', '=', True)
])
for partner_channel in channel_completed:
channel = partner_channel.channel_id
total_karma[partner_channel.partner_id.id] += channel.karma_gen_channel_finish
return total_karma
def _remove_membership(self, partner_ids):
""" Unlink (!!!) the relationships between the passed partner_ids
and the channels and their slides (done in the unlink of slide.channel.partner model).
Remove earned karma when completed quizz """
if not partner_ids:
raise ValueError("Do not use this method with an empty partner_id recordset")
earned_karma = self._get_earned_karma(partner_ids)
users = self.env['res.users'].sudo().search([
('partner_id', 'in', list(earned_karma)),
])
for user in users:
if earned_karma[user.partner_id.id]:
user.add_karma(-1 * earned_karma[user.partner_id.id])
removed_channel_partner_domain = []
for channel in self:
removed_channel_partner_domain = expression.OR([
removed_channel_partner_domain,
[('partner_id', 'in', partner_ids),
('channel_id', '=', channel.id)]
])
self.message_unsubscribe(partner_ids=partner_ids)
if removed_channel_partner_domain:
self.env['slide.channel.partner'].sudo().search(removed_channel_partner_domain).unlink()
def action_view_slides(self):
action = self.env["ir.actions.actions"]._for_xml_id("website_slides.slide_slide_action")
action['context'] = {
'search_default_published': 1,
'default_channel_id': self.id
}
action['domain'] = [('channel_id', "=", self.id), ('is_category', '=', False)]
return action
def action_view_ratings(self):
action = self.env["ir.actions.actions"]._for_xml_id("website_slides.rating_rating_action_slide_channel")
action['name'] = _('Rating of %s') % (self.name)
action['domain'] = expression.AND([ast.literal_eval(action.get('domain', '[]')), [('res_id', 'in', self.ids)]])
return action
def action_request_access(self):
""" Request access to the channel. Returns a dict with keys being either 'error'
(specific error raised) or 'done' (request done or not). """
if self.env.user.has_group('base.group_public'):
return {'error': _('You have to sign in before')}
if not self.is_published:
return {'error': _('Course not published yet')}
if self.is_member:
return {'error': _('Already member')}
if self.enroll == 'invite':
activities = self.sudo()._action_request_access(self.env.user.partner_id)
if activities:
return {'done': True}
return {'error': _('Already Requested')}
return {'done': False}
def action_grant_access(self, partner_id):
partner = self.env['res.partner'].browse(partner_id).exists()
if partner:
if self._action_add_members(partner):
self.activity_search(
['website_slides.mail_activity_data_access_request'],
user_id=self.user_id.id, additional_domain=[('request_partner_id', '=', partner.id)]
).action_feedback(feedback=_('Access Granted'))
def action_refuse_access(self, partner_id):
partner = self.env['res.partner'].browse(partner_id).exists()
if partner:
self.activity_search(
['website_slides.mail_activity_data_access_request'],
user_id=self.user_id.id, additional_domain=[('request_partner_id', '=', partner.id)]
).action_feedback(feedback=_('Access Refused'))
# ---------------------------------------------------------
# Mailing Mixin API
# ---------------------------------------------------------
def _rating_domain(self):
""" Only take the published rating into account to compute avg and count """
domain = super(Channel, self)._rating_domain()
return expression.AND([domain, [('is_internal', '=', False)]])
def _action_request_access(self, partner):
activities = self.env['mail.activity']
requested_cids = self.sudo().activity_search(
['website_slides.mail_activity_data_access_request'],
additional_domain=[('request_partner_id', '=', partner.id)]
).mapped('res_id')
for channel in self:
if channel.id not in requested_cids:
activities += channel.activity_schedule(
'website_slides.mail_activity_data_access_request',
note=_('<b>%s</b> is requesting access to this course.') % partner.name,
user_id=channel.user_id.id,
request_partner_id=partner.id
)
return activities
# ---------------------------------------------------------
# Data / Misc
# ---------------------------------------------------------
def _get_categorized_slides(self, base_domain, order, force_void=True, limit=False, offset=False):
""" Return an ordered structure of slides by categories within a given
base_domain that must fulfill slides. As a course structure is based on
its slides sequences, uncategorized slides must have the lowest sequences.
Example
* category 1 (sequence 1), category 2 (sequence 3)
* slide 1 (sequence 0), slide 2 (sequence 2)
* course structure is: slide 1, category 1, slide 2, category 2
* slide 1 is uncategorized,
* category 1 has one slide : Slide 2
* category 2 is empty.
Backend and frontend ordering is the same, uncategorized first. It
eases resequencing based on DOM / displayed order, notably when
drag n drop is involved. """
self.ensure_one()
all_categories = self.env['slide.slide'].sudo().search([('channel_id', '=', self.id), ('is_category', '=', True)])
all_slides = self.env['slide.slide'].sudo().search(base_domain, order=order)
category_data = []
# Prepare all categories by natural order
for category in all_categories:
category_slides = all_slides.filtered(lambda slide: slide.category_id == category)
if not category_slides and not force_void:
continue
category_data.append({
'category': category, 'id': category.id,
'name': category.name, 'slug_name': slug(category),
'total_slides': len(category_slides),
'slides': category_slides[(offset or 0):(limit + offset or len(category_slides))],
})
# Add uncategorized slides in first position
uncategorized_slides = all_slides.filtered(lambda slide: not slide.category_id)
if uncategorized_slides or force_void:
category_data.insert(0, {
'category': False, 'id': False,
'name': _('Uncategorized'), 'slug_name': _('Uncategorized'),
'total_slides': len(uncategorized_slides),
'slides': uncategorized_slides[(offset or 0):(offset + limit or len(uncategorized_slides))],
})
return category_data
def _move_category_slides(self, category, new_category):
if not category.slide_ids:
return
truncated_slide_ids = [slide_id for slide_id in self.slide_ids.ids if slide_id not in category.slide_ids.ids]
if new_category:
place_idx = truncated_slide_ids.index(new_category.id)
ordered_slide_ids = truncated_slide_ids[:place_idx] + category.slide_ids.ids + truncated_slide_ids[place_idx]
else:
ordered_slide_ids = category.slide_ids.ids + truncated_slide_ids
for index, slide_id in enumerate(ordered_slide_ids):
self.env['slide.slide'].browse([slide_id]).sequence = index + 1
def _resequence_slides(self, slide, force_category=False):
ids_to_resequence = self.slide_ids.ids
index_of_added_slide = ids_to_resequence.index(slide.id)
next_category_id = None
if self.slide_category_ids:
force_category_id = force_category.id if force_category else slide.category_id.id
index_of_category = self.slide_category_ids.ids.index(force_category_id) if force_category_id else None
if index_of_category is None:
next_category_id = self.slide_category_ids.ids[0]
elif index_of_category < len(self.slide_category_ids.ids) - 1:
next_category_id = self.slide_category_ids.ids[index_of_category + 1]
if next_category_id:
added_slide_id = ids_to_resequence.pop(index_of_added_slide)
index_of_next_category = ids_to_resequence.index(next_category_id)
ids_to_resequence.insert(index_of_next_category, added_slide_id)
for i, record in enumerate(self.env['slide.slide'].browse(ids_to_resequence)):
record.write({'sequence': i + 1}) # start at 1 to make people scream
else:
slide.write({
'sequence': self.env['slide.slide'].browse(ids_to_resequence[-1]).sequence + 1
})
def get_backend_menu_id(self):
return self.env.ref('website_slides.website_slides_menu_root').id
@api.model
def _search_get_detail(self, website, order, options):
with_description = options['displayDescription']
with_date = options['displayDetail']
my = options.get('my')
search_tags = options.get('tag')
slide_type = options.get('slide_type')
domain = [website.website_domain()]
if my:
domain.append([('partner_ids', '=', self.env.user.partner_id.id)])
if search_tags:
ChannelTag = self.env['slide.channel.tag']
try:
tag_ids = list(filter(None, [unslug(tag)[1] for tag in search_tags.split(',')]))
tags = ChannelTag.search([('id', 'in', tag_ids)]) if tag_ids else ChannelTag
except Exception:
tags = ChannelTag
# Group by group_id
grouped_tags = defaultdict(list)
for tag in tags:
grouped_tags[tag.group_id].append(tag)
# OR inside a group, AND between groups.
for group in grouped_tags:
domain.append([('tag_ids', 'in', [tag.id for tag in grouped_tags[group]])])
if slide_type and 'nbr_%s' % slide_type in self:
domain.append([('nbr_%s' % slide_type, '>', 0)])
search_fields = ['name']
fetch_fields = ['name', 'website_url']
mapping = {
'name': {'name': 'name', 'type': 'text', 'match': True},
'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False},
}
if with_description:
search_fields.append('description_short')
fetch_fields.append('description_short')
mapping['description'] = {'name': 'description_short', 'type': 'text', 'html': True, 'match': True}
if with_date:
fetch_fields.append('slide_last_update')
mapping['detail'] = {'name': 'slide_last_update', 'type': 'date'}
return {
'model': 'slide.channel',
'base_domain': domain,
'search_fields': search_fields,
'fetch_fields': fetch_fields,
'mapping': mapping,
'icon': 'fa-graduation-cap',
}
| 51.977427 | 46,052 |
3,085 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class SlideQuestion(models.Model):
_name = "slide.question"
_rec_name = "question"
_description = "Content Quiz Question"
_order = "sequence"
sequence = fields.Integer("Sequence")
question = fields.Char("Question Name", required=True, translate=True)
slide_id = fields.Many2one('slide.slide', string="Content", required=True)
answer_ids = fields.One2many('slide.answer', 'question_id', string="Answer")
# statistics
attempts_count = fields.Integer(compute='_compute_statistics', groups='website_slides.group_website_slides_officer')
attempts_avg = fields.Float(compute="_compute_statistics", digits=(6, 2), groups='website_slides.group_website_slides_officer')
done_count = fields.Integer(compute="_compute_statistics", groups='website_slides.group_website_slides_officer')
@api.constrains('answer_ids')
def _check_answers_integrity(self):
for question in self:
if len(question.answer_ids.filtered(lambda answer: answer.is_correct)) != 1:
raise ValidationError(_('Question "%s" must have 1 correct answer', question.question))
if len(question.answer_ids) < 2:
raise ValidationError(_('Question "%s" must have 1 correct answer and at least 1 incorrect answer', question.question))
@api.depends('slide_id')
def _compute_statistics(self):
slide_partners = self.env['slide.slide.partner'].sudo().search([('slide_id', 'in', self.slide_id.ids)])
slide_stats = dict((s.slide_id.id, dict({'attempts_count': 0, 'attempts_unique': 0, 'done_count': 0})) for s in slide_partners)
for slide_partner in slide_partners:
slide_stats[slide_partner.slide_id.id]['attempts_count'] += slide_partner.quiz_attempts_count
slide_stats[slide_partner.slide_id.id]['attempts_unique'] += 1
if slide_partner.completed:
slide_stats[slide_partner.slide_id.id]['done_count'] += 1
for question in self:
stats = slide_stats.get(question.slide_id.id)
question.attempts_count = stats.get('attempts_count', 0) if stats else 0
question.attempts_avg = stats.get('attempts_count', 0) / stats.get('attempts_unique', 1) if stats else 0
question.done_count = stats.get('done_count', 0) if stats else 0
class SlideAnswer(models.Model):
_name = "slide.answer"
_rec_name = "text_value"
_description = "Slide Question's Answer"
_order = 'question_id, sequence'
sequence = fields.Integer("Sequence")
question_id = fields.Many2one('slide.question', string="Question", required=True, ondelete='cascade')
text_value = fields.Char("Answer", required=True, translate=True)
is_correct = fields.Boolean("Is correct answer")
comment = fields.Text("Comment", translate=True, help='This comment will be displayed to the user if he selects this answer')
| 52.288136 | 3,085 |
589 |
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 UserGroup(models.Model):
_inherit = 'res.groups'
def write(self, vals):
""" Automatically subscribe new users to linked slide channels """
write_res = super(UserGroup, self).write(vals)
if vals.get('users'):
# TDE FIXME: maybe directly check users and subscribe them
self.env['slide.channel'].sudo().search([('enroll_group_ids', 'in', self._ids)])._add_groups_members()
return write_res
| 36.8125 | 589 |
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, models, _
class Users(models.Model):
_inherit = 'res.users'
@api.model_create_multi
def create(self, vals_list):
""" Trigger automatic subscription based on user groups """
users = super(Users, self).create(vals_list)
for user in users:
self.env['slide.channel'].sudo().search([
('enroll_group_ids', 'in', user.groups_id.ids)
])._action_add_members(user.partner_id)
return users
def write(self, vals):
""" Trigger automatic subscription based on updated user groups """
res = super(Users, self).write(vals)
if vals.get('groups_id'):
added_group_ids = [command[1] for command in vals['groups_id'] if command[0] == 4]
added_group_ids += [id for command in vals['groups_id'] if command[0] == 6 for id in command[2]]
self.env['slide.channel'].sudo().search([('enroll_group_ids', 'in', added_group_ids)])._action_add_members(self.mapped('partner_id'))
return res
def get_gamification_redirection_data(self):
res = super(Users, self).get_gamification_redirection_data()
res.append({
'url': '/slides',
'label': _('See our eLearning')
})
return res
| 39.542857 | 1,384 |
616 |
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"
website_slide_google_app_key = fields.Char(related='website_id.website_slide_google_app_key', readonly=False)
module_website_sale_slides = fields.Boolean(string="Sell on eCommerce")
module_website_slides_forum = fields.Boolean(string="Forum")
module_website_slides_survey = fields.Boolean(string="Certifications")
module_mass_mailing_slides = fields.Boolean(string="Mailing")
| 44 | 616 |
1,043 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.addons.http_routing.models.ir_http import url_for
class Website(models.Model):
_inherit = "website"
website_slide_google_app_key = fields.Char('Google Doc Key')
def get_suggested_controllers(self):
suggested_controllers = super(Website, self).get_suggested_controllers()
suggested_controllers.append((_('Courses'), url_for('/slides'), 'website_slides'))
return suggested_controllers
def _search_get_details(self, search_type, order, options):
result = super()._search_get_details(search_type, order, options)
if search_type in ['slides', 'slide_channels_only', 'all']:
result.append(self.env['slide.channel']._search_get_detail(self, order, options))
if search_type in ['slides', 'slides_only', 'all']:
result.append(self.env['slide.slide']._search_get_detail(self, order, options))
return result
| 43.458333 | 1,043 |
3,257 |
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 ResPartner(models.Model):
_inherit = 'res.partner'
slide_channel_ids = fields.Many2many(
'slide.channel', 'slide_channel_partner', 'partner_id', 'channel_id',
string='eLearning Courses', groups="website_slides.group_website_slides_officer", copy=False)
slide_channel_completed_ids = fields.One2many(
'slide.channel', string='Completed Courses',
compute='_compute_slide_channel_completed_ids',
search='_search_slide_channel_completed_ids',
groups="website_slides.group_website_slides_officer")
slide_channel_count = fields.Integer(
'Course Count', compute='_compute_slide_channel_count',
groups="website_slides.group_website_slides_officer")
slide_channel_company_count = fields.Integer(
'Company Course Count', compute='_compute_slide_channel_company_count',
groups="website_slides.group_website_slides_officer")
def _compute_slide_channel_completed_ids(self):
for partner in self:
partner.slide_channel_completed_ids = self.env['slide.channel.partner'].search([
('partner_id', '=', partner.id),
('completed', '=', True)
]).mapped('channel_id')
def _search_slide_channel_completed_ids(self, operator, value):
cp_done = self.env['slide.channel.partner'].sudo().search([
('channel_id', operator, value),
('completed', '=', True)
])
return [('id', 'in', cp_done.partner_id.ids)]
@api.depends('is_company')
def _compute_slide_channel_count(self):
read_group_res = self.env['slide.channel.partner'].sudo().read_group(
[('partner_id', 'in', self.ids)],
['partner_id'], 'partner_id'
)
data = dict((res['partner_id'][0], res['partner_id_count']) for res in read_group_res)
for partner in self:
partner.slide_channel_count = data.get(partner.id, 0)
@api.depends('is_company', 'child_ids.slide_channel_count')
def _compute_slide_channel_company_count(self):
for partner in self:
if partner.is_company:
partner.slide_channel_company_count = self.env['slide.channel'].sudo().search_count(
[('partner_ids', 'in', partner.child_ids.ids)]
)
else:
partner.slide_channel_company_count = 0
def action_view_courses(self):
""" View partners courses. In singleton mode, return courses followed
by all its contacts (if company) or by himself (if not a company).
Otherwise simply set a domain on required partners. """
action = self.env["ir.actions.actions"]._for_xml_id("website_slides.slide_channel_partner_action")
action['name'] = _('Followed Courses')
if len(self) == 1 and self.is_company:
action['domain'] = [('partner_id', 'in', self.child_ids.ids)]
elif len(self) == 1:
action['context'] = {'search_default_partner_id': self.id}
else:
action['domain'] = [('partner_id', 'in', self.ids)]
return action
| 45.873239 | 3,257 |
1,569 |
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 SlideChannelTagGroup(models.Model):
_name = 'slide.channel.tag.group'
_description = 'Channel/Course Groups'
_inherit = 'website.published.mixin'
_order = 'sequence asc'
name = fields.Char('Group Name', required=True, translate=True)
sequence = fields.Integer('Sequence', default=10, index=True, required=True)
tag_ids = fields.One2many('slide.channel.tag', 'group_id', string='Tags')
def _default_is_published(self):
return True
class SlideChannelTag(models.Model):
_name = 'slide.channel.tag'
_description = 'Channel/Course Tag'
_order = 'group_sequence asc, sequence asc'
name = fields.Char('Name', required=True, translate=True)
sequence = fields.Integer('Sequence', default=10, index=True, required=True)
group_id = fields.Many2one('slide.channel.tag.group', string='Group', index=True, required=True)
group_sequence = fields.Integer(
'Group sequence', related='group_id.sequence',
index=True, readonly=True, store=True)
channel_ids = fields.Many2many('slide.channel', 'slide_channel_tag_rel', 'tag_id', 'channel_id', string='Channels')
color = fields.Integer(
string='Color Index', default=lambda self: randint(1, 11),
help="Tag color used in both backend and website. No color means no display in kanban or front-end, to distinguish internal tags from public categorization tags")
| 42.405405 | 1,569 |
3,998 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug
from werkzeug.exceptions import NotFound, Forbidden
from odoo import http
from odoo.http import request
from odoo.addons.portal.controllers.mail import _check_special_access, PortalChatter
from odoo.tools import plaintext2html, html2plaintext
class SlidesPortalChatter(PortalChatter):
@http.route(['/mail/chatter_post'], type='json', methods=['POST'], auth='public', website=True)
def portal_chatter_post(self, res_model, res_id, message, **kw):
result = super(SlidesPortalChatter, self).portal_chatter_post(res_model, res_id, message, **kw)
if res_model == 'slide.channel':
rating_value = kw.get('rating_value', False)
slide_channel = request.env[res_model].sudo().browse(int(res_id))
if rating_value and slide_channel and request.env.user.partner_id.id == int(kw.get('pid')):
# apply karma gain rule only once
request.env.user.add_karma(slide_channel.karma_gen_channel_rank)
result.update({
'default_rating_value': rating_value,
'rating_avg': slide_channel.rating_avg,
'rating_count': slide_channel.rating_count,
'force_submit_url': result.get('default_message_id') and '/slides/mail/update_comment',
})
return result
@http.route([
'/slides/mail/update_comment',
'/mail/chatter_update',
], type='json', auth="user", methods=['POST'])
def mail_update_message(self, res_model, res_id, message, message_id, attachment_ids=None, attachment_tokens=None, **post):
# keep this mechanism intern to slide currently (saas 12.5) as it is
# considered experimental
if res_model != 'slide.channel':
raise Forbidden()
res_id = int(res_id)
self._portal_post_check_attachments(attachment_ids, attachment_tokens)
pid = int(post['pid']) if post.get('pid') else False
if not _check_special_access(res_model, res_id, token=post.get('token'), _hash=post.get('hash'), pid=pid):
raise Forbidden()
# fetch and update mail.message
message_id = int(message_id)
message_body = plaintext2html(message)
subtype_comment_id = request.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment')
domain = [
('model', '=', res_model),
('res_id', '=', res_id),
('subtype_id', '=', subtype_comment_id),
('author_id', '=', request.env.user.partner_id.id),
('message_type', '=', 'comment'),
('id', '=', message_id)
] # restrict to the given message_id
message = request.env['mail.message'].search(domain, limit=1)
if not message:
raise NotFound()
message.sudo().write({
'body': message_body,
'attachment_ids': [(4, aid) for aid in attachment_ids],
})
# update rating
if post.get('rating_value'):
domain = [('res_model', '=', res_model), ('res_id', '=', res_id), ('message_id', '=', message.id)]
rating = request.env['rating.rating'].sudo().search(domain, order='write_date DESC', limit=1)
rating.write({
'rating': float(post['rating_value']),
'feedback': html2plaintext(message.body),
})
channel = request.env[res_model].browse(res_id)
return {
'default_message_id': message.id,
'default_message': html2plaintext(message.body),
'default_rating_value': message.rating_value,
'rating_avg': channel.rating_avg,
'rating_count': channel.rating_count,
'default_attachment_ids': message.attachment_ids.sudo().read(['id', 'name', 'mimetype', 'file_size', 'access_token']),
'force_submit_url': '/slides/mail/update_comment',
}
| 45.954023 | 3,998 |
57,196 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from collections import defaultdict
import base64
import json
import logging
import math
import werkzeug
from odoo import http, tools, _
from odoo.addons.http_routing.models.ir_http import slug, unslug
from odoo.addons.website.controllers.main import QueryURL
from odoo.addons.website.models.ir_http import sitemap_qs2dom
from odoo.addons.website_profile.controllers.main import WebsiteProfile
from odoo.exceptions import AccessError, UserError
from odoo.http import request
from odoo.osv import expression
_logger = logging.getLogger(__name__)
class WebsiteSlides(WebsiteProfile):
_slides_per_page = 12
_slides_per_aside = 20
_slides_per_category = 4
_channel_order_by_criterion = {
'vote': 'total_votes desc',
'view': 'total_views desc',
'date': 'create_date desc',
}
def sitemap_slide(env, rule, qs):
Channel = env['slide.channel']
dom = sitemap_qs2dom(qs=qs, route='/slides/', field=Channel._rec_name)
dom += env['website'].get_current_website().website_domain()
for channel in Channel.search(dom):
loc = '/slides/%s' % slug(channel)
if not qs or qs.lower() in loc:
yield {'loc': loc}
# SLIDE UTILITIES
# --------------------------------------------------
def _fetch_slide(self, slide_id):
slide = request.env['slide.slide'].browse(int(slide_id)).exists()
if not slide:
return {'error': 'slide_wrong'}
try:
slide.check_access_rights('read')
slide.check_access_rule('read')
except AccessError:
return {'error': 'slide_access'}
return {'slide': slide}
def _set_viewed_slide(self, slide, quiz_attempts_inc=False):
if request.env.user._is_public() or not slide.website_published or not slide.channel_id.is_member:
viewed_slides = request.session.setdefault('viewed_slides', list())
if slide.id not in viewed_slides:
if tools.sql.increment_field_skiplock(slide, 'public_views'):
viewed_slides.append(slide.id)
request.session['viewed_slides'] = viewed_slides
else:
slide.action_set_viewed(quiz_attempts_inc=quiz_attempts_inc)
return True
def _set_completed_slide(self, slide):
# quiz use their specific mechanism to be marked as done
if slide.slide_type == 'quiz' or slide.question_ids:
raise UserError(_("Slide with questions must be marked as done when submitting all good answers "))
if slide.website_published and slide.channel_id.is_member:
slide.action_set_completed()
return True
def _get_slide_detail(self, slide):
base_domain = self._get_channel_slides_base_domain(slide.channel_id)
category_data = slide.channel_id._get_categorized_slides(
base_domain,
order=request.env['slide.slide']._order_by_strategy['sequence'],
force_void=True
)
if slide.channel_id.channel_type == 'documentation':
most_viewed_slides = request.env['slide.slide'].search(base_domain, limit=self._slides_per_aside, order='total_views desc')
related_domain = expression.AND([base_domain, [('category_id', '=', slide.category_id.id)]])
related_slides = request.env['slide.slide'].search(related_domain, limit=self._slides_per_aside)
else:
most_viewed_slides, related_slides = request.env['slide.slide'], request.env['slide.slide']
channel_slides_ids = slide.channel_id.slide_content_ids.ids
slide_index = channel_slides_ids.index(slide.id)
previous_slide = slide.channel_id.slide_content_ids[slide_index-1] if slide_index > 0 else None
next_slide = slide.channel_id.slide_content_ids[slide_index+1] if slide_index < len(channel_slides_ids) - 1 else None
values = {
# slide
'slide': slide,
'main_object': slide,
'most_viewed_slides': most_viewed_slides,
'related_slides': related_slides,
'previous_slide': previous_slide,
'next_slide': next_slide,
'category_data': category_data,
# user
'user': request.env.user,
'is_public_user': request.website.is_public_user(),
# rating and comments
'comments': slide.website_message_ids or [],
}
# allow rating and comments
if slide.channel_id.allow_comment:
values.update({
'message_post_pid': request.env.user.partner_id.id,
})
return values
def _get_slide_quiz_partner_info(self, slide, quiz_done=False):
return slide._compute_quiz_info(request.env.user.partner_id, quiz_done=quiz_done)[slide.id]
def _get_slide_quiz_data(self, slide):
slide_completed = slide.user_membership_id.sudo().completed
values = {
'slide_questions': [{
'id': question.id,
'question': question.question,
'answer_ids': [{
'id': answer.id,
'text_value': answer.text_value,
'is_correct': answer.is_correct if slide_completed or request.website.is_publisher() else None,
'comment': answer.comment if request.website.is_publisher() else None
} for answer in question.sudo().answer_ids],
} for question in slide.question_ids]
}
if 'slide_answer_quiz' in request.session:
slide_answer_quiz = json.loads(request.session['slide_answer_quiz'])
if str(slide.id) in slide_answer_quiz:
values['session_answers'] = slide_answer_quiz[str(slide.id)]
values.update(self._get_slide_quiz_partner_info(slide))
return values
def _get_new_slide_category_values(self, channel, name):
return {
'name': name,
'channel_id': channel.id,
'is_category': True,
'is_published': True,
'sequence': channel.slide_ids[-1]['sequence'] + 1 if channel.slide_ids else 1,
}
# CHANNEL UTILITIES
# --------------------------------------------------
def _get_channel_slides_base_domain(self, channel):
""" base domain when fetching slide list data related to a given channel
* website related domain, and restricted to the channel and is not a
category slide (behavior is different from classic slide);
* if publisher: everything is ok;
* if not publisher but has user: either slide is published, either
current user is the one that uploaded it;
* if not publisher and public: published;
"""
base_domain = expression.AND([request.website.website_domain(), ['&', ('channel_id', '=', channel.id), ('is_category', '=', False)]])
if not channel.can_publish:
if request.website.is_public_user():
base_domain = expression.AND([base_domain, [('website_published', '=', True)]])
else:
base_domain = expression.AND([base_domain, ['|', ('website_published', '=', True), ('user_id', '=', request.env.user.id)]])
return base_domain
def _get_channel_progress(self, channel, include_quiz=False):
""" Replacement to user_progress. Both may exist in some transient state. """
slides = request.env['slide.slide'].sudo().search([('channel_id', '=', channel.id)])
channel_progress = dict((sid, dict()) for sid in slides.ids)
if not request.env.user._is_public() and channel.is_member:
slide_partners = request.env['slide.slide.partner'].sudo().search([
('channel_id', '=', channel.id),
('partner_id', '=', request.env.user.partner_id.id),
('slide_id', 'in', slides.ids)
])
for slide_partner in slide_partners:
channel_progress[slide_partner.slide_id.id].update(slide_partner.read()[0])
if slide_partner.slide_id.question_ids:
gains = [slide_partner.slide_id.quiz_first_attempt_reward,
slide_partner.slide_id.quiz_second_attempt_reward,
slide_partner.slide_id.quiz_third_attempt_reward,
slide_partner.slide_id.quiz_fourth_attempt_reward]
channel_progress[slide_partner.slide_id.id]['quiz_gain'] = gains[slide_partner.quiz_attempts_count] if slide_partner.quiz_attempts_count < len(gains) else gains[-1]
if include_quiz:
quiz_info = slides._compute_quiz_info(request.env.user.partner_id, quiz_done=False)
for slide_id, slide_info in quiz_info.items():
channel_progress[slide_id].update(slide_info)
return channel_progress
def _channel_remove_session_answers(self, channel, slide=False):
""" Will remove the answers saved in the session for a specific channel / slide. """
if 'slide_answer_quiz' not in request.session:
return
slides_domain = [('channel_id', '=', channel.id)]
if slide:
slides_domain = expression.AND([slides_domain, [('id', '=', slide.id)]])
slides = request.env['slide.slide'].search_read(slides_domain, ['id'])
session_slide_answer_quiz = json.loads(request.session['slide_answer_quiz'])
for slide in slides:
session_slide_answer_quiz.pop(str(slide['id']), None)
request.session['slide_answer_quiz'] = json.dumps(session_slide_answer_quiz)
# TAG UTILITIES
# --------------------------------------------------
def _slugify_tags(self, tag_ids, toggle_tag_id=None):
""" Prepares a comma separated slugified tags for the sake of readable
URLs.
:param toggle_tag_id: add the tag being clicked (current_tag) to the already
selected tags (tag_ids) as well as in URL; if tag is already selected
by the user it is removed from the selected tags (and so from the URL);
"""
tag_ids = list(tag_ids) # required to avoid using the same list
if toggle_tag_id and toggle_tag_id in tag_ids:
tag_ids.remove(toggle_tag_id)
elif toggle_tag_id:
tag_ids.append(toggle_tag_id)
return ','.join(slug(tag) for tag in request.env['slide.channel.tag'].browse(tag_ids))
def _channel_search_tags_ids(self, search_tags):
""" Input: %5B4%5D """
ChannelTag = request.env['slide.channel.tag']
try:
tag_ids = literal_eval(search_tags or '')
except Exception:
return ChannelTag
# perform a search to filter on existing / valid tags implicitly
return ChannelTag.search([('id', 'in', tag_ids)]) if tag_ids else ChannelTag
def _channel_search_tags_slug(self, search_tags):
""" Input: hotels-1,adventure-2 """
ChannelTag = request.env['slide.channel.tag']
try:
tag_ids = list(filter(None, [unslug(tag)[1] for tag in (search_tags or '').split(',')]))
except Exception:
return ChannelTag
# perform a search to filter on existing / valid tags implicitly
return ChannelTag.search([('id', 'in', tag_ids)]) if tag_ids else ChannelTag
def _create_or_get_channel_tag(self, tag_id, group_id):
if not tag_id:
return request.env['slide.channel.tag']
# handle creation of new channel tag
if tag_id[0] == 0:
group_id = self._create_or_get_channel_tag_group_id(group_id)
if not group_id:
return {'error': _('Missing "Tag Group" for creating a new "Tag".')}
return request.env['slide.channel.tag'].create({
'name': tag_id[1]['name'],
'group_id': group_id,
})
return request.env['slide.channel.tag'].browse(tag_id[0])
def _create_or_get_channel_tag_group_id(self, group_id):
if not group_id:
return False
# handle creation of new channel tag group
if group_id[0] == 0:
return request.env['slide.channel.tag.group'].create({
'name': group_id[1]['name'],
}).id
# use existing channel tag group
return group_id[0]
# --------------------------------------------------
# SLIDE.CHANNEL MAIN / SEARCH
# --------------------------------------------------
@http.route('/slides', type='http', auth="public", website=True, sitemap=True)
def slides_channel_home(self, **post):
""" Home page for eLearning platform. Is mainly a container page, does not allow search / filter. """
domain = request.website.website_domain()
channels_all = request.env['slide.channel'].search(domain)
if not request.env.user._is_public():
#If a course is completed, we don't want to see it in first position but in last
channels_my = channels_all.filtered(lambda channel: channel.is_member).sorted(lambda channel: 0 if channel.completed else channel.completion, reverse=True)[:3]
else:
channels_my = request.env['slide.channel']
channels_popular = channels_all.sorted('total_votes', reverse=True)[:3]
channels_newest = channels_all.sorted('create_date', reverse=True)[:3]
achievements = request.env['gamification.badge.user'].sudo().search([('badge_id.is_published', '=', True)], limit=5)
if request.env.user._is_public():
challenges = None
challenges_done = None
else:
challenges = request.env['gamification.challenge'].sudo().search([
('challenge_category', '=', 'slides'),
('reward_id.is_published', '=', True)
], order='id asc', limit=5)
challenges_done = request.env['gamification.badge.user'].sudo().search([
('challenge_id', 'in', challenges.ids),
('user_id', '=', request.env.user.id),
('badge_id.is_published', '=', True)
]).mapped('challenge_id')
users = request.env['res.users'].sudo().search([
('karma', '>', 0),
('website_published', '=', True)], limit=5, order='karma desc')
values = self._prepare_user_values(**post)
values.update({
'channels_my': channels_my,
'channels_popular': channels_popular,
'channels_newest': channels_newest,
'achievements': achievements,
'users': users,
'top3_users': self._get_top3_users(),
'challenges': challenges,
'challenges_done': challenges_done,
'search_tags': request.env['slide.channel.tag'],
'slide_query_url': QueryURL('/slides/all', ['tag']),
'slugify_tags': self._slugify_tags,
})
return request.render('website_slides.courses_home', values)
@http.route(['/slides/all', '/slides/all/tag/<string:slug_tags>'], type='http', auth="public", website=True, sitemap=True)
def slides_channel_all(self, slide_type=None, slug_tags=None, my=False, **post):
""" Home page displaying a list of courses displayed according to some
criterion and search terms.
:param string slide_type: if provided, filter the course to contain at
least one slide of type 'slide_type'. Used notably to display courses
with certifications;
:param string slug_tags: if provided, filter the slide.channels having
the tag(s) (in comma separated slugified form);
:param bool my: if provided, filter the slide.channels for which the
current user is a member of
:param dict post: post parameters, including
* ``search``: filter on course description / name;
"""
if slug_tags and request.httprequest.method == 'GET':
# Redirect `tag-1,tag-2` to `tag-1` to disallow multi tags
# in GET request for proper bot indexation;
# if the search term is available, do not remove any existing
# tags because it is user who provided search term with GET
# request and so clearly it's not SEO bot.
tag_list = slug_tags.split(',')
if len(tag_list) > 1 and not post.get('search'):
url = QueryURL('/slides/all', ['tag'], tag=tag_list[0], my=my, slide_type=slide_type)()
return request.redirect(url, code=302)
options = {
'displayDescription': True,
'displayDetail': False,
'displayExtraDetail': False,
'displayExtraLink': False,
'displayImage': False,
'allowFuzzy': not post.get('noFuzzy'),
'my': my,
'tag': slug_tags or post.get('tag'),
'slide_type': slide_type,
}
search = post.get('search')
order = self._channel_order_by_criterion.get(post.get('sorting'))
_, details, fuzzy_search_term = request.website._search_with_fuzzy("slide_channels_only", search,
limit=1000, order=order, options=options)
channels = details[0].get('results', request.env['slide.channel'])
tag_groups = request.env['slide.channel.tag.group'].search(
['&', ('tag_ids', '!=', False), ('website_published', '=', True)])
if slug_tags:
search_tags = self._channel_search_tags_slug(slug_tags)
elif post.get('tags'):
search_tags = self._channel_search_tags_ids(post['tags'])
else:
search_tags = request.env['slide.channel.tag']
values = self._prepare_user_values(**post)
values.update({
'channels': channels,
'tag_groups': tag_groups,
'search_term': fuzzy_search_term or search,
'original_search': fuzzy_search_term and search,
'search_slide_type': slide_type,
'search_my': my,
'search_tags': search_tags,
'top3_users': self._get_top3_users(),
'slugify_tags': self._slugify_tags,
'slide_query_url': QueryURL('/slides/all', ['tag']),
})
return request.render('website_slides.courses_all', values)
def _prepare_additional_channel_values(self, values, **kwargs):
return values
def _get_top3_users(self):
return request.env['res.users'].sudo().search_read([
('karma', '>', 0),
('website_published', '=', True)], ['id'], limit=3, order='karma desc')
@http.route([
'/slides/<model("slide.channel"):channel>',
'/slides/<model("slide.channel"):channel>/page/<int:page>',
'/slides/<model("slide.channel"):channel>/tag/<model("slide.tag"):tag>',
'/slides/<model("slide.channel"):channel>/tag/<model("slide.tag"):tag>/page/<int:page>',
'/slides/<model("slide.channel"):channel>/category/<model("slide.slide"):category>',
'/slides/<model("slide.channel"):channel>/category/<model("slide.slide"):category>/page/<int:page>',
], type='http', auth="public", website=True, sitemap=sitemap_slide)
def channel(self, channel, category=None, tag=None, page=1, slide_type=None, uncategorized=False, sorting=None, search=None, **kw):
"""
Will return all necessary data to display the requested slide_channel along with a possible category.
"""
domain = self._get_channel_slides_base_domain(channel)
pager_url = "/slides/%s" % (channel.id)
pager_args = {}
slide_types = dict(request.env['slide.slide']._fields['slide_type']._description_selection(request.env))
if search:
domain += [
'|', '|',
('name', 'ilike', search),
('description', 'ilike', search),
('html_content', 'ilike', search)]
pager_args['search'] = search
else:
if category:
domain += [('category_id', '=', category.id)]
pager_url += "/category/%s" % category.id
elif tag:
domain += [('tag_ids.id', '=', tag.id)]
pager_url += "/tag/%s" % tag.id
if uncategorized:
domain += [('category_id', '=', False)]
pager_args['uncategorized'] = 1
elif slide_type:
domain += [('slide_type', '=', slide_type)]
pager_url += "?slide_type=%s" % slide_type
# sorting criterion
if channel.channel_type == 'documentation':
default_sorting = 'latest' if channel.promote_strategy in ['specific', 'none', False] else channel.promote_strategy
actual_sorting = sorting if sorting and sorting in request.env['slide.slide']._order_by_strategy else default_sorting
else:
actual_sorting = 'sequence'
order = request.env['slide.slide']._order_by_strategy[actual_sorting]
pager_args['sorting'] = actual_sorting
slide_count = request.env['slide.slide'].sudo().search_count(domain)
page_count = math.ceil(slide_count / self._slides_per_page)
pager = request.website.pager(url=pager_url, total=slide_count, page=page,
step=self._slides_per_page, url_args=pager_args,
scope=page_count if page_count < self._pager_max_pages else self._pager_max_pages)
query_string = None
if category:
query_string = "?search_category=%s" % category.id
elif tag:
query_string = "?search_tag=%s" % tag.id
elif slide_type:
query_string = "?search_slide_type=%s" % slide_type
elif uncategorized:
query_string = "?search_uncategorized=1"
values = {
'channel': channel,
'main_object': channel,
'active_tab': kw.get('active_tab', 'home'),
# search
'search_category': category,
'search_tag': tag,
'search_slide_type': slide_type,
'search_uncategorized': uncategorized,
'query_string': query_string,
'slide_types': slide_types,
'sorting': actual_sorting,
'search': search,
# display data
'user': request.env.user,
'pager': pager,
'is_public_user': request.website.is_public_user(),
# display upload modal
'enable_slide_upload': 'enable_slide_upload' in kw,
** self._slide_channel_prepare_review_values(channel),
}
# fetch slides and handle uncategorized slides; done as sudo because we want to display all
# of them but unreachable ones won't be clickable (+ slide controller will crash anyway)
# documentation mode may display less slides than content by category but overhead of
# computation is reasonable
if channel.promote_strategy == 'specific':
values['slide_promoted'] = channel.sudo().promoted_slide_id
else:
values['slide_promoted'] = request.env['slide.slide'].sudo().search(domain, limit=1, order=order)
limit_category_data = False
if channel.channel_type == 'documentation':
if category or uncategorized:
limit_category_data = self._slides_per_page
else:
limit_category_data = self._slides_per_category
values['category_data'] = channel._get_categorized_slides(
domain, order,
force_void=not category,
limit=limit_category_data,
offset=pager['offset'])
values['channel_progress'] = self._get_channel_progress(channel, include_quiz=True)
# for sys admins: prepare data to install directly modules from eLearning when
# uploading slides. Currently supporting only survey, because why not.
if request.env.user.has_group('base.group_system'):
module = request.env.ref('base.module_survey')
if module.state != 'installed':
values['modules_to_install'] = [{
'id': module.id,
'name': module.shortdesc,
'motivational': _('Evaluate and certify your students.'),
}]
values = self._prepare_additional_channel_values(values, **kw)
return request.render('website_slides.course_main', values)
# SLIDE.CHANNEL UTILS
# --------------------------------------------------
@http.route('/slides/channel/add', type='http', auth='user', methods=['POST'], website=True)
def slide_channel_create(self, *args, **kw):
channel = request.env['slide.channel'].create(self._slide_channel_prepare_values(**kw))
return request.redirect("/slides/%s" % (slug(channel)))
def _slide_channel_prepare_values(self, **kw):
# `tag_ids` is a string representing a list of int with coma. i.e.: '2,5,7'
# We don't want to allow user to create tags and tag groups on the fly.
tag_ids = []
if kw.get('tag_ids'):
tag_ids = [int(item) for item in kw['tag_ids'].split(',')]
return {
'name': kw['name'],
'description': kw.get('description'),
'channel_type': kw.get('channel_type', 'documentation'),
'user_id': request.env.user.id,
'tag_ids': [(6, 0, tag_ids)],
'allow_comment': bool(kw.get('allow_comment')),
}
def _slide_channel_prepare_review_values(self, channel):
values = {
'rating_avg': channel.rating_avg,
'rating_count': channel.rating_count,
}
if not request.env.user._is_public():
subtype_comment_id = request.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment')
last_message = request.env['mail.message'].search([
('model', '=', channel._name),
('res_id', '=', channel.id),
('author_id', '=', request.env.user.partner_id.id),
('message_type', '=', 'comment'),
('subtype_id', '=', subtype_comment_id)
], order='write_date DESC', limit=1)
if last_message:
last_message_values = last_message.read(['body', 'rating_value', 'attachment_ids'])[0]
last_message_attachment_ids = last_message_values.pop('attachment_ids', [])
if last_message_attachment_ids:
# use sudo as portal user cannot read access_token, necessary for updating attachments
# through frontend chatter -> access is already granted and limited to current user message
last_message_attachment_ids = json.dumps(
request.env['ir.attachment'].sudo().browse(last_message_attachment_ids).read(
['id', 'name', 'mimetype', 'file_size', 'access_token']
)
)
else:
last_message_values = {}
last_message_attachment_ids = []
values.update({
'last_message_id': last_message_values.get('id'),
'last_message': tools.html2plaintext(last_message_values.get('body', '')),
'last_rating_value': last_message_values.get('rating_value'),
'last_message_attachment_ids': last_message_attachment_ids,
})
if channel.can_review:
values.update({
'message_post_hash': channel._sign_token(request.env.user.partner_id.id),
'message_post_pid': request.env.user.partner_id.id,
})
return values
@http.route('/slides/channel/enroll', type='http', auth='public', website=True)
def slide_channel_join_http(self, channel_id):
# TDE FIXME: why 2 routes ?
if not request.website.is_public_user():
channel = request.env['slide.channel'].browse(int(channel_id))
channel.action_add_member()
return request.redirect("/slides/%s" % (slug(channel)))
@http.route(['/slides/channel/join'], type='json', auth='public', website=True)
def slide_channel_join(self, channel_id):
if request.website.is_public_user():
return {'error': 'public_user', 'error_signup_allowed': request.env['res.users'].sudo()._get_signup_invitation_scope() == 'b2c'}
success = request.env['slide.channel'].browse(channel_id).action_add_member()
if not success:
return {'error': 'join_done'}
return success
@http.route(['/slides/channel/leave'], type='json', auth='user', website=True)
def slide_channel_leave(self, channel_id):
channel = request.env['slide.channel'].browse(channel_id)
channel._remove_membership(request.env.user.partner_id.ids)
self._channel_remove_session_answers(channel)
return True
@http.route(['/slides/channel/tag/search_read'], type='json', auth='user', methods=['POST'], website=True)
def slide_channel_tag_search_read(self, fields, domain):
can_create = request.env['slide.channel.tag'].check_access_rights('create', raise_exception=False)
return {
'read_results': request.env['slide.channel.tag'].search_read(domain, fields),
'can_create': can_create,
}
@http.route(['/slides/channel/tag/group/search_read'], type='json', auth='user', methods=['POST'], website=True)
def slide_channel_tag_group_search_read(self, fields, domain):
can_create = request.env['slide.channel.tag.group'].check_access_rights('create', raise_exception=False)
return {
'read_results': request.env['slide.channel.tag.group'].search_read(domain, fields),
'can_create': can_create,
}
@http.route('/slides/channel/tag/add', type='json', auth='user', methods=['POST'], website=True)
def slide_channel_tag_add(self, channel_id, tag_id=None, group_id=None):
""" Adds a slide channel tag to the specified slide channel.
:param integer channel_id: Channel ID
:param list tag_id: Channel Tag ID as first value of list. If id=0, then this is a new tag to
generate and expects a second list value of the name of the new tag.
:param list group_id: Channel Tag Group ID as first value of list. If id=0, then this is a new
tag group to generate and expects a second list value of the name of the
new tag group. This value is required for when a new tag is being created.
tag_id and group_id values are provided by a Select2. Default "None" values allow for
graceful failures in exceptional cases when values are not provided.
:return: channel's course page
"""
# handle exception during addition of course tag and send error notification to the client
# otherwise client slide create dialog box continue processing even server fail to create a slide
try:
channel = request.env['slide.channel'].browse(int(channel_id))
can_upload = channel.can_upload
can_publish = channel.can_publish
except UserError as e:
_logger.error(e)
return {'error': e.args[0]}
else:
if not can_upload or not can_publish:
return {'error': _('You cannot add tags to this course.')}
tag = self._create_or_get_channel_tag(tag_id, group_id)
tag.write({'channel_ids': [(4, channel.id, 0)]})
return {'url': "/slides/%s" % (slug(channel))}
@http.route(['/slides/channel/subscribe'], type='json', auth='user', website=True)
def slide_channel_subscribe(self, channel_id):
return request.env['slide.channel'].browse(channel_id).message_subscribe(partner_ids=[request.env.user.partner_id.id])
@http.route(['/slides/channel/unsubscribe'], type='json', auth='user', website=True)
def slide_channel_unsubscribe(self, channel_id):
request.env['slide.channel'].browse(channel_id).message_unsubscribe(partner_ids=[request.env.user.partner_id.id])
return True
# --------------------------------------------------
# SLIDE.SLIDE MAIN / SEARCH
# --------------------------------------------------
@http.route('''/slides/slide/<model("slide.slide"):slide>''', type='http', auth="public", website=True, sitemap=True)
def slide_view(self, slide, **kwargs):
if not slide.channel_id.can_access_from_current_website() or not slide.active:
raise werkzeug.exceptions.NotFound()
# redirection to channel's homepage for category slides
if slide.is_category:
return request.redirect(slide.channel_id.website_url)
self._set_viewed_slide(slide)
values = self._get_slide_detail(slide)
# quiz-specific: update with karma and quiz information
if slide.question_ids:
values.update(self._get_slide_quiz_data(slide))
# sidebar: update with user channel progress
values['channel_progress'] = self._get_channel_progress(slide.channel_id, include_quiz=True)
# Allows to have breadcrumb for the previously used filter
values.update({
'search_category': slide.category_id if kwargs.get('search_category') else None,
'search_tag': request.env['slide.tag'].browse(int(kwargs.get('search_tag'))) if kwargs.get('search_tag') else None,
'slide_types': dict(request.env['slide.slide']._fields['slide_type']._description_selection(request.env)) if kwargs.get('search_slide_type') else None,
'search_slide_type': kwargs.get('search_slide_type'),
'search_uncategorized': kwargs.get('search_uncategorized')
})
values['channel'] = slide.channel_id
values = self._prepare_additional_channel_values(values, **kwargs)
values['signup_allowed'] = request.env['res.users'].sudo()._get_signup_invitation_scope() == 'b2c'
if kwargs.get('fullscreen') == '1':
values.update(self._slide_channel_prepare_review_values(slide.channel_id))
return request.render("website_slides.slide_fullscreen", values)
values.pop('channel', None)
return request.render("website_slides.slide_main", values)
@http.route('''/slides/slide/<model("slide.slide"):slide>/pdf_content''',
type='http', auth="public", website=True, sitemap=False)
def slide_get_pdf_content(self, slide):
response = werkzeug.wrappers.Response()
response.data = slide.datas and base64.b64decode(slide.datas) or b''
response.mimetype = 'application/pdf'
return response
@http.route('/slides/slide/<int:slide_id>/get_image', type='http', auth="public", website=True, sitemap=False)
def slide_get_image(self, slide_id, field='image_128', width=0, height=0, crop=False):
# Protect infographics by limiting access to 256px (large) images
if field not in ('image_128', 'image_256', 'image_512', 'image_1024', 'image_1920'):
return werkzeug.exceptions.Forbidden()
slide = request.env['slide.slide'].sudo().browse(slide_id).exists()
if not slide:
raise werkzeug.exceptions.NotFound()
status, headers, image_base64 = request.env['ir.http'].sudo().binary_content(
model='slide.slide', id=slide.id, field=field,
default_mimetype='image/png')
if status == 301:
return request.env['ir.http']._response_by_status(status, headers, image_base64)
if status == 304:
return werkzeug.wrappers.Response(status=304)
if not image_base64:
image_base64 = self._get_default_avatar()
if not (width or height):
width, height = tools.image_guess_size_from_field_name(field)
image_base64 = tools.image_process(image_base64, size=(int(width), int(height)), crop=crop)
content = base64.b64decode(image_base64)
headers = http.set_safe_image_headers(headers, content)
response = request.make_response(content, headers)
response.status_code = status
return response
# SLIDE.SLIDE UTILS
# --------------------------------------------------
@http.route('/slides/slide/get_html_content', type="json", auth="public", website=True)
def get_html_content(self, slide_id):
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
return {
'html_content': fetch_res['slide'].html_content
}
@http.route('/slides/slide/<model("slide.slide"):slide>/set_completed', website=True, type="http", auth="user")
def slide_set_completed_and_redirect(self, slide, next_slide_id=None):
self._set_completed_slide(slide)
next_slide = None
if next_slide_id:
next_slide = self._fetch_slide(next_slide_id).get('slide', None)
return request.redirect("/slides/slide/%s" % (slug(next_slide) if next_slide else slug(slide)))
@http.route('/slides/slide/set_completed', website=True, type="json", auth="public")
def slide_set_completed(self, slide_id):
if request.website.is_public_user():
return {'error': 'public_user'}
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
self._set_completed_slide(fetch_res['slide'])
return {
'channel_completion': fetch_res['slide'].channel_id.completion
}
@http.route('/slides/slide/like', type='json', auth="public", website=True)
def slide_like(self, slide_id, upvote):
if request.website.is_public_user():
return {'error': 'public_user', 'error_signup_allowed': request.env['res.users'].sudo()._get_signup_invitation_scope() == 'b2c'}
slide_partners = request.env['slide.slide.partner'].sudo().search([
('slide_id', '=', slide_id),
('partner_id', '=', request.env.user.partner_id.id)
])
if (upvote and slide_partners.vote == 1) or (not upvote and slide_partners.vote == -1):
return {'error': 'vote_done'}
# check slide access
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
# check slide operation
slide = fetch_res['slide']
if not slide.channel_id.is_member:
return {'error': 'channel_membership_required'}
if not slide.channel_id.allow_comment:
return {'error': 'channel_comment_disabled'}
if not slide.channel_id.can_vote:
return {'error': 'channel_karma_required'}
if upvote:
slide.action_like()
else:
slide.action_dislike()
slide.invalidate_cache()
return slide.read(['likes', 'dislikes', 'user_vote'])[0]
@http.route('/slides/slide/archive', type='json', auth='user', website=True)
def slide_archive(self, slide_id):
""" This route allows channel publishers to archive slides.
It has to be done in sudo mode since only website_publishers can write on slides in ACLs """
slide = request.env['slide.slide'].browse(int(slide_id))
if slide.channel_id.can_publish:
slide.sudo().active = False
return True
return False
@http.route('/slides/slide/toggle_is_preview', type='json', auth='user', website=True)
def slide_preview(self, slide_id):
slide = request.env['slide.slide'].browse(int(slide_id))
if slide.channel_id.can_publish:
slide.is_preview = not slide.is_preview
return slide.is_preview
@http.route(['/slides/slide/send_share_email'], type='json', auth='user', website=True)
def slide_send_share_email(self, slide_id, email, fullscreen=False):
slide = request.env['slide.slide'].browse(int(slide_id))
result = slide._send_share_email(email, fullscreen)
return result
# --------------------------------------------------
# TAGS SECTION
# --------------------------------------------------
@http.route('/slide_channel_tag/add', type='json', auth='user', methods=['POST'], website=True)
def slide_channel_tag_create_or_get(self, tag_id, group_id):
tag = self._create_or_get_channel_tag(tag_id, group_id)
return {'tag_id': tag.id}
# --------------------------------------------------
# QUIZ SECTION
# --------------------------------------------------
@http.route('/slides/slide/quiz/question_add_or_update', type='json', methods=['POST'], auth='user', website=True)
def slide_quiz_question_add_or_update(self, slide_id, question, sequence, answer_ids, existing_question_id=None):
""" Add a new question to an existing slide. Completed field of slide.partner
link is set to False to make sure that the creator can take the quiz again.
An optional question_id to udpate can be given. In this case question is
deleted first before creating a new one to simplify management.
:param integer slide_id: Slide ID
:param string question: Question Title
:param integer sequence: Question Sequence
:param array answer_ids: Array containing all the answers :
[
'sequence': Answer Sequence (Integer),
'text_value': Answer Title (String),
'is_correct': Answer Is Correct (Boolean)
]
:param integer existing_question_id: question ID if this is an update
:return: rendered question template
"""
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
slide = fetch_res['slide']
if existing_question_id:
request.env['slide.question'].search([
('slide_id', '=', slide.id),
('id', '=', int(existing_question_id))
]).unlink()
request.env['slide.slide.partner'].search([
('slide_id', '=', slide_id),
('partner_id', '=', request.env.user.partner_id.id)
]).write({'completed': False})
slide_question = request.env['slide.question'].create({
'sequence': sequence,
'question': question,
'slide_id': slide_id,
'answer_ids': [(0, 0, {
'sequence': answer['sequence'],
'text_value': answer['text_value'],
'is_correct': answer['is_correct'],
'comment': answer['comment']
}) for answer in answer_ids]
})
return request.env.ref('website_slides.lesson_content_quiz_question')._render({
'slide': slide,
'question': slide_question,
})
@http.route('/slides/slide/quiz/get', type="json", auth="public", website=True)
def slide_quiz_get(self, slide_id):
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
slide = fetch_res['slide']
return self._get_slide_quiz_data(slide)
@http.route('/slides/slide/quiz/reset', type="json", auth="user", website=True)
def slide_quiz_reset(self, slide_id):
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
request.env['slide.slide.partner'].search([
('slide_id', '=', fetch_res['slide'].id),
('partner_id', '=', request.env.user.partner_id.id)
]).write({'completed': False, 'quiz_attempts_count': 0})
@http.route('/slides/slide/quiz/submit', type="json", auth="public", website=True)
def slide_quiz_submit(self, slide_id, answer_ids):
if request.website.is_public_user():
return {'error': 'public_user'}
fetch_res = self._fetch_slide(slide_id)
if fetch_res.get('error'):
return fetch_res
slide = fetch_res['slide']
if slide.user_membership_id.sudo().completed:
self._channel_remove_session_answers(slide.channel_id, slide)
return {'error': 'slide_quiz_done'}
all_questions = request.env['slide.question'].sudo().search([('slide_id', '=', slide.id)])
user_answers = request.env['slide.answer'].sudo().search([('id', 'in', answer_ids)])
if user_answers.mapped('question_id') != all_questions:
return {'error': 'slide_quiz_incomplete'}
user_bad_answers = user_answers.filtered(lambda answer: not answer.is_correct)
self._set_viewed_slide(slide, quiz_attempts_inc=True)
quiz_info = self._get_slide_quiz_partner_info(slide, quiz_done=True)
rank_progress = {}
if not user_bad_answers:
rank_progress['previous_rank'] = self._get_rank_values(request.env.user)
slide._action_set_quiz_done()
slide.action_set_completed()
rank_progress['new_rank'] = self._get_rank_values(request.env.user)
rank_progress.update({
'description': request.env.user.rank_id.description,
'last_rank': not request.env.user._get_next_rank(),
'level_up': rank_progress['previous_rank']['lower_bound'] != rank_progress['new_rank']['lower_bound']
})
self._channel_remove_session_answers(slide.channel_id, slide)
return {
'answers': {
answer.question_id.id: {
'is_correct': answer.is_correct,
'comment': answer.comment
} for answer in user_answers
},
'completed': slide.user_membership_id.sudo().completed,
'channel_completion': slide.channel_id.completion,
'quizKarmaWon': quiz_info['quiz_karma_won'],
'quizKarmaGain': quiz_info['quiz_karma_gain'],
'quizAttemptsCount': quiz_info['quiz_attempts_count'],
'rankProgress': rank_progress,
}
@http.route(['/slides/slide/quiz/save_to_session'], type='json', auth='public', website=True)
def slide_quiz_save_to_session(self, quiz_answers):
session_slide_answer_quiz = json.loads(request.session.get('slide_answer_quiz', '{}'))
slide_id = quiz_answers['slide_id']
session_slide_answer_quiz[str(slide_id)] = quiz_answers['slide_answers']
request.session['slide_answer_quiz'] = json.dumps(session_slide_answer_quiz)
def _get_rank_values(self, user):
lower_bound = user.rank_id.karma_min or 0
next_rank = user._get_next_rank()
upper_bound = next_rank.karma_min
progress = 100
if next_rank and (upper_bound - lower_bound) != 0:
progress = 100 * ((user.karma - lower_bound) / (upper_bound - lower_bound))
return {
'lower_bound': lower_bound,
'upper_bound': upper_bound,
'karma': user.karma,
'motivational': next_rank.description_motivational,
'progress': progress
}
# --------------------------------------------------
# CATEGORY MANAGEMENT
# --------------------------------------------------
@http.route(['/slides/category/search_read'], type='json', auth='user', methods=['POST'], website=True)
def slide_category_search_read(self, fields, domain):
category_slide_domain = domain if domain else []
category_slide_domain = expression.AND([category_slide_domain, [('is_category', '=', True)]])
can_create = request.env['slide.slide'].check_access_rights('create', raise_exception=False)
return {
'read_results': request.env['slide.slide'].search_read(category_slide_domain, fields),
'can_create': can_create,
}
@http.route('/slides/category/add', type="http", website=True, auth="user", methods=['POST'])
def slide_category_add(self, channel_id, name):
""" Adds a category to the specified channel. Slide is added at the end
of slide list based on sequence. """
channel = request.env['slide.channel'].browse(int(channel_id))
if not channel.can_upload or not channel.can_publish:
raise werkzeug.exceptions.NotFound()
request.env['slide.slide'].create(self._get_new_slide_category_values(channel, name))
return request.redirect("/slides/%s" % (slug(channel)))
# --------------------------------------------------
# SLIDE.UPLOAD
# --------------------------------------------------
@http.route(['/slides/prepare_preview'], type='json', auth='user', methods=['POST'], website=True)
def prepare_preview(self, **data):
Slide = request.env['slide.slide']
unused, document_id = Slide._find_document_data_from_url(data['url'])
preview = {}
if not document_id:
preview['error'] = _('Please enter valid youtube or google doc url')
return preview
existing_slide = Slide.search([('channel_id', '=', int(data['channel_id'])), ('document_id', '=', document_id)], limit=1)
if existing_slide:
preview['error'] = _('This video already exists in this channel on the following slide: %s', existing_slide.name)
return preview
values = Slide._parse_document_url(data['url'], only_preview_fields=True)
if values.get('error'):
preview['error'] = values['error']
return preview
return values
@http.route(['/slides/add_slide'], type='json', auth='user', methods=['POST'], website=True)
def create_slide(self, *args, **post):
# check the size only when we upload a file.
if post.get('datas'):
file_size = len(post['datas']) * 3 / 4 # base64
if (file_size / 1024.0 / 1024.0) > 25:
return {'error': _('File is too big. File size cannot exceed 25MB')}
values = dict((fname, post[fname]) for fname in self._get_valid_slide_post_values() if post.get(fname))
# handle exception during creation of slide and sent error notification to the client
# otherwise client slide create dialog box continue processing even server fail to create a slide
try:
channel = request.env['slide.channel'].browse(values['channel_id'])
can_upload = channel.can_upload
can_publish = channel.can_publish
except UserError as e:
_logger.error(e)
return {'error': e.args[0]}
else:
if not can_upload:
return {'error': _('You cannot upload on this channel.')}
if post.get('duration'):
# minutes to hours conversion
values['completion_time'] = int(post['duration']) / 60
category = False
# handle creation of new categories on the fly
if post.get('category_id'):
category_id = post['category_id'][0]
if category_id == 0:
category = request.env['slide.slide'].create(self._get_new_slide_category_values(channel, post['category_id'][1]['name']))
values['sequence'] = category.sequence + 1
else:
category = request.env['slide.slide'].browse(category_id)
values.update({
'sequence': request.env['slide.slide'].browse(post['category_id'][0]).sequence + 1
})
# create slide itself
try:
values['user_id'] = request.env.uid
values['is_published'] = values.get('is_published', False) and can_publish
slide = request.env['slide.slide'].sudo().create(values)
except UserError as e:
_logger.error(e)
return {'error': e.args[0]}
except Exception as e:
_logger.error(e)
return {'error': _('Internal server error, please try again later or contact administrator.\nHere is the error message: %s', e)}
# ensure correct ordering by re sequencing slides in front-end (backend should be ok thanks to list view)
channel._resequence_slides(slide, force_category=category)
redirect_url = "/slides/slide/%s" % (slide.id)
if channel.channel_type == "training" and not slide.slide_type == "webpage":
redirect_url = "/slides/%s" % (slug(channel))
if slide.slide_type == 'webpage':
redirect_url += "?enable_editor=1"
return {
'url': redirect_url,
'channel_type': channel.channel_type,
'slide_id': slide.id,
'category_id': slide.category_id
}
def _get_valid_slide_post_values(self):
return ['name', 'url', 'tag_ids', 'slide_type', 'channel_id', 'is_preview',
'mime_type', 'datas', 'description', 'image_1920', 'is_published']
@http.route(['/slides/tag/search_read'], type='json', auth='user', methods=['POST'], website=True)
def slide_tag_search_read(self, fields, domain):
can_create = request.env['slide.tag'].check_access_rights('create', raise_exception=False)
return {
'read_results': request.env['slide.tag'].search_read(domain, fields),
'can_create': can_create,
}
# --------------------------------------------------
# EMBED IN THIRD PARTY WEBSITES
# --------------------------------------------------
@http.route('/slides/embed/<int:slide_id>', type='http', auth='public', website=True, sitemap=False)
def slides_embed(self, slide_id, page="1", **kw):
# Note : don't use the 'model' in the route (use 'slide_id'), otherwise if public cannot access the embedded
# slide, the error will be the website.403 page instead of the one of the website_slides.embed_slide.
# Do not forget the rendering here will be displayed in the embedded iframe
# try accessing slide, and display to corresponding template
try:
slide = request.env['slide.slide'].browse(slide_id)
# determine if it is embedded from external web page
referrer_url = request.httprequest.headers.get('Referer', '')
base_url = slide.get_base_url()
is_embedded = referrer_url and not bool(base_url in referrer_url) or False
if is_embedded:
request.env['slide.embed'].sudo()._add_embed_url(slide.id, referrer_url)
values = self._get_slide_detail(slide)
values['page'] = page
values['is_embedded'] = is_embedded
self._set_viewed_slide(slide)
return request.render('website_slides.embed_slide', values)
except AccessError: # TODO : please, make it clean one day, or find another secure way to detect
# if the slide can be embedded, and properly display the error message.
return request.render('website_slides.embed_slide_forbidden', {})
# --------------------------------------------------
# PROFILE
# --------------------------------------------------
def _prepare_user_values(self, **kwargs):
values = super(WebsiteSlides, self)._prepare_user_values(**kwargs)
channel = self._get_channels(**kwargs)
if channel:
values['channel'] = channel
return values
def _get_channels(self, **kwargs):
channels = []
if kwargs.get('channel'):
channels = kwargs['channel']
elif kwargs.get('channel_id'):
channels = request.env['slide.channel'].browse(int(kwargs['channel_id']))
return channels
def _prepare_user_slides_profile(self, user):
courses = request.env['slide.channel.partner'].sudo().search([('partner_id', '=', user.partner_id.id)])
courses_completed = courses.filtered(lambda c: c.completed)
courses_ongoing = courses - courses_completed
values = {
'uid': request.env.user.id,
'user': user,
'main_object': user,
'courses_completed': courses_completed,
'courses_ongoing': courses_ongoing,
'is_profile_page': True,
'badge_category': 'slides',
}
return values
def _prepare_user_profile_values(self, user, **post):
values = super(WebsiteSlides, self)._prepare_user_profile_values(user, **post)
if post.get('channel_id'):
values.update({'edit_button_url_param': 'channel_id=' + str(post['channel_id'])})
channels = self._get_channels(**post)
if not channels:
channels = request.env['slide.channel'].search([])
values.update(self._prepare_user_values(channel=channels[0] if len(channels) == 1 else True, **post))
values.update(self._prepare_user_slides_profile(user))
return values
| 47.46556 | 57,196 |
292 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Germany - Repair',
'category': 'Accounting/Localizations',
'depends': [
'l10n_de',
'repair',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 22.461538 | 292 |
1,139 |
py
|
PYTHON
|
15.0
|
from odoo import models, fields, _
from odoo.tools import format_date
class RepairOrder(models.Model):
_inherit = 'repair.order'
l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data')
l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title')
def _compute_l10n_de_template_data(self):
for record in self:
record.l10n_de_template_data = data = []
if record.product_id:
data.append((_("Product to Repair"), record.product_id.name))
if record.lot_id:
data.append((_("Lot/Serial Number"), record.lot_id.name))
if record.guarantee_limit:
data.append((_("Warranty"), format_date(self.env, record.guarantee_limit)))
data.append((_("Printing Date"), format_date(self.env, fields.Date.today())))
def _compute_l10n_de_document_title(self):
for record in self:
if record.state == 'draft':
record.l10n_de_document_title = _("Repair Quotation")
else:
record.l10n_de_document_title = _("Repair Order")
| 42.185185 | 1,139 |
546 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Contacts',
'category': 'Sales/CRM',
'sequence': 150,
'summary': 'Centralize your address book',
'description': """
This module gives you a quick view of your contacts directory, accessible from your home page.
You can track your vendors, customers and other contacts.
""",
'depends': ['base', 'mail'],
'data': [
'views/contact_views.xml',
],
'application': True,
'license': 'LGPL-3',
}
| 27.3 | 546 |
682 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, modules
class Users(models.Model):
_name = 'res.users'
_inherit = ['res.users']
@api.model
def systray_get_activities(self):
""" Update the systray icon of res.partner activities to use the
contact application one instead of base icon. """
activities = super(Users, self).systray_get_activities()
for activity in activities:
if activity['model'] != 'res.partner':
continue
activity['icon'] = modules.module.get_module_icon('contacts')
return activities
| 34.1 | 682 |
1,166 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2011 CCI Connect asbl (http://www.cciconnect.be) All Rights Reserved.
# Philmer <[email protected]>
{
'name': 'Accounting Consistency Tests',
'version': '1.0',
'category': 'Accounting/Accounting',
'description': """
Asserts on accounting.
======================
With this module you can manually check consistencies and inconsistencies of accounting module from menu Reporting/Accounting/Accounting Tests.
You can write a query in order to create Consistency Test and you will get the result of the test
in PDF format which can be accessed by Menu Reporting -> Accounting Tests, then select the test
and print the report from Print button in header area.
""",
'depends': ['account'],
'data': [
'security/ir.model.access.csv',
'views/accounting_assert_test_views.xml',
'report/accounting_assert_test_reports.xml',
'data/accounting_assert_test_data.xml',
'report/report_account_test_templates.xml',
],
'installable': True,
'license': 'LGPL-3',
}
| 38.866667 | 1,166 |
789 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
CODE_EXEC_DEFAULT = '''\
res = []
cr.execute("select id, code from account_journal")
for record in cr.dictfetchall():
res.append(record['code'])
result = res
'''
class AccountingAssertTest(models.Model):
_name = "accounting.assert.test"
_description = 'Accounting Assert Test'
_order = "sequence"
name = fields.Char(string='Test Name', required=True, index=True, translate=True)
desc = fields.Text(string='Test Description', index=True, translate=True)
code_exec = fields.Text(string='Python code', required=True, default=CODE_EXEC_DEFAULT)
active = fields.Boolean(default=True)
sequence = fields.Integer(default=10)
| 32.875 | 789 |
2,831 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from odoo import api, models, _
from odoo.tools.safe_eval import safe_eval
#
# Use period and Journal for selection or resources
#
class ReportAssertAccount(models.AbstractModel):
_name = 'report.account_test.report_accounttest'
_description = 'Account Test Report'
@api.model
def execute_code(self, code_exec):
def reconciled_inv():
"""
returns the list of invoices that are set as reconciled = True
"""
return self.env['account.move'].search([('reconciled', '=', True)]).ids
def order_columns(item, cols=None):
"""
This function is used to display a dictionary as a string, with its columns in the order chosen.
:param item: dict
:param cols: list of field names
:returns: a list of tuples (fieldname: value) in a similar way that would dict.items() do except that the
returned values are following the order given by cols
:rtype: [(key, value)]
"""
if cols is None:
cols = list(item)
return [(col, item.get(col)) for col in cols if col in item]
localdict = {
'cr': self.env.cr,
'uid': self.env.uid,
'reconciled_inv': reconciled_inv, # specific function used in different tests
'result': None, # used to store the result of the test
'column_order': None, # used to choose the display order of columns (in case you are returning a list of dict)
'_': _,
}
safe_eval(code_exec, localdict, mode="exec", nocopy=True)
result = localdict['result']
column_order = localdict.get('column_order', None)
if not isinstance(result, (tuple, list, set)):
result = [result]
if not result:
result = [_('The test was passed successfully')]
else:
def _format(item):
if isinstance(item, dict):
return ', '.join(["%s: %s" % (tup[0], tup[1]) for tup in order_columns(item, column_order)])
else:
return item
result = [_format(rec) for rec in result]
return result
@api.model
def _get_report_values(self, docids, data=None):
report = self.env['ir.actions.report']._get_report_from_name('account_test.report_accounttest')
records = self.env['accounting.assert.test'].browse(self.ids)
return {
'doc_ids': self._ids,
'doc_model': report.model,
'docs': records,
'data': data,
'execute_code': self.execute_code,
'datetime': datetime
}
| 37.746667 | 2,831 |
724 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'KPI Digests',
'category': 'Marketing',
'description': """
Send KPI Digests periodically
=============================
""",
'version': '1.1',
'depends': [
'mail',
'portal',
'resource',
],
'data': [
'security/ir.model.access.csv',
'data/digest_data.xml',
'data/digest_tips_data.xml',
'data/ir_cron_data.xml',
'data/res_config_settings_data.xml',
'views/digest_views.xml',
'views/digest_templates.xml',
'views/res_config_settings_views.xml',
],
'installable': True,
'license': 'LGPL-3',
}
| 25.857143 | 724 |
10,818 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import itertools
import random
from dateutil.relativedelta import relativedelta
from lxml import html
from werkzeug.urls import url_encode
from odoo import fields, SUPERUSER_ID
from odoo.addons.base.tests.common import HttpCaseWithUserDemo
from odoo.addons.mail.tests import common as mail_test
from odoo.tests import tagged
from odoo.tests.common import users
class TestDigest(mail_test.MailCommon):
@classmethod
def setUpClass(cls):
super(TestDigest, cls).setUpClass()
cls._activate_multi_company()
# clean messages
cls.env['mail.message'].search([
('subtype_id', '=', cls.env.ref('mail.mt_comment').id),
('message_type', 'in', ['comment', 'email']),
]).unlink()
cls._setup_messages()
# clean demo users so that we keep only the test users
cls.env['res.users'].search([('login', 'in', ['demo', 'portal'])]).action_archive()
# clean logs so that town down is activated
cls.env['res.users.log'].search([('create_uid', 'in', (cls.user_admin + cls.user_employee).ids)]).unlink()
cls.test_digest = cls.env['digest.digest'].create({
'kpi_mail_message_total': True,
'kpi_res_users_connected': True,
'name': "My Digest",
'periodicity': 'daily',
})
@classmethod
def _setup_messages(cls):
""" Remove all existing messages, then create a bunch of them on random
partners with the correct types in correct time-bucket:
- 3 in the previous 24h
- 5 more in the 6 days before that for a total of 8 in the previous week
- 7 more in the 20 days before *that* (because digest doc lies and is
based around weeks and months not days), for a total of 15 in the
previous month
"""
# regular employee can't necessarily access "private" addresses
partners = cls.env['res.partner'].search([('type', '!=', 'private')])
messages = cls.env['mail.message']
counter = itertools.count()
now = fields.Datetime.now()
for count, (low, high) in [(3, (0 * 24, 1 * 24)),
(5, (1 * 24, 7 * 24)),
(7, (7 * 24, 27 * 24)),
]:
for _ in range(count):
create_date = now - relativedelta(hours=random.randint(low + 1, high - 1))
messages += random.choice(partners).message_post(
author_id=cls.partner_admin.id,
body=f"Awesome Partner! ({next(counter)})",
email_from=cls.partner_admin.email_formatted,
message_type='comment',
subtype_xmlid='mail.mt_comment',
# adjust top and bottom by 1h to avoid overlapping with the
# range limit and dropping out of the digest's selection thing
create_date=create_date,
)
messages.flush()
@users('admin')
def test_digest_numbers(self):
digest = self.env['digest.digest'].browse(self.test_digest.ids)
digest._action_subscribe_users(self.user_employee)
# digest creates its mails in auto_delete mode so we need to capture
# the formatted body during the sending process
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(len(self._new_mails), 1, "A new mail.mail should have been created")
mail = self._new_mails[0]
# check mail.mail content
self.assertEqual(mail.author_id, self.partner_admin)
self.assertEqual(mail.email_from, self.company_admin.email_formatted)
self.assertEqual(mail.state, 'outgoing', 'Mail should use the queue')
kpi_message_values = html.fromstring(mail.body_html).xpath('//div[@data-field="kpi_mail_message_total"]//*[hasclass("kpi_value")]/text()')
self.assertEqual(
[t.strip() for t in kpi_message_values],
['3', '8', '15']
)
@users('admin')
def test_digest_subscribe(self):
digest_user = self.test_digest.with_user(self.user_employee)
self.assertFalse(digest_user.is_subscribed)
# subscribe a user so at least one mail gets sent
digest_user.action_subscribe()
self.assertTrue(
digest_user.is_subscribed,
"check the user was subscribed as action_subscribe will silently "
"ignore subs of non-employees"
)
@users('admin')
def test_digest_tone_down(self):
digest = self.env['digest.digest'].browse(self.test_digest.ids)
digest._action_subscribe_users(self.user_employee)
# initial data
self.assertEqual(digest.periodicity, 'daily')
# no logs for employee -> should tone down periodicity
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(digest.periodicity, 'weekly')
# no logs for employee -> should tone down periodicity
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(digest.periodicity, 'monthly')
# no logs for employee -> should tone down periodicity
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(digest.periodicity, 'quarterly')
@users('admin')
def test_digest_tip_description(self):
self.env["digest.tip"].create({
'name': "Test digest tips",
'tip_description': """
<t t-set="record_exists" t-value="True" />
<t t-if="record_exists">
<p class="rendered">Record exists.</p>
</t>
<t t-else="">
<p class="not-rendered">Record doesn't exist.</p>
</t>
""",
})
with self.mock_mail_gateway():
self.test_digest._action_send_to_user(self.user_employee)
self.assertEqual(len(self._new_mails), 1, "A new Email should have been created")
sent_mail_body = html.fromstring(self._new_mails.body_html)
values_to_check = [
sent_mail_body.xpath('//t[@t-set="record_exists"]'),
sent_mail_body.xpath('//p[@class="rendered"]/text()'),
sent_mail_body.xpath('//p[@class="not-rendered"]/text()')
]
self.assertEqual(
values_to_check,
[[], ['Record exists.'], []],
"Sent mail should contain properly rendered tip content"
)
@users('admin')
def test_digest_tone_down_wlogs(self):
digest = self.env['digest.digest'].browse(self.test_digest.ids)
digest._action_subscribe_users(self.user_employee)
# initial data
self.assertEqual(digest.periodicity, 'daily')
# logs for employee -> should not tone down
logs = self.env['res.users.log'].with_user(SUPERUSER_ID).create({'create_uid': self.user_employee.id})
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
logs.unlink()
logs = self.env['res.users.log'].with_user(SUPERUSER_ID).create({
'create_uid': self.user_employee.id,
'create_date': fields.Datetime.now() - relativedelta(days=20),
})
# logs for employee are more than 3 days old -> should tone down
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(digest.periodicity, 'weekly')
# logs for employee are more than 2 weeks old -> should tone down
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(digest.periodicity, 'monthly')
# logs for employee are less than 1 month old -> should not tone down
digest.flush()
with self.mock_mail_gateway():
digest.action_send()
self.assertEqual(digest.periodicity, 'monthly')
@tagged('-at_install', 'post_install')
class TestUnsubscribe(HttpCaseWithUserDemo):
def setUp(self):
super(TestUnsubscribe, self).setUp()
self.test_digest = self.env['digest.digest'].create({
'kpi_mail_message_total': True,
'kpi_res_users_connected': True,
'name': "My Digest",
'periodicity': 'daily',
'user_ids': self.user_demo.ids,
})
self.test_digest._action_subscribe_users(self.user_demo)
self.base_url = self.test_digest.get_base_url()
self.user_demo_unsubscribe_token = self.test_digest._get_unsubscribe_token(self.user_demo.id)
@users('demo')
def test_unsubscribe_classic(self):
self.assertIn(self.user_demo, self.test_digest.user_ids)
self.authenticate(self.env.user.login, self.env.user.login)
response = self._url_unsubscribe()
self.assertEqual(response.status_code, 200)
self.assertNotIn(self.user_demo, self.test_digest.user_ids)
@users('demo')
def test_unsubscribe_issues(self):
""" Test when not being member """
self.test_digest.write({'user_ids': [(3, self.user_demo.id)]})
self.assertNotIn(self.user_demo, self.test_digest.user_ids)
# unsubscribe
self.authenticate(self.env.user.login, self.env.user.login)
response = self._url_unsubscribe()
self.assertEqual(response.status_code, 200)
self.assertNotIn(self.user_demo, self.test_digest.user_ids)
def test_unsubscribe_token(self):
self.assertIn(self.user_demo, self.test_digest.user_ids)
self.authenticate(None, None)
response = self._url_unsubscribe(token=self.user_demo_unsubscribe_token, user_id=self.user_demo.id)
self.assertEqual(response.status_code, 200)
self.test_digest.invalidate_cache()
self.assertNotIn(self.user_demo, self.test_digest.user_ids)
def test_unsubscribe_public(self):
""" Check public users are redirected when trying to catch unsubscribe
route. """
self.authenticate(None, None)
response = self._url_unsubscribe()
self.assertEqual(response.status_code, 404)
def _url_unsubscribe(self, token=None, user_id=None):
url_params = {}
if token is not None:
url_params['token'] = token
if user_id is not None:
url_params['user_id'] = user_id
url = "%s/digest/%s/unsubscribe?%s" % (
self.base_url,
self.test_digest.id,
url_encode(url_params)
)
return self.url_open(url)
| 38.774194 | 10,818 |
17,909 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pytz
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from markupsafe import Markup
from odoo import api, fields, models, tools, _
from odoo.addons.base.models.ir_mail_server import MailDeliveryException
from odoo.exceptions import AccessError
from odoo.tools.float_utils import float_round
_logger = logging.getLogger(__name__)
class Digest(models.Model):
_name = 'digest.digest'
_description = 'Digest'
# Digest description
name = fields.Char(string='Name', required=True, translate=True)
user_ids = fields.Many2many('res.users', string='Recipients', domain="[('share', '=', False)]")
periodicity = fields.Selection([('daily', 'Daily'),
('weekly', 'Weekly'),
('monthly', 'Monthly'),
('quarterly', 'Quarterly')],
string='Periodicity', default='daily', required=True)
next_run_date = fields.Date(string='Next Send Date')
currency_id = fields.Many2one(related="company_id.currency_id", string='Currency', readonly=False)
company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company.id)
available_fields = fields.Char(compute='_compute_available_fields')
is_subscribed = fields.Boolean('Is user subscribed', compute='_compute_is_subscribed')
state = fields.Selection([('activated', 'Activated'), ('deactivated', 'Deactivated')], string='Status', readonly=True, default='activated')
# First base-related KPIs
kpi_res_users_connected = fields.Boolean('Connected Users')
kpi_res_users_connected_value = fields.Integer(compute='_compute_kpi_res_users_connected_value')
kpi_mail_message_total = fields.Boolean('Messages')
kpi_mail_message_total_value = fields.Integer(compute='_compute_kpi_mail_message_total_value')
@api.depends('user_ids')
def _compute_is_subscribed(self):
for digest in self:
digest.is_subscribed = self.env.user in digest.user_ids
def _compute_available_fields(self):
for digest in self:
kpis_values_fields = []
for field_name, field in digest._fields.items():
if field.type == 'boolean' and field_name.startswith(('kpi_', 'x_kpi_', 'x_studio_kpi_')) and digest[field_name]:
kpis_values_fields += [field_name + '_value']
digest.available_fields = ', '.join(kpis_values_fields)
def _get_kpi_compute_parameters(self):
return fields.Datetime.to_string(self._context.get('start_datetime')), fields.Datetime.to_string(self._context.get('end_datetime')), self.env.company
def _compute_kpi_res_users_connected_value(self):
for record in self:
start, end, company = record._get_kpi_compute_parameters()
user_connected = self.env['res.users'].search_count([('company_id', '=', company.id), ('login_date', '>=', start), ('login_date', '<', end)])
record.kpi_res_users_connected_value = user_connected
def _compute_kpi_mail_message_total_value(self):
discussion_subtype_id = self.env.ref('mail.mt_comment').id
for record in self:
start, end, company = record._get_kpi_compute_parameters()
total_messages = self.env['mail.message'].search_count([('create_date', '>=', start), ('create_date', '<', end), ('subtype_id', '=', discussion_subtype_id), ('message_type', 'in', ['comment', 'email'])])
record.kpi_mail_message_total_value = total_messages
@api.onchange('periodicity')
def _onchange_periodicity(self):
self.next_run_date = self._get_next_run_date()
@api.model_create_multi
def create(self, vals_list):
digests = super().create(vals_list)
for digest in digests:
if not digest.next_run_date:
digest.next_run_date = digest._get_next_run_date()
return digests
# ------------------------------------------------------------
# ACTIONS
# ------------------------------------------------------------
def action_subscribe(self):
if self.env.user.has_group('base.group_user') and self.env.user not in self.user_ids:
self._action_subscribe_users(self.env.user)
def _action_subscribe_users(self, users):
""" Private method to manage subscriptions. Done as sudo() to speedup
computation and avoid ACLs issues. """
self.sudo().user_ids |= users
def action_unsubcribe(self):
if self.env.user.has_group('base.group_user') and self.env.user in self.user_ids:
self._action_unsubscribe_users(self.env.user)
def _action_unsubscribe_users(self, users):
""" Private method to manage subscriptions. Done as sudo() to speedup
computation and avoid ACLs issues. """
self.sudo().user_ids -= users
def action_activate(self):
self.state = 'activated'
def action_deactivate(self):
self.state = 'deactivated'
def action_set_periodicity(self, periodicity):
self.periodicity = periodicity
def action_send(self):
to_slowdown = self._check_daily_logs()
for digest in self:
for user in digest.user_ids:
digest.with_context(
digest_slowdown=digest in to_slowdown,
lang=user.lang
)._action_send_to_user(user, tips_count=1)
if digest in to_slowdown:
digest.write({'periodicity': self._get_next_periodicity()[0]})
digest.next_run_date = digest._get_next_run_date()
def _action_send_to_user(self, user, tips_count=1, consum_tips=True):
rendered_body = self.env['mail.render.mixin'].with_context(preserve_comments=True)._render_template(
'digest.digest_mail_main',
'digest.digest',
self.ids,
engine='qweb_view',
add_context={
'title': self.name,
'top_button_label': _('Connect'),
'top_button_url': self.get_base_url(),
'company': user.company_id,
'user': user,
'unsubscribe_token': self._get_unsubscribe_token(user.id),
'tips_count': tips_count,
'formatted_date': datetime.today().strftime('%B %d, %Y'),
'display_mobile_banner': True,
'kpi_data': self._compute_kpis(user.company_id, user),
'tips': self._compute_tips(user.company_id, user, tips_count=tips_count, consumed=consum_tips),
'preferences': self._compute_preferences(user.company_id, user),
},
post_process=True
)[self.id]
full_mail = self.env['mail.render.mixin']._render_encapsulate(
'digest.digest_mail_layout',
rendered_body,
add_context={
'company': user.company_id,
'user': user,
},
)
# create a mail_mail based on values, without attachments
mail_values = {
'auto_delete': True,
'author_id': self.env.user.partner_id.id,
'email_from': (
self.company_id.partner_id.email_formatted
or self.env.user.email_formatted
or self.env.ref('base.user_root').email_formatted
),
'email_to': user.email_formatted,
'body_html': full_mail,
'state': 'outgoing',
'subject': '%s: %s' % (user.company_id.name, self.name),
}
self.env['mail.mail'].sudo().create(mail_values)
return True
@api.model
def _cron_send_digest_email(self):
digests = self.search([('next_run_date', '<=', fields.Date.today()), ('state', '=', 'activated')])
for digest in digests:
try:
digest.action_send()
except MailDeliveryException as e:
_logger.warning('MailDeliveryException while sending digest %d. Digest is now scheduled for next cron update.', digest.id)
def _get_unsubscribe_token(self, user_id):
"""Generate a secure hash for this digest and user. It allows to
unsubscribe from a digest while keeping some security in that process.
:param int user_id: ID of the user to unsubscribe
"""
return tools.hmac(self.env(su=True), 'digest-unsubscribe', (self.id, user_id))
# ------------------------------------------------------------
# KPIS
# ------------------------------------------------------------
def _compute_kpis(self, company, user):
""" Compute KPIs to display in the digest template. It is expected to be
a list of KPIs, each containing values for 3 columns display.
:return list: result [{
'kpi_name': 'kpi_mail_message',
'kpi_fullname': 'Messages', # translated
'kpi_action': 'crm.crm_lead_action_pipeline', # xml id of an action to execute
'kpi_col1': {
'value': '12.0',
'margin': 32.36,
'col_subtitle': 'Yesterday', # translated
},
'kpi_col2': { ... },
'kpi_col3': { ... },
}, { ... }] """
self.ensure_one()
digest_fields = self._get_kpi_fields()
invalid_fields = []
kpis = [
dict(kpi_name=field_name,
kpi_fullname=self.env['ir.model.fields']._get(self._name, field_name).field_description,
kpi_action=False,
kpi_col1=dict(),
kpi_col2=dict(),
kpi_col3=dict(),
)
for field_name in digest_fields
]
kpis_actions = self._compute_kpis_actions(company, user)
for col_index, (tf_name, tf) in enumerate(self._compute_timeframes(company)):
digest = self.with_context(start_datetime=tf[0][0], end_datetime=tf[0][1]).with_user(user).with_company(company)
previous_digest = self.with_context(start_datetime=tf[1][0], end_datetime=tf[1][1]).with_user(user).with_company(company)
for index, field_name in enumerate(digest_fields):
kpi_values = kpis[index]
kpi_values['kpi_action'] = kpis_actions.get(field_name)
try:
compute_value = digest[field_name + '_value']
# Context start and end date is different each time so invalidate to recompute.
digest.invalidate_cache([field_name + '_value'])
previous_value = previous_digest[field_name + '_value']
# Context start and end date is different each time so invalidate to recompute.
previous_digest.invalidate_cache([field_name + '_value'])
except AccessError: # no access rights -> just skip that digest details from that user's digest email
invalid_fields.append(field_name)
continue
margin = self._get_margin_value(compute_value, previous_value)
if self._fields['%s_value' % field_name].type == 'monetary':
converted_amount = tools.format_decimalized_amount(compute_value)
compute_value = self._format_currency_amount(converted_amount, company.currency_id)
kpi_values['kpi_col%s' % (col_index + 1)].update({
'value': compute_value,
'margin': margin,
'col_subtitle': tf_name,
})
# filter failed KPIs
return [kpi for kpi in kpis if kpi['kpi_name'] not in invalid_fields]
def _compute_tips(self, company, user, tips_count=1, consumed=True):
tips = self.env['digest.tip'].search([
('user_ids', '!=', user.id),
'|', ('group_id', 'in', user.groups_id.ids), ('group_id', '=', False)
], limit=tips_count)
tip_descriptions = [
tools.html_sanitize(self.env['mail.render.mixin'].sudo()._render_template(tip.tip_description, 'digest.tip', tip.ids, post_process=True, engine="qweb")[tip.id])
for tip in tips
]
if consumed:
tips.user_ids += user
return tip_descriptions
def _compute_kpis_actions(self, company, user):
""" Give an optional action to display in digest email linked to some KPIs.
:return dict: key: kpi name (field name), value: an action that will be
concatenated with /web#action={action}
"""
return {}
def _compute_preferences(self, company, user):
""" Give an optional text for preferences, like a shortcut for configuration.
:return string: html to put in template
"""
preferences = []
if self._context.get('digest_slowdown'):
_dummy, new_perioridicy_str = self._get_next_periodicity()
preferences.append(
_("We have noticed you did not connect these last few days. We have automatically switched your preference to %(new_perioridicy_str)s Digests.",
new_perioridicy_str=new_perioridicy_str)
)
elif self.periodicity == 'daily' and user.has_group('base.group_erp_manager'):
preferences.append(Markup('<p>%s<br /><a href="%s" target="_blank" style="color:#875A7B; font-weight: bold;">%s</a></p>') % (
_('Prefer a broader overview ?'),
f'/digest/{self.id:d}/set_periodicity?periodicity=weekly',
_('Switch to weekly Digests')
))
if user.has_group('base.group_erp_manager'):
preferences.append(Markup('<p>%s<br /><a href="%s" target="_blank" style="color:#875A7B; font-weight: bold;">%s</a></p>') % (
_('Want to customize this email?'),
f'/web#view_type=form&model={self._name}&id={self.id:d}',
_('Choose the metrics you care about')
))
return preferences
def _get_next_run_date(self):
self.ensure_one()
if self.periodicity == 'daily':
delta = relativedelta(days=1)
if self.periodicity == 'weekly':
delta = relativedelta(weeks=1)
elif self.periodicity == 'monthly':
delta = relativedelta(months=1)
elif self.periodicity == 'quarterly':
delta = relativedelta(months=3)
return date.today() + delta
def _compute_timeframes(self, company):
start_datetime = datetime.utcnow()
tz_name = company.resource_calendar_id.tz
if tz_name:
start_datetime = pytz.timezone(tz_name).localize(start_datetime)
return [
(_('Last 24 hours'), (
(start_datetime + relativedelta(days=-1), start_datetime),
(start_datetime + relativedelta(days=-2), start_datetime + relativedelta(days=-1)))
), (_('Last 7 Days'), (
(start_datetime + relativedelta(weeks=-1), start_datetime),
(start_datetime + relativedelta(weeks=-2), start_datetime + relativedelta(weeks=-1)))
), (_('Last 30 Days'), (
(start_datetime + relativedelta(months=-1), start_datetime),
(start_datetime + relativedelta(months=-2), start_datetime + relativedelta(months=-1)))
)
]
# ------------------------------------------------------------
# FORMATTING / TOOLS
# ------------------------------------------------------------
def _get_kpi_fields(self):
return [field_name for field_name, field in self._fields.items()
if field.type == 'boolean' and field_name.startswith(('kpi_', 'x_kpi_', 'x_studio_kpi_')) and self[field_name]
]
def _get_margin_value(self, value, previous_value=0.0):
margin = 0.0
if (value != previous_value) and (value != 0.0 and previous_value != 0.0):
margin = float_round((float(value-previous_value) / previous_value or 1) * 100, precision_digits=2)
return margin
def _check_daily_logs(self):
""" Badly named method that checks user logs and slowdown the sending
of digest emails based on recipients being away. """
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
to_slowdown = self.env['digest.digest']
for digest in self:
if digest.periodicity == 'daily': # 3 days ago
limit_dt = today - relativedelta(days=3)
elif digest.periodicity == 'weekly': # 2 weeks ago
limit_dt = today - relativedelta(days=14)
elif digest.periodicity == 'monthly': # 1 month ago
limit_dt = today - relativedelta(months=1)
elif digest.periodicity == 'quarterly': # 3 month ago
limit_dt = today - relativedelta(months=3)
users_logs = self.env['res.users.log'].sudo().search_count([
('create_uid', 'in', digest.user_ids.ids),
('create_date', '>=', limit_dt)
])
if not users_logs:
to_slowdown += digest
return to_slowdown
def _get_next_periodicity(self):
if self.periodicity == 'weekly':
return 'monthly', _('monthly')
if self.periodicity == 'monthly':
return 'quarterly', _('quarterly')
return 'weekly', _('weekly')
def _format_currency_amount(self, amount, currency_id):
pre = currency_id.position == 'before'
symbol = u'{symbol}'.format(symbol=currency_id.symbol or '')
return u'{pre}{0}{post}'.format(amount, pre=symbol if pre else '', post=symbol if not pre else '')
| 47.128947 | 17,909 |
847 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.tools.translate import html_translate
class DigestTip(models.Model):
_name = 'digest.tip'
_description = 'Digest Tips'
_order = 'sequence'
sequence = fields.Integer(
'Sequence', default=1,
help='Used to display digest tip in email template base on order')
name = fields.Char('Name', translate=True)
user_ids = fields.Many2many(
'res.users', string='Recipients',
help='Users having already received this tip')
tip_description = fields.Html('Tip description', translate=html_translate, sanitize=False)
group_id = fields.Many2one(
'res.groups', string='Authorized Group',
default=lambda self: self.env.ref('base.group_user'))
| 38.5 | 847 |
858 |
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 ResUsers(models.Model):
_inherit = "res.users"
@api.model_create_multi
def create(self, vals_list):
""" Automatically subscribe employee users to default digest if activated """
users = super(ResUsers, self).create(vals_list)
default_digest_emails = self.env['ir.config_parameter'].sudo().get_param('digest.default_digest_emails')
default_digest_id = self.env['ir.config_parameter'].sudo().get_param('digest.default_digest_id')
if default_digest_emails and default_digest_id:
digest = self.env['digest.digest'].sudo().browse(int(default_digest_id)).exists()
digest.user_ids |= users.filtered_domain([('share', '=', False)])
return users
| 47.666667 | 858 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.