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
|
|---|---|---|---|---|---|---|
911
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'
def retrieve_attachment(self, record):
# Override this method in order to force to re-render the pdf in case of
# using snailmail
if self.env.context.get('snailmail_layout'):
return False
return super(IrActionsReport, self).retrieve_attachment(record)
@api.model
def get_paperformat(self):
# force the right format (euro/A4) when sending letters, only if we are not using the l10n_DE layout
res = super(IrActionsReport, self).get_paperformat()
if self.env.context.get('snailmail_layout') and res != self.env.ref('l10n_de.paperformat_euro_din', False):
paperformat_id = self.env.ref('base.paperformat_euro')
return paperformat_id
else:
return res
| 37.958333
| 911
|
782
|
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 Contact(models.AbstractModel):
_inherit = 'ir.qweb.field.contact'
@api.model
def value_to_html(self, value, options):
if self.env.context.get('snailmail_layout'):
value = value.with_context(snailmail_layout=self.env.context['snailmail_layout'])
return super(Contact, self).value_to_html(value, options)
@api.model
def record_to_html(self, record, field_name, options):
if self.env.context.get('snailmail_layout'):
record = record.with_context(snailmail_layout=self.env.context['snailmail_layout'])
return super(Contact, self).record_to_html(record, field_name, options)
| 41.157895
| 782
|
412
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Company(models.Model):
_inherit = "res.company"
snailmail_color = fields.Boolean(string='Color', default=True)
snailmail_cover = fields.Boolean(string='Add a Cover Page', default=False)
snailmail_duplex = fields.Boolean(string='Both sides', default=False)
| 37.454545
| 412
|
579
|
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'
snailmail_color = fields.Boolean(string='Print In Color', related='company_id.snailmail_color', readonly=False)
snailmail_cover = fields.Boolean(string='Add a Cover Page', related='company_id.snailmail_cover', readonly=False)
snailmail_duplex = fields.Boolean(string='Print Both sides', related='company_id.snailmail_duplex', readonly=False)
| 48.25
| 579
|
22,328
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
import base64
import io
from PyPDF2 import PdfFileReader, PdfFileMerger, PdfFileWriter
from reportlab.platypus import Frame, Paragraph, KeepInFrame
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen.canvas import Canvas
from odoo import fields, models, api, _
from odoo.addons.iap.tools import iap_tools
from odoo.exceptions import AccessError, UserError
from odoo.tools.safe_eval import safe_eval
DEFAULT_ENDPOINT = 'https://iap-snailmail.odoo.com'
PRINT_ENDPOINT = '/iap/snailmail/1/print'
DEFAULT_TIMEOUT = 30
ERROR_CODES = [
'MISSING_REQUIRED_FIELDS',
'CREDIT_ERROR',
'TRIAL_ERROR',
'NO_PRICE_AVAILABLE',
'FORMAT_ERROR',
'UNKNOWN_ERROR',
]
class SnailmailLetter(models.Model):
_name = 'snailmail.letter'
_description = 'Snailmail Letter'
user_id = fields.Many2one('res.users', 'Sent by')
model = fields.Char('Model', required=True)
res_id = fields.Integer('Document ID', required=True)
partner_id = fields.Many2one('res.partner', string='Recipient', required=True)
company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True,
default=lambda self: self.env.company.id)
report_template = fields.Many2one('ir.actions.report', 'Optional report to print and attach')
attachment_id = fields.Many2one('ir.attachment', string='Attachment', ondelete='cascade')
attachment_datas = fields.Binary('Document', related='attachment_id.datas')
attachment_fname = fields.Char('Attachment Filename', related='attachment_id.name')
color = fields.Boolean(string='Color', default=lambda self: self.env.company.snailmail_color)
cover = fields.Boolean(string='Cover Page', default=lambda self: self.env.company.snailmail_cover)
duplex = fields.Boolean(string='Both side', default=lambda self: self.env.company.snailmail_duplex)
state = fields.Selection([
('pending', 'In Queue'),
('sent', 'Sent'),
('error', 'Error'),
('canceled', 'Canceled')
], 'Status', readonly=True, copy=False, default='pending', required=True,
help="When a letter is created, the status is 'Pending'.\n"
"If the letter is correctly sent, the status goes in 'Sent',\n"
"If not, it will got in state 'Error' and the error message will be displayed in the field 'Error Message'.")
error_code = fields.Selection([(err_code, err_code) for err_code in ERROR_CODES], string="Error")
info_msg = fields.Char('Information')
display_name = fields.Char('Display Name', compute="_compute_display_name")
reference = fields.Char(string='Related Record', compute='_compute_reference', readonly=True, store=False)
message_id = fields.Many2one('mail.message', string="Snailmail Status Message")
notification_ids = fields.One2many('mail.notification', 'letter_id', "Notifications")
street = fields.Char('Street')
street2 = fields.Char('Street2')
zip = fields.Char('Zip')
city = fields.Char('City')
state_id = fields.Many2one("res.country.state", string='State')
country_id = fields.Many2one('res.country', string='Country')
@api.depends('reference', 'partner_id')
def _compute_display_name(self):
for letter in self:
if letter.attachment_id:
letter.display_name = "%s - %s" % (letter.attachment_id.name, letter.partner_id.name)
else:
letter.display_name = letter.partner_id.name
@api.depends('model', 'res_id')
def _compute_reference(self):
for res in self:
res.reference = "%s,%s" % (res.model, res.res_id)
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
msg_id = self.env[vals['model']].browse(vals['res_id']).message_post(
body=_("Letter sent by post with Snailmail"),
message_type='snailmail',
)
partner_id = self.env['res.partner'].browse(vals['partner_id'])
vals.update({
'message_id': msg_id.id,
'street': partner_id.street,
'street2': partner_id.street2,
'zip': partner_id.zip,
'city': partner_id.city,
'state_id': partner_id.state_id.id,
'country_id': partner_id.country_id.id,
})
letters = super().create(vals_list)
notification_vals = []
for letter in letters:
notification_vals.append({
'mail_message_id': letter.message_id.id,
'res_partner_id': letter.partner_id.id,
'notification_type': 'snail',
'letter_id': letter.id,
'is_read': True, # discard Inbox notification
'notification_status': 'ready',
})
self.env['mail.notification'].sudo().create(notification_vals)
letters.attachment_id.check('read')
return letters
def write(self, vals):
res = super().write(vals)
if 'attachment_id' in vals:
self.attachment_id.check('read')
return res
def _fetch_attachment(self):
"""
This method will check if we have any existent attachement matching the model
and res_ids and create them if not found.
"""
self.ensure_one()
obj = self.env[self.model].browse(self.res_id)
if not self.attachment_id:
report = self.report_template
if not report:
report_name = self.env.context.get('report_name')
report = self.env['ir.actions.report']._get_report_from_name(report_name)
if not report:
return False
else:
self.write({'report_template': report.id})
# report = self.env.ref('account.account_invoices')
if report.print_report_name:
report_name = safe_eval(report.print_report_name, {'object': obj})
elif report.attachment:
report_name = safe_eval(report.attachment, {'object': obj})
else:
report_name = 'Document'
filename = "%s.%s" % (report_name, "pdf")
paperformat = report.get_paperformat()
if (paperformat.format == 'custom' and paperformat.page_width != 210 and paperformat.page_height != 297) or paperformat.format != 'A4':
raise UserError(_("Please use an A4 Paper format."))
pdf_bin, unused_filetype = report.with_context(snailmail_layout=not self.cover, lang='en_US')._render_qweb_pdf(self.res_id)
pdf_bin = self._overwrite_margins(pdf_bin)
if self.cover:
pdf_bin = self._append_cover_page(pdf_bin)
attachment = self.env['ir.attachment'].create({
'name': filename,
'datas': base64.b64encode(pdf_bin),
'res_model': 'snailmail.letter',
'res_id': self.id,
'type': 'binary', # override default_type from context, possibly meant for another model!
})
self.write({'attachment_id': attachment.id})
return self.attachment_id
def _count_pages_pdf(self, bin_pdf):
""" Count the number of pages of the given pdf file.
:param bin_pdf : binary content of the pdf file
"""
pages = 0
for match in re.compile(b"/Count\s+(\d+)").finditer(bin_pdf):
pages = int(match.group(1))
return pages
def _snailmail_create(self, route):
"""
Create a dictionnary object to send to snailmail server.
:return: Dict in the form:
{
account_token: string, //IAP Account token of the user
documents: [{
pages: int,
pdf_bin: pdf file
res_id: int (client-side res_id),
res_model: char (client-side res_model),
address: {
name: char,
street: char,
street2: char (OPTIONAL),
zip: int,
city: char,
state: char (state code (OPTIONAL)),
country_code: char (country code)
}
return_address: {
name: char,
street: char,
street2: char (OPTIONAL),
zip: int,
city: char,at
state: char (state code (OPTIONAL)),
country_code: char (country code)
}
}],
options: {
color: boolean (true if color, false if black-white),
duplex: boolean (true if duplex, false otherwise),
currency_name: char
}
}
"""
account_token = self.env['iap.account'].get('snailmail').account_token
dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
documents = []
batch = len(self) > 1
for letter in self:
recipient_name = letter.partner_id.name or letter.partner_id.parent_id and letter.partner_id.parent_id.name
if not recipient_name:
letter.write({
'info_msg': _('Invalid recipient name.'),
'state': 'error',
'error_code': 'MISSING_REQUIRED_FIELDS'
})
continue
document = {
# generic informations to send
'letter_id': letter.id,
'res_model': letter.model,
'res_id': letter.res_id,
'contact_address': letter.partner_id.with_context(snailmail_layout=True, show_address=True).name_get()[0][1],
'address': {
'name': recipient_name,
'street': letter.partner_id.street,
'street2': letter.partner_id.street2,
'zip': letter.partner_id.zip,
'state': letter.partner_id.state_id.code if letter.partner_id.state_id else False,
'city': letter.partner_id.city,
'country_code': letter.partner_id.country_id.code
},
'return_address': {
'name': letter.company_id.partner_id.name,
'street': letter.company_id.partner_id.street,
'street2': letter.company_id.partner_id.street2,
'zip': letter.company_id.partner_id.zip,
'state': letter.company_id.partner_id.state_id.code if letter.company_id.partner_id.state_id else False,
'city': letter.company_id.partner_id.city,
'country_code': letter.company_id.partner_id.country_id.code,
}
}
# Specific to each case:
# If we are estimating the price: 1 object = 1 page
# If we are printing -> attach the pdf
if route == 'estimate':
document.update(pages=1)
else:
# adding the web logo from the company for future possible customization
document.update({
'company_logo': letter.company_id.logo_web and letter.company_id.logo_web.decode('utf-8') or False,
})
attachment = letter._fetch_attachment()
if attachment:
document.update({
'pdf_bin': route == 'print' and attachment.datas.decode('utf-8'),
'pages': route == 'estimate' and self._count_pages_pdf(base64.b64decode(attachment.datas)),
})
else:
letter.write({
'info_msg': 'The attachment could not be generated.',
'state': 'error',
'error_code': 'UNKNOWN_ERROR'
})
continue
if letter.company_id.external_report_layout_id == self.env.ref('l10n_de.external_layout_din5008', False):
document.update({
'rightaddress': 0,
})
documents.append(document)
return {
'account_token': account_token,
'dbuuid': dbuuid,
'documents': documents,
'options': {
'color': self and self[0].color,
'cover': self and self[0].cover,
'duplex': self and self[0].duplex,
'currency_name': 'EUR',
},
# this will not raise the InsufficientCreditError which is the behaviour we want for now
'batch': True,
}
def _get_error_message(self, error):
if error == 'CREDIT_ERROR':
link = self.env['iap.account'].get_credits_url(service_name='snailmail')
return _('You don\'t have enough credits to perform this operation.<br>Please go to your <a href=%s target="new">iap account</a>.', link)
if error == 'TRIAL_ERROR':
link = self.env['iap.account'].get_credits_url(service_name='snailmail', trial=True)
return _('You don\'t have an IAP account registered for this service.<br>Please go to <a href=%s target="new">iap.odoo.com</a> to claim your free credits.', link)
if error == 'NO_PRICE_AVAILABLE':
return _('The country of the partner is not covered by Snailmail.')
if error == 'MISSING_REQUIRED_FIELDS':
return _('One or more required fields are empty.')
if error == 'FORMAT_ERROR':
return _('The attachment of the letter could not be sent. Please check its content and contact the support if the problem persists.')
else:
return _('An unknown error happened. Please contact the support.')
return error
def _get_failure_type(self, error):
if error == 'CREDIT_ERROR':
return 'sn_credit'
if error == 'TRIAL_ERROR':
return 'sn_trial'
if error == 'NO_PRICE_AVAILABLE':
return 'sn_price'
if error == 'MISSING_REQUIRED_FIELDS':
return 'sn_fields'
if error == 'FORMAT_ERROR':
return 'sn_format'
else:
return 'sn_error'
def _snailmail_print(self, immediate=True):
valid_address_letters = self.filtered(lambda l: l._is_valid_address(l))
invalid_address_letters = self - valid_address_letters
invalid_address_letters._snailmail_print_invalid_address()
if valid_address_letters and immediate:
for letter in valid_address_letters:
letter._snailmail_print_valid_address()
self.env.cr.commit()
def _snailmail_print_invalid_address(self):
error = 'MISSING_REQUIRED_FIELDS'
error_message = _("The address of the recipient is not complete")
self.write({
'state': 'error',
'error_code': error,
'info_msg': error_message,
})
self.notification_ids.sudo().write({
'notification_status': 'exception',
'failure_type': self._get_failure_type(error),
'failure_reason': error_message,
})
self.message_id._notify_message_notification_update()
def _snailmail_print_valid_address(self):
"""
get response
{
'request_code': RESPONSE_OK, # because we receive 200 if good or fail
'total_cost': total_cost,
'credit_error': credit_error,
'request': {
'documents': documents,
'options': options
}
}
}
"""
endpoint = self.env['ir.config_parameter'].sudo().get_param('snailmail.endpoint', DEFAULT_ENDPOINT)
timeout = int(self.env['ir.config_parameter'].sudo().get_param('snailmail.timeout', DEFAULT_TIMEOUT))
params = self._snailmail_create('print')
try:
response = iap_tools.iap_jsonrpc(endpoint + PRINT_ENDPOINT, params=params, timeout=timeout)
except AccessError as ae:
for doc in params['documents']:
letter = self.browse(doc['letter_id'])
letter.state = 'error'
letter.error_code = 'UNKNOWN_ERROR'
raise ae
for doc in response['request']['documents']:
if doc.get('sent') and response['request_code'] == 200:
note = _('The document was correctly sent by post.<br>The tracking id is %s', doc['send_id'])
letter_data = {'info_msg': note, 'state': 'sent', 'error_code': False}
notification_data = {
'notification_status': 'sent',
'failure_type': False,
'failure_reason': False,
}
else:
error = doc['error'] if response['request_code'] == 200 else response['reason']
note = _('An error occurred when sending the document by post.<br>Error: %s', self._get_error_message(error))
letter_data = {
'info_msg': note,
'state': 'error',
'error_code': error if error in ERROR_CODES else 'UNKNOWN_ERROR'
}
notification_data = {
'notification_status': 'exception',
'failure_type': self._get_failure_type(error),
'failure_reason': note,
}
letter = self.browse(doc['letter_id'])
letter.write(letter_data)
letter.notification_ids.sudo().write(notification_data)
self.message_id._notify_message_notification_update()
def snailmail_print(self):
self.write({'state': 'pending'})
self.notification_ids.sudo().write({
'notification_status': 'ready',
'failure_type': False,
'failure_reason': False,
})
self.message_id._notify_message_notification_update()
if len(self) == 1:
self._snailmail_print()
def cancel(self):
self.write({'state': 'canceled', 'error_code': False})
self.notification_ids.sudo().write({
'notification_status': 'canceled',
})
self.message_id._notify_message_notification_update()
@api.model
def _snailmail_cron(self, autocommit=True):
letters_send = self.search([
'|',
('state', '=', 'pending'),
'&',
('state', '=', 'error'),
('error_code', 'in', ['TRIAL_ERROR', 'CREDIT_ERROR', 'MISSING_REQUIRED_FIELDS'])
])
for letter in letters_send:
letter._snailmail_print()
if letter.error_code == 'CREDIT_ERROR':
break # avoid spam
# Commit after every letter sent to avoid to send it again in case of a rollback
if autocommit:
self.env.cr.commit()
@api.model
def _is_valid_address(self, record):
record.ensure_one()
required_keys = ['street', 'city', 'zip', 'country_id']
return all(record[key] for key in required_keys)
def _append_cover_page(self, invoice_bin: bytes):
address_split = self.partner_id.with_context(show_address=True, lang='en_US')._get_name().split('\n')
address_split[0] = self.partner_id.name or self.partner_id.parent_id and self.partner_id.parent_id.name or address_split[0]
address = '<br/>'.join(address_split)
address_x = 118 * mm
address_y = 60 * mm
frame_width = 85.5 * mm
frame_height = 25.5 * mm
cover_buf = io.BytesIO()
canvas = Canvas(cover_buf, pagesize=A4)
styles = getSampleStyleSheet()
frame = Frame(address_x, A4[1] - address_y - frame_height, frame_width, frame_height)
story = [Paragraph(address, styles['Normal'])]
address_inframe = KeepInFrame(0, 0, story)
frame.addFromList([address_inframe], canvas)
canvas.save()
cover_buf.seek(0)
invoice = PdfFileReader(io.BytesIO(invoice_bin))
cover_bin = io.BytesIO(cover_buf.getvalue())
cover_file = PdfFileReader(cover_bin)
merger = PdfFileMerger()
merger.append(cover_file, import_bookmarks=False)
merger.append(invoice, import_bookmarks=False)
out_buff = io.BytesIO()
merger.write(out_buff)
return out_buff.getvalue()
def _overwrite_margins(self, invoice_bin: bytes):
"""
Fill the margins with white for validation purposes.
"""
pdf_buf = io.BytesIO()
canvas = Canvas(pdf_buf, pagesize=A4)
canvas.setFillColorRGB(255, 255, 255)
page_width = A4[0]
page_height = A4[1]
# Horizontal Margin
hmargin_width = page_width
hmargin_height = 5 * mm
# Vertical Margin
vmargin_width = 5 * mm
vmargin_height = page_height
# Bottom left square
sq_width = 15 * mm
# Draw the horizontal margins
canvas.rect(0, 0, hmargin_width, hmargin_height, stroke=0, fill=1)
canvas.rect(0, page_height, hmargin_width, -hmargin_height, stroke=0, fill=1)
# Draw the vertical margins
canvas.rect(0, 0, vmargin_width, vmargin_height, stroke=0, fill=1)
canvas.rect(page_width, 0, -vmargin_width, vmargin_height, stroke=0, fill=1)
# Draw the bottom left white square
canvas.rect(0, 0, sq_width, sq_width, stroke=0, fill=1)
canvas.save()
pdf_buf.seek(0)
new_pdf = PdfFileReader(pdf_buf)
curr_pdf = PdfFileReader(io.BytesIO(invoice_bin))
out = PdfFileWriter()
for page in curr_pdf.pages:
page.mergePage(new_pdf.getPage(0))
out.addPage(page)
out_stream = io.BytesIO()
out.write(out_stream)
out_bin = out_stream.getvalue()
out_stream.close()
return out_bin
| 42.287879
| 22,328
|
1,313
|
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class Message(models.Model):
_inherit = 'mail.message'
snailmail_error = fields.Boolean("Snailmail message in error", compute="_compute_snailmail_error", search="_search_snailmail_error")
letter_ids = fields.One2many(comodel_name='snailmail.letter', inverse_name='message_id')
message_type = fields.Selection(selection_add=[
('snailmail', 'Snailmail')
], ondelete={'snailmail': lambda recs: recs.write({'message_type': 'email'})})
@api.depends('letter_ids', 'letter_ids.state')
def _compute_snailmail_error(self):
for message in self:
if message.message_type == 'snailmail' and message.letter_ids:
message.snailmail_error = message.letter_ids[0].state == 'error'
else:
message.snailmail_error = False
def _search_snailmail_error(self, operator, operand):
if operator == '=' and operand:
return ['&', ('letter_ids.state', '=', 'error'), ('letter_ids.user_id', '=', self.env.user.id)]
return ['!', '&', ('letter_ids.state', '=', 'error'), ('letter_ids.user_id', '=', self.env.user.id)]
def cancel_letter(self):
self.mapped('letter_ids').cancel()
def send_letter(self):
self.mapped('letter_ids')._snailmail_print()
| 42.354839
| 1,313
|
1,756
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
from odoo.addons.snailmail.country_utils import SNAILMAIL_COUNTRIES
class ResPartner(models.Model):
_inherit = "res.partner"
def write(self, vals):
letter_address_vals = {}
address_fields = ['street', 'street2', 'city', 'zip', 'state_id', 'country_id']
for field in address_fields:
if field in vals:
letter_address_vals[field] = vals[field]
if letter_address_vals:
letters = self.env['snailmail.letter'].search([
('state', 'not in', ['sent', 'canceled']),
('partner_id', 'in', self.ids),
])
letters.write(letter_address_vals)
return super(ResPartner, self).write(vals)
def _get_country_name(self):
# when sending a letter, thus rendering the report with the snailmail_layout,
# we need to override the country name to its english version following the
# dictionary imported in country_utils.py
country_code = self.country_id.code
if self.env.context.get('snailmail_layout') and country_code in SNAILMAIL_COUNTRIES:
return SNAILMAIL_COUNTRIES.get(country_code)
return super(ResPartner, self)._get_country_name()
@api.model
def _get_address_format(self):
# When sending a letter, the fields 'street' and 'street2' should be on a single line to fit in the address area
if self.env.context.get('snailmail_layout') and self.street2:
return "%(street)s, %(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
return super(ResPartner, self)._get_address_format()
| 39.909091
| 1,756
|
617
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Gift Card for sales module",
'summary': "Use gift card in your sales orders",
'description': """Integrate gift card mechanism in sales orders.""",
'category': 'Sales/Sales',
'version': '1.0',
'depends': ['gift_card', 'sale'],
'auto_install': True,
'data': [
'data/gift_card_data.xml',
'data/mail_template_data.xml',
'views/sale_order_view.xml',
'views/templates.xml',
'security/ir.model.access.csv',
],
'license': 'LGPL-3',
}
| 30.85
| 617
|
2,197
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo.addons.sale_gift_card.tests.common import TestSaleGiftCardCommon
from odoo.exceptions import UserError
from odoo.tests.common import tagged
@tagged('-at_install', 'post_install')
class TestPayWithGiftCard(TestSaleGiftCardCommon):
def test_paying_with_single_gift_card(self):
gift_card = self.env['gift.card'].create({
'initial_amount': 100,
})
order = self.empty_order
order.write({'order_line': [
Command.create({
'product_id': self.product_A.id,
'name': 'Ordinary Product A',
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
]})
before_gift_card_payment = order.amount_total
self.assertNotEqual(before_gift_card_payment, 0)
order._pay_with_gift_card(gift_card)
order.action_confirm()
self.assertEqual(before_gift_card_payment - order.amount_total, gift_card.initial_amount - gift_card.balance)
def test_paying_with_multiple_gift_card(self):
gift_card_1 = self.env['gift.card'].create({
'initial_amount': 100,
})
gift_card_2 = self.env['gift.card'].create({
'initial_amount': 100,
})
order = self.empty_order
order.write({'order_line': [
Command.create({
'product_id': self.product_A.id,
'name': 'Ordinary Product A',
'product_uom': self.uom_unit.id,
'product_uom_qty': 20.0,
})
]})
before_gift_card_payment = order.amount_total
order._pay_with_gift_card(gift_card_1)
order._pay_with_gift_card(gift_card_2)
self.assertEqual(order.amount_total, before_gift_card_payment - 200)
def test_unlink_gift_card_product(self):
with self.assertRaises(UserError):
# try to delete several product including pay_with_gift_card_product
self.env['product.template'].search([('purchase_ok', '=', False), ('sale_ok', '=', False)]).unlink()
| 39.945455
| 2,197
|
1,653
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale.tests.test_sale_product_attribute_value_config import TestSaleProductAttributeValueCommon
class TestSaleGiftCardCommon(TestSaleProductAttributeValueCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
# set currency to not rely on demo data and avoid possible race condition
cls.currency_ratio = 1.0
pricelist = cls.env.ref("product.list0")
pricelist.currency_id = cls._setup_currency(cls.currency_ratio)
# create partner for sale order.
cls.fatima = cls.env['res.partner'].create({
'name': 'Fatima Kalai',
'email': 'fatima.kalai@example.com',
})
cls.empty_order = cls.env['sale.order'].create({
'partner_id': cls.fatima.id
})
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
# Taxes
cls.tax_15pc_excl = cls.env['account.tax'].create({
'name': "Tax 15%",
'amount_type': 'percent',
'amount': 15,
'type_tax_use': 'sale',
})
#products
cls.product_A = cls.env['product.product'].create({
'name': 'Product A',
'list_price': 100,
'sale_ok': True,
'taxes_id': [(6, 0, [cls.tax_15pc_excl.id])],
})
cls.product_gift_card = cls.env['product.product'].create({
'name': 'Gift Card 50',
'detailed_type': 'gift',
'list_price': 50,
'sale_ok': True,
'taxes_id': False,
})
| 31.788462
| 1,653
|
2,455
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo.addons.sale_gift_card.tests.common import TestSaleGiftCardCommon
from odoo.tests.common import tagged
@tagged('-at_install', 'post_install')
class TestBuyGiftCard(TestSaleGiftCardCommon):
def test_buying_simple_gift_card(self):
order = self.empty_order
order.write({'order_line': [
(0, False, {
'product_id': self.product_A.id,
'name': 'Ordinary Product A',
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
}),
(0, False, {
'product_id': self.product_gift_card.id,
'name': 'Gift Card Product',
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
]})
self.assertEqual(len(order.order_line.ids), 2)
self.assertEqual(order.gift_card_count, 0)
self.assertEqual(len(order.order_line.mapped('generated_gift_card_ids')), 0)
order.action_confirm()
# After Confirmation
self.assertEqual(order.gift_card_count, 1)
self.assertEqual(len(order.order_line.mapped('generated_gift_card_ids')), 1)
def test_buying_multiple_gift_card(self):
order = self.empty_order
order.write({'order_line': [
Command.create({
'product_id': self.product_A.id,
'name': 'Ordinary Product A',
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
}),
Command.create({
'product_id': self.product_gift_card.id,
'name': 'Gift Card Product',
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
}),
Command.create({
'product_id': self.product_gift_card.id,
'name': 'Gift Card Product',
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
]})
self.assertEqual(order.gift_card_count, 0)
self.assertEqual(len(order.order_line.mapped('generated_gift_card_ids')), 0)
order.action_confirm()
# After Confirmation
self.assertEqual(order.gift_card_count, 2)
self.assertEqual(len(order.order_line.mapped('generated_gift_card_ids')), 2)
| 39.596774
| 2,455
|
4,950
|
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 SaleOrder(models.Model):
_inherit = "sale.order"
gift_card_count = fields.Integer(compute="_compute_gift_card_count")
@api.depends("order_line.generated_gift_card_ids")
def _compute_gift_card_count(self):
for record in self:
record.gift_card_count = len(record.order_line.mapped("generated_gift_card_ids"))
@api.constrains('state')
def _constrains_state(self):
# release gift card amount when order state become canceled
for record in self.filtered(lambda so: so.state == 'cancel'):
record.order_line.filtered(lambda ol: ol.gift_card_id).unlink()
# create and send gift card when order become confirmed
for record in self.filtered(lambda so: so.state == 'sale'):
for gift_card_order_line in record.order_line.filtered(lambda ol: ol.product_id.detailed_type == 'gift'):
gift_card_order_line._create_gift_cards()
record.sudo()._send_gift_card_mail()
def _pay_with_gift_card(self, gift_card):
error = False
if not gift_card.can_be_used():
error = _('Invalid or Expired Gift Card.')
elif gift_card in self.order_line.mapped("gift_card_id"):
error = _('Gift Card already used.')
elif gift_card.partner_id and gift_card.partner_id != self.env.user.partner_id:
error = _('Gift Card are restricted for another user.')
amount = min(self.amount_total, gift_card.balance_converted(self.currency_id))
if not error and amount > 0:
pay_gift_card_id = self.env.ref('gift_card.pay_with_gift_card_product')
gift_card.redeem_line_ids.filtered(lambda redeem: redeem.state != "sale").unlink()
self.env["sale.order.line"].create({
'product_id': pay_gift_card_id.id,
'price_unit': - amount,
'product_uom_qty': 1,
'product_uom': pay_gift_card_id.uom_id.id,
'gift_card_id': gift_card.id,
'order_id': self.id
})
return error
def _compute_amount_total_without_delivery(self):
self.ensure_one()
# Add back 'payment' rewards from the total without delivery, they should count towards the delivery price goal.
lines = self.order_line.filtered(lambda l: l.gift_card_id)
return super()._compute_amount_total_without_delivery() - sum(lines.mapped('price_unit'))
def _send_gift_card_mail(self):
template = self.env.ref('sale_gift_card.mail_template_gift_card', raise_if_not_found=False)
if template and self.gift_card_count:
for gift in self.order_line.mapped("generated_gift_card_ids"):
template.send_mail(gift.id, force_send=True, notif_layout='mail.mail_notification_light')
def _recompute_gift_card_lines(self):
for record in self:
lines_to_remove = self.env['sale.order.line']
lines_to_update = []
gift_payment_lines = record.order_line.filtered('gift_card_id')
to_pay = sum((self.order_line - gift_payment_lines).mapped('price_total'))
# consume older gift card first
for gift_card_line in gift_payment_lines.sorted(lambda line: line.gift_card_id.expired_date):
amount = min(to_pay, gift_card_line.gift_card_id.balance_converted(record.currency_id))
if amount:
to_pay -= amount
if gift_card_line.price_unit != -amount or gift_card_line.product_uom_qty != 1:
lines_to_update.append(
fields.Command.update(gift_card_line.id, {'price_unit': -amount, 'product_uom_qty': 1})
)
else:
lines_to_remove += gift_card_line
lines_to_remove.unlink()
record.update({'order_line': lines_to_update})
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
generated_gift_card_ids = fields.One2many('gift.card', "buy_line_id", string="Bought Gift Card")
gift_card_id = fields.Many2one('gift.card', help="Deducted from this Gift Card", copy=False)
def _is_not_sellable_line(self):
return self.gift_card_id or super()._is_not_sellable_line()
def _create_gift_cards(self):
return self.env['gift.card'].create(
[self._build_gift_card() for _ in range(int(self.product_uom_qty))]
)
def _build_gift_card(self):
return {
'initial_amount': self.order_id.currency_id._convert(
self.price_unit,
self.order_id.env.company.currency_id,
self.order_id.env.company,
fields.Date.today()
),
'buy_line_id': self.id,
}
| 44.594595
| 4,950
|
1,013
|
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 GiftCard(models.Model):
_inherit = "gift.card"
buy_line_id = fields.Many2one("sale.order.line", copy=False, readonly=True,
help="Sale Order line where this gift card has been bought.")
redeem_line_ids = fields.One2many('sale.order.line', 'gift_card_id', string="Redeems")
@api.depends("redeem_line_ids")
def _compute_balance(self):
super()._compute_balance()
for record in self:
confirmed_line = record.redeem_line_ids.filtered(lambda l: l.state in ('sale', 'done'))
balance = record.balance
if confirmed_line:
balance -= sum(confirmed_line.mapped(
lambda line: line.currency_id._convert(line.price_unit, record.currency_id, record.env.company, line.create_date) * -1
))
record.balance = balance
| 42.208333
| 1,013
|
1,447
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Repairs',
'version': '1.0',
'sequence': 230,
'category': 'Inventory/Inventory',
'summary': 'Repair damaged products',
'description': """
The aim is to have a complete module to manage all products repairs.
====================================================================
The following topics are covered by this module:
------------------------------------------------------
* Add/remove products in the reparation
* Impact for stocks
* Invoicing (products and/or services)
* Warranty concept
* Repair quotation report
* Notes for the technician and for the final customer
""",
'depends': ['stock', 'sale_management', 'account'],
'data': [
'security/ir.model.access.csv',
'security/repair_security.xml',
'wizard/repair_make_invoice_views.xml',
'wizard/stock_warn_insufficient_qty_views.xml',
'views/stock_move_views.xml',
'views/repair_views.xml',
'views/stock_production_lot_views.xml',
'report/repair_reports.xml',
'report/repair_templates_repair_order.xml',
'data/ir_sequence_data.xml',
'data/mail_template_data.xml',
],
'demo': ['data/repair_demo.xml'],
'test': [],
'installable': True,
'auto_install': False,
'application': True,
'license': 'LGPL-3',
}
| 32.886364
| 1,447
|
17,260
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged, Form
@tagged('post_install', '-at_install')
class TestRepair(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# Partners
cls.res_partner_1 = cls.env['res.partner'].create({'name': 'Wood Corner'})
cls.res_partner_address_1 = cls.env['res.partner'].create({'name': 'Willie Burke', 'parent_id': cls.res_partner_1.id})
cls.res_partner_12 = cls.env['res.partner'].create({'name': 'Partner 12'})
# Products
cls.product_product_3 = cls.env['product.product'].create({'name': 'Desk Combination'})
cls.product_product_11 = cls.env['product.product'].create({'name': 'Conference Chair'})
cls.product_product_5 = cls.env['product.product'].create({'name': 'Product 5'})
cls.product_product_6 = cls.env['product.product'].create({'name': 'Large Cabinet'})
cls.product_product_12 = cls.env['product.product'].create({'name': 'Office Chair Black'})
cls.product_product_13 = cls.env['product.product'].create({'name': 'Corner Desk Left Sit'})
cls.product_product_2 = cls.env['product.product'].create({'name': 'Virtual Home Staging'})
cls.product_service_order_repair = cls.env['product.product'].create({
'name': 'Repair Services',
'type': 'service',
})
# Location
cls.stock_warehouse = cls.env['stock.warehouse'].search([('company_id', '=', cls.env.company.id)], limit=1)
cls.stock_location_14 = cls.env['stock.location'].create({
'name': 'Shelf 2',
'location_id': cls.stock_warehouse.lot_stock_id.id,
})
# Repair Orders
cls.repair1 = cls.env['repair.order'].create({
'address_id': cls.res_partner_address_1.id,
'guarantee_limit': '2019-01-01',
'invoice_method': 'none',
'user_id': False,
'product_id': cls.product_product_3.id,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'partner_invoice_id': cls.res_partner_address_1.id,
'location_id': cls.stock_warehouse.lot_stock_id.id,
'operations': [
(0, 0, {
'location_dest_id': cls.product_product_11.property_stock_production.id,
'location_id': cls.stock_warehouse.lot_stock_id.id,
'name': cls.product_product_11.get_product_multiline_description_sale(),
'product_id': cls.product_product_11.id,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'product_uom_qty': 1.0,
'price_unit': 50.0,
'state': 'draft',
'type': 'add',
'company_id': cls.env.company.id,
})
],
'fees_lines': [
(0, 0, {
'name': cls.product_service_order_repair.get_product_multiline_description_sale(),
'product_id': cls.product_service_order_repair.id,
'product_uom_qty': 1.0,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'price_unit': 50.0,
'company_id': cls.env.company.id,
})
],
'partner_id': cls.res_partner_12.id,
})
cls.repair0 = cls.env['repair.order'].create({
'product_id': cls.product_product_5.id,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'address_id': cls.res_partner_address_1.id,
'guarantee_limit': '2019-01-01',
'invoice_method': 'after_repair',
'user_id': False,
'partner_invoice_id': cls.res_partner_address_1.id,
'location_id': cls.stock_warehouse.lot_stock_id.id,
'operations': [
(0, 0, {
'location_dest_id': cls.product_product_12.property_stock_production.id,
'location_id': cls.stock_warehouse.lot_stock_id.id,
'name': cls.product_product_12.get_product_multiline_description_sale(),
'price_unit': 50.0,
'product_id': cls.product_product_12.id,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'product_uom_qty': 1.0,
'state': 'draft',
'type': 'add',
'company_id': cls.env.company.id,
})
],
'fees_lines': [
(0, 0, {
'name': cls.product_service_order_repair.get_product_multiline_description_sale(),
'product_id': cls.product_service_order_repair.id,
'product_uom_qty': 1.0,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'price_unit': 50.0,
'company_id': cls.env.company.id,
})
],
'partner_id': cls.res_partner_12.id,
})
cls.repair2 = cls.env['repair.order'].create({
'product_id': cls.product_product_6.id,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'address_id': cls.res_partner_address_1.id,
'guarantee_limit': '2019-01-01',
'invoice_method': 'b4repair',
'user_id': False,
'partner_invoice_id': cls.res_partner_address_1.id,
'location_id': cls.stock_location_14.id,
'operations': [
(0, 0, {
'location_dest_id': cls.product_product_13.property_stock_production.id,
'location_id': cls.stock_warehouse.lot_stock_id.id,
'name': cls.product_product_13.get_product_multiline_description_sale(),
'price_unit': 50.0,
'product_id': cls.product_product_13.id,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'product_uom_qty': 1.0,
'state': 'draft',
'type': 'add',
'company_id': cls.env.company.id,
})
],
'fees_lines': [
(0, 0, {
'name': cls.product_service_order_repair.get_product_multiline_description_sale(),
'product_id': cls.product_service_order_repair.id,
'product_uom_qty': 1.0,
'product_uom': cls.env.ref('uom.product_uom_unit').id,
'price_unit': 50.0,
'company_id': cls.env.company.id,
})
],
'partner_id': cls.res_partner_12.id,
})
cls.env.user.groups_id |= cls.env.ref('stock.group_stock_user')
def _create_simple_repair_order(self, invoice_method):
product_to_repair = self.product_product_5
partner = self.res_partner_address_1
return self.env['repair.order'].create({
'product_id': product_to_repair.id,
'product_uom': product_to_repair.uom_id.id,
'address_id': partner.id,
'guarantee_limit': '2019-01-01',
'invoice_method': invoice_method,
'partner_invoice_id': partner.id,
'location_id': self.stock_warehouse.lot_stock_id.id,
'partner_id': self.res_partner_12.id
})
def _create_simple_operation(self, repair_id=False, qty=0.0, price_unit=0.0):
product_to_add = self.product_product_5
return self.env['repair.line'].create({
'name': 'Add The product',
'type': 'add',
'product_id': product_to_add.id,
'product_uom_qty': qty,
'product_uom': product_to_add.uom_id.id,
'price_unit': price_unit,
'repair_id': repair_id,
'location_id': self.stock_warehouse.lot_stock_id.id,
'location_dest_id': product_to_add.property_stock_production.id,
'company_id': self.env.company.id,
})
def _create_simple_fee(self, repair_id=False, qty=0.0, price_unit=0.0):
product_service = self.product_product_2
return self.env['repair.fee'].create({
'name': 'PC Assemble + Custom (PC on Demand)',
'product_id': product_service.id,
'product_uom_qty': qty,
'product_uom': product_service.uom_id.id,
'price_unit': price_unit,
'repair_id': repair_id,
'company_id': self.env.company.id,
})
def test_00_repair_afterinv(self):
repair = self._create_simple_repair_order('after_repair')
self._create_simple_operation(repair_id=repair.id, qty=1.0, price_unit=50.0)
# I confirm Repair order taking Invoice Method 'After Repair'.
repair.action_repair_confirm()
# I check the state is in "Confirmed".
self.assertEqual(repair.state, "confirmed", 'Repair order should be in "Confirmed" state.')
repair.action_repair_start()
# I check the state is in "Under Repair".
self.assertEqual(repair.state, "under_repair", 'Repair order should be in "Under_repair" state.')
# Repairing process for product is in Done state and I end Repair process by clicking on "End Repair" button.
repair.action_repair_end()
# I define Invoice Method 'After Repair' option in this Repair order.so I create invoice by clicking on "Make Invoice" wizard.
make_invoice = self.env['repair.order.make_invoice'].create({
'group': True})
# I click on "Create Invoice" button of this wizard to make invoice.
context = {
"active_model": 'repair_order',
"active_ids": [repair.id],
"active_id": repair.id
}
make_invoice.with_context(context).make_invoices()
# I check that invoice is created for this Repair order.
self.assertEqual(len(repair.invoice_id), 1, "No invoice exists for this repair order")
self.assertEqual(len(repair.move_id.move_line_ids[0].consume_line_ids), 1, "Consume lines should be set")
def test_01_repair_b4inv(self):
repair = self._create_simple_repair_order('b4repair')
# I confirm Repair order for Invoice Method 'Before Repair'.
repair.action_repair_confirm()
# I click on "Create Invoice" button of this wizard to make invoice.
repair.action_repair_invoice_create()
# I check that invoice is created for this Repair order.
self.assertEqual(len(repair.invoice_id), 1, "No invoice exists for this repair order")
def test_02_repair_noneinv(self):
repair = self._create_simple_repair_order('none')
# Add a new fee line
self._create_simple_fee(repair_id=repair.id, qty=1.0, price_unit=12.0)
self.assertEqual(repair.amount_total, 12, "Amount_total should be 12")
# Add new operation line
self._create_simple_operation(repair_id=repair.id, qty=1.0, price_unit=14.0)
self.assertEqual(repair.amount_total, 26, "Amount_total should be 26")
# I confirm Repair order for Invoice Method 'No Invoice'.
repair.action_repair_confirm()
# I start the repairing process by clicking on "Start Repair" button for Invoice Method 'No Invoice'.
repair.action_repair_start()
# I check its state which is in "Under Repair".
self.assertEqual(repair.state, "under_repair", 'Repair order should be in "Under_repair" state.')
# Repairing process for product is in Done state and I end this process by clicking on "End Repair" button.
repair.action_repair_end()
self.assertEqual(repair.move_id.location_id.id, self.stock_warehouse.lot_stock_id.id,
'Repaired product was taken in the wrong location')
self.assertEqual(repair.move_id.location_dest_id.id, self.stock_warehouse.lot_stock_id.id,
'Repaired product went to the wrong location')
self.assertEqual(repair.operations.move_id.location_id.id, self.stock_warehouse.lot_stock_id.id,
'Consumed product was taken in the wrong location')
self.assertEqual(repair.operations.move_id.location_dest_id.id, self.product_product_5.property_stock_production.id,
'Consumed product went to the wrong location')
# I define Invoice Method 'No Invoice' option in this repair order.
# So, I check that Invoice has not been created for this repair order.
self.assertNotEqual(len(repair.invoice_id), 1, "Invoice should not exist for this repair order")
def test_repair_state(self):
repair = self._create_simple_repair_order('b4repair')
repair.action_repair_confirm()
repair.action_repair_invoice_create()
repair.invoice_id.unlink()
# Repair order state should be changed to 2binvoiced so that new invoice can be created
self.assertEqual(repair.state, '2binvoiced', 'Repair order should be in 2binvoiced state, if invoice is deleted.')
repair.action_repair_invoice_create()
repair.action_repair_cancel()
# Repair order and linked invoice both should be cancelled.
self.assertEqual(repair.state, 'cancel', 'Repair order should be in cancel state.')
self.assertEqual(repair.invoice_id.state, 'cancel', 'Invoice should be in cancel state.')
repair.action_repair_cancel_draft()
# Linked invoice should be unlinked
self.assertEqual(len(repair.invoice_id), 0, "No invoice should be exists for this repair order")
def test_03_repair_multicompany(self):
""" This test ensures that the correct taxes are selected when the user fills in the RO form """
company01 = self.env.company
company02 = self.env['res.company'].create({
'name': 'SuperCompany',
})
tax01 = self.env["account.tax"].create({
"name": "C01 Tax",
"amount": "0.00",
"company_id": company01.id
})
tax02 = self.env["account.tax"].create({
"name": "C02 Tax",
"amount": "0.00",
"company_id": company02.id
})
super_product = self.env['product.template'].create({
"name": "SuperProduct",
"taxes_id": [(4, tax01.id), (4, tax02.id)],
})
super_variant = super_product.product_variant_id
self.assertEqual(super_variant.taxes_id, tax01 | tax02)
ro_form = Form(self.env['repair.order'])
ro_form.product_id = super_variant
ro_form.partner_id = company01.partner_id
with ro_form.operations.new() as ro_line:
ro_line.product_id = super_variant
with ro_form.fees_lines.new() as fee_line:
fee_line.product_id = super_variant
repair_order = ro_form.save()
# tax02 should not be present since it belongs to the second company.
self.assertEqual(repair_order.operations.tax_id, tax01)
self.assertEqual(repair_order.fees_lines.tax_id, tax01)
def test_repair_order_send_to_self(self):
# when sender(logged in user) is also present in recipients of the mail composer,
# user should receive mail.
product_to_repair = self.product_product_5
partner = self.res_partner_address_1
repair_order = self.env['repair.order'].with_user(self.env.user).create({
'product_id': product_to_repair.id,
'product_uom': product_to_repair.uom_id.id,
'address_id': partner.id,
'guarantee_limit': '2019-01-01',
'location_id': self.stock_warehouse.lot_stock_id.id,
'partner_id': self.env.user.partner_id.id
})
email_ctx = repair_order.action_send_mail().get('context', {})
# We need to prevent auto mail deletion, and so we copy the template and send the mail with
# added configuration in copied template. It will allow us to check whether mail is being
# sent to to author or not (in case author is present in 'Recipients' of composer).
mail_template = self.env['mail.template'].browse(email_ctx.get('default_template_id')).copy({'auto_delete': False})
# send the mail with same user as customer
repair_order.with_context(**email_ctx).with_user(self.env.user).message_post_with_template(mail_template.id)
mail_message = repair_order.message_ids[0]
self.assertEqual(mail_message.author_id, repair_order.partner_id, 'Repair: author should be same as customer')
self.assertEqual(mail_message.author_id, mail_message.partner_ids, 'Repair: author should be in composer recipients thanks to "partner_to" field set on template')
self.assertEqual(mail_message.partner_ids, mail_message.sudo().mail_ids.recipient_ids, 'Repair: author should receive mail due to presence in composer recipients')
| 49.597701
| 17,260
|
1,482
|
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 MakeInvoice(models.TransientModel):
_name = 'repair.order.make_invoice'
_description = 'Create Mass Invoice (repair)'
group = fields.Boolean('Group by partner invoice address')
def make_invoices(self):
if not self._context.get('active_ids'):
return {'type': 'ir.actions.act_window_close'}
new_invoice = {}
for wizard in self:
repairs = self.env['repair.order'].browse(self._context['active_ids'])
new_invoice = repairs._create_invoices(group=wizard.group)
# We have to udpate the state of the given repairs, otherwise they remain 'to be invoiced'.
# Note that this will trigger another call to the method '_create_invoices',
# but that second call will not do anything, since the repairs are already invoiced.
repairs.action_repair_invoice_create()
return {
'domain': [('id', 'in', list(new_invoice.values()))],
'name': 'Invoices',
'view_mode': 'tree,form',
'res_model': 'account.move',
'view_id': False,
'views': [(self.env.ref('account.view_move_tree').id, 'tree'), (self.env.ref('account.view_move_form').id, 'form')],
'context': "{'move_type':'out_invoice'}",
'type': 'ir.actions.act_window'
}
| 43.588235
| 1,482
|
609
|
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 StockWarnInsufficientQtyRepair(models.TransientModel):
_name = 'stock.warn.insufficient.qty.repair'
_inherit = 'stock.warn.insufficient.qty'
_description = 'Warn Insufficient Repair Quantity'
repair_id = fields.Many2one('repair.order', string='Repair')
def _get_reference_document_company_id(self):
return self.repair_id.company_id
def action_done(self):
self.ensure_one()
return self.repair_id.action_repair_confirm()
| 33.833333
| 609
|
44,325
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from random import randint
from markupsafe import Markup
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare, is_html_empty
class StockMove(models.Model):
_inherit = 'stock.move'
repair_id = fields.Many2one('repair.order', check_company=True)
class Repair(models.Model):
_name = 'repair.order'
_description = 'Repair Order'
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = 'priority desc, create_date desc'
name = fields.Char(
'Repair Reference',
default='New',
copy=False, required=True,
readonly=True)
description = fields.Char('Repair Description')
product_id = fields.Many2one(
'product.product', string='Product to Repair',
domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', company_id), ('company_id', '=', False)]",
readonly=True, required=True, states={'draft': [('readonly', False)]}, check_company=True)
product_qty = fields.Float(
'Product Quantity',
default=1.0, digits='Product Unit of Measure',
readonly=True, required=True, states={'draft': [('readonly', False)]})
product_uom = fields.Many2one(
'uom.uom', 'Product Unit of Measure',
readonly=True, required=True, states={'draft': [('readonly', False)]}, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
partner_id = fields.Many2one(
'res.partner', 'Customer',
index=True, states={'confirmed': [('readonly', True)]}, check_company=True, change_default=True,
help='Choose partner for whom the order will be invoiced and delivered. You can find a partner by its Name, TIN, Email or Internal Reference.')
address_id = fields.Many2one(
'res.partner', 'Delivery Address',
domain="[('parent_id','=',partner_id)]", check_company=True,
states={'confirmed': [('readonly', True)]})
default_address_id = fields.Many2one('res.partner', compute='_compute_default_address_id')
state = fields.Selection([
('draft', 'Quotation'),
('confirmed', 'Confirmed'),
('ready', 'Ready to Repair'),
('under_repair', 'Under Repair'),
('2binvoiced', 'To be Invoiced'),
('done', 'Repaired'),
('cancel', 'Cancelled')], string='Status',
copy=False, default='draft', readonly=True, tracking=True,
help="* The \'Draft\' status is used when a user is encoding a new and unconfirmed repair order.\n"
"* The \'Confirmed\' status is used when a user confirms the repair order.\n"
"* The \'Ready to Repair\' status is used to start to repairing, user can start repairing only after repair order is confirmed.\n"
"* The \'Under Repair\' status is used when the repair is ongoing.\n"
"* The \'To be Invoiced\' status is used to generate the invoice before or after repairing done.\n"
"* The \'Done\' status is set when repairing is completed.\n"
"* The \'Cancelled\' status is used when user cancel repair order.")
schedule_date = fields.Date("Scheduled Date")
location_id = fields.Many2one(
'stock.location', 'Location',
index=True, readonly=True, required=True, check_company=True,
help="This is the location where the product to repair is located.",
states={'draft': [('readonly', False)], 'confirmed': [('readonly', True)]})
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial',
domain="[('product_id','=', product_id), ('company_id', '=', company_id)]", check_company=True,
help="Products repaired are all belonging to this lot")
guarantee_limit = fields.Date('Warranty Expiration', states={'confirmed': [('readonly', True)]})
operations = fields.One2many(
'repair.line', 'repair_id', 'Parts',
copy=True)
pricelist_id = fields.Many2one(
'product.pricelist', 'Pricelist',
default=lambda self: self.env['product.pricelist'].search([('company_id', 'in', [self.env.company.id, False])], limit=1).id,
help='Pricelist of the selected partner.', check_company=True)
currency_id = fields.Many2one(related='pricelist_id.currency_id')
partner_invoice_id = fields.Many2one('res.partner', 'Invoicing Address', check_company=True)
invoice_method = fields.Selection([
("none", "No Invoice"),
("b4repair", "Before Repair"),
("after_repair", "After Repair")], string="Invoice Method",
default='none', index=True, readonly=True, required=True,
states={'draft': [('readonly', False)]},
help='Selecting \'Before Repair\' or \'After Repair\' will allow you to generate invoice before or after the repair is done respectively. \'No invoice\' means you don\'t want to generate invoice for this repair order.')
invoice_id = fields.Many2one(
'account.move', 'Invoice',
copy=False, readonly=True, tracking=True,
domain=[('move_type', '=', 'out_invoice')])
move_id = fields.Many2one(
'stock.move', 'Move',
copy=False, readonly=True, tracking=True, check_company=True,
help="Move created by the repair order")
fees_lines = fields.One2many(
'repair.fee', 'repair_id', 'Operations',
copy=True, readonly=False)
internal_notes = fields.Html('Internal Notes')
quotation_notes = fields.Html('Quotation Notes')
user_id = fields.Many2one('res.users', string="Responsible", default=lambda self: self.env.user, check_company=True)
company_id = fields.Many2one(
'res.company', 'Company',
readonly=True, required=True, index=True,
default=lambda self: self.env.company)
sale_order_id = fields.Many2one('sale.order', 'Sale Order', copy=False, help="Sale Order from which the product to be repaired comes from.")
tag_ids = fields.Many2many('repair.tags', string="Tags")
invoiced = fields.Boolean('Invoiced', copy=False, readonly=True)
repaired = fields.Boolean('Repaired', copy=False, readonly=True)
amount_untaxed = fields.Float('Untaxed Amount', compute='_amount_untaxed', store=True)
amount_tax = fields.Float('Taxes', compute='_amount_tax', store=True)
amount_total = fields.Float('Total', compute='_amount_total', store=True)
tracking = fields.Selection(string='Product Tracking', related="product_id.tracking", readonly=False)
invoice_state = fields.Selection(string='Invoice State', related='invoice_id.state')
priority = fields.Selection([('0', 'Normal'), ('1', 'Urgent')], default='0', string="Priority", help="Important repair order")
@api.depends('partner_id')
def _compute_default_address_id(self):
for order in self:
if order.partner_id:
order.default_address_id = order.partner_id.address_get(['contact'])['contact']
@api.depends('operations.price_subtotal', 'invoice_method', 'fees_lines.price_subtotal', 'pricelist_id.currency_id')
def _amount_untaxed(self):
for order in self:
total = sum(operation.price_subtotal for operation in order.operations)
total += sum(fee.price_subtotal for fee in order.fees_lines)
currency = order.pricelist_id.currency_id or self.env.company.currency_id
order.amount_untaxed = currency.round(total)
@api.depends('operations.price_unit', 'operations.product_uom_qty', 'operations.product_id',
'fees_lines.price_unit', 'fees_lines.product_uom_qty', 'fees_lines.product_id',
'pricelist_id.currency_id', 'partner_id')
def _amount_tax(self):
for order in self:
val = 0.0
currency = order.pricelist_id.currency_id or self.env.company.currency_id
for operation in order.operations:
if operation.tax_id:
tax_calculate = operation.tax_id.compute_all(operation.price_unit, currency, operation.product_uom_qty, operation.product_id, order.partner_id)
for c in tax_calculate['taxes']:
val += c['amount']
for fee in order.fees_lines:
if fee.tax_id:
tax_calculate = fee.tax_id.compute_all(fee.price_unit, currency, fee.product_uom_qty, fee.product_id, order.partner_id)
for c in tax_calculate['taxes']:
val += c['amount']
order.amount_tax = val
@api.depends('amount_untaxed', 'amount_tax')
def _amount_total(self):
for order in self:
currency = order.pricelist_id.currency_id or self.env.company.currency_id
order.amount_total = currency.round(order.amount_untaxed + order.amount_tax)
_sql_constraints = [
('name', 'unique (name)', 'The name of the Repair Order must be unique!'),
]
@api.onchange('product_id')
def onchange_product_id(self):
self.guarantee_limit = False
if (self.product_id and self.lot_id and self.lot_id.product_id != self.product_id) or not self.product_id:
self.lot_id = False
if self.product_id:
self.product_uom = self.product_id.uom_id.id
@api.onchange('product_uom')
def onchange_product_uom(self):
res = {}
if not self.product_id or not self.product_uom:
return res
if self.product_uom.category_id != self.product_id.uom_id.category_id:
res['warning'] = {'title': _('Warning'), 'message': _('The product unit of measure you chose has a different category than the product unit of measure.')}
self.product_uom = self.product_id.uom_id.id
return res
@api.onchange('partner_id')
def onchange_partner_id(self):
self = self.with_company(self.company_id)
if not self.partner_id:
self.address_id = False
self.partner_invoice_id = False
self.pricelist_id = self.env['product.pricelist'].search([
('company_id', 'in', [self.env.company.id, False]),
], limit=1)
else:
addresses = self.partner_id.address_get(['delivery', 'invoice', 'contact'])
self.address_id = addresses['delivery'] or addresses['contact']
self.partner_invoice_id = addresses['invoice']
self.pricelist_id = self.partner_id.property_product_pricelist.id
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
if self.location_id.company_id != self.company_id:
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
self.location_id = warehouse.lot_stock_id
else:
self.location_id = False
@api.ondelete(at_uninstall=False)
def _unlink_except_confirmed(self):
for order in self:
if order.invoice_id and order.invoice_id.posted_before:
raise UserError(_('You can not delete a repair order which is linked to an invoice which has been posted once.'))
if order.state == 'done':
raise UserError(_('You cannot delete a completed repair order.'))
if order.state not in ('draft', 'cancel'):
raise UserError(_('You can not delete a repair order once it has been confirmed. You must first cancel it.'))
@api.model
def create(self, vals):
# We generate a standard reference
vals['name'] = self.env['ir.sequence'].next_by_code('repair.order') or '/'
return super(Repair, self).create(vals)
def button_dummy(self):
# TDE FIXME: this button is very interesting
return True
def action_repair_cancel_draft(self):
if self.filtered(lambda repair: repair.state != 'cancel'):
raise UserError(_("Repair must be canceled in order to reset it to draft."))
self.mapped('operations').write({'state': 'draft'})
return self.write({'state': 'draft', 'invoice_id': False})
def action_validate(self):
self.ensure_one()
if self.filtered(lambda repair: any(op.product_uom_qty < 0 for op in repair.operations)):
raise UserError(_("You can not enter negative quantities."))
if self.product_id.type == 'consu':
return self.action_repair_confirm()
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
available_qty_owner = self.env['stock.quant']._get_available_quantity(self.product_id, self.location_id, self.lot_id, owner_id=self.partner_id, strict=True)
available_qty_noown = self.env['stock.quant']._get_available_quantity(self.product_id, self.location_id, self.lot_id, strict=True)
repair_qty = self.product_uom._compute_quantity(self.product_qty, self.product_id.uom_id)
for available_qty in [available_qty_owner, available_qty_noown]:
if float_compare(available_qty, repair_qty, precision_digits=precision) >= 0:
return self.action_repair_confirm()
else:
return {
'name': self.product_id.display_name + _(': Insufficient Quantity To Repair'),
'view_mode': 'form',
'res_model': 'stock.warn.insufficient.qty.repair',
'view_id': self.env.ref('repair.stock_warn_insufficient_qty_repair_form_view').id,
'type': 'ir.actions.act_window',
'context': {
'default_product_id': self.product_id.id,
'default_location_id': self.location_id.id,
'default_repair_id': self.id,
'default_quantity': repair_qty,
'default_product_uom_name': self.product_id.uom_name
},
'target': 'new'
}
def action_repair_confirm(self):
""" Repair order state is set to 'To be invoiced' when invoice method
is 'Before repair' else state becomes 'Confirmed'.
@param *arg: Arguments
@return: True
"""
if self.filtered(lambda repair: repair.state != 'draft'):
raise UserError(_("Only draft repairs can be confirmed."))
self._check_company()
self.operations._check_company()
self.fees_lines._check_company()
before_repair = self.filtered(lambda repair: repair.invoice_method == 'b4repair')
before_repair.write({'state': '2binvoiced'})
to_confirm = self - before_repair
to_confirm_operations = to_confirm.mapped('operations')
to_confirm_operations.write({'state': 'confirmed'})
to_confirm.write({'state': 'confirmed'})
return True
def action_repair_cancel(self):
if any(repair.state == 'done' for repair in self):
raise UserError(_("You cannot cancel a completed repair order."))
invoice_to_cancel = self.filtered(lambda repair: repair.invoice_id.state == 'draft').invoice_id
if invoice_to_cancel:
invoice_to_cancel.button_cancel()
self.mapped('operations').write({'state': 'cancel'})
return self.write({'state': 'cancel'})
def action_send_mail(self):
self.ensure_one()
template_id = self.env.ref('repair.mail_template_repair_quotation').id
ctx = {
'default_model': 'repair.order',
'default_res_id': self.id,
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_composition_mode': 'comment',
'custom_layout': 'mail.mail_notification_light',
}
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'target': 'new',
'context': ctx,
}
def print_repair_order(self):
return self.env.ref('repair.action_report_repair_order').report_action(self)
def action_repair_invoice_create(self):
for repair in self:
repair._create_invoices()
if repair.invoice_method == 'b4repair':
repair.action_repair_ready()
elif repair.invoice_method == 'after_repair':
repair.write({'state': 'done'})
return True
def _create_invoices(self, group=False):
""" Creates invoice(s) for repair order.
@param group: It is set to true when group invoice is to be generated.
@return: Invoice Ids.
"""
grouped_invoices_vals = {}
repairs = self.filtered(lambda repair: repair.state not in ('draft', 'cancel')
and not repair.invoice_id
and repair.invoice_method != 'none')
for repair in repairs:
repair = repair.with_company(repair.company_id)
partner_invoice = repair.partner_invoice_id or repair.partner_id
if not partner_invoice:
raise UserError(_('You have to select an invoice address in the repair form.'))
narration = repair.quotation_notes
currency = repair.pricelist_id.currency_id
company = repair.env.company
journal = repair.env['account.move'].with_context(move_type='out_invoice')._get_default_journal()
if not journal:
raise UserError(_('Please define an accounting sales journal for the company %s (%s).') % (company.name, company.id))
if (partner_invoice.id, currency.id, company.id) not in grouped_invoices_vals:
grouped_invoices_vals[(partner_invoice.id, currency.id, company.id)] = []
current_invoices_list = grouped_invoices_vals[(partner_invoice.id, currency.id, company.id)]
if not group or len(current_invoices_list) == 0:
fpos = self.env['account.fiscal.position'].get_fiscal_position(partner_invoice.id, delivery_id=repair.address_id.id)
invoice_vals = {
'move_type': 'out_invoice',
'partner_id': partner_invoice.id,
'partner_shipping_id': repair.address_id.id,
'currency_id': currency.id,
'narration': narration if not is_html_empty(narration) else '',
'invoice_origin': repair.name,
'repair_ids': [(4, repair.id)],
'invoice_line_ids': [],
'fiscal_position_id': fpos.id
}
if partner_invoice.property_payment_term_id:
invoice_vals['invoice_payment_term_id'] = partner_invoice.property_payment_term_id.id
current_invoices_list.append(invoice_vals)
else:
# if group == True: concatenate invoices by partner and currency
invoice_vals = current_invoices_list[0]
invoice_vals['invoice_origin'] += ', ' + repair.name
invoice_vals['repair_ids'].append((4, repair.id))
if not is_html_empty(narration):
if is_html_empty(invoice_vals['narration']):
invoice_vals['narration'] = narration
else:
invoice_vals['narration'] += Markup('<br/>') + narration
# Create invoice lines from operations.
for operation in repair.operations.filtered(lambda op: op.type == 'add'):
if group:
name = repair.name + '-' + operation.name
else:
name = operation.name
account = operation.product_id.product_tmpl_id.get_product_accounts(fiscal_pos=fpos)['income']
if not account:
raise UserError(_('No account defined for product "%s".', operation.product_id.name))
invoice_line_vals = {
'name': name,
'account_id': account.id,
'quantity': operation.product_uom_qty,
'tax_ids': [(6, 0, operation.tax_id.ids)],
'product_uom_id': operation.product_uom.id,
'price_unit': operation.price_unit,
'product_id': operation.product_id.id,
'repair_line_ids': [(4, operation.id)],
}
if currency == company.currency_id:
balance = -(operation.product_uom_qty * operation.price_unit)
invoice_line_vals.update({
'debit': balance > 0.0 and balance or 0.0,
'credit': balance < 0.0 and -balance or 0.0,
})
else:
amount_currency = -(operation.product_uom_qty * operation.price_unit)
balance = currency._convert(amount_currency, company.currency_id, company, fields.Date.today())
invoice_line_vals.update({
'amount_currency': amount_currency,
'debit': balance > 0.0 and balance or 0.0,
'credit': balance < 0.0 and -balance or 0.0,
'currency_id': currency.id,
})
invoice_vals['invoice_line_ids'].append((0, 0, invoice_line_vals))
# Create invoice lines from fees.
for fee in repair.fees_lines:
if group:
name = repair.name + '-' + fee.name
else:
name = fee.name
if not fee.product_id:
raise UserError(_('No product defined on fees.'))
account = fee.product_id.product_tmpl_id.get_product_accounts(fiscal_pos=fpos)['income']
if not account:
raise UserError(_('No account defined for product "%s".', fee.product_id.name))
invoice_line_vals = {
'name': name,
'account_id': account.id,
'quantity': fee.product_uom_qty,
'tax_ids': [(6, 0, fee.tax_id.ids)],
'product_uom_id': fee.product_uom.id,
'price_unit': fee.price_unit,
'product_id': fee.product_id.id,
'repair_fee_ids': [(4, fee.id)],
}
if currency == company.currency_id:
balance = -(fee.product_uom_qty * fee.price_unit)
invoice_line_vals.update({
'debit': balance > 0.0 and balance or 0.0,
'credit': balance < 0.0 and -balance or 0.0,
})
else:
amount_currency = -(fee.product_uom_qty * fee.price_unit)
balance = currency._convert(amount_currency, company.currency_id, company,
fields.Date.today())
invoice_line_vals.update({
'amount_currency': amount_currency,
'debit': balance > 0.0 and balance or 0.0,
'credit': balance < 0.0 and -balance or 0.0,
'currency_id': currency.id,
})
invoice_vals['invoice_line_ids'].append((0, 0, invoice_line_vals))
# Create invoices.
invoices_vals_list_per_company = defaultdict(list)
for (partner_invoice_id, currency_id, company_id), invoices in grouped_invoices_vals.items():
for invoice in invoices:
invoices_vals_list_per_company[company_id].append(invoice)
for company_id, invoices_vals_list in invoices_vals_list_per_company.items():
# VFE TODO remove the default_company_id ctxt key ?
# Account fallbacks on self.env.company, which is correct with with_company
self.env['account.move'].with_company(company_id).with_context(default_company_id=company_id, default_move_type='out_invoice').create(invoices_vals_list)
repairs.write({'invoiced': True})
repairs.mapped('operations').filtered(lambda op: op.type == 'add').write({'invoiced': True})
repairs.mapped('fees_lines').write({'invoiced': True})
return dict((repair.id, repair.invoice_id.id) for repair in repairs)
def action_created_invoice(self):
self.ensure_one()
return {
'name': _('Invoice created'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'account.move',
'view_id': self.env.ref('account.view_move_form').id,
'target': 'current',
'res_id': self.invoice_id.id,
}
def action_repair_ready(self):
self.mapped('operations').write({'state': 'confirmed'})
return self.write({'state': 'ready'})
def action_repair_start(self):
""" Writes repair order state to 'Under Repair'
@return: True
"""
if self.filtered(lambda repair: repair.state not in ['confirmed', 'ready']):
raise UserError(_("Repair must be confirmed before starting reparation."))
self.mapped('operations').write({'state': 'confirmed'})
return self.write({'state': 'under_repair'})
def action_repair_end(self):
""" Writes repair order state to 'To be invoiced' if invoice method is
After repair else state is set to 'Ready'.
@return: True
"""
if self.filtered(lambda repair: repair.state != 'under_repair'):
raise UserError(_("Repair must be under repair in order to end reparation."))
self._check_product_tracking()
for repair in self:
repair.write({'repaired': True})
vals = {'state': 'done'}
vals['move_id'] = repair.action_repair_done().get(repair.id)
if not repair.invoice_id and repair.invoice_method == 'after_repair':
vals['state'] = '2binvoiced'
repair.write(vals)
return True
def action_repair_done(self):
""" Creates stock move for operation and stock move for final product of repair order.
@return: Move ids of final products
"""
if self.filtered(lambda repair: not repair.repaired):
raise UserError(_("Repair must be repaired in order to make the product moves."))
self._check_company()
self.operations._check_company()
self.fees_lines._check_company()
res = {}
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
Move = self.env['stock.move']
for repair in self:
# Try to create move with the appropriate owner
owner_id = False
available_qty_owner = self.env['stock.quant']._get_available_quantity(repair.product_id, repair.location_id, repair.lot_id, owner_id=repair.partner_id, strict=True)
if float_compare(available_qty_owner, repair.product_qty, precision_digits=precision) >= 0:
owner_id = repair.partner_id.id
moves = self.env['stock.move']
for operation in repair.operations:
move = Move.create({
'name': repair.name,
'product_id': operation.product_id.id,
'product_uom_qty': operation.product_uom_qty,
'product_uom': operation.product_uom.id,
'partner_id': repair.address_id.id,
'location_id': operation.location_id.id,
'location_dest_id': operation.location_dest_id.id,
'repair_id': repair.id,
'origin': repair.name,
'company_id': repair.company_id.id,
})
# Best effort to reserve the product in a (sub)-location where it is available
product_qty = move.product_uom._compute_quantity(
operation.product_uom_qty, move.product_id.uom_id, rounding_method='HALF-UP')
available_quantity = self.env['stock.quant']._get_available_quantity(
move.product_id,
move.location_id,
lot_id=operation.lot_id,
strict=False,
)
move._update_reserved_quantity(
product_qty,
available_quantity,
move.location_id,
lot_id=operation.lot_id,
strict=False,
)
# Then, set the quantity done. If the required quantity was not reserved, negative
# quant is created in operation.location_id.
move._set_quantity_done(operation.product_uom_qty)
if operation.lot_id:
move.move_line_ids.lot_id = operation.lot_id
moves |= move
operation.write({'move_id': move.id, 'state': 'done'})
move = Move.create({
'name': repair.name,
'product_id': repair.product_id.id,
'product_uom': repair.product_uom.id or repair.product_id.uom_id.id,
'product_uom_qty': repair.product_qty,
'partner_id': repair.address_id.id,
'location_id': repair.location_id.id,
'location_dest_id': repair.location_id.id,
'move_line_ids': [(0, 0, {'product_id': repair.product_id.id,
'lot_id': repair.lot_id.id,
'product_uom_qty': 0, # bypass reservation here
'product_uom_id': repair.product_uom.id or repair.product_id.uom_id.id,
'qty_done': repair.product_qty,
'package_id': False,
'result_package_id': False,
'owner_id': owner_id,
'location_id': repair.location_id.id, #TODO: owner stuff
'company_id': repair.company_id.id,
'location_dest_id': repair.location_id.id,})],
'repair_id': repair.id,
'origin': repair.name,
'company_id': repair.company_id.id,
})
consumed_lines = moves.mapped('move_line_ids')
produced_lines = move.move_line_ids
moves |= move
moves._action_done()
produced_lines.write({'consume_line_ids': [(6, 0, consumed_lines.ids)]})
res[repair.id] = move.id
return res
def _check_product_tracking(self):
invalid_lines = self.operations.filtered(lambda x: x.tracking != 'none' and not x.lot_id)
if invalid_lines:
products = invalid_lines.product_id
raise ValidationError(_(
"Serial number is required for operation lines with products: %s",
", ".join(products.mapped('display_name')),
))
class RepairLine(models.Model):
_name = 'repair.line'
_description = 'Repair Line (parts)'
name = fields.Text('Description', required=True)
repair_id = fields.Many2one(
'repair.order', 'Repair Order Reference', required=True,
index=True, ondelete='cascade', check_company=True)
company_id = fields.Many2one(
related='repair_id.company_id', store=True, index=True)
currency_id = fields.Many2one(
related='repair_id.currency_id')
type = fields.Selection([
('add', 'Add'),
('remove', 'Remove')], 'Type', default='add', required=True)
product_id = fields.Many2one(
'product.product', 'Product', required=True, check_company=True,
domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', company_id), ('company_id', '=', False)]")
invoiced = fields.Boolean('Invoiced', copy=False, readonly=True)
price_unit = fields.Float('Unit Price', required=True, digits='Product Price')
price_subtotal = fields.Float('Subtotal', compute='_compute_price_subtotal', store=True, digits=0)
price_total = fields.Float('Total', compute='_compute_price_total', compute_sudo=True, digits=0)
tax_id = fields.Many2many(
'account.tax', 'repair_operation_line_tax', 'repair_operation_line_id', 'tax_id', 'Taxes',
domain="[('type_tax_use','=','sale'), ('company_id', '=', company_id)]", check_company=True)
product_uom_qty = fields.Float(
'Quantity', default=1.0,
digits='Product Unit of Measure', required=True)
product_uom = fields.Many2one(
'uom.uom', 'Product Unit of Measure',
required=True, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
invoice_line_id = fields.Many2one(
'account.move.line', 'Invoice Line',
copy=False, readonly=True, check_company=True)
location_id = fields.Many2one(
'stock.location', 'Source Location',
index=True, required=True, check_company=True)
location_dest_id = fields.Many2one(
'stock.location', 'Dest. Location',
index=True, required=True, check_company=True)
move_id = fields.Many2one(
'stock.move', 'Inventory Move',
copy=False, readonly=True)
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial',
domain="[('product_id','=', product_id), ('company_id', '=', company_id)]", check_company=True)
state = fields.Selection([
('draft', 'Draft'),
('confirmed', 'Confirmed'),
('done', 'Done'),
('cancel', 'Cancelled')], 'Status', default='draft',
copy=False, readonly=True, required=True,
help='The status of a repair line is set automatically to the one of the linked repair order.')
tracking = fields.Selection(string='Product Tracking', related="product_id.tracking")
@api.depends('price_unit', 'repair_id', 'product_uom_qty', 'product_id', 'repair_id.invoice_method')
def _compute_price_subtotal(self):
for line in self:
taxes = line.tax_id.compute_all(line.price_unit, line.repair_id.pricelist_id.currency_id, line.product_uom_qty, line.product_id, line.repair_id.partner_id)
line.price_subtotal = taxes['total_excluded']
@api.depends('price_unit', 'repair_id', 'product_uom_qty', 'product_id', 'tax_id', 'repair_id.invoice_method')
def _compute_price_total(self):
for line in self:
taxes = line.tax_id.compute_all(line.price_unit, line.repair_id.pricelist_id.currency_id, line.product_uom_qty, line.product_id, line.repair_id.partner_id)
line.price_total = taxes['total_included']
@api.onchange('type')
def onchange_operation_type(self):
""" On change of operation type it sets source location, destination location
and to invoice field.
@param product: Changed operation type.
@param guarantee_limit: Guarantee limit of current record.
@return: Dictionary of values.
"""
if not self.type:
self.location_id = False
self.location_dest_id = False
elif self.type == 'add':
self.onchange_product_id()
args = self.repair_id.company_id and [('company_id', '=', self.repair_id.company_id.id)] or []
warehouse = self.env['stock.warehouse'].search(args, limit=1)
self.location_id = warehouse.lot_stock_id
self.location_dest_id = self.env['stock.location'].search([('usage', '=', 'production'), ('company_id', '=', self.repair_id.company_id.id)], limit=1)
else:
self.price_unit = 0.0
self.tax_id = False
self.location_id = self.env['stock.location'].search([('usage', '=', 'production'), ('company_id', '=', self.repair_id.company_id.id)], limit=1).id
self.location_dest_id = self.env['stock.location'].search([('scrap_location', '=', True), ('company_id', 'in', [self.repair_id.company_id.id, False])], limit=1).id
@api.onchange('repair_id', 'product_id', 'product_uom_qty')
def onchange_product_id(self):
""" On change of product it sets product quantity, tax account, name,
uom of product, unit price and price subtotal. """
if not self.product_id or not self.product_uom_qty:
return
self = self.with_company(self.company_id)
partner = self.repair_id.partner_id
partner_invoice = self.repair_id.partner_invoice_id or partner
if partner:
self = self.with_context(lang=partner.lang)
product = self.product_id
self.name = product.display_name
if product.description_sale:
if partner:
self.name += '\n' + self.product_id.with_context(lang=partner.lang).description_sale
else:
self.name += '\n' + self.product_id.description_sale
self.product_uom = product.uom_id.id
if self.type != 'remove':
if partner:
fpos = self.env['account.fiscal.position'].get_fiscal_position(partner_invoice.id, delivery_id=self.repair_id.address_id.id)
taxes = self.product_id.taxes_id.filtered(lambda x: x.company_id == self.repair_id.company_id)
self.tax_id = fpos.map_tax(taxes)
warning = False
pricelist = self.repair_id.pricelist_id
if not pricelist:
warning = {
'title': _('No pricelist found.'),
'message':
_('You have to select a pricelist in the Repair form !\n Please set one before choosing a product.')}
return {'warning': warning}
else:
self._onchange_product_uom()
@api.onchange('product_uom')
def _onchange_product_uom(self):
partner = self.repair_id.partner_id
pricelist = self.repair_id.pricelist_id
if pricelist and self.product_id and self.type != 'remove':
price = pricelist.get_product_price(self.product_id, self.product_uom_qty, partner, uom_id=self.product_uom.id)
if price is False:
warning = {
'title': _('No valid pricelist line found.'),
'message':
_("Couldn't find a pricelist line matching this product and quantity.\nYou have to change either the product, the quantity or the pricelist.")}
return {'warning': warning}
else:
self.price_unit = price
class RepairFee(models.Model):
_name = 'repair.fee'
_description = 'Repair Fees'
repair_id = fields.Many2one(
'repair.order', 'Repair Order Reference',
index=True, ondelete='cascade', required=True)
company_id = fields.Many2one(
related="repair_id.company_id", index=True, store=True)
currency_id = fields.Many2one(
related="repair_id.currency_id")
name = fields.Text('Description', index=True, required=True)
product_id = fields.Many2one(
'product.product', 'Product', check_company=True,
domain="[('type', '=', 'service'), '|', ('company_id', '=', company_id), ('company_id', '=', False)]")
product_uom_qty = fields.Float('Quantity', digits='Product Unit of Measure', required=True, default=1.0)
price_unit = fields.Float('Unit Price', required=True, digits='Product Price')
product_uom = fields.Many2one('uom.uom', 'Product Unit of Measure', required=True, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
price_subtotal = fields.Float('Subtotal', compute='_compute_price_subtotal', store=True, digits=0)
price_total = fields.Float('Total', compute='_compute_price_total', compute_sudo=True, digits=0)
tax_id = fields.Many2many(
'account.tax', 'repair_fee_line_tax', 'repair_fee_line_id', 'tax_id', 'Taxes',
domain="[('type_tax_use','=','sale'), ('company_id', '=', company_id)]", check_company=True)
invoice_line_id = fields.Many2one('account.move.line', 'Invoice Line', copy=False, readonly=True, check_company=True)
invoiced = fields.Boolean('Invoiced', copy=False, readonly=True)
@api.depends('price_unit', 'repair_id', 'product_uom_qty', 'product_id')
def _compute_price_subtotal(self):
for fee in self:
taxes = fee.tax_id.compute_all(fee.price_unit, fee.repair_id.pricelist_id.currency_id, fee.product_uom_qty, fee.product_id, fee.repair_id.partner_id)
fee.price_subtotal = taxes['total_excluded']
@api.depends('price_unit', 'repair_id', 'product_uom_qty', 'product_id', 'tax_id')
def _compute_price_total(self):
for fee in self:
taxes = fee.tax_id.compute_all(fee.price_unit, fee.repair_id.pricelist_id.currency_id, fee.product_uom_qty, fee.product_id, fee.repair_id.partner_id)
fee.price_total = taxes['total_included']
@api.onchange('repair_id', 'product_id', 'product_uom_qty')
def onchange_product_id(self):
""" On change of product it sets product quantity, tax account, name,
uom of product, unit price and price subtotal. """
if not self.product_id:
return
self = self.with_company(self.company_id)
partner = self.repair_id.partner_id
partner_invoice = self.repair_id.partner_invoice_id or partner
pricelist = self.repair_id.pricelist_id
if partner and self.product_id:
fpos = self.env['account.fiscal.position'].get_fiscal_position(partner_invoice.id, delivery_id=self.repair_id.address_id.id)
taxes = self.product_id.taxes_id.filtered(lambda x: x.company_id == self.repair_id.company_id)
self.tax_id = fpos.map_tax(taxes)
if partner:
self.name = self.product_id.with_context(lang=partner.lang).display_name
else:
self.name = self.product_id.display_name
self.product_uom = self.product_id.uom_id.id
if self.product_id.description_sale:
if partner:
self.name += '\n' + self.product_id.with_context(lang=partner.lang).description_sale
else:
self.name += '\n' + self.product_id.description_sale
warning = False
if not pricelist:
warning = {
'title': _('No pricelist found.'),
'message':
_('You have to select a pricelist in the Repair form !\n Please set one before choosing a product.')}
return {'warning': warning}
else:
self._onchange_product_uom()
@api.onchange('product_uom')
def _onchange_product_uom(self):
partner = self.repair_id.partner_id
pricelist = self.repair_id.pricelist_id
if pricelist and self.product_id:
price = pricelist.get_product_price(self.product_id, self.product_uom_qty, partner, uom_id=self.product_uom.id)
if price is False:
warning = {
'title': _('No valid pricelist line found.'),
'message':
_("Couldn't find a pricelist line matching this product and quantity.\nYou have to change either the product, the quantity or the pricelist.")}
return {'warning': warning}
else:
self.price_unit = price
class RepairTags(models.Model):
""" Tags of Repair's tasks """
_name = "repair.tags"
_description = "Repair Tags"
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!"),
]
| 51.065668
| 44,325
|
703
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, fields
class AccountMove(models.Model):
_inherit = 'account.move'
repair_ids = fields.One2many('repair.order', 'invoice_id', readonly=True, copy=False)
def unlink(self):
repairs = self.sudo().repair_ids.filtered(lambda repair: repair.state != 'cancel')
if repairs:
repairs.sudo(False).state = '2binvoiced'
return super().unlink()
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
repair_line_ids = fields.One2many('repair.line', 'invoice_line_id', readonly=True, copy=False)
repair_fee_ids = fields.One2many('repair.fee', 'invoice_line_id', readonly=True, copy=False)
| 31.954545
| 703
|
499
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailComposeMessage(models.TransientModel):
_inherit = 'mail.compose.message'
def _action_send_mail(self, auto_commit=False):
if self.model == 'repair.order':
self = self.with_context(mail_notify_author=self.env.user.partner_id in self.partner_ids)
return super(MailComposeMessage, self)._action_send_mail(auto_commit=auto_commit)
| 38.384615
| 499
|
1,461
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from collections import defaultdict
from odoo import api, fields, models, _
class ProductionLot(models.Model):
_inherit = 'stock.production.lot'
repair_order_ids = fields.Many2many('repair.order', string="Repair Orders", compute="_compute_repair_order_ids")
repair_order_count = fields.Integer('Repair order count', compute="_compute_repair_order_ids")
@api.depends('name')
def _compute_repair_order_ids(self):
repair_orders = defaultdict(lambda: self.env['repair.order'])
for repair_line in self.env['repair.line'].search([('lot_id', 'in', self.ids), ('state', '=', 'done')]):
repair_orders[repair_line.lot_id.id] |= repair_line.repair_id
for lot in self:
lot.repair_order_ids = repair_orders[lot.id]
lot.repair_order_count = len(lot.repair_order_ids)
def action_view_ro(self):
self.ensure_one()
action = {
'res_model': 'repair.order',
'type': 'ir.actions.act_window'
}
if len(self.repair_order_ids) == 1:
action.update({
'view_mode': 'form',
'res_id': self.repair_order_ids[0].id
})
else:
action.update({
'name': _("Repair orders of %s", self.name),
'domain': [('id', 'in', self.repair_order_ids.ids)],
'view_mode': 'tree,form'
})
return action
| 37.461538
| 1,461
|
968
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
class MrpStockReport(models.TransientModel):
_inherit = 'stock.traceability.report'
@api.model
def _get_reference(self, move_line):
res_model, res_id, ref = super(MrpStockReport, self)._get_reference(move_line)
if move_line.move_id.repair_id:
res_model = 'repair.order'
res_id = move_line.move_id.repair_id.id
ref = move_line.move_id.repair_id.name
return res_model, res_id, ref
@api.model
def _get_linked_move_lines(self, move_line):
move_lines, is_used = super(MrpStockReport, self)._get_linked_move_lines(move_line)
if not move_lines:
move_lines = move_line.move_id.repair_id and move_line.consume_line_ids
if not is_used:
is_used = move_line.move_id.repair_id and move_line.produce_line_ids
return move_lines, is_used
| 37.230769
| 968
|
580
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class Product(models.Model):
_inherit = "product.product"
def _count_returned_sn_products(self, sn_lot):
res = self.env['repair.line'].search_count([
('type', '=', 'remove'),
('product_uom_qty', '=', 1),
('lot_id', '=', sn_lot.id),
('state', '=', 'done'),
('location_dest_id.usage', '=', 'internal'),
])
return super()._count_returned_sn_products(sn_lot) + res
| 32.222222
| 580
|
986
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Adyen Payment Acquirer',
'version': '2.0',
'category': 'Accounting/Payment Acquirers',
'sequence': 340,
'summary': 'Payment Acquirer: Adyen Implementation',
'description': """Adyen Payment Acquirer""",
'depends': ['payment'],
'data': [
'views/payment_adyen_templates.xml',
'views/payment_views.xml',
'data/payment_acquirer_data.xml', # Depends on views/payment_adyen_templates.xml
],
'application': True,
'uninstall_hook': 'uninstall_hook',
'assets': {
'web.assets_frontend': [
'https://checkoutshopper-live.adyen.com/checkoutshopper/sdk/4.7.3/adyen.css',
'https://checkoutshopper-live.adyen.com/checkoutshopper/sdk/4.7.3/adyen.js',
'payment_adyen/static/src/js/payment_form.js',
'payment_adyen/static/src/scss/dropin.scss',
],
},
'license': 'LGPL-3',
}
| 36.518519
| 986
|
4,539
|
py
|
PYTHON
|
15.0
|
import re
from odoo import _
from odoo.exceptions import UserError
from odoo.addons.payment import utils as payment_utils
def format_partner_name(partner_name):
""" Format the partner name to comply with the payload structure of the API request.
:param str partner_name: The name of the partner making the payment.
:return: The formatted partner name.
:rtype: dict
"""
first_name, last_name = payment_utils.split_partner_name(partner_name)
return {
'firstName': first_name,
'lastName': last_name,
}
def include_partner_addresses(tx_sudo):
""" Include the billing and delivery addresses of the related sales order to the payload of the
API request.
If no related sales order exists, the addresses are not included.
Note: `self.ensure_one()`
:param payment.transaction tx_sudo: The sudoed transaction of the payment.
:return: The subset of the API payload that includes the billing and delivery addresses.
:rtype: dict
"""
tx_sudo.ensure_one()
if 'sale_order_ids' in tx_sudo._fields: # The module `sale` is installed.
order = tx_sudo.sale_order_ids[:1]
if order:
return {
'billingAddress': format_partner_address(order.partner_invoice_id),
'deliveryAddress': format_partner_address(order.partner_shipping_id),
}
return {}
def format_partner_address(partner):
""" Format the partner address to comply with the payload structure of the API request.
:param res.partner partner: The partner making the payment.
:return: The formatted partner address.
:rtype: dict
"""
STREET_FORMAT = '%(street_number)s/%(street_number2)s %(street_name)s'
street_data = split_street_with_params(partner.street, STREET_FORMAT)
return {
'city': partner.city,
'country': partner.country_id.code or 'ZZ', # 'ZZ' if the country is not known.
'stateOrProvince': partner.state_id.code,
'postalCode': partner.zip,
# Fill in the address fields if the format is supported, or fallback to the raw address.
'street': street_data.get('street_name', partner.street),
'houseNumberOrName': street_data.get('street_number'),
}
# The method is copy-pasted from `base_address_extended` with small modifications.
def split_street_with_params(street_raw, street_format):
street_fields = ['street_name', 'street_number', 'street_number2']
vals = {}
previous_pos = 0
field_name = None
# iter on fields in street_format, detected as '%(<field_name>)s'
for re_match in re.finditer(r'%\(\w+\)s', street_format):
field_pos = re_match.start()
if not field_name:
#first iteration: remove the heading chars
street_raw = street_raw[field_pos:]
# get the substring between 2 fields, to be used as separator
separator = street_format[previous_pos:field_pos]
field_value = None
if separator and field_name:
#maxsplit set to 1 to unpack only the first element and let the rest untouched
tmp = street_raw.split(separator, 1)
if previous_greedy in vals:
# attach part before space to preceding greedy field
append_previous, sep, tmp[0] = tmp[0].rpartition(' ')
street_raw = separator.join(tmp)
vals[previous_greedy] += sep + append_previous
if len(tmp) == 2:
field_value, street_raw = tmp
vals[field_name] = field_value
if field_value or not field_name:
previous_greedy = None
if field_name == 'street_name' and separator == ' ':
previous_greedy = field_name
# select next field to find (first pass OR field found)
# [2:-2] is used to remove the extra chars '%(' and ')s'
field_name = re_match.group()[2:-2]
else:
# value not found: keep looking for the same field
pass
if field_name not in street_fields:
raise UserError(_("Unrecognized field %s in street format.", field_name))
previous_pos = re_match.end()
# last field value is what remains in street_raw minus trailing chars in street_format
trailing_chars = street_format[previous_pos:]
if trailing_chars and street_raw.endswith(trailing_chars):
vals[field_name] = street_raw[:-len(trailing_chars)]
else:
vals[field_name] = street_raw
return vals
| 39.815789
| 4,539
|
1,316
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Endpoints of the API.
# See https://docs.adyen.com/api-explorer/#/CheckoutService/v67/overview for Checkout API
# See https://docs.adyen.com/api-explorer/#/Recurring/v49/overview for Recurring API
API_ENDPOINT_VERSIONS = {
'/disable': 49, # Recurring API
'/payments': 67, # Checkout API
'/payments/details': 67, # Checkout API
'/payments/{}/refunds': 67, # Checkout API
'/paymentMethods': 67, # Checkout API
}
# Adyen-specific mapping of currency codes in ISO 4217 format to the number of decimals.
# Only currencies for which Adyen does not follow the ISO 4217 norm are listed here.
# See https://docs.adyen.com/development-resources/currency-codes
CURRENCY_DECIMALS = {
'CLP': 2,
'CVE': 0,
'IDR': 0,
'ISK': 2,
}
# Mapping of transaction states to Adyen result codes.
# See https://docs.adyen.com/checkout/payment-result-codes for the exhaustive list of result codes.
RESULT_CODES_MAPPING = {
'pending': (
'ChallengeShopper', 'IdentifyShopper', 'Pending', 'PresentToShopper', 'Received',
'RedirectShopper'
),
'done': ('Authorised',),
'cancel': ('Cancelled',),
'error': ('Error',),
'refused': ('Refused',),
}
| 37.6
| 1,316
|
745
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.payment.tests.common import PaymentCommon
class AdyenCommon(PaymentCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.adyen = cls._prepare_acquirer('adyen', update_values={
'adyen_merchant_account': 'dummy',
'adyen_api_key': 'dummy',
'adyen_client_key': 'dummy',
'adyen_hmac_key': 'dummy',
'adyen_checkout_api_url': 'https://this.is.an.url',
'adyen_recurring_api_url': 'https://this.is.an.url',
})
# Override default values
cls.acquirer = cls.adyen
| 35.47619
| 745
|
2,754
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.tools import mute_logger
from odoo.addons.payment import utils as payment_utils
from .common import AdyenCommon
@tagged('post_install', '-at_install')
class AdyenForm(AdyenCommon):
def test_processing_values(self):
tx = self.create_transaction(flow='direct')
with mute_logger('odoo.addons.payment.models.payment_transaction'), \
patch(
'odoo.addons.payment.utils.generate_access_token',
new=self._generate_test_access_token
):
processing_values = tx._get_processing_values()
converted_amount = 111111
self.assertEqual(
payment_utils.to_minor_currency_units(self.amount, self.currency),
converted_amount,
)
self.assertEqual(processing_values['converted_amount'], converted_amount)
with patch(
'odoo.addons.payment.utils.generate_access_token', new=self._generate_test_access_token
):
self.assertTrue(payment_utils.check_access_token(
processing_values['access_token'], self.reference, converted_amount, self.partner.id
))
def test_token_activation(self):
"""Activation of disabled adyen tokens is forbidden"""
token = self.create_token(active=False)
with self.assertRaises(UserError):
token._handle_reactivation_request()
@mute_logger('odoo.addons.payment_adyen.models.payment_transaction')
def test_send_refund_request(self):
self.acquirer.support_refund = 'full_only' # Should simply not be False
tx = self.create_transaction(
'redirect', state='done', acquirer_reference='source_reference'
)
tx._reconcile_after_done() # Create the payment
# Send the refund request
with patch(
'odoo.addons.payment_adyen.models.payment_acquirer.PaymentAcquirer._adyen_make_request',
new=lambda *args, **kwargs: {'pspReference': "refund_reference", 'status': "received"}
):
tx._send_refund_request()
refund_tx = self.env['payment.transaction'].search([('source_transaction_id', '=', tx.id)])
self.assertTrue(
refund_tx,
msg="Refunding an Adyen transaction should always create a refund transaction."
)
self.assertNotEqual(
refund_tx.acquirer_reference,
tx.acquirer_reference,
msg="The acquirer reference of the refund transaction should different from that of "
"the source transaction."
)
| 39.342857
| 2,754
|
12,583
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.addons.payment import utils as payment_utils
from odoo.addons.payment_adyen import utils as adyen_utils
from odoo.addons.payment_adyen.const import CURRENCY_DECIMALS, RESULT_CODES_MAPPING
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
#=== BUSINESS METHODS ===#
def _get_specific_processing_values(self, processing_values):
""" Override of payment to return Adyen-specific processing values.
Note: self.ensure_one() from `_get_processing_values`
:param dict processing_values: The generic processing values of the transaction
:return: The dict of acquirer-specific processing values
:rtype: dict
"""
res = super()._get_specific_processing_values(processing_values)
if self.provider != 'adyen':
return res
converted_amount = payment_utils.to_minor_currency_units(
self.amount, self.currency_id, CURRENCY_DECIMALS.get(self.currency_id.name)
)
return {
'converted_amount': converted_amount,
'access_token': payment_utils.generate_access_token(
processing_values['reference'],
converted_amount,
processing_values['partner_id']
)
}
def _send_payment_request(self):
""" Override of payment to send a payment request to Adyen.
Note: self.ensure_one()
:return: None
:raise: UserError if the transaction is not linked to a token
"""
super()._send_payment_request()
if self.provider != 'adyen':
return
# Make the payment request to Adyen
if not self.token_id:
raise UserError("Adyen: " + _("The transaction is not linked to a token."))
converted_amount = payment_utils.to_minor_currency_units(
self.amount, self.currency_id, CURRENCY_DECIMALS.get(self.currency_id.name)
)
data = {
'merchantAccount': self.acquirer_id.adyen_merchant_account,
'amount': {
'value': converted_amount,
'currency': self.currency_id.name,
},
'reference': self.reference,
'paymentMethod': {
'recurringDetailReference': self.token_id.acquirer_ref,
},
'shopperReference': self.token_id.adyen_shopper_reference,
'recurringProcessingModel': 'Subscription',
'shopperIP': payment_utils.get_customer_ip_address(),
'shopperInteraction': 'ContAuth',
'shopperEmail': self.partner_email,
'shopperName': adyen_utils.format_partner_name(self.partner_name),
'telephoneNumber': self.partner_phone,
**adyen_utils.include_partner_addresses(self),
}
response_content = self.acquirer_id._adyen_make_request(
url_field_name='adyen_checkout_api_url',
endpoint='/payments',
payload=data,
method='POST'
)
# Handle the payment request response
_logger.info("payment request response:\n%s", pprint.pformat(response_content))
self._handle_feedback_data('adyen', response_content)
def _send_refund_request(self, amount_to_refund=None, create_refund_transaction=True):
""" Override of payment to send a refund request to Adyen.
Note: self.ensure_one()
:param float amount_to_refund: The amount to refund
:param bool create_refund_transaction: Whether a refund transaction should be created or not
:return: The refund transaction if any
:rtype: recordset of `payment.transaction`
"""
if self.provider != 'adyen':
return super()._send_refund_request(
amount_to_refund=amount_to_refund,
create_refund_transaction=create_refund_transaction
)
refund_tx = super()._send_refund_request(
amount_to_refund=amount_to_refund, create_refund_transaction=True
)
# Make the refund request to Adyen
converted_amount = payment_utils.to_minor_currency_units(
-refund_tx.amount, # The amount is negative for refund transactions
refund_tx.currency_id,
arbitrary_decimal_number=CURRENCY_DECIMALS.get(refund_tx.currency_id.name)
)
data = {
'merchantAccount': self.acquirer_id.adyen_merchant_account,
'amount': {
'value': converted_amount,
'currency': refund_tx.currency_id.name,
},
'reference': refund_tx.reference,
}
response_content = refund_tx.acquirer_id._adyen_make_request(
url_field_name='adyen_checkout_api_url',
endpoint='/payments/{}/refunds',
endpoint_param=self.acquirer_reference,
payload=data,
method='POST'
)
_logger.info("refund request response:\n%s", pprint.pformat(response_content))
# Handle the refund request response
psp_reference = response_content.get('pspReference')
status = response_content.get('status')
if psp_reference and status == 'received':
# The PSP reference associated with this /refunds request is different from the psp
# reference associated with the original payment request.
refund_tx.acquirer_reference = psp_reference
return refund_tx
@api.model
def _get_tx_from_feedback_data(self, provider, data):
""" Override of payment to find the transaction based on Adyen data.
:param str provider: The provider of the acquirer that handled the transaction
:param dict data: The feedback data sent by the provider
:return: The transaction if found
:rtype: recordset of `payment.transaction`
:raise: ValidationError if inconsistent data were received
:raise: ValidationError if the data match no transaction
"""
tx = super()._get_tx_from_feedback_data(provider, data)
if provider != 'adyen':
return tx
reference = data.get('merchantReference')
if not reference:
raise ValidationError("Adyen: " + _("Received data with missing merchant reference"))
event_code = data.get('eventCode')
tx = self.search([('reference', '=', reference), ('provider', '=', 'adyen')])
if event_code == 'REFUND' and (not tx or tx.operation != 'refund'):
# If a refund is initiated from Adyen, the merchant reference can be personalized. We
# need to get the source transaction and manually create the refund transaction.
source_acquirer_reference = data.get('originalReference')
source_tx = self.search(
[('acquirer_reference', '=', source_acquirer_reference), ('provider', '=', 'adyen')]
)
if source_tx:
# Manually create a refund transaction with a new reference. The reference of
# the refund transaction was personalized from Adyen and could be identical to
# that of an existing transaction.
tx = self._adyen_create_refund_tx_from_feedback_data(source_tx, data)
else: # The refund was initiated for an unknown source transaction
pass # Don't do anything with the refund notification
if not tx:
raise ValidationError(
"Adyen: " + _("No transaction found matching reference %s.", reference)
)
return tx
def _adyen_create_refund_tx_from_feedback_data(self, source_tx, data):
""" Create a refund transaction based on Adyen data.
:param recordset source_tx: The source transaction for which a refund is initiated, as a
`payment.transaction` recordset
:param dict data: The feedback data sent by the provider
:return: The created refund transaction
:rtype: recordset of `payment.transaction`
:raise: ValidationError if inconsistent data were received
"""
refund_acquirer_reference = data.get('pspReference')
amount_to_refund = data.get('amount', {}).get('value')
if not refund_acquirer_reference or not amount_to_refund:
raise ValidationError(
"Adyen: " + _("Received refund data with missing transaction values")
)
converted_amount = payment_utils.to_major_currency_units(
amount_to_refund, source_tx.currency_id
)
return source_tx._create_refund_transaction(
amount_to_refund=converted_amount, acquirer_reference=refund_acquirer_reference
)
def _process_feedback_data(self, data):
""" Override of payment to process the transaction based on Adyen data.
Note: self.ensure_one()
:param dict data: The feedback data sent by the provider
:return: None
:raise: ValidationError if inconsistent data were received
"""
super()._process_feedback_data(data)
if self.provider != 'adyen':
return
# Handle the acquirer reference
if 'pspReference' in data:
self.acquirer_reference = data.get('pspReference')
# Handle the payment state
payment_state = data.get('resultCode')
refusal_reason = data.get('refusalReason') or data.get('reason')
if not payment_state:
raise ValidationError("Adyen: " + _("Received data with missing payment state."))
if payment_state in RESULT_CODES_MAPPING['pending']:
self._set_pending()
elif payment_state in RESULT_CODES_MAPPING['done']:
has_token_data = 'recurring.recurringDetailReference' in data.get('additionalData', {})
if self.tokenize and has_token_data:
self._adyen_tokenize_from_feedback_data(data)
self._set_done()
if self.operation == 'refund':
self.env.ref('payment.cron_post_process_payment_tx')._trigger()
elif payment_state in RESULT_CODES_MAPPING['cancel']:
_logger.warning("The transaction with reference %s was cancelled (reason: %s)",
self.reference, refusal_reason)
self._set_canceled()
elif payment_state in RESULT_CODES_MAPPING['error']:
_logger.warning("An error occurred on transaction with reference %s (reason: %s)",
self.reference, refusal_reason)
self._set_error(
_("An error occurred during the processing of your payment. Please try again.")
)
elif payment_state in RESULT_CODES_MAPPING['refused']:
_logger.warning("The transaction with reference %s was refused (reason: %s)",
self.reference, refusal_reason)
self._set_error(_("Your payment was refused. Please try again."))
else: # Classify unsupported payment state as `error` tx state
_logger.warning("received data with invalid payment state: %s", payment_state)
self._set_error(
"Adyen: " + _("Received data with invalid payment state: %s", payment_state)
)
def _adyen_tokenize_from_feedback_data(self, data):
""" Create a new token based on the feedback data.
Note: self.ensure_one()
:param dict data: The feedback data sent by the provider
:return: None
"""
self.ensure_one()
token = self.env['payment.token'].create({
'acquirer_id': self.acquirer_id.id,
'name': payment_utils.build_token_name(data['additionalData'].get('cardSummary')),
'partner_id': self.partner_id.id,
'acquirer_ref': data['additionalData']['recurring.recurringDetailReference'],
'adyen_shopper_reference': data['additionalData']['recurring.shopperReference'],
'verified': True, # The payment is authorized, so the payment method is valid
})
self.write({
'token_id': token,
'tokenize': False,
})
_logger.info(
"created token with id %s for partner with id %s", token.id, self.partner_id.id
)
| 43.539792
| 12,583
|
1,766
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, fields, models
from odoo.exceptions import UserError, ValidationError
class PaymentToken(models.Model):
_inherit = 'payment.token'
adyen_shopper_reference = fields.Char(
string="Shopper Reference", help="The unique reference of the partner owning this token",
readonly=True)
#=== BUSINESS METHODS ===#
def _handle_deactivation_request(self):
""" Override of payment to request request Adyen to delete the token.
Note: self.ensure_one()
:return: None
"""
super()._handle_deactivation_request()
if self.provider != 'adyen':
return
data = {
'merchantAccount': self.acquirer_id.adyen_merchant_account,
'shopperReference': self.adyen_shopper_reference,
'recurringDetailReference': self.acquirer_ref,
}
try:
self.acquirer_id._adyen_make_request(
url_field_name='adyen_recurring_api_url',
endpoint='/disable',
payload=data,
method='POST'
)
except ValidationError:
pass # Deactivating the token in Odoo is more important than in Adyen
def _handle_reactivation_request(self):
""" Override of payment to raise an error informing that Adyen tokens cannot be restored.
Note: self.ensure_one()
:return: None
:raise: UserError if the token is managed by Adyen
"""
super()._handle_reactivation_request()
if self.provider != 'adyen':
return
raise UserError(_("Saved payment methods cannot be restored once they have been deleted."))
| 32.703704
| 1,766
|
428
|
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['adyen'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]}
return res
| 30.571429
| 428
|
5,878
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import re
import requests
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.addons.payment_adyen.const import API_ENDPOINT_VERSIONS
_logger = logging.getLogger(__name__)
class PaymentAcquirer(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(
selection_add=[('adyen', "Adyen")], ondelete={'adyen': 'set default'})
adyen_merchant_account = fields.Char(
string="Merchant Account",
help="The code of the merchant account to use with this acquirer",
required_if_provider='adyen', groups='base.group_system')
adyen_api_key = fields.Char(
string="API Key", help="The API key of the webservice user", required_if_provider='adyen',
groups='base.group_system')
adyen_client_key = fields.Char(
string="Client Key", help="The client key of the webservice user",
required_if_provider='adyen')
adyen_hmac_key = fields.Char(
string="HMAC Key", help="The HMAC key of the webhook", required_if_provider='adyen',
groups='base.group_system')
adyen_checkout_api_url = fields.Char(
string="Checkout API URL", help="The base URL for the Checkout API endpoints",
required_if_provider='adyen')
adyen_recurring_api_url = fields.Char(
string="Recurring API URL", help="The base URL for the Recurring API endpoints",
required_if_provider='adyen')
#=== CRUD METHODS ===#
@api.model_create_multi
def create(self, values_list):
for values in values_list:
self._adyen_trim_api_urls(values)
return super().create(values_list)
def write(self, values):
self._adyen_trim_api_urls(values)
return super().write(values)
@api.model
def _adyen_trim_api_urls(self, values):
""" Remove the version and the endpoint from the url of Adyen API fields.
:param dict values: The create or write values
:return: None
"""
for field_name in ('adyen_checkout_api_url', 'adyen_recurring_api_url'):
if values.get(field_name): # Test the value in case we're duplicating an acquirer
values[field_name] = re.sub(r'[vV]\d+(/.*)?', '', values[field_name])
#=== BUSINESS METHODS ===#
def _adyen_make_request(
self, url_field_name, endpoint, endpoint_param=None, payload=None, method='POST'
):
""" Make a request to Adyen API at the specified endpoint.
Note: self.ensure_one()
:param str url_field_name: The name of the field holding the base URL for the request
:param str endpoint: The endpoint to be reached by the request
:param str endpoint_param: A variable required by some endpoints which are interpolated with
it if provided. For example, the acquirer reference of the source
transaction for the '/payments/{}/refunds' endpoint.
:param dict payload: The payload of the request
:param str method: The HTTP method of the request
:return: The JSON-formatted content of the response
:rtype: dict
:raise: ValidationError if an HTTP error occurs
"""
def _build_url(_base_url, _version, _endpoint):
""" Build an API URL by appending the version and endpoint to a base URL.
The final URL follows this pattern: `<_base>/V<_version>/<_endpoint>`.
:param str _base_url: The base of the url prefixed with `https://`
:param int _version: The version of the endpoint
:param str _endpoint: The endpoint of the URL.
:return: The final URL
:rtype: str
"""
_base = _base_url.rstrip('/') # Remove potential trailing slash
_endpoint = _endpoint.lstrip('/') # Remove potential leading slash
return f'{_base}/V{_version}/{_endpoint}'
self.ensure_one()
base_url = self[url_field_name] # Restrict request URL to the stored API URL fields
version = API_ENDPOINT_VERSIONS[endpoint]
endpoint = endpoint if not endpoint_param else endpoint.format(endpoint_param)
url = _build_url(base_url, version, endpoint)
headers = {'X-API-Key': self.adyen_api_key}
try:
response = requests.request(method, url, json=payload, headers=headers, timeout=60)
response.raise_for_status()
except requests.exceptions.ConnectionError:
_logger.exception("unable to reach endpoint at %s", url)
raise ValidationError("Adyen: " + _("Could not establish the connection to the API."))
except requests.exceptions.HTTPError as error:
_logger.exception(
"invalid API request at %s with data %s: %s", url, payload, error.response.text
)
raise ValidationError("Adyen: " + _("The communication with the API failed."))
return response.json()
def _adyen_compute_shopper_reference(self, partner_id):
""" Compute a unique reference of the partner for Adyen.
This is used for the `shopperReference` field in communications with Adyen and stored in the
`adyen_shopper_reference` field on `payment.token` if the payment method is tokenized.
:param recordset partner_id: The partner making the transaction, as a `res.partner` id
:return: The unique reference for the partner
:rtype: str
"""
return f'ODOO_PARTNER_{partner_id}'
def _get_default_payment_method_id(self):
self.ensure_one()
if self.provider != 'adyen':
return super()._get_default_payment_method_id()
return self.env.ref('payment_adyen.payment_method_adyen').id
| 43.220588
| 5,878
|
18,045
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import binascii
import hashlib
import hmac
import json
import logging
import pprint
from werkzeug import urls
from odoo import _, http
from odoo.exceptions import ValidationError
from odoo.http import request
from odoo.tools.pycompat import to_text
from odoo.addons.payment import utils as payment_utils
from odoo.addons.payment_adyen import utils as adyen_utils
from odoo.addons.payment_adyen.const import CURRENCY_DECIMALS
_logger = logging.getLogger(__name__)
class AdyenController(http.Controller):
@http.route('/payment/adyen/acquirer_info', type='json', auth='public')
def adyen_acquirer_info(self, acquirer_id):
""" Return public information on the acquirer.
:param int acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id
:return: Public information on the acquirer, namely: the state and client key
:rtype: str
"""
acquirer_sudo = request.env['payment.acquirer'].sudo().browse(acquirer_id).exists()
return {
'state': acquirer_sudo.state,
'client_key': acquirer_sudo.adyen_client_key,
}
@http.route('/payment/adyen/payment_methods', type='json', auth='public')
def adyen_payment_methods(self, acquirer_id, amount=None, currency_id=None, partner_id=None):
""" Query the available payment methods based on the transaction context.
:param int acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id
:param float amount: The transaction amount
:param int currency_id: The transaction currency, as a `res.currency` id
:param int partner_id: The partner making the transaction, as a `res.partner` id
:return: The JSON-formatted content of the response
:rtype: dict
"""
acquirer_sudo = request.env['payment.acquirer'].sudo().browse(acquirer_id)
currency = request.env['res.currency'].browse(currency_id)
currency_code = currency_id and currency.name
converted_amount = amount and currency_code and payment_utils.to_minor_currency_units(
amount, currency, CURRENCY_DECIMALS.get(currency_code)
)
partner_sudo = partner_id and request.env['res.partner'].sudo().browse(partner_id).exists()
# The lang is taken from the context rather than from the partner because it is not required
# to be logged in to make a payment, and because the lang is not always set on the partner.
# Adyen only supports a limited set of languages but, instead of looking for the closest
# match in https://docs.adyen.com/checkout/components-web/localization-components, we simply
# provide the lang string as is (after adapting the format) and let Adyen find the best fit.
lang_code = (request.context.get('lang') or 'en-US').replace('_', '-')
shopper_reference = partner_sudo and f'ODOO_PARTNER_{partner_sudo.id}'
data = {
'merchantAccount': acquirer_sudo.adyen_merchant_account,
'amount': converted_amount,
'countryCode': partner_sudo.country_id.code or None, # ISO 3166-1 alpha-2 (e.g.: 'BE')
'shopperLocale': lang_code, # IETF language tag (e.g.: 'fr-BE')
'shopperReference': shopper_reference,
'channel': 'Web',
}
response_content = acquirer_sudo._adyen_make_request(
url_field_name='adyen_checkout_api_url',
endpoint='/paymentMethods',
payload=data,
method='POST'
)
_logger.info("paymentMethods request response:\n%s", pprint.pformat(response_content))
return response_content
@http.route('/payment/adyen/payments', type='json', auth='public')
def adyen_payments(
self, acquirer_id, reference, converted_amount, currency_id, partner_id, payment_method,
access_token, browser_info=None
):
""" Make a payment request and process the feedback data.
:param int acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id
:param str reference: The reference of the transaction
:param int converted_amount: The amount of the transaction in minor units of the currency
:param int currency_id: The currency of the transaction, as a `res.currency` id
:param int partner_id: The partner making the transaction, as a `res.partner` id
:param dict payment_method: The details of the payment method used for the transaction
:param str access_token: The access token used to verify the provided values
:param dict browser_info: The browser info to pass to Adyen
:return: The JSON-formatted content of the response
:rtype: dict
"""
# Check that the transaction details have not been altered. This allows preventing users
# from validating transactions by paying less than agreed upon.
if not payment_utils.check_access_token(
access_token, reference, converted_amount, partner_id
):
raise ValidationError("Adyen: " + _("Received tampered payment request data."))
# Make the payment request to Adyen
acquirer_sudo = request.env['payment.acquirer'].sudo().browse(acquirer_id).exists()
tx_sudo = request.env['payment.transaction'].sudo().search([('reference', '=', reference)])
data = {
'merchantAccount': acquirer_sudo.adyen_merchant_account,
'amount': {
'value': converted_amount,
'currency': request.env['res.currency'].browse(currency_id).name, # ISO 4217
},
'reference': reference,
'paymentMethod': payment_method,
'shopperReference': acquirer_sudo._adyen_compute_shopper_reference(partner_id),
'recurringProcessingModel': 'CardOnFile', # Most susceptible to trigger a 3DS check
'shopperIP': payment_utils.get_customer_ip_address(),
'shopperInteraction': 'Ecommerce',
'shopperEmail': tx_sudo.partner_email,
'shopperName': adyen_utils.format_partner_name(tx_sudo.partner_name),
'telephoneNumber': tx_sudo.partner_phone,
'storePaymentMethod': tx_sudo.tokenize, # True by default on Adyen side
'additionalData': {
'allow3DS2': True
},
'channel': 'web', # Required to support 3DS
'origin': acquirer_sudo.get_base_url(), # Required to support 3DS
'browserInfo': browser_info, # Required to support 3DS
'returnUrl': urls.url_join(
acquirer_sudo.get_base_url(),
# Include the reference in the return url to be able to match it after redirection.
# The key 'merchantReference' is chosen on purpose to be the same as that returned
# by the /payments endpoint of Adyen.
f'/payment/adyen/return?merchantReference={reference}'
),
**adyen_utils.include_partner_addresses(tx_sudo),
}
response_content = acquirer_sudo._adyen_make_request(
url_field_name='adyen_checkout_api_url',
endpoint='/payments',
payload=data,
method='POST'
)
# Handle the payment request response
_logger.info("payment request response:\n%s", pprint.pformat(response_content))
request.env['payment.transaction'].sudo()._handle_feedback_data(
'adyen', dict(response_content, merchantReference=reference), # Match the transaction
)
return response_content
@http.route('/payment/adyen/payment_details', type='json', auth='public')
def adyen_payment_details(self, acquirer_id, reference, payment_details):
""" Submit the details of the additional actions and process the feedback data.
The additional actions can have been performed both from the inline form or during a
redirection.
:param int acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id
:param str reference: The reference of the transaction
:param dict payment_details: The details of the additional actions performed for the payment
:return: The JSON-formatted content of the response
:rtype: dict
"""
# Make the payment details request to Adyen
acquirer_sudo = request.env['payment.acquirer'].browse(acquirer_id).sudo()
response_content = acquirer_sudo._adyen_make_request(
url_field_name='adyen_checkout_api_url',
endpoint='/payments/details',
payload=payment_details,
method='POST'
)
# Handle the payment details request response
_logger.info("payment details request response:\n%s", pprint.pformat(response_content))
request.env['payment.transaction'].sudo()._handle_feedback_data(
'adyen', dict(response_content, merchantReference=reference), # Match the transaction
)
return response_content
@http.route('/payment/adyen/return', type='http', auth='public', csrf=False, save_session=False)
def adyen_return_from_redirect(self, **data):
""" Process the data returned by Adyen after redirection.
The route is flagged with `save_session=False` to prevent Odoo from assigning a new session
to the user if they are redirected to this route with a POST request. Indeed, as the session
cookie is created without a `SameSite` attribute, some browsers that don't implement the
recommended default `SameSite=Lax` behavior will not include the cookie in the redirection
request from the payment provider to Odoo. As the redirection to the '/payment/status' page
will satisfy any specification of the `SameSite` attribute, the session of the user will be
retrieved and with it the transaction which will be immediately post-processed.
:param dict data: Feedback data. May include custom params sent to Adyen in the request to
allow matching the transaction when redirected here.
"""
# Retrieve the transaction based on the reference included in the return url
tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_feedback_data(
'adyen', data
)
# Overwrite the operation to force the flow to 'redirect'. This is necessary because even
# thought Adyen is implemented as a direct payment provider, it will redirect the user out
# of Odoo in some cases. For instance, when a 3DS1 authentication is required, or for
# special payment methods that are not handled by the drop-in (e.g. Sofort).
tx_sudo.operation = 'online_redirect'
# Query and process the result of the additional actions that have been performed
_logger.info("handling redirection from Adyen with data:\n%s", pprint.pformat(data))
self.adyen_payment_details(
tx_sudo.acquirer_id.id,
data['merchantReference'],
{
'details': {
'redirectResult': data['redirectResult'],
},
},
)
# Redirect the user to the status page
return request.redirect('/payment/status')
@http.route('/payment/adyen/notification', type='json', auth='public')
def adyen_notification(self):
""" Process the data sent by Adyen to the webhook based on the event code.
See https://docs.adyen.com/development-resources/webhooks/understand-notifications for the
exhaustive list of event codes.
:return: The '[accepted]' string to acknowledge the notification
:rtype: str
"""
data = json.loads(request.httprequest.data)
for notification_item in data['notificationItems']:
notification_data = notification_item['NotificationRequestItem']
# Check the source and integrity of the notification
received_signature = notification_data.get('additionalData', {}).get('hmacSignature')
PaymentTransaction = request.env['payment.transaction']
try:
acquirer_sudo = PaymentTransaction.sudo()._get_tx_from_feedback_data(
'adyen', notification_data
).acquirer_id # Find the acquirer based on the transaction
except ValidationError:
# Warn rather than log the traceback to avoid noise when a POS payment notification
# is received and the corresponding `payment.transaction` record is not found.
_logger.warning("unable to find the transaction; skipping to acknowledge")
else:
if not self._verify_notification_signature(
received_signature, notification_data, acquirer_sudo.adyen_hmac_key
):
continue
# Check whether the event of the notification succeeded and reshape the notification
# data for parsing
_logger.info("notification received:\n%s", pprint.pformat(notification_data))
success = notification_data['success'] == 'true'
event_code = notification_data['eventCode']
if event_code == 'AUTHORISATION' and success:
notification_data['resultCode'] = 'Authorised'
elif event_code == 'CANCELLATION' and success:
notification_data['resultCode'] = 'Cancelled'
elif event_code == 'REFUND':
notification_data['resultCode'] = 'Authorised' if success else 'Error'
else:
continue # Don't handle unsupported event codes and failed events
try:
# Handle the notification data as a regular feedback
PaymentTransaction.sudo()._handle_feedback_data('adyen', notification_data)
except ValidationError: # Acknowledge the notification to avoid getting spammed
_logger.exception(
"unable to handle the notification data;skipping to acknowledge"
)
return '[accepted]' # Acknowledge the notification
def _verify_notification_signature(self, received_signature, payload, hmac_key):
""" Check that the signature computed from the payload matches the received one.
See https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures
:param str received_signature: The signature sent with the notification
:param dict payload: The notification payload
:param str hmac_key: The HMAC key of the acquirer handling the transaction
:return: Whether the signatures match
:rtype: str
"""
def _flatten_dict(_value, _path_base='', _separator='.'):
""" Recursively generate a flat representation of a dict.
:param Object _value: The value to flatten. A dict or an already flat value
:param str _path_base: They base path for keys of _value, including preceding separators
:param str _separator: The string to use as a separator in the key path
"""
if isinstance(_value, dict): # The inner value is a dict, flatten it
_path_base = _path_base if not _path_base else _path_base + _separator
for _key in _value:
yield from _flatten_dict(_value[_key], _path_base + str(_key))
else: # The inner value cannot be flattened, yield it
yield _path_base, _value
def _to_escaped_string(_value):
""" Escape payload values that are using illegal symbols and cast them to string.
String values containing `\\` or `:` are prefixed with `\\`.
Empty values (`None`) are replaced by an empty string.
:param Object _value: The value to escape
:return: The escaped value
:rtype: string
"""
if isinstance(_value, str):
return _value.replace('\\', '\\\\').replace(':', '\\:')
elif _value is None:
return ''
else:
return str(_value)
if not received_signature:
_logger.warning("ignored notification with missing signature")
return False
# Compute the signature from the payload
signature_keys = [
'pspReference', 'originalReference', 'merchantAccountCode', 'merchantReference',
'amount.value', 'amount.currency', 'eventCode', 'success'
]
# Flatten the payload to allow accessing inner dicts naively
flattened_payload = {k: v for k, v in _flatten_dict(payload)}
# Build the list of signature values as per the list of required signature keys
signature_values = [flattened_payload.get(key) for key in signature_keys]
# Escape values using forbidden symbols
escaped_values = [_to_escaped_string(value) for value in signature_values]
# Concatenate values together with ':' as delimiter
signing_string = ':'.join(escaped_values)
# Convert the HMAC key to the binary representation
binary_hmac_key = binascii.a2b_hex(hmac_key.encode('ascii'))
# Calculate the HMAC with the binary representation of the signing string with SHA-256
binary_hmac = hmac.new(binary_hmac_key, signing_string.encode('utf-8'), hashlib.sha256)
# Calculate the signature by encoding the result with Base64
expected_signature = base64.b64encode(binary_hmac.digest())
# Compare signatures
if received_signature != to_text(expected_signature):
_logger.warning("ignored event with invalid signature")
return False
return True
| 51.11898
| 18,045
|
1,518
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": """Indian - E-waybill""",
"version": "1.03.00",
"icon": "/l10n_in/static/description/icon.png",
"category": "Accounting/Localizations/EDI",
"depends": [
"l10n_in_edi",
],
"description": """
Indian - E-waybill
====================================
To submit E-waybill through API to the government.
We use "Tera Software Limited" as GSP
Step 1: First you need to create an API username and password in the E-waybill portal.
Step 2: Switch to company related to that GST number
Step 3: Set that username and password in Odoo (Goto: Invoicing/Accounting -> Configration -> Settings -> Indian Electronic WayBill or find "E-waybill" in search bar)
Step 4: Repeat steps 1,2,3 for all GSTIN you have in odoo. If you have a multi-company with the same GST number then perform step 1 for the first company only.
""",
"data": [
"security/ir.model.access.csv",
"data/account_edi_data.xml",
"data/ewaybill_type_data.xml",
"views/account_move_views.xml",
"views/edi_pdf_report.xml",
"views/res_config_settings_views.xml",
],
"demo": [
"demo/demo_company.xml",
"demo/res_partner_demo.xml",
"demo/account_invoice_demo.xml",
],
"installable": True,
# not applicable when company is related to service industry so auto install is False
"auto_install": False,
"license": "LGPL-3",
}
| 38.923077
| 1,518
|
4,602
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.l10n_in_edi.tests.test_edi_json import TestEdiJson
from odoo.tests import tagged
@tagged("post_install_l10n", "post_install", "-at_install")
class TestEdiEwaybillJson(TestEdiJson):
def test_edi_json(self):
(self.invoice + self.invoice_full_discount + self.invoice_zero_qty).write({
"l10n_in_type_id": self.env.ref("l10n_in_edi_ewaybill.type_tax_invoice_sub_type_supply"),
"l10n_in_distance": 20,
"l10n_in_mode": "1",
"l10n_in_vehicle_no": "GJ11AA1234",
"l10n_in_vehicle_type": "R",
})
json_value = self.env["account.edi.format"]._l10n_in_edi_ewaybill_generate_json(self.invoice)
expected = {
"supplyType": "O",
"docType": "INV",
"subSupplyType": "1",
"transactionType": 1,
"transDistance": "20",
"transMode": "1",
"vehicleNo": "GJ11AA1234",
"vehicleType": "R",
"docNo": "INV/2019/00001",
"docDate": "01/01/2019",
"fromGstin": "36AABCT1332L011",
"fromTrdName": "company_1_data",
"fromAddr1": "Block no. 401",
"fromAddr2": "Street 2",
"fromPlace": "City 1",
"fromPincode": 500001,
"fromStateCode": 36,
"actFromStateCode": 36,
"toGstin": "36BBBFF5679L8ZR",
"toTrdName": "partner_a",
"toAddr1": "Block no. 401",
"toAddr2": "Street 2",
"toPlace": "City 2",
"toPincode": 500001,
"actToStateCode": 36,
"toStateCode": 36,
"itemList": [
{
"productName": "product_a",
"hsnCode": "01111",
"productDesc": "product_a",
"quantity": 1.0,
"qtyUnit": "UNT",
"taxableAmount": 900.0,
"cgstRate": 2.5,
"sgstRate": 2.5
},
{
"productName": "product_with_cess",
"hsnCode": "02222",
"productDesc": "product_with_cess",
"quantity": 1.0,
"qtyUnit": "UNT",
"taxableAmount": 900.0,
"cgstRate": 6.0,
"sgstRate": 6.0,
"cessRate": 5.0
}
],
"totalValue": 1800.0,
"cgstValue": 76.5,
"sgstValue": 76.5,
"igstValue": 0.0,
"cessValue": 45.0,
"cessNonAdvolValue": 1.59,
"otherValue": 0.0,
"totInvValue": 1999.59
}
self.assertDictEqual(json_value, expected, "Indian EDI send json value is not matched")
#=================================== Full discount test =====================================
json_value = self.env["account.edi.format"]._l10n_in_edi_ewaybill_generate_json(self.invoice_full_discount)
expected.update({
"docNo": "INV/2019/00002",
"itemList": [{
"productName": "product_a", "hsnCode": "01111", "productDesc": "product_a", "quantity": 1.0,
"qtyUnit": "UNT", "taxableAmount": 0.0, "cgstRate": 0.0, "sgstRate": 0.0
}],
"totalValue": 0.0,
"cgstValue": 0.0,
"sgstValue": 0.0,
"igstValue": 0.0,
"cessValue": 0.0,
"cessNonAdvolValue": 0.00,
"otherValue": 0.0,
"totInvValue": 0.0
})
self.assertDictEqual(json_value, expected, "Indian EDI with 100% discount sent json value is not matched")
#=================================== Zero quantity test =============================================
json_value = self.env["account.edi.format"]._l10n_in_edi_ewaybill_generate_json(self.invoice_zero_qty)
expected.update({
"docNo": "INV/2019/00003",
"itemList": [{
"productName": "product_a", "hsnCode": "01111", "productDesc": "product_a", "quantity": 0.0,
"qtyUnit": "UNT", "taxableAmount": 0.0, "cgstRate": 0.0, "sgstRate": 0.0
}],
"totalValue": 0.0,
"cgstValue": 0.0,
"sgstValue": 0.0,
"igstValue": 0.0,
"cessValue": 0.0,
"cessNonAdvolValue": 0.00,
"otherValue": 0.0,
"totInvValue": 0.0
})
self.assertDictEqual(json_value, expected, "Indian EDI with 0(zero) quantity sent json value is not matched")
| 40.017391
| 4,602
|
6,124
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import fields, models, api, _
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
# Transaction Details
l10n_in_type_id = fields.Many2one("l10n.in.ewaybill.type", "E-waybill Document Type", tracking=True)
# transportation details
l10n_in_distance = fields.Integer("Distance", tracking=True)
l10n_in_mode = fields.Selection([
("0", "Managed by Transporter"),
("1", "By Road"),
("2", "Rail"),
("3", "Air"),
("4", "Ship")],
string="Transportation Mode", copy=False, tracking=True)
# Vehicle Number and Type required when transportation mode is By Road.
l10n_in_vehicle_no = fields.Char("Vehicle Number", copy=False, tracking=True)
l10n_in_vehicle_type = fields.Selection([
("R", "Regular"),
("O", "ODC")],
string="Vehicle Type", copy=False, tracking=True)
# Document number and date required in case of transportation mode is Rail, Air or Ship.
l10n_in_transportation_doc_no = fields.Char(
string="E-waybill Document Number",
help="""Transport document number. If it is more than 15 chars, last 15 chars may be entered""",
copy=False, tracking=True)
l10n_in_transportation_doc_date = fields.Date(
string="Document Date",
help="Date on the transporter document",
copy=False,
tracking=True)
# transporter id required when transportation done by other party.
l10n_in_transporter_id = fields.Many2one("res.partner", "Transporter", copy=False, tracking=True)
# show and hide fields base on this
l10n_in_edi_ewaybill_direct_api = fields.Boolean(string="E-waybill(IN) direct API", compute="_compute_l10n_in_edi_ewaybill_direct")
l10n_in_edi_ewaybill_show_send_button = fields.Boolean(string="Show Send E-waybill Button", compute="_compute_l10n_in_edi_ewaybill_show_send_button")
@api.depends('state', 'edi_document_ids', 'edi_document_ids.state')
def _compute_l10n_in_edi_ewaybill_show_send_button(self):
edi_format = self.env.ref('l10n_in_edi_ewaybill.edi_in_ewaybill_json_1_03')
posted_moves = self.filtered(lambda x: x.is_invoice() and x.state == 'posted' and x.country_code == "IN")
for move in posted_moves:
already_sent = move.edi_document_ids.filtered(lambda x: x.edi_format_id == edi_format and x.state in ('sent', 'to_cancel', 'to_send'))
if already_sent:
move.l10n_in_edi_ewaybill_show_send_button = False
else:
move.l10n_in_edi_ewaybill_show_send_button = True
(self - posted_moves).l10n_in_edi_ewaybill_show_send_button = False
@api.depends("l10n_in_gst_treatment")
def _compute_l10n_in_edi_ewaybill_direct(self):
for move in self:
base = self.env["account.edi.format"]._l10n_in_edi_ewaybill_base_irn_or_direct(move)
move.l10n_in_edi_ewaybill_direct_api = base == "direct"
@api.depends("edi_document_ids")
def _compute_l10n_in_edi_show_cancel(self):
super()._compute_l10n_in_edi_show_cancel()
for invoice in self:
if invoice.edi_document_ids.filtered(lambda i: i.edi_format_id.code == "in_ewaybill_1_03" and i.state in ("sent", "to_cancel", "cancelled")):
invoice.l10n_in_edi_show_cancel = True
def _get_l10n_in_edi_ewaybill_response_json(self):
self.ensure_one()
l10n_in_edi = self.edi_document_ids.filtered(lambda i: i.edi_format_id.code == "in_ewaybill_1_03"
and i.state in ("sent", "to_cancel"))
if l10n_in_edi and l10n_in_edi.attachment_id:
return json.loads(l10n_in_edi.attachment_id.raw.decode("utf-8"))
else:
return {}
def button_cancel_posted_moves(self):
"""Mark the edi.document related to this move to be canceled."""
reason_and_remarks_not_set = self.env["account.move"]
for move in self:
send_l10n_in_edi_ewaybill = move.edi_document_ids.filtered(lambda doc: doc.edi_format_id.code == "in_ewaybill_1_03")
# check submitted E-waybill does not have reason and remarks
# because it's needed to cancel E-waybill
if send_l10n_in_edi_ewaybill and (not move.l10n_in_edi_cancel_reason or not move.l10n_in_edi_cancel_remarks):
reason_and_remarks_not_set += move
if reason_and_remarks_not_set:
raise UserError(_(
"To cancel E-waybill set cancel reason and remarks at E-waybill tab in: \n%s",
("\n".join(reason_and_remarks_not_set.mapped("name"))),
))
return super().button_cancel_posted_moves()
def l10n_in_edi_ewaybill_send(self):
edi_format = self.env.ref('l10n_in_edi_ewaybill.edi_in_ewaybill_json_1_03')
edi_document_vals_list = []
for move in self:
if move.state != 'posted':
raise UserError(_("You can only create E-waybill from posted invoice"))
errors = edi_format._check_move_configuration(move)
if errors:
raise UserError(_("Invalid invoice configuration:\n\n%s") % '\n'.join(errors))
existing_edi_document = move.edi_document_ids.filtered(lambda x: x.edi_format_id == edi_format)
if existing_edi_document:
if existing_edi_document.state in ('sent', 'to_cancel'):
raise UserError(_("E-waybill is already created") % '\n'.join(errors))
existing_edi_document.write({
'state': 'to_send',
'attachment_id': False,
})
else:
edi_document_vals_list.append({
'edi_format_id': edi_format.id,
'move_id': move.id,
'state': 'to_send',
})
self.env['account.edi.document'].create(edi_document_vals_list)
self.env.ref('account_edi.ir_cron_edi_network')._trigger()
| 49.788618
| 6,124
|
31,949
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
import json
from datetime import timedelta
from odoo import models, fields, api, _
from odoo.tools import html_escape
from odoo.exceptions import AccessError
from odoo.addons.iap import jsonrpc
from odoo.addons.l10n_in_edi.models.account_edi_format import DEFAULT_IAP_ENDPOINT, DEFAULT_IAP_TEST_ENDPOINT
from .error_codes import ERROR_CODES
import logging
_logger = logging.getLogger(__name__)
class AccountEdiFormat(models.Model):
_inherit = "account.edi.format"
def _l10n_in_edi_ewaybill_base_irn_or_direct(self, move):
"""
There is two type of api call to create E-waybill
1. base on IRN, IRN is number created when we do E-invoice
2. direct call, when E-invoice not aplicable or it"s credit not
"""
if move.move_type == "out_refund":
return "direct"
einvoice_in_edi_format = move.journal_id.edi_format_ids.filtered(lambda f: f.code == "in_einvoice_1_03")
return einvoice_in_edi_format and einvoice_in_edi_format._is_required_for_invoice(move) and "irn" or "direct"
def _is_compatible_with_journal(self, journal):
if self.code == "in_ewaybill_1_03":
return journal.type in ("sale", "purchase")
return super()._is_compatible_with_journal(journal)
def _is_enabled_by_default_on_journal(self, journal):
"""
It's sent with a button action on the invoice so it's disabled by default
"""
self.ensure_one()
if self.code == "in_ewaybill_1_03":
return False
return super()._is_enabled_by_default_on_journal(journal)
def _is_required_for_invoice(self, invoice):
self.ensure_one()
if self.code == "in_ewaybill_1_03":
return invoice.l10n_in_mode and invoice.is_invoice(include_receipts=True)
return super()._is_required_for_invoice(invoice)
def _needs_web_services(self):
self.ensure_one()
return self.code == "in_ewaybill_1_03" or super()._needs_web_services()
def _get_invoice_edi_content(self, move):
if self.code != "in_ewaybill_1_03":
return super()._get_invoice_edi_content(move)
base = self._l10n_in_edi_ewaybill_base_irn_or_direct(move)
if base == "irn":
json_dump = json.dumps(self._l10n_in_edi_irn_ewaybill_generate_json(move))
else:
json_dump = json.dumps(self._l10n_in_edi_ewaybill_generate_json(move))
return json_dump.encode()
def _check_move_configuration(self, move):
if self.code != "in_ewaybill_1_03":
return super()._check_move_configuration(move)
error_message = []
base = self._l10n_in_edi_ewaybill_base_irn_or_direct(move)
if not move.l10n_in_type_id and base == "direct":
error_message.append(_("- Document Type"))
if not move.l10n_in_mode:
error_message.append(_("- Transportation Mode"))
elif move.l10n_in_mode == "0" and not move.l10n_in_transporter_id:
error_message.append(_("- Transporter is required when E-waybill is managed by transporter"))
elif move.l10n_in_mode == "0" and move.l10n_in_transporter_id and not move.l10n_in_transporter_id.vat:
error_message.append(_("- Selected Transporter is missing GSTIN"))
elif move.l10n_in_mode == "1":
if not move.l10n_in_vehicle_no and move.l10n_in_vehicle_type:
error_message.append(_("- Vehicle Number and Type is required when Transportation Mode is By Road"))
elif move.l10n_in_mode in ("2", "3", "4"):
if not move.l10n_in_transportation_doc_no and move.l10n_in_transportation_doc_date:
error_message.append(_("- Transport document number and date is required when Transportation Mode is Rail,Air or Ship"))
if error_message:
error_message.insert(0, _("The following information are missing on the invoice (see eWayBill tab):"))
if base == "irn":
# already checked by E-invoice (l10n_in_edi) so no need to check
return error_message
is_purchase = move.is_purchase_document(include_receipts=True)
error_message += self._l10n_in_validate_partner(move.partner_id)
error_message += self._l10n_in_validate_partner(move.company_id.partner_id, is_company=True)
if not re.match("^.{1,16}$", is_purchase and move.ref or move.name):
error_message.append(_("%s number should be set and not more than 16 characters",
(is_purchase and "Bill Reference" or "Invoice")))
goods_line_is_available = False
for line in move.invoice_line_ids.filtered(lambda line: not (line.display_type or line.is_rounding_line or line.product_id.type == "service")):
goods_line_is_available = True
if line.product_id:
hsn_code = self._l10n_in_edi_extract_digits(line.product_id.l10n_in_hsn_code)
if not hsn_code:
error_message.append(_("HSN code is not set in product %s", line.product_id.name))
elif not re.match("^[0-9]+$", hsn_code):
error_message.append(_(
"Invalid HSN Code (%s) in product %s", hsn_code, line.product_id.name
))
else:
error_message.append(_("product is required to get HSN code"))
if not goods_line_is_available:
error_message.append(_('You need at least one product having "Product Type" as stockable or consumable.'))
if error_message:
error_message.insert(0, _("Impossible to send the Ewaybill."))
return error_message
def _post_invoice_edi(self, invoices):
if self.code != "in_ewaybill_1_03":
return super()._post_invoice_edi(invoices)
base = self._l10n_in_edi_ewaybill_base_irn_or_direct(invoices)
if base == "irn":
return self._l10n_in_edi_ewaybill_irn_post_invoice_edi(invoices)
else:
return self._l10n_in_edi_ewaybill_post_invoice_edi(invoices)
def _cancel_invoice_edi(self, invoices):
if self.code != "in_ewaybill_1_03":
return super()._cancel_invoice_edi(invoices)
response = {}
res = {}
ewaybill_response_json = invoices._get_l10n_in_edi_ewaybill_response_json()
cancel_json = {
"ewbNo": ewaybill_response_json.get("ewayBillNo") or ewaybill_response_json.get("EwbNo"),
"cancelRsnCode": int(invoices.l10n_in_edi_cancel_reason),
"CnlRem": invoices.l10n_in_edi_cancel_remarks,
}
response = self._l10n_in_edi_ewaybill_cancel(invoices.company_id, cancel_json)
if response.get("error"):
error = response["error"]
error_codes = [e.get("code") for e in error]
if "238" in error_codes:
# Invalid token eror then create new token and send generate request again.
# This happen when authenticate called from another odoo instance with same credentials (like. Demo/Test)
authenticate_response = self._l10n_in_edi_ewaybill_authenticate(invoices.company_id)
if not authenticate_response.get("error"):
error = []
response = self._l10n_in_edi_ewaybill_cancel(invoices.company_id, cancel_json)
if response.get("error"):
error = response["error"]
error_codes = [e.get("code") for e in error]
if "312" in error_codes:
# E-waybill is already canceled
# this happens when timeout from the Government portal but IRN is generated
error_message = "<br/>".join(["[%s] %s" % (e.get("code"), html_escape(e.get("message") or self._l10n_in_edi_ewaybill_get_error_message(e.get('code')))) for e in error])
error = []
response = {"data": ""}
odoobot = self.env.ref("base.partner_root")
invoices.message_post(author_id=odoobot.id, body=
"%s<br/>%s:<br/>%s" %(
_("Somehow this E-waybill has been canceled in the government portal before. You can verify by checking the details into the government (https://ewaybillgst.gov.in/Others/EBPrintnew.asp)"),
_("Error"),
error_message
)
)
if "no-credit" in error_codes:
res[invoices] = {
"success": False,
"error": self._l10n_in_edi_get_iap_buy_credits_message(invoices.company_id),
"blocking_level": "error",
}
elif error:
error_message = "<br/>".join(["[%s] %s" % (e.get("code"), html_escape(e.get("message") or self._l10n_in_edi_ewaybill_get_error_message(e.get('code')))) for e in error])
blocking_level = "error"
if "404" in error_codes:
blocking_level = "warning"
res[invoices] = {
"success": False,
"error": error_message,
"blocking_level": blocking_level,
}
if not response.get("error"):
json_dump = json.dumps(response.get("data"))
json_name = "%s_ewaybill_cancel.json" % (invoices.name.replace("/", "_"))
attachment = self.env["ir.attachment"].create({
"name": json_name,
"raw": json_dump.encode(),
"res_model": "account.move",
"res_id": invoices.id,
"mimetype": "application/json",
})
inv_res = {"success": True, "attachment": attachment}
res[invoices] = inv_res
return res
def _l10n_in_edi_ewaybill_irn_post_invoice_edi(self, invoices):
response = {}
res = {}
generate_json = self._l10n_in_edi_irn_ewaybill_generate_json(invoices)
response = self._l10n_in_edi_irn_ewaybill_generate(invoices.company_id, generate_json)
if response.get("error"):
error = response["error"]
error_codes = [e.get("code") for e in error]
if "1005" in error_codes:
# Invalid token eror then create new token and send generate request again.
# This happen when authenticate called from another odoo instance with same credentials (like. Demo/Test)
authenticate_response = self._l10n_in_edi_authenticate(invoices.company_id)
if not authenticate_response.get("error"):
error = []
response = self._l10n_in_edi_irn_ewaybill_generate(invoices.company_id, generate_json)
if response.get("error"):
error = response["error"]
error_codes = [e.get("code") for e in error]
if "4002" in error_codes or "4026" in error_codes:
# Get E-waybill by details in case of IRN is already generated
# this happens when timeout from the Government portal but E-waybill is generated
response = self._l10n_in_edi_irn_ewaybill_get(invoices.company_id, generate_json.get("Irn"))
if not response.get("error"):
error = []
odoobot = self.env.ref("base.partner_root")
invoices.message_post(author_id=odoobot.id, body=
_("Somehow this E-waybill has been generated in the government portal before. You can verify by checking the invoice details into the government (https://ewaybillgst.gov.in/Others/EBPrintnew.asp)")
)
if "no-credit" in error_codes:
res[invoices] = {
"success": False,
"error": self._l10n_in_edi_get_iap_buy_credits_message(invoices.company_id),
"blocking_level": "error",
}
elif error:
error_message = "<br/>".join(["[%s] %s" % (e.get("code"), html_escape(e.get("message") or self._l10n_in_edi_ewaybill_get_error_message(e.get('code')))) for e in error])
blocking_level = "error"
if "404" in error_codes or "waiting" in error_codes:
blocking_level = "warning"
res[invoices] = {
"success": False,
"error": error_message,
"blocking_level": blocking_level,
}
if not response.get("error"):
json_dump = json.dumps(response.get("data"))
json_name = "%s_irn_ewaybill.json" % (invoices.name.replace("/", "_"))
attachment = self.env["ir.attachment"].create({
"name": json_name,
"raw": json_dump.encode(),
"res_model": "account.move",
"res_id": invoices.id,
"mimetype": "application/json",
})
inv_res = {"success": True, "attachment": attachment}
res[invoices] = inv_res
return res
def _l10n_in_edi_irn_ewaybill_generate_json(self, invoice):
json_payload = {
"Irn": invoice._get_l10n_in_edi_response_json().get("Irn"),
"Distance": invoice.l10n_in_distance,
}
if invoice.l10n_in_mode == "0":
json_payload.update({
"TransId": invoice.l10n_in_transporter_id.vat,
"TransName": invoice.l10n_in_transporter_id.name,
})
elif invoice.l10n_in_mode == "1":
json_payload.update({
"TransMode": invoice.l10n_in_mode,
"VehNo": invoice.l10n_in_vehicle_no,
"VehType": invoice.l10n_in_vehicle_type,
})
elif invoice.l10n_in_mode in ("2", "3", "4"):
doc_date = invoice.l10n_in_transportation_doc_date
json_payload.update({
"TransMode": invoice.l10n_in_mode,
"TransDocDt": doc_date and doc_date.strftime("%d/%m/%Y") or False,
"TransDocNo": invoice.l10n_in_transportation_doc_no,
})
return json_payload
def _l10n_in_edi_ewaybill_post_invoice_edi(self, invoices):
response = {}
res = {}
generate_json = self._l10n_in_edi_ewaybill_generate_json(invoices)
response = self._l10n_in_edi_ewaybill_generate(invoices.company_id, generate_json)
if response.get("error"):
error = response["error"]
error_codes = [e.get("code") for e in error]
if "238" in error_codes:
# Invalid token eror then create new token and send generate request again.
# This happen when authenticate called from another odoo instance with same credentials (like. Demo/Test)
authenticate_response = self._l10n_in_edi_ewaybill_authenticate(invoices.company_id)
if not authenticate_response.get("error"):
error = []
response = self._l10n_in_edi_ewaybill_generate(invoices.company_id, generate_json)
if response.get("error"):
error = response["error"]
error_codes = [e.get("code") for e in error]
if "604" in error_codes:
# Get E-waybill by details in case of E-waybill is already generated
# this happens when timeout from the Government portal but E-waybill is generated
response = self._l10n_in_edi_ewaybill_get_by_consigner(
invoices.company_id, generate_json.get("docType"), generate_json.get("docNo"))
if not response.get("error"):
error = []
odoobot = self.env.ref("base.partner_root")
invoices.message_post(author_id=odoobot.id, body=
_("Somehow this E-waybill has been generated in the government portal before. You can verify by checking the invoice details into the government (https://ewaybillgst.gov.in/Others/EBPrintnew.asp)")
)
if "no-credit" in error_codes:
res[invoices] = {
"success": False,
"error": self._l10n_in_edi_get_iap_buy_credits_message(invoices.company_id),
"blocking_level": "error",
}
elif error:
error_message = "<br/>".join(["[%s] %s" % (e.get("code"), html_escape(e.get("message") or self._l10n_in_edi_ewaybill_get_error_message(e.get('code')))) for e in error])
blocking_level = "error"
if "404" in error_codes:
blocking_level = "warning"
res[invoices] = {
"success": False,
"error": error_message,
"blocking_level": blocking_level,
}
if not response.get("error"):
json_dump = json.dumps(response.get("data"))
json_name = "%s_ewaybill.json" % (invoices.name.replace("/", "_"))
attachment = self.env["ir.attachment"].create({
"name": json_name,
"raw": json_dump.encode(),
"res_model": "account.move",
"res_id": invoices.id,
"mimetype": "application/json",
})
inv_res = {"success": True, "attachment": attachment}
res[invoices] = inv_res
return res
def _l10n_in_edi_ewaybill_get_error_message(self, code):
error_message = ERROR_CODES.get(code)
return error_message or _("We don't know the error message for this error code. Please contact support.")
def _get_l10n_in_edi_saler_buyer_party(self, move):
res = super()._get_l10n_in_edi_saler_buyer_party(move)
if move.is_purchase_document(include_receipts=True):
res = {
"seller_details": move.partner_id,
"dispatch_details": move._l10n_in_get_shipping_partner(),
"buyer_details": move.company_id.partner_id,
"ship_to_details": move._l10n_in_get_warehouse_address() or move.company_id.partner_id,
}
return res
def _l10n_in_edi_ewaybill_generate_json(self, invoices):
def get_transaction_type(seller_details, dispatch_details, buyer_details, ship_to_details):
"""
1 - Regular
2 - Bill To - Ship To
3 - Bill From - Dispatch From
4 - Combination of 2 and 3
"""
if seller_details != dispatch_details and buyer_details != ship_to_details:
return 4
elif seller_details != dispatch_details:
return 3
elif buyer_details != ship_to_details:
return 2
else:
return 1
saler_buyer = self._get_l10n_in_edi_saler_buyer_party(invoices)
seller_details = saler_buyer.get("seller_details")
dispatch_details = saler_buyer.get("dispatch_details")
buyer_details = saler_buyer.get("buyer_details")
ship_to_details = saler_buyer.get("ship_to_details")
sign = invoices.is_inbound() and -1 or 1
extract_digits = self._l10n_in_edi_extract_digits
tax_details = self._l10n_in_prepare_edi_tax_details(invoices)
tax_details_by_code = self._get_l10n_in_tax_details_by_line_code(tax_details.get("tax_details", {}))
invoice_line_tax_details = tax_details.get("invoice_line_tax_details")
json_payload = {
"supplyType": invoices.is_purchase_document(include_receipts=True) and "I" or "O",
"subSupplyType": invoices.l10n_in_type_id.sub_type_code,
"docType": invoices.l10n_in_type_id.code,
"transactionType": get_transaction_type(seller_details, dispatch_details, buyer_details, ship_to_details),
"transDistance": str(invoices.l10n_in_distance),
"docNo": invoices.is_purchase_document(include_receipts=True) and invoices.ref or invoices.name,
"docDate": invoices.date.strftime("%d/%m/%Y"),
"fromGstin": seller_details.commercial_partner_id.vat or "URP",
"fromTrdName": seller_details.commercial_partner_id.name,
"fromAddr1": dispatch_details.street or "",
"fromAddr2": dispatch_details.street2 or "",
"fromPlace": dispatch_details.city or "",
"fromPincode": dispatch_details.country_id.code == "IN" and int(extract_digits(dispatch_details.zip)) or "",
"fromStateCode": int(seller_details.state_id.l10n_in_tin) or "",
"actFromStateCode": dispatch_details.state_id.l10n_in_tin and int(dispatch_details.state_id.l10n_in_tin) or "",
"toGstin": buyer_details.commercial_partner_id.vat or "URP",
"toTrdName": buyer_details.commercial_partner_id.name,
"toAddr1": ship_to_details.street or "",
"toAddr2": ship_to_details.street2 or "",
"toPlace": ship_to_details.city or "",
"toPincode": int(extract_digits(ship_to_details.zip)),
"actToStateCode": int(ship_to_details.state_id.l10n_in_tin),
"toStateCode": invoices.l10n_in_state_id.l10n_in_tin and int(invoices.l10n_in_state_id.l10n_in_tin) or (
buyer_details.state_id.l10n_in_tin or int(buyer_details.state_id.l10n_in_tin) or ""
),
"itemList": [
self._get_l10n_in_edi_ewaybill_line_details(line, line_tax_details, sign)
for line, line_tax_details in invoice_line_tax_details.items()
],
"totalValue": self._l10n_in_round_value(tax_details.get("base_amount") * sign),
"cgstValue": self._l10n_in_round_value(tax_details_by_code.get("cgst_amount", 0.00) * sign),
"sgstValue": self._l10n_in_round_value(tax_details_by_code.get("sgst_amount", 0.00) * sign),
"igstValue": self._l10n_in_round_value(tax_details_by_code.get("igst_amount", 0.00) * sign),
"cessValue": self._l10n_in_round_value(tax_details_by_code.get("cess_amount", 0.00) * sign),
"cessNonAdvolValue": self._l10n_in_round_value(tax_details_by_code.get("cess_non_advol_amount", 0.00) * sign),
"otherValue": self._l10n_in_round_value(tax_details_by_code.get("other_amount", 0.00) * sign),
"totInvValue": self._l10n_in_round_value((tax_details.get("base_amount") + tax_details.get("tax_amount")) * sign),
}
is_overseas = invoices.l10n_in_gst_treatment in ("overseas", "special_economic_zone")
if invoices.is_purchase_document(include_receipts=True):
if is_overseas:
json_payload.update({"fromStateCode": 99})
if is_overseas and dispatch_details.state_id.country_id.code != "IN":
json_payload.update({
"actFromStateCode": 99,
"fromPincode": 999999,
})
else:
json_payload.update({
"actFromStateCode": dispatch_details.state_id.l10n_in_tin and int(dispatch_details.state_id.l10n_in_tin) or "",
"fromPincode": int(extract_digits(dispatch_details.zip)),
})
else:
if is_overseas:
json_payload.update({"toStateCode": 99})
if is_overseas and ship_to_details.state_id.country_id.code != "IN":
json_payload.update({
"actToStateCode": 99,
"toPincode": 999999,
})
else:
json_payload.update({
"actToStateCode": int(ship_to_details.state_id.l10n_in_tin),
"toPincode": int(extract_digits(ship_to_details.zip)),
})
if invoices.l10n_in_mode == "0":
json_payload.update({
"transporterId": invoices.l10n_in_transporter_id.vat or "",
"transporterName": invoices.l10n_in_transporter_id.name or "",
})
if invoices.l10n_in_mode in ("2", "3", "4"):
json_payload.update({
"transMode": invoices.l10n_in_mode,
"transDocNo": invoices.l10n_in_transportation_doc_no or "",
"transDocDate": invoices.l10n_in_transportation_doc_date and
invoices.l10n_in_transportation_doc_date.strftime("%d/%m/%Y") or "",
})
if invoices.l10n_in_mode == "1":
json_payload.update({
"transMode": invoices.l10n_in_mode,
"vehicleNo": invoices.l10n_in_vehicle_no or "",
"vehicleType": invoices.l10n_in_vehicle_type or "",
})
return json_payload
def _get_l10n_in_edi_ewaybill_line_details(self, line, line_tax_details, sign):
extract_digits = self._l10n_in_edi_extract_digits
tax_details_by_code = self._get_l10n_in_tax_details_by_line_code(line_tax_details.get("tax_details", {}))
line_details = {
"productName": line.product_id.name,
"hsnCode": extract_digits(line.product_id.l10n_in_hsn_code),
"productDesc": line.name,
"quantity": line.quantity,
"qtyUnit": line.product_id.uom_id.l10n_in_code and line.product_id.uom_id.l10n_in_code.split("-")[0] or "OTH",
"taxableAmount": self._l10n_in_round_value(line.balance * sign),
}
if tax_details_by_code.get("igst_rate") or (line.move_id.l10n_in_state_id.l10n_in_tin != line.company_id.state_id.l10n_in_tin):
line_details.update({"igstRate": self._l10n_in_round_value(tax_details_by_code.get("igst_rate", 0.00))})
else:
line_details.update({
"cgstRate": self._l10n_in_round_value(tax_details_by_code.get("cgst_rate", 0.00)),
"sgstRate": self._l10n_in_round_value(tax_details_by_code.get("sgst_rate", 0.00)),
})
if tax_details_by_code.get("cess_rate"):
line_details.update({"cessRate": self._l10n_in_round_value(tax_details_by_code.get("cess_rate"))})
return line_details
#================================ E-invoice API methods ===========================
@api.model
def _l10n_in_edi_irn_ewaybill_generate(self, company, json_payload):
# IRN is created by E-invoice API call so waiting for it.
if not json_payload.get("Irn"):
return {"error": [{
"code": "waiting",
"message": _("waiting For IRN generation To create E-waybill")}
]}
token = self._l10n_in_edi_get_token(company)
if not token:
return self._l10n_in_edi_no_config_response()
params = {
"auth_token": token,
"json_payload": json_payload,
}
return self._l10n_in_edi_connect_to_server(company, url_path="/iap/l10n_in_edi/1/generate_ewaybill_by_irn", params=params)
@api.model
def _l10n_in_edi_irn_ewaybill_get(self, company, irn):
token = self._l10n_in_edi_get_token(company)
if not token:
return self._l10n_in_edi_no_config_response()
params = {
"auth_token": token,
"irn": irn,
}
return self._l10n_in_edi_connect_to_server(company, url_path="/iap/l10n_in_edi/1/get_ewaybill_by_irn", params=params)
#=============================== E-waybill API methods ===================================
@api.model
def _l10n_in_edi_ewaybill_no_config_response(self):
return {"error": [{
"code": "0",
"message": _(
"Unable to send E-waybill."
"Create an API user in NIC portal, and set it using the top menu: Configuration > Settings."
)}
]}
@api.model
def _l10n_in_edi_ewaybill_check_authentication(self, company):
sudo_company = company.sudo()
if sudo_company.l10n_in_edi_ewaybill_username and sudo_company._l10n_in_edi_ewaybill_token_is_valid():
return True
elif sudo_company.l10n_in_edi_ewaybill_username and sudo_company.l10n_in_edi_ewaybill_password:
authenticate_response = self._l10n_in_edi_ewaybill_authenticate(company)
if not authenticate_response.get("error"):
return True
return False
@api.model
def _l10n_in_edi_ewaybill_connect_to_server(self, company, url_path, params):
user_token = self.env["iap.account"].get("l10n_in_edi")
params.update({
"account_token": user_token.account_token,
"dbuuid": self.env["ir.config_parameter"].sudo().get_param("database.uuid"),
"username": company.sudo().l10n_in_edi_ewaybill_username,
"gstin": company.vat,
})
if company.sudo().l10n_in_edi_production_env:
default_endpoint = DEFAULT_IAP_ENDPOINT
else:
default_endpoint = DEFAULT_IAP_TEST_ENDPOINT
endpoint = self.env["ir.config_parameter"].sudo().get_param("l10n_in_edi_ewaybill.endpoint", default_endpoint)
url = "%s%s" % (endpoint, url_path)
try:
return jsonrpc(url, params=params, timeout=70)
except AccessError as e:
_logger.warning("Connection error: %s", e.args[0])
return {
"error": [{
"code": "access_error",
"message": _("Unable to connect to the E-WayBill service."
"The web service may be temporary down. Please try again in a moment.")
}]
}
@api.model
def _l10n_in_edi_ewaybill_authenticate(self, company):
params = {"password": company.sudo().l10n_in_edi_ewaybill_password}
response = self._l10n_in_edi_ewaybill_connect_to_server(
company, url_path="/iap/l10n_in_edi_ewaybill/1/authenticate", params=params
)
if response and response.get("status_cd") == "1":
company.sudo().l10n_in_edi_ewaybill_auth_validity = fields.Datetime.now() + timedelta(
hours=6, minutes=00, seconds=00)
return response
@api.model
def _l10n_in_edi_ewaybill_generate(self, company, json_payload):
is_authenticated = self._l10n_in_edi_ewaybill_check_authentication(company)
if not is_authenticated:
return self._l10n_in_edi_ewaybill_no_config_response()
params = {"json_payload": json_payload}
return self._l10n_in_edi_ewaybill_connect_to_server(
company, url_path="/iap/l10n_in_edi_ewaybill/1/generate", params=params
)
@api.model
def _l10n_in_edi_ewaybill_cancel(self, company, json_payload):
is_authenticated = self._l10n_in_edi_ewaybill_check_authentication(company)
if not is_authenticated:
return self._l10n_in_edi_ewaybill_no_config_response()
params = {"json_payload": json_payload}
return self._l10n_in_edi_ewaybill_connect_to_server(
company, url_path="/iap/l10n_in_edi_ewaybill/1/cancel", params=params
)
@api.model
def _l10n_in_edi_ewaybill_get_by_consigner(self, company, document_type, document_number):
is_authenticated = self._l10n_in_edi_ewaybill_check_authentication(company)
if not is_authenticated:
return self._l10n_in_edi_ewaybill_no_config_response()
params = {"document_type": document_type, "document_number": document_number}
return self._l10n_in_edi_ewaybill_connect_to_server(
company, url_path="/iap/l10n_in_edi_ewaybill/1/getewaybillgeneratedbyconsigner", params=params
)
| 52.461412
| 31,949
|
761
|
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 ResCompany(models.Model):
_inherit = "res.company"
l10n_in_edi_ewaybill_username = fields.Char("E-Waybill (IN) Username", groups="base.group_system")
l10n_in_edi_ewaybill_password = fields.Char("E-Waybill (IN) Password", groups="base.group_system")
l10n_in_edi_ewaybill_auth_validity = fields.Datetime("E-Waybill (IN) Valid Until", groups="base.group_system")
def _l10n_in_edi_ewaybill_token_is_valid(self):
self.ensure_one()
if self.l10n_in_edi_ewaybill_auth_validity and self.l10n_in_edi_ewaybill_auth_validity > fields.Datetime.now():
return True
return False
| 42.277778
| 761
|
1,171
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, _
from odoo.exceptions import UserError
from odoo.tools import html_escape
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
l10n_in_edi_ewaybill_username = fields.Char("Indian EDI Stock username",
related="company_id.l10n_in_edi_ewaybill_username", readonly=False)
l10n_in_edi_ewaybill_password = fields.Char("Indian EDI Stock password",
related="company_id.l10n_in_edi_ewaybill_password", readonly=False)
def l10n_in_edi_ewaybill_test(self):
response = self.env["account.edi.format"]._l10n_in_edi_ewaybill_authenticate(self.company_id)
if response.get("error") or not self.company_id.sudo()._l10n_in_edi_ewaybill_token_is_valid():
error_message = _("Incorrect username or password, or the GST number on company does not match.")
if response.get("error"):
error_message = "\n".join(["[%s] %s" % (e.get("code"), html_escape(e.get("message"))) for e in response["error"]])
raise UserError(error_message)
| 50.913043
| 1,171
|
1,012
|
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 EWayBillType(models.Model):
_name = "l10n.in.ewaybill.type"
_description = "E-Waybill Document Type"
name = fields.Char("Type")
code = fields.Char("Type Code")
sub_type = fields.Char("Sub-type")
sub_type_code = fields.Char("Sub-type Code")
allowed_supply_type = fields.Selection(
[
("both", "Incoming and Outgoing"),
("out", "Outgoing"),
("in", "Incoming"),
],
string="Allowed for supply type",
)
active = fields.Boolean("Active", default=True)
def name_get(self):
"""Show name and sub_type in name"""
result_dict = dict()
for ewaybill_type in self:
name = ewaybill_type.name
name += _(" (Sub-Type: %s)", ewaybill_type.sub_type)
result_dict[ewaybill_type.id] = name
return list(result_dict.items())
| 31.625
| 1,012
|
21,354
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _lt
ERROR_CODES = {
"100": _lt("Invalid json"),
"101": _lt("Invalid Username"),
"102": _lt("Invalid Password"),
"103": _lt("Invalid Client -Id"),
"104": _lt("Invalid Client -Id"),
"105": _lt("Invalid Token"),
"106": _lt("Token Expired"),
"107": _lt("Authentication failed. Pls. inform the helpdesk"),
"108": _lt("Invalid login credentials."),
"109": _lt("Decryption of data failed"),
"110": _lt("Invalid Client-ID/Client-Secret"),
"111": _lt("GSTIN is not registerd to this GSP"),
"112": _lt("IMEI does not belong to the user"),
"113": _lt("operating-system-type is mandatory in header"),
"114": _lt("Invalid operating-system-type parameter value"),
"201": _lt("Invalid Supply Type"),
"202": _lt("Invalid Sub-supply Type"),
"203": _lt("Sub-transaction type does not belongs to transaction type"),
"204": _lt("Invalid Document type"),
"205": _lt("Document type does not match with transaction & Sub trans type"),
"206": _lt("Invaild Invoice Number"),
"207": _lt("Invalid Invoice Date"),
"208": _lt("Invalid Supplier GSTIN"),
"209": _lt("Blank Supplier Address"),
"210": _lt("Invalid or Blank Supplier PIN Code"),
"211": _lt("Invalid or Blank Supplier state Code"),
"212": _lt("Invalid Consignee GSTIN"),
"213": _lt("Invalid Consignee Address"),
"214": _lt("Invalid Consignee PIN Code"),
"215": _lt("Invalid Consignee State Code"),
"216": _lt("Invalid HSN Code"),
"217": _lt("Invalid UQC Code"),
"218": _lt("Invalid Tax Rate for Intra State Transaction"),
"219": _lt("Invalid Tax Rate for Inter State Transaction"),
"220": _lt("Invalid Trans mode"),
"221": _lt("Invalid Approximate Distance"),
"222": _lt("Invalid Transporter Id"),
"223": _lt("Invalid Transaction Document Number"),
"224": _lt("Invalid Transaction Date"),
"225": _lt("Invalid Vehicle Number Format"),
"226": _lt("Both Transaction and Vehicle Number Blank"),
"227": _lt("User Gstin cannot be blank"),
"228": _lt("User id cannot be blank"),
"229": _lt("Supplier name is required"),
"230": _lt("Supplier place is required"),
"231": _lt("Consignee name is required"),
"232": _lt("Consignee place is required"),
"233": _lt("Eway bill does not contains any items"),
"234": _lt("Total amount/Taxable amout is mandatory"),
"235": _lt("Tax rates for Intra state transaction is blank"),
"236": _lt("Tax rates for Inter state transaction is blank"),
"237": _lt("Invalid client -Id/client-secret"),
"238": _lt("Invalid auth token"),
"239": _lt("Invalid action"),
"240": _lt("Could not generate eway bill, pls contact helpdesk"),
"242": _lt("Invalid or Blank Officer StateCode"),
"243": _lt("Invalid or Blank IR Number"),
"244": _lt("Invalid or Blank Actual Vehicle Number Format"),
"245": _lt("Invalid Verification Date Format"),
"246": _lt("Invalid Vehicle Release Date Format"),
"247": _lt("Invalid Verification Time Format"),
"248": _lt("Invalid Vehicle Release Date Format"),
"249": _lt("Actual Value cannot be less than or equal to zero"),
"250": _lt("Invalid Vehicle Release Date Format"),
"251": _lt("CGST nad SGST TaxRate should be same"),
"252": _lt("Invalid CGST Tax Rate"),
"253": _lt("Invalid SGST Tax Rate"),
"254": _lt("Invalid IGST Tax Rate"),
"255": _lt("Invalid CESS Rate"),
"256": _lt("Invalid Cess Non Advol value"),
"278": _lt("User Gstin does not match with Transporter Id"),
"280": _lt("Status is not ACTIVE"),
"281": _lt("Eway Bill is already expired hence update transporter is not allowed."),
"301": _lt("Invalid eway bill number"),
"302": _lt("Invalid transporter mode"),
"303": _lt("Vehicle number is required"),
"304": _lt("Invalid vehicle format"),
"305": _lt("Place from is required"),
"306": _lt("Invalid from state"),
"307": _lt("Invalid reason"),
"308": _lt("Invalid remarks"),
"309": _lt("Could not update vehicle details, pl contact helpdesk"),
"311": _lt("Validity period lapsed, you cannot update vehicle details"),
"312": _lt("This eway bill is either not generated by you or cancelled"),
"313": _lt("Error in validating ewaybill for vehicle updation"),
"315": _lt("Validity period lapsed, you cannot cancel this eway bill"),
"316": _lt("Eway bill is already verified, you cannot cancel it"),
"317": _lt("Could not cancel eway bill, please contact helpdesk"),
"320": _lt("Invalid state to"),
"321": _lt("Invalid place to"),
"322": _lt("Could not generate consolidated eway bill"),
"325": _lt("Could not retrieve data"),
"326": _lt("Could not retrieve GSTIN details for the given GSTIN number"),
"327": _lt("Could not retrieve data from hsn"),
"328": _lt("Could not retrieve transporter details from gstin"),
"329": _lt("Could not retrieve States List"),
"330": _lt("Could not retrieve UQC list"),
"331": _lt("Could not retrieve Error code"),
"334": _lt("Could not retrieve user details by userid "),
"336": _lt("Could not retrieve transporter data by gstin "),
"337": _lt("Could not retrieve HSN details for the given HSN number"),
"338": _lt("You cannot update transporter details, as the current tranporter is already entered Part B details of the eway bill"),
"339": _lt("You are not assigned to update the tranporter details of this eway bill"),
"341": _lt("This e-way bill is generated by you and hence you cannot reject it"),
"342": _lt("You cannot reject this e-way bill as you are not the other party to do so"),
"343": _lt("This e-way bill is cancelled"),
"344": _lt("Invalid eway bill number"),
"345": _lt("Validity period lapsed, you cannot reject the e-way bill"),
"346": _lt("You can reject the e-way bill only within 72 hours from generated time"),
"347": _lt("Validation of eway bill number failed, while rejecting ewaybill"),
"348": _lt("Part-B is not generated for this e-way bill, hence rejection is not allowed."),
"350": _lt("Could not generate consolidated eway bill"),
"351": _lt("Invalid state code"),
"352": _lt("Invalid rfid date"),
"353": _lt("Invalid location code"),
"354": _lt("Invalid rfid number"),
"355": _lt("Invalid Vehicle Number Format"),
"356": _lt("Invalid wt on bridge"),
"357": _lt("Could not retrieve eway bill details, pl. contact helpdesk"),
"358": _lt("GSTIN passed in request header is not matching with the user gstin mentioned in payload JSON"),
"359": _lt("User GSTIN should match to GSTIN(from) for outward transactions"),
"360": _lt("User GSTIN should match to GSTIN(to) for inward transactions"),
"361": _lt("Invalid Vehicle Type"),
"362": _lt("Transporter document date cannot be earlier than the invoice date"),
"363": _lt("E-way bill is not enabled for intra state movement for you state"),
"364": _lt("Error in verifying eway bill"),
"365": _lt("Error in verifying consolidated eway bill"),
"366": _lt("You will not get the ewaybills generated today, howerver you cann access the ewaybills of yester days"),
"367": _lt("Could not retrieve data for officer login"),
"368": _lt("Could not update transporter"),
"369": _lt("GSTIN/Transin passed in request header should match with the transported Id mentioned in payload JSON"),
"370": _lt("GSTIN/Transin passed in request header should not be the same as supplier(fromGSTIN) or recepient(toGSTIN)"),
"371": _lt("Invalid or Blank Supplier Ship-to State Code"),
"372": _lt("Invalid or Blank Consignee Ship-to State Code"),
"373": _lt("The Supplier ship-to state code should be Other Country for Sub Supply Type- Export"),
"374": _lt("The Consignee pin code should be 999999 for Sub Supply Type- Export"),
"375": _lt("The Supplier ship-from state code should be Other Country for Sub Supply Type- Import"),
"376": _lt("The Supplier pin code should be 999999 for Sub Supply Type- Import"),
"377": _lt("Sub Supply Type is mentioned as Others, the description for that is mandatory"),
"378": _lt("The supplier or conginee belong to SEZ, Inter state tax rates are applicable here"),
"379": _lt("Eway Bill can not be extended.. Already Cancelled"),
"380": _lt("Eway Bill Can not be Extended. Not in Active State"),
"381": _lt("There is No PART-B/Vehicle Entry.. So Please Update Vehicle Information.."),
"382": _lt("You Cannot Extend as EWB can be Extended only 8 hour before or after w.r.t Validity of EWB..!!"),
"383": _lt("Error While Extending..Please Contact Helpdesk. "),
"384": _lt("You are not current transporter or Generator of the ewayBill, with no transporter details."),
"385": _lt("For Rail/Ship/Air transDocDate is mandatory"),
"386": _lt("Reason Code, Remarks is mandatory."),
"387": _lt("No Record Found for Entered consolidated eWay bill."),
"388": _lt("Exception in regenration of consolidated eWayBill!!Please Contact helpdesk"),
"389": _lt("Remaining Distance Required"),
"390": _lt("Remaining Distance Can not be greater than Actual Distance."),
"391": _lt("No eway bill of specified tripsheet, neither ACTIVE nor not Valid."),
"392": _lt("Tripsheet is already cancelled, Hence Regeration is not possible"),
"393": _lt("Invalid GSTIN"),
"394": _lt("For other than Road Transport, TransDoc number is required"),
"395": _lt("Eway Bill Number should be numeric only"),
"396": _lt("Either Eway Bill Number Or Consolidated Eway Bill Number is required for Verification"),
"397": _lt("Error in Multi Vehicle Movement Initiation"),
"398": _lt("Eway Bill Item List is Empty"),
"399": _lt("Unit Code is not matching with any of the Unit Code from eway bill ItemList"),
"400": _lt("total quantity is exceeding from multi vehicle movement initiation quantity"),
"401": _lt("Error in inserting multi vehicle details"),
"402": _lt("total quantity can not be less than or equal to zero"),
"403": _lt("Error in multi vehicle details"),
"405": _lt("No record found for multi vehicle update with specified ewbNo groupNo and old vehicleNo/transDocNo with status as ACT"),
"406": _lt("Group number cannot be empty or zero"),
"407": _lt("Invalid old vehicle number format"),
"408": _lt("Invalid new vehicle number format"),
"409": _lt("Invalid old transDoc number"),
"410": _lt("Invalid new transDoc number"),
"411": _lt("Multi Vehicle Initiation data is not there for specified ewayBill and group No"),
"412": _lt("Multi Vehicle movement is already Initiated,hence PART B updation not allowed"),
"413": _lt("Unit Code is not matching with unit code of first initiaton"),
"415": _lt("Error in fetching in verification data for officer"),
"416": _lt("Date range is exceeding allowed date range "),
"417": _lt("No verification data found for officer "),
"418": _lt("No record found"),
"419": _lt("Error in fetching search result for taxpayer/transporter"),
"420": _lt("Minimum six character required for Tradename/legalname search"),
"421": _lt("Invalid pincode"),
"422": _lt("Invalid mobile number"),
"423": _lt("Error in fetching ewaybill list by vehicle number"),
"424": _lt("Invalid PAN number"),
"425": _lt("Error in fetching Part A data by IR Number"),
"426": _lt("For Vehicle Released vehicle release date and time is mandatory"),
"427": _lt("Error in saving Part-A verification Report"),
"428": _lt("For Goods Detained,Vehicle Released feild is mandatory"),
"429": _lt("Error in saving Part-B verification Report"),
"430": _lt("Goods Detained Field required."),
"431": _lt("Part-A for this ewaybill is already generated by you."),
"432": _lt("invalid vehicle released value"),
"433": _lt("invalid goods detained parameter value"),
"434": _lt("invalid ewbNoAvailable parameter value"),
"435": _lt("Part B is already updated,hence updation is not allowed"),
"436": _lt("Invalid Consignee ship to State Code for the given pincode"),
"437": _lt("Invalid Supplier ship from State Code for the given pincode"),
"438": _lt("Invalid Latitude"),
"439": _lt("Invalid Longitude"),
"440": _lt("Error in inserting in verification data"),
"441": _lt("Invalid verification type"),
"442": _lt("Error in inserting verification details"),
"443": _lt("invalid invoice available value"),
"600": _lt("Invalid category"),
"601": _lt("Invalid date format"),
"602": _lt("Invalid File Number"),
"603": _lt("For file details file number is required"),
"604": _lt("E-way bill(s) are already generated for the same document number, you cannot generate again on same document number"),
"607": _lt("dispatch from gstin is mandatary "),
"608": _lt("ship to from gstin is mandatary"),
"609": _lt(" invalid ship to from gstin "),
"610": _lt("invalid dispatch from gstin "),
"611": _lt("invalid document type for the given supply type "),
"612": _lt("Invalid transaction type"),
"613": _lt("Exception in getting Officer Role"),
"614": _lt("Transaction type is mandatory"),
"615": _lt("Dispatch From GSTIN cannot be sent as the transaction type selected is Regular"),
"616": _lt("Ship to GSTIN cannot be sent as the transaction type selected is Regular"),
"617": _lt("Bill-from and dispatch-from gstin should not be same for this transaction type"),
"618": _lt("Bill-to and ship-to gstin should not be same for this transaction type"),
"619": _lt("Transporter Id is mandatory for generation of Part A slip"),
"620": _lt("Total invoice value cannot be less than the sum of total assessible value and tax values"),
"621": _lt("Transport mode is mandatory since vehicle number is present"),
"622": _lt("Transport mode is mandatory since transport document number is present"),
"623": _lt("IGST value is not applicable for Intra State Transaction"),
"624": _lt("CGST/SGST value is not applicable for Inter State Transaction"),
"627": _lt("Total value should not be negative"),
"628": _lt("Total invoice value should not be negative"),
"629": _lt("IGST value should not be negative"),
"630": _lt("CGST value should not be negative"),
"631": _lt("SGST value should not be negative"),
"632": _lt("Cess value should not be negative"),
"633": _lt("Cess non advol should not be negative"),
"634": _lt("Vehicle type should not be ODC when transmode is other than road"),
"635": _lt("You cannot update part B, as the current tranporter is already entered Part B details of the eway bill"),
"636": _lt("You are not assigned to update part B"),
"637": _lt("You cannot extend ewaybill, as the current tranporter is already entered Part B details of the ewaybill"),
"638": _lt("Transport mode is mandatory as Vehicle Number/Transport Document Number is given"),
"640": _lt("Tolal Invoice value is mandatory"),
"641": _lt("For outward CKD/SKD/Lots supply type, Bill To state should be as Other Country, since the Bill To GSTIN given is of SEZ unit"),
"642": _lt("For inward CKD/SKD/Lots supply type, Bill From state should be as Other Country, since the Bill From GSTIN given is of SEZ unit"),
"643": _lt("For regular transaction, Bill from state code and Dispatch from state code should be same"),
"644": _lt("For regular transaction, Bill to state code and Ship to state code should be same"),
"645": _lt("You cannot do multivehicle movement, as the current tranporter is already entered Part B details of the ewaybill"),
"646": _lt("You are not assigned to do MultiVehicle Movement"),
"647": _lt("Could not insert RFID data, pl. contact helpdisk"),
"648": _lt("Multi Vehicle movement is already Initiated,hence generation of consolidated eway bill is not allowed"),
"649": _lt("You cannot generate consolidated eway bill , as the current tranporter is already entered Part B details of the eway bill"),
"650": _lt("You are not assigned to generate consolidated ewaybill"),
"651": _lt("For Category Part-A or Part-B ewbdt is mandatory"),
"652": _lt("For Category EWB03 procdt is mandatory"),
"654": _lt("This GSTIN has generated a common Enrolment Number. Hence you are not allowed to generate Eway bill"),
"655": _lt("This GSTIN has generated a common Enrolment Number. Hence you cannot mention it as a tranporter"),
"656": _lt("This Eway Bill does not belongs to your state"),
"657": _lt("Eway Bill Category wise details will be available after 4 days only"),
"658": _lt("You are blocked for accesing this API as the allowed number of requests has been exceeded for this duration"),
"659": _lt("Remarks is mandatory"),
"670": _lt("Invalid Month Parameter"),
"671": _lt("Invalid Year Parameter"),
"672": _lt("User Id is mandatory"),
"673": _lt("Error in getting officer dashboard"),
"675": _lt("Error in getting EWB03 details by acknowledgement date range"),
"676": _lt("Error in getting EWB Not Available List by entered date range"),
"677": _lt("Error in getting EWB Not Available List by closed date range"),
"678": _lt("Invalid Uniq No"),
"679": _lt("Invalid EWB03 Ack No"),
"680": _lt("Invalid Close Reason"),
"681": _lt("Error in Closing EWB Verification Data"),
"682": _lt("No Record available to Close"),
"683": _lt("Error in fetching WatchList Data"),
"685": _lt("Exception in fetching dashboard data"),
"700": _lt("You are not assigned to extend e-waybill"),
"701": _lt("Invalid Vehicle Direction"),
"702": _lt("The distance between the pincodes given is too high"),
"703": _lt("Since the consignor is Composite Taxpayer, inter state transactions are not allowed"),
"704": _lt("Since the consignor is Composite Taxpayer, Tax rates should be zero"),
"705": _lt("Invalid transit type"),
"706": _lt("Address Line1 is mandatory"),
"707": _lt("Address Line2 is mandatory"),
"708": _lt("Address Line3 is mandatory"),
"709": _lt("Pin to pin distance is not available for the given pin codes"),
"710": _lt("Invalid state code for the given pincode"),
"711": _lt("Invalid consignment status for the given transmode"),
"712": _lt("Transit Type is not required as the goods are in movement"),
"713": _lt("Transit Address is not required as the goods are in movement"),
"714": _lt("Document type - Tax Invoice is not allowed for composite tax payer"),
"715": _lt("The Consignor GSTIN is blocked from e-waybill generation as Return is not filed for past 2 months"),
"716": _lt("The Consignee GSTIN is blocked from e-waybill generation as Return is not filed for past 2 months"),
"717": _lt("The Transporter GSTIN is blocked from e-waybill generation as Return is not filed for past 2 months"),
"718": _lt("The User GSTIN is blocked from Transporter Updation as Return is not filed for past 2 months"),
"719": _lt("The Transporter GSTIN is blocked from Transporter Updation as Return is not filed for past 2 months"),
"720": _lt("E Way Bill should be generated as part of IRN generation or with reference to IRN in E Invoice System, Since Supplier is enabled for E Invoice."),
"721": _lt("The distance between the given pincodes are not available in the system. Please provide distance."),
"722": _lt("Consignee GSTIN is cancelled and document date is later than the De-Registration date"),
"724": _lt("HSN code of at least one item should be of goods to generate e-Way Bill"),
"726": _lt("Vehicle type can not be regular when transportation mode is ship"),
"727": _lt("This e-Way Bill does not have Oxygen items"),
"728": _lt("You can cancel the ewaybill within 24 hours from Part B entry"),
"801": _lt("Transporter id is not required for ewaybill for gold"),
"802": _lt("Transporter name is not required for ewaybill for gold"),
"803": _lt("TransDocNo is not required for ewaybill for gold"),
"804": _lt("TransDocDate is not required for ewaybill for gold"),
"805": _lt("Vehicle No is not required for ewaybill for gold"),
"806": _lt("Vehicle Type is not required for ewaybill for gold"),
"807": _lt("Transmode is mandatory for ewaybill for gold"),
"808": _lt("Inter-State ewaybill is not allowed for gold"),
"809": _lt("Other items are not allowed with eway bill for gold"),
"810": _lt("Transport can not be updated for EwayBill For Gold"),
"811": _lt("Vehicle can not be updated for EwayBill For Gold"),
"812": _lt("ConsolidatedEWB cannot be generated for EwayBill For Gold "),
"813": _lt("Duplicate request at the same time"),
"814": _lt("MultiVehicleMovement cannot be initiated for EWay Bill For Gold"),
"815": _lt("Only trans mode road is allowed for Eway Bill For Gold"),
"816": _lt("Only transmode road is allowed for extending ewaybill for gold"),
"817": _lt("MultiVehicleMovement cannot be initiated.Eway Bill is not in Active State"),
"818": _lt("Validity period lapsed.Cannot generate consolidated Eway Bill"),
"819": _lt("Ewaybill cannot be generated for the document date which is prior to 01/07/2017"),
}
| 65.907407
| 21,354
|
790
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Product Availability Notifications',
'category': 'Website/Website',
'summary': 'Notify the user when a product is back in stock',
'description': """
Allow the user to select if he wants to receive email notifications when a product of his wishlist gets back in stock.
""",
'depends': [
'website_sale_stock',
'website_sale_wishlist',
],
'data': [
'views/templates.xml',
'data/template_email.xml',
'data/ir_cron_data.xml',
],
'assets': {
'web.assets_frontend': [
'website_sale_stock_wishlist/static/src/**/*',
],
},
'auto_install': True,
'license': 'LGPL-3',
}
| 29.259259
| 790
|
3,633
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_sale_stock.tests.test_website_sale_stock_product_warehouse import TestWebsiteSaleStockProductWarehouse
class TestWishlistEmail(TestWebsiteSaleStockProductWarehouse):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Create a partner
cls.partner = cls.env['res.partner'].create({
'name': 'John',
'email': 'john@doe.com'
})
# Create the warehouse
warehouse = cls.env['stock.warehouse'].create({
'name': 'Wishlist Warehouse',
'code': 'W_WH'
})
current_website = cls.env['website'].get_current_website()
current_website.warehouse_id = warehouse
cls.warehouse = warehouse
cls.current_website = current_website
# Create two stockable products
cls.product_1 = cls.env['product.product'].create({
'name': 'Product A',
'allow_out_of_stock_order': False,
'type': 'product',
'default_code': 'E-COM1',
})
cls.product_2 = cls.env['product.product'].create({
'name': 'Product B',
'allow_out_of_stock_order': False,
'type': 'product',
'default_code': 'E-COM2',
})
# Pricelist and currency
cls.pricelist = cls.env['product.pricelist'].create({
'name': 'Public Pricelist',
})
cls.currency = cls.env.ref("base.USD")
def test_send_availability_email(self):
"""
For two products in a users wishlist, test that an email is sent
when one is replenished
"""
# Update quantity of Product A
quants = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_1.id,
'inventory_quantity': 10.0,
'location_id': self.warehouse.lot_stock_id.id,
})
quants.action_apply_inventory()
# Only sold out product B wishlist should be registered for
# email notifications
Wishlist = self.env['product.wishlist']
wish_1 = Wishlist._add_to_wishlist(product_id=self.product_1.id, partner_id=self.partner.id, website_id=self.current_website.id, currency_id=self.currency.id, pricelist_id=self.pricelist.id, price=self.product_1.price)
self.assertEqual(wish_1.stock_notification, False)
wish_2 = Wishlist._add_to_wishlist(product_id=self.product_2.id, partner_id=self.partner.id, website_id=self.current_website.id, currency_id=self.currency.id, pricelist_id=self.pricelist.id, price=self.product_2.price)
self.assertEqual(wish_2.stock_notification, True)
# No email should be sent
Wishlist._send_availability_email()
emails = self.env['mail.mail'].search([('email_to', '=', self.partner.email)])
self.assertEqual(len(emails), 0)
# Replenish Product B
quants = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_2.id,
'inventory_quantity': 10.0,
'location_id': self.warehouse.lot_stock_id.id,
})
quants.action_apply_inventory()
# An email should be sent for Product B
Wishlist._send_availability_email()
emails = self.env['mail.mail'].search([('email_to', '=', self.partner.email_formatted)])
self.assertEqual(emails[0].subject, "The product 'Product B' is now available")
self.assertEqual(wish_2.stock_notification, False)
| 41.758621
| 3,633
|
1,012
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ProductTemplate(models.Model):
_inherit = "product.template"
def _get_combination_info(self, combination=False, product_id=False, add_qty=1, pricelist=False, parent_combination=False, only_template=False):
combination_info = super(ProductTemplate, self)._get_combination_info(
combination=combination,
product_id=product_id,
add_qty=add_qty,
pricelist=pricelist,
parent_combination=parent_combination,
only_template=only_template,
)
if not self.env.context.get('website_sale_stock_wishlist_get_wish'):
return combination_info
if combination_info['product_id']:
product = self.env['product.product'].sudo().browse(combination_info["product_id"])
combination_info['wish'] = product._is_in_wishlist()
return combination_info
| 40.48
| 1,012
|
2,318
|
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 ProductWishlist(models.Model):
_inherit = "product.wishlist"
stock_notification = fields.Boolean(default=False, required=True)
def _add_to_wishlist(self, pricelist_id, currency_id, website_id, price, product_id, partner_id=False):
wish = super()._add_to_wishlist(
pricelist_id=pricelist_id,
currency_id=currency_id,
website_id=website_id,
price=price,
product_id=product_id,
partner_id=partner_id,
)
wish['stock_notification'] = wish.product_id._is_sold_out()
return wish
def _send_availability_email(self):
to_notify = self.env['product.wishlist'].search([('stock_notification', '=', True)])
if not to_notify:
return
notified = self.env['product.wishlist']
# cannot group by product_id because it depend of website_id -> warehouse_id
tmpl = self.env.ref("website_sale_stock_wishlist.availability_email_body")
for wishlist in to_notify:
product = wishlist.with_context(website_id=wishlist.website_id.id).product_id
if not product._is_sold_out():
body_html = tmpl._render({"wishlist": wishlist})
msg = self.env["mail.message"].sudo().new(dict(body=body_html, record_name=product.name))
full_mail = self.env["mail.render.mixin"]._render_encapsulate(
"mail.mail_notification_light",
body_html,
add_context=dict(message=msg, model_description=_("Wishlist")),
)
mail_values = {
"subject": _("The product '%(product_name)s' is now available") % {'product_name': product.name},
"email_from": (product.company_id.partner_id or self.env.user).email_formatted,
"email_to": wishlist.partner_id.email_formatted,
"body_html": full_mail,
}
mail = self.env["mail.mail"].sudo().create(mail_values)
mail.send(raise_exception=False)
notified += wishlist
notified.stock_notification = False
| 42.925926
| 2,318
|
574
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo.addons.website_sale.controllers.main import WebsiteSale
class WebsiteSaleStockWishlist(WebsiteSale):
@http.route(['/shop/wishlist/notify/<model("product.wishlist"):wish>'], type='json', auth="public", website=True)
def notify_stock(self, wish, notify=True, **kw):
if not request.website.is_public_user():
wish['stock_notification'] = notify
return wish['stock_notification']
| 44.153846
| 574
|
643
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.addons.website_sale.controllers.variant import WebsiteSaleVariantController
class WebsiteSaleStockWishlistVariantController(WebsiteSaleVariantController):
@http.route()
def get_combination_info_website(self, product_template_id, product_id, combination, add_qty, **kw):
kw['context'] = kw.get('context', {})
kw['context'].update(website_sale_stock_wishlist_get_wish=True)
return super().get_combination_info_website(product_template_id, product_id, combination, add_qty, **kw)
| 49.461538
| 643
|
926
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name' : 'Import/Export Invoices From XML/PDF',
'description':"""
Electronic Data Interchange
=======================================
EDI is the electronic interchange of business information using a standardized format.
This is the base module for import and export of invoices in various EDI formats, and the
the transmission of said documents to various parties involved in the exchange (other company,
governements, etc.)
""",
'version' : '1.0',
'category': 'Accounting/Accounting',
'depends' : ['account'],
'data': [
'security/ir.model.access.csv',
'views/account_edi_document_views.xml',
'views/account_move_views.xml',
'views/account_payment_views.xml',
'views/account_journal_views.xml',
'data/cron.xml'
],
'installable': True,
'application': False,
'auto_install': True,
'license': 'LGPL-3',
}
| 33.071429
| 926
|
11,729
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo.addons.account_edi.tests.common import AccountEdiTestCommon, _mocked_post_two_steps, _generate_mocked_needs_web_services, _mocked_cancel_failed, _generate_mocked_support_batching
from unittest.mock import patch
from odoo.addons.base.tests.test_ir_cron import CronMixinCase
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestAccountEdi(AccountEdiTestCommon, CronMixinCase):
@classmethod
def setUpClass(cls, chart_template_ref=None, edi_format_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref)
cls.invoice = cls.init_invoice('out_invoice', products=cls.product_a + cls.product_b)
def test_export_edi(self):
self.assertEqual(len(self.invoice.edi_document_ids), 0)
self.invoice.action_post()
self.assertEqual(len(self.invoice.edi_document_ids), 1)
def test_prepare_jobs(self):
edi_docs = self.env['account.edi.document']
edi_docs |= self.create_edi_document(self.edi_format, 'to_send')
edi_docs |= self.create_edi_document(self.edi_format, 'to_send')
to_process = edi_docs._prepare_jobs()
self.assertEqual(len(to_process), 2)
with patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._support_batching', return_value=True):
to_process = edi_docs._prepare_jobs()
self.assertEqual(len(to_process), 1)
other_edi = self.env['account.edi.format'].sudo().create({
'name': 'Batchable EDI format 2',
'code': 'test_batch_edi_2',
})
edi_docs |= self.create_edi_document(other_edi, 'to_send')
edi_docs |= self.create_edi_document(other_edi, 'to_send')
with patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._support_batching', return_value=True):
to_process = edi_docs._prepare_jobs()
self.assertEqual(len(to_process), 2)
@patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._post_invoice_edi', return_value={})
def test_warning_is_retried(self, patched):
with patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._needs_web_services',
new=lambda edi_format: True):
edi_docs = self.create_edi_document(self.edi_format, 'to_send')
edi_docs.error = 'Test Error'
edi_docs.blocking_level = 'warning'
edi_docs.move_id.action_process_edi_web_services()
patched.assert_called_once()
def test_edi_flow(self):
with self.mock_edi():
doc = self.invoice._get_edi_document(self.edi_format)
self.assertFalse(doc)
self.invoice.action_post()
doc = self.invoice._get_edi_document(self.edi_format)
self.assertEqual(len(doc), 1)
self.assertEqual(doc.state, 'sent')
self.invoice.button_draft()
self.invoice.button_cancel()
self.assertEqual(doc.state, 'cancelled')
def test_edi_flow_two_steps(self):
with self.mock_edi(_post_invoice_edi_method=_mocked_post_two_steps,
_needs_web_services_method=_generate_mocked_needs_web_services(True)):
doc = self.invoice._get_edi_document(self.edi_format)
self.assertFalse(doc)
self.invoice.action_post()
doc = self.invoice._get_edi_document(self.edi_format)
self.assertEqual(len(doc), 1)
self.assertEqual(doc.state, 'to_send')
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'to_send')
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'sent')
def test_edi_flow_request_cancel_success(self):
with self.mock_edi(_needs_web_services_method=_generate_mocked_needs_web_services(True)):
self.assertEqual(self.invoice.state, 'draft')
self.invoice.action_post()
doc = self.invoice._get_edi_document(self.edi_format)
self.assertEqual(doc.state, 'to_send')
self.assertEqual(self.invoice.state, 'posted')
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'sent')
self.assertEqual(self.invoice.state, 'posted')
self.invoice.button_cancel_posted_moves()
self.assertEqual(doc.state, 'to_cancel')
self.assertEqual(self.invoice.state, 'posted')
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'cancelled')
self.assertEqual(self.invoice.state, 'cancel')
def test_edi_flow_request_cancel_failed(self):
with self.mock_edi(_needs_web_services_method=_generate_mocked_needs_web_services(True),
_cancel_invoice_edi_method=_mocked_cancel_failed):
self.assertEqual(self.invoice.state, 'draft')
self.invoice.action_post()
doc = self.invoice._get_edi_document(self.edi_format)
self.assertEqual(doc.state, 'to_send')
self.assertEqual(self.invoice.state, 'posted')
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'sent')
self.assertEqual(self.invoice.state, 'posted')
self.invoice.button_cancel_posted_moves()
self.assertEqual(doc.state, 'to_cancel')
self.assertEqual(self.invoice.state, 'posted')
# Call off edi Cancellation
self.invoice.button_abandon_cancel_posted_posted_moves()
self.assertEqual(doc.state, 'sent')
self.assertFalse(doc.error)
# Failed cancel
self.invoice.button_cancel_posted_moves()
self.assertEqual(doc.state, 'to_cancel')
self.assertEqual(self.invoice.state, 'posted')
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'to_cancel')
self.assertEqual(self.invoice.state, 'posted')
# Call off edi Cancellation
self.invoice.button_abandon_cancel_posted_posted_moves()
self.assertEqual(doc.state, 'sent')
self.assertIsNotNone(doc.error)
def test_edi_flow_two_step_cancel_with_call_off_request(self):
def _mock_cancel(edi_format, invoices):
invoices_no_ref = invoices.filtered(lambda i: not i.ref)
if len(invoices_no_ref) == len(invoices): # first step
invoices_no_ref.ref = 'test_ref_cancel'
return {invoice: {} for invoice in invoices}
elif len(invoices_no_ref) == 0: # second step
for invoice in invoices:
invoice.ref = None
return {invoice: {'success': True} for invoice in invoices}
else:
raise ValueError('wrong use of "_mocked_post_two_steps"')
def _is_needed_for_invoice(edi_format, invoice):
return not bool(invoice.ref)
with self.mock_edi(_needs_web_services_method=_generate_mocked_needs_web_services(True),
_is_required_for_invoice_method=_is_needed_for_invoice,
_cancel_invoice_edi_method=_mock_cancel):
self.invoice.action_post()
doc = self.invoice._get_edi_document(self.edi_format)
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'sent')
# Request Cancellation
self.invoice.button_cancel_posted_moves()
doc._process_documents_web_services(with_commit=False) # first step of cancel
self.assertEqual(doc.state, 'to_cancel')
# Call off edi Cancellation
self.invoice.button_abandon_cancel_posted_posted_moves()
self.assertEqual(doc.state, 'to_cancel')
# If we cannot call off edi cancellation, only solution is to post again
doc._process_documents_web_services(with_commit=False) # second step of cancel
self.assertEqual(doc.state, 'cancelled')
self.invoice.action_post()
doc._process_documents_web_services(with_commit=False)
self.assertEqual(doc.state, 'sent')
def test_batches(self):
def _get_batch_key_method(edi_format, move, state):
return (move.ref)
with self.mock_edi(_get_batch_key_method=_get_batch_key_method,
_support_batching_method=_generate_mocked_support_batching(True)):
edi_docs = self.env['account.edi.document']
doc1 = self.create_edi_document(self.edi_format, 'to_send')
edi_docs |= doc1
doc2 = self.create_edi_document(self.edi_format, 'to_send')
edi_docs |= doc2
doc3 = self.create_edi_document(self.edi_format, 'to_send')
edi_docs |= doc3
to_process = edi_docs._prepare_jobs()
self.assertEqual(len(to_process), 1)
doc1.move_id.ref = 'batch1'
doc2.move_id.ref = 'batch2'
doc3.move_id.ref = 'batch3'
to_process = edi_docs._prepare_jobs()
self.assertEqual(len(to_process), 3)
doc2.move_id.ref = 'batch1'
to_process = edi_docs._prepare_jobs()
self.assertEqual(len(to_process), 2)
def test_cron_triggers(self):
with self.capture_triggers('account_edi.ir_cron_edi_network') as capt, \
self.mock_edi(_needs_web_services_method=_generate_mocked_needs_web_services(True)):
self.invoice._get_edi_document(self.edi_format)
self.invoice.action_post()
capt.records.ensure_one()
def test_cron_self_trigger(self):
# Process single job by CRON call (and thus, disable the auto-commit).
edi_cron = self.env.ref('account_edi.ir_cron_edi_network')
edi_cron.code = 'model._cron_process_documents_web_services(job_count=1)'
# Create invoices.
invoices = self.env['account.move'].create([{
'move_type': 'out_invoice',
'invoice_date': '2019-01-01',
'date': '2019-01-01',
'partner_id': self.partner_a.id,
'invoice_line_ids': [Command.create({'product_id': self.product_a.id})],
} for i in range(4)])
with self.capture_triggers('account_edi.ir_cron_edi_network') as capt, \
self.mock_edi(_needs_web_services_method=_generate_mocked_needs_web_services(True)):
invoices.action_post()
self.env.ref('account_edi.ir_cron_edi_network').method_direct_trigger()
self.assertEqual(len(capt.records), 2, "Not all records have been processed in this run, the cron should "
"re-trigger itself to process some more later")
def test_invoice_ready_to_be_sent(self):
def _is_needed_for_invoice(edi_format, invoice):
return True
with self.mock_edi(
_needs_web_services_method=_generate_mocked_needs_web_services(True),
_is_required_for_invoice_method=_is_needed_for_invoice,
):
self.invoice.action_post()
doc = self.invoice._get_edi_document(self.edi_format)
self.assertFalse(self.invoice._is_ready_to_be_sent())
doc._process_documents_web_services(with_commit=False)
self.assertTrue(self.invoice._is_ready_to_be_sent())
| 47.873469
| 11,729
|
10,085
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.modules.module import get_module_resource
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from contextlib import contextmanager
from unittest.mock import patch
from unittest import mock
import base64
def _generate_mocked_needs_web_services(needs_web_services):
return lambda edi_format: needs_web_services
def _generate_mocked_support_batching(support_batching):
return lambda edi_format, move, state, company: support_batching
def _mocked_get_batch_key(edi_format, move, state):
return ()
def _mocked_check_move_configuration_success(edi_format, move):
return []
def _mocked_check_move_configuration_fail(edi_format, move):
return ['Fake error (mocked)']
def _mocked_post(edi_format, invoices):
res = {}
for invoice in invoices:
attachment = edi_format.env['ir.attachment'].create({
'name': 'mock_simple.xml',
'datas': base64.encodebytes(b"<?xml version='1.0' encoding='UTF-8'?><Invoice/>"),
'mimetype': 'application/xml'
})
res[invoice] = {'success': True, 'attachment': attachment}
return res
def _mocked_post_two_steps(edi_format, invoices):
# For this test, we use the field ref to know if the first step is already done or not.
# Typically, a technical field for the reference of the upload to the web-service will
# be saved on the invoice.
invoices_no_ref = invoices.filtered(lambda i: not i.ref)
if len(invoices_no_ref) == len(invoices): # first step
invoices_no_ref.ref = 'test_ref'
return {invoice: {} for invoice in invoices}
elif len(invoices_no_ref) == 0: # second step
res = {}
for invoice in invoices:
attachment = edi_format.env['ir.attachment'].create({
'name': 'mock_simple.xml',
'datas': base64.encodebytes(b"<?xml version='1.0' encoding='UTF-8'?><Invoice/>"),
'mimetype': 'application/xml'
})
res[invoice] = {'success': True, 'attachment': attachment}
return res
else:
raise ValueError('wrong use of "_mocked_post_two_steps"')
def _mocked_cancel_success(edi_format, invoices):
return {invoice: {'success': True} for invoice in invoices}
def _mocked_cancel_failed(edi_format, invoices):
return {invoice: {'error': 'Faked error (mocked)'} for invoice in invoices}
class AccountEdiTestCommon(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None, edi_format_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# ==== EDI ====
if edi_format_ref:
cls.edi_format = cls.env.ref(edi_format_ref)
else:
with cls.mock_edi(cls, _needs_web_services_method=_generate_mocked_needs_web_services(True)):
cls.edi_format = cls.env['account.edi.format'].sudo().create({
'name': 'Test EDI format',
'code': 'test_edi',
})
cls.journal = cls.company_data['default_journal_sale']
cls.journal.edi_format_ids = [(6, 0, cls.edi_format.ids)]
####################################################
# EDI helpers
####################################################
@contextmanager
def mock_edi(self,
_is_required_for_invoice_method=lambda edi_format, invoice: True,
_is_required_for_payment_method=lambda edi_format, invoice: True,
_support_batching_method=_generate_mocked_support_batching(False),
_get_batch_key_method=_mocked_get_batch_key,
_needs_web_services_method=_generate_mocked_needs_web_services(False),
_check_move_configuration_method=_mocked_check_move_configuration_success,
_post_invoice_edi_method=_mocked_post,
_cancel_invoice_edi_method=_mocked_cancel_success,
_post_payment_edi_method=_mocked_post,
_cancel_payment_edi_method=_mocked_cancel_success,
):
try:
with patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._is_required_for_invoice',
new=_is_required_for_invoice_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._is_required_for_payment',
new=_is_required_for_payment_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._needs_web_services',
new=_needs_web_services_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._support_batching',
new=_support_batching_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._get_batch_key',
new=_get_batch_key_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._check_move_configuration',
new=_check_move_configuration_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._post_invoice_edi',
new=_post_invoice_edi_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._cancel_invoice_edi',
new=_cancel_invoice_edi_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._post_payment_edi',
new=_post_payment_edi_method), \
patch('odoo.addons.account_edi.models.account_edi_format.AccountEdiFormat._cancel_payment_edi',
new=_cancel_payment_edi_method):
yield
finally:
pass
def edi_cron(self):
self.env['account.edi.document'].sudo().search([('state', 'in', ('to_send', 'to_cancel'))])._process_documents_web_services(with_commit=False)
def _create_empty_vendor_bill(self):
invoice = self.env['account.move'].create({
'move_type': 'in_invoice',
'journal_id': self.company_data['default_journal_purchase'].id,
})
return invoice
def update_invoice_from_file(self, module_name, subfolder, filename, invoice):
file_path = get_module_resource(module_name, subfolder, filename)
file = open(file_path, 'rb').read()
attachment = self.env['ir.attachment'].create({
'name': filename,
'datas': base64.encodebytes(file),
'res_id': invoice.id,
'res_model': 'account.move',
})
invoice.message_post(attachment_ids=[attachment.id])
def create_invoice_from_file(self, module_name, subfolder, filename):
file_path = get_module_resource(module_name, subfolder, filename)
file = open(file_path, 'rb').read()
attachment = self.env['ir.attachment'].create({
'name': filename,
'datas': base64.encodebytes(file),
'res_model': 'account.move',
})
journal_id = self.company_data['default_journal_sale']
action_vals = journal_id.with_context(default_move_type='in_invoice').create_invoice_from_attachment(attachment.ids)
return self.env['account.move'].browse(action_vals['res_id'])
def assert_generated_file_equal(self, invoice, expected_values, applied_xpath=None):
invoice.action_post()
invoice.edi_document_ids._process_documents_web_services(with_commit=False) # synchronous are called in post, but there's no CRON in tests for asynchronous
attachment = invoice._get_edi_attachment(self.edi_format)
if not attachment:
raise ValueError('No attachment was generated after posting EDI')
xml_content = base64.b64decode(attachment.with_context(bin_size=False).datas)
current_etree = self.get_xml_tree_from_string(xml_content)
expected_etree = self.get_xml_tree_from_string(expected_values)
if applied_xpath:
expected_etree = self.with_applied_xpath(expected_etree, applied_xpath)
self.assertXmlTreeEqual(current_etree, expected_etree)
def create_edi_document(self, edi_format, state, move=None, move_type=None):
""" Creates a document based on an existing invoice or creates one, too.
:param edi_format: The edi_format of the document.
:param state: The state of the document.
:param move: The move of the document or None to create a new one.
:param move_type: If move is None, the type of the invoice to create, defaults to 'out_invoice'.
"""
move = move or self.init_invoice(move_type or 'out_invoice', products=self.product_a)
return self.env['account.edi.document'].create({
'edi_format_id': edi_format.id,
'move_id': move.id,
'state': state
})
def _process_documents_web_services(self, moves, formats_to_return=None):
""" Generates and returns EDI files for the specified moves.
formats_to_return is an optional parameter used to pass a set of codes from
the formats we want to return the files for (in case we want to test specific formats).
Other formats will still generate documents, they simply won't be returned.
"""
moves.edi_document_ids._process_documents_web_services(with_commit=False)
documents_to_return = moves.edi_document_ids
if formats_to_return != None:
documents_to_return = documents_to_return.filtered(lambda x: x.edi_format_id.code in formats_to_return)
attachments = documents_to_return.attachment_id
data_str_list = []
for attachment in attachments.with_context(bin_size=False):
data_str_list.append(base64.decodebytes(attachment.datas))
return data_str_list
| 46.474654
| 10,085
|
1,192
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestImportVendorBill(AccountTestInvoicingCommon):
def test_retrieve_partner(self):
def retrieve_partner(vat, import_vat):
self.partner_a.with_context(no_vat_validation=True).vat = vat
self.partner_a.flush()
return self.env['account.edi.format']._retrieve_partner(vat=import_vat)
self.assertEqual(self.partner_a, retrieve_partner('BE0477472701', 'BE0477472701'))
self.assertEqual(self.partner_a, retrieve_partner('BE0477472701', '0477472701'))
self.assertEqual(self.partner_a, retrieve_partner('BE0477472701', '477472701'))
self.assertEqual(self.partner_a, retrieve_partner('0477472701', 'BE0477472701'))
self.assertEqual(self.partner_a, retrieve_partner('477472701', 'BE0477472701'))
self.assertEqual(self.env['res.partner'], retrieve_partner('DE0477472701', 'BE0477472701'))
self.assertEqual(self.partner_a, retrieve_partner('CHE-107.787.577 IVA', 'CHE-107.787.577 IVA')) # note that base_vat forces the space
| 54.181818
| 1,192
|
37,399
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import frozendict
class AccountMove(models.Model):
_inherit = 'account.move'
edi_document_ids = fields.One2many(
comodel_name='account.edi.document',
inverse_name='move_id')
edi_state = fields.Selection(
selection=[('to_send', 'To Send'), ('sent', 'Sent'), ('to_cancel', 'To Cancel'), ('cancelled', 'Cancelled')],
string="Electronic invoicing",
store=True,
compute='_compute_edi_state',
help='The aggregated state of all the EDIs with web-service of this move')
edi_error_count = fields.Integer(
compute='_compute_edi_error_count',
help='How many EDIs are in error for this move ?')
edi_blocking_level = fields.Selection(
selection=[('info', 'Info'), ('warning', 'Warning'), ('error', 'Error')],
compute='_compute_edi_error_message')
edi_error_message = fields.Html(
compute='_compute_edi_error_message')
edi_web_services_to_process = fields.Text(
compute='_compute_edi_web_services_to_process',
help="Technical field to display the documents that will be processed by the CRON")
edi_show_cancel_button = fields.Boolean(
compute='_compute_edi_show_cancel_button')
edi_show_abandon_cancel_button = fields.Boolean(
compute='_compute_edi_show_abandon_cancel_button')
@api.depends('edi_document_ids.state')
def _compute_edi_state(self):
for move in self:
all_states = set(move.edi_document_ids.filtered(lambda d: d.edi_format_id._needs_web_services()).mapped('state'))
if all_states == {'sent'}:
move.edi_state = 'sent'
elif all_states == {'cancelled'}:
move.edi_state = 'cancelled'
elif 'to_send' in all_states:
move.edi_state = 'to_send'
elif 'to_cancel' in all_states:
move.edi_state = 'to_cancel'
else:
move.edi_state = False
@api.depends('edi_document_ids.error')
def _compute_edi_error_count(self):
for move in self:
move.edi_error_count = len(move.edi_document_ids.filtered(lambda d: d.error))
@api.depends('edi_error_count', 'edi_document_ids.error', 'edi_document_ids.blocking_level')
def _compute_edi_error_message(self):
for move in self:
if move.edi_error_count == 0:
move.edi_error_message = None
move.edi_blocking_level = None
elif move.edi_error_count == 1:
error_doc = move.edi_document_ids.filtered(lambda d: d.error)
move.edi_error_message = error_doc.error
move.edi_blocking_level = error_doc.blocking_level
else:
error_levels = set([doc.blocking_level for doc in move.edi_document_ids])
if 'error' in error_levels:
move.edi_error_message = str(move.edi_error_count) + _(" Electronic invoicing error(s)")
move.edi_blocking_level = 'error'
elif 'warning' in error_levels:
move.edi_error_message = str(move.edi_error_count) + _(" Electronic invoicing warning(s)")
move.edi_blocking_level = 'warning'
else:
move.edi_error_message = str(move.edi_error_count) + _(" Electronic invoicing info(s)")
move.edi_blocking_level = 'info'
@api.depends(
'edi_document_ids',
'edi_document_ids.state',
'edi_document_ids.blocking_level',
'edi_document_ids.edi_format_id',
'edi_document_ids.edi_format_id.name')
def _compute_edi_web_services_to_process(self):
for move in self:
to_process = move.edi_document_ids.filtered(lambda d: d.state in ['to_send', 'to_cancel'] and d.blocking_level != 'error')
format_web_services = to_process.edi_format_id.filtered(lambda f: f._needs_web_services())
move.edi_web_services_to_process = ', '.join(f.name for f in format_web_services)
@api.depends(
'state',
'edi_document_ids.state')
def _compute_show_reset_to_draft_button(self):
# OVERRIDE
super()._compute_show_reset_to_draft_button()
for move in self:
for doc in move.edi_document_ids:
if doc.edi_format_id._needs_web_services() \
and doc.state in ('sent', 'to_cancel') \
and move.is_invoice(include_receipts=True) \
and doc.edi_format_id._is_required_for_invoice(move):
move.show_reset_to_draft_button = False
break
@api.depends(
'state',
'edi_document_ids.state')
def _compute_edi_show_cancel_button(self):
for move in self:
if move.state != 'posted':
move.edi_show_cancel_button = False
continue
move.edi_show_cancel_button = any([doc.edi_format_id._needs_web_services()
and doc.state == 'sent'
and move.is_invoice(include_receipts=True)
and doc.edi_format_id._is_required_for_invoice(move)
for doc in move.edi_document_ids])
@api.depends(
'state',
'edi_document_ids.state')
def _compute_edi_show_abandon_cancel_button(self):
for move in self:
move.edi_show_abandon_cancel_button = any(doc.edi_format_id._needs_web_services()
and doc.state == 'to_cancel'
and move.is_invoice(include_receipts=True)
and doc.edi_format_id._is_required_for_invoice(move)
for doc in move.edi_document_ids)
####################################################
# Export Electronic Document
####################################################
@api.model
def _add_edi_tax_values(self, results, grouping_key, serialized_grouping_key, tax_values, key_by_tax=None):
# Add to global results.
results['tax_amount'] += tax_values['tax_amount']
results['tax_amount_currency'] += tax_values['tax_amount_currency']
# Add to tax details.
if serialized_grouping_key not in results['tax_details']:
tax_details = results['tax_details'][serialized_grouping_key]
tax_details.update(grouping_key)
tax_details.update({
'base_amount': tax_values['base_amount'],
'base_amount_currency': tax_values['base_amount_currency'],
})
else:
tax_details = results['tax_details'][serialized_grouping_key]
if key_by_tax:
add_to_base_amount = key_by_tax[tax_values['tax_id']] != key_by_tax.get(tax_values['src_line_id'].tax_line_id)
else:
add_to_base_amount = tax_values['base_line_id'] not in set(x['base_line_id'] for x in tax_details['group_tax_details'])
if add_to_base_amount:
tax_details['base_amount'] += tax_values['base_amount']
tax_details['base_amount_currency'] += tax_values['base_amount_currency']
tax_details['tax_amount'] += tax_values['tax_amount']
tax_details['tax_amount_currency'] += tax_values['tax_amount_currency']
tax_details['exemption_reason'] = tax_values['tax_id'].name
tax_details['group_tax_details'].append(tax_values)
def _prepare_edi_tax_details(self, filter_to_apply=None, filter_invl_to_apply=None, grouping_key_generator=None, compute_mode='tax_details'):
''' Compute amounts related to taxes for the current invoice.
:param filter_to_apply: Optional filter to exclude some tax values from the final results.
The filter is defined as a method getting a dictionary as parameter
representing the tax values for a single repartition line.
This dictionary contains:
'base_line_id': An account.move.line record.
'tax_id': An account.tax record.
'tax_repartition_line_id': An account.tax.repartition.line record.
'base_amount': The tax base amount expressed in company currency.
'tax_amount': The tax amount expressed in company currency.
'base_amount_currency': The tax base amount expressed in foreign currency.
'tax_amount_currency': The tax amount expressed in foreign currency.
If the filter is returning False, it means the current tax values will be
ignored when computing the final results.
:param filter_invl_to_apply: Optional filter to exclude some invoice lines.
:param grouping_key_generator: Optional method used to group tax values together. By default, the tax values
are grouped by tax. This parameter is a method getting a dictionary as parameter
(same signature as 'filter_to_apply').
This method must returns a dictionary where values will be used to create the
grouping_key to aggregate tax values together. The returned dictionary is added
to each tax details in order to retrieve the full grouping_key later.
:param compute_mode: Optional parameter to specify the method used to allocate the tax line amounts
among the invoice lines:
'tax_details' (the default) uses the AccountMove._get_query_tax_details method.
'compute_all' uses the AccountTax._compute_all method.
The 'tax_details' method takes the tax line balance and allocates it among the
invoice lines to which that tax applies, proportionately to the invoice lines'
base amounts. This always ensures that the sum of the tax amounts equals the
tax line's balance, which, depending on the constraints of a particular
localization, can be more appropriate when 'Round Globally' is set.
The 'compute_all' method returns, for each invoice line, the exact tax amounts
corresponding to the taxes applied to the invoice line. Depending on the
constraints of the particular localization, this can be more appropriate when
'Round per Line' is set.
:return: The full tax details for the current invoice and for each invoice line
separately. The returned dictionary is the following:
'base_amount': The total tax base amount in company currency for the whole invoice.
'tax_amount': The total tax amount in company currency for the whole invoice.
'base_amount_currency': The total tax base amount in foreign currency for the whole invoice.
'tax_amount_currency': The total tax amount in foreign currency for the whole invoice.
'tax_details': A mapping of each grouping key (see 'grouping_key_generator') to a dictionary
containing:
'base_amount': The tax base amount in company currency for the current group.
'tax_amount': The tax amount in company currency for the current group.
'base_amount_currency': The tax base amount in foreign currency for the current group.
'tax_amount_currency': The tax amount in foreign currency for the current group.
'group_tax_details': The list of all tax values aggregated into this group.
'invoice_line_tax_details': A mapping of each invoice line to a dictionary containing:
'base_amount': The total tax base amount in company currency for the whole invoice line.
'tax_amount': The total tax amount in company currency for the whole invoice line.
'base_amount_currency': The total tax base amount in foreign currency for the whole invoice line.
'tax_amount_currency': The total tax amount in foreign currency for the whole invoice line.
'tax_details': A mapping of each grouping key (see 'grouping_key_generator') to a dictionary
containing:
'base_amount': The tax base amount in company currency for the current group.
'tax_amount': The tax amount in company currency for the current group.
'base_amount_currency': The tax base amount in foreign currency for the current group.
'tax_amount_currency': The tax amount in foreign currency for the current group.
'group_tax_details': The list of all tax values aggregated into this group.
'''
self.ensure_one()
def default_grouping_key_generator(tax_values):
return {'tax': tax_values['tax_id']}
def compute_invoice_lines_tax_values_dict_from_tax_details(invoice_lines):
invoice_lines_tax_values_dict = defaultdict(list)
tax_details_query, tax_details_params = invoice_lines._get_query_tax_details_from_domain([('move_id', '=', self.id)])
self._cr.execute(tax_details_query, tax_details_params)
for row in self._cr.dictfetchall():
invoice_line = invoice_lines.browse(row['base_line_id'])
tax_line = invoice_lines.browse(row['tax_line_id'])
src_line = invoice_lines.browse(row['src_line_id'])
tax = self.env['account.tax'].browse(row['tax_id'])
src_tax = self.env['account.tax'].browse(row['group_tax_id']) if row['group_tax_id'] else tax
invoice_lines_tax_values_dict[invoice_line].append({
'base_line_id': invoice_line,
'tax_line_id': tax_line,
'src_line_id': src_line,
'tax_id': tax,
'src_tax_id': src_tax,
'tax_repartition_line_id': tax_line.tax_repartition_line_id,
'base_amount': row['base_amount'],
'tax_amount': row['tax_amount'],
'base_amount_currency': row['base_amount_currency'],
'tax_amount_currency': row['tax_amount_currency'],
})
return invoice_lines_tax_values_dict
def compute_invoice_lines_tax_values_dict_from_compute_all(invoice_lines):
invoice_lines_tax_values_dict = {}
sign = -1 if self.is_inbound() else 1
for invoice_line in invoice_lines:
taxes_res = invoice_line.tax_ids.compute_all(
invoice_line.price_unit * (1 - (invoice_line.discount / 100.0)),
currency=invoice_line.currency_id,
quantity=invoice_line.quantity,
product=invoice_line.product_id,
partner=invoice_line.partner_id,
is_refund=invoice_line.move_id.move_type in ('in_refund', 'out_refund'),
)
invoice_lines_tax_values_dict[invoice_line] = []
rate = abs(invoice_line.balance) / abs(invoice_line.amount_currency) if invoice_line.amount_currency else 0.0
for tax_res in taxes_res['taxes']:
tax_amount = tax_res['amount'] * rate
if self.company_id.tax_calculation_rounding_method == 'round_per_line':
tax_amount = invoice_line.company_currency_id.round(tax_amount)
invoice_lines_tax_values_dict[invoice_line].append({
'base_line_id': invoice_line,
'tax_id': self.env['account.tax'].browse(tax_res['id']),
'tax_repartition_line_id': self.env['account.tax.repartition.line'].browse(tax_res['tax_repartition_line_id']),
'base_amount': sign * invoice_line.company_currency_id.round(tax_res['base'] * rate),
'tax_amount': sign * tax_amount,
'base_amount_currency': sign * tax_res['base'],
'tax_amount_currency': sign * tax_res['amount'],
})
return invoice_lines_tax_values_dict
# Compute the taxes values for each invoice line.
invoice_lines = self.invoice_line_ids.filtered(lambda line: not line.display_type)
if filter_invl_to_apply:
invoice_lines = invoice_lines.filtered(filter_invl_to_apply)
if compute_mode == 'compute_all':
invoice_lines_tax_values_dict = compute_invoice_lines_tax_values_dict_from_compute_all(invoice_lines)
else:
invoice_lines_tax_values_dict = compute_invoice_lines_tax_values_dict_from_tax_details(invoice_lines)
grouping_key_generator = grouping_key_generator or default_grouping_key_generator
# Apply 'filter_to_apply'.
if self.move_type in ('out_refund', 'in_refund'):
tax_rep_lines_field = 'refund_repartition_line_ids'
else:
tax_rep_lines_field = 'invoice_repartition_line_ids'
filtered_invoice_lines_tax_values_dict = {}
for invoice_line in invoice_lines:
tax_values_list = invoice_lines_tax_values_dict.get(invoice_line, [])
filtered_invoice_lines_tax_values_dict[invoice_line] = []
# Search for unhandled taxes.
taxes_set = set(invoice_line.tax_ids.flatten_taxes_hierarchy())
for tax_values in tax_values_list:
taxes_set.discard(tax_values['tax_id'])
if not filter_to_apply or filter_to_apply(tax_values):
filtered_invoice_lines_tax_values_dict[invoice_line].append(tax_values)
# Restore zero-tax tax details.
for zero_tax in taxes_set:
affect_base_amount = 0.0
affect_base_amount_currency = 0.0
for tax_values in tax_values_list:
if zero_tax in tax_values['tax_line_id'].tax_ids:
affect_base_amount += tax_values['tax_amount']
affect_base_amount_currency += tax_values['tax_amount_currency']
for tax_rep in zero_tax[tax_rep_lines_field].filtered(lambda x: x.repartition_type == 'tax'):
tax_values = {
'base_line_id': invoice_line,
'tax_line_id': self.env['account.move.line'],
'src_line_id': invoice_line,
'tax_id': zero_tax,
'src_tax_id': zero_tax,
'tax_repartition_line_id': tax_rep,
'base_amount': invoice_line.balance + affect_base_amount,
'tax_amount': 0.0,
'base_amount_currency': invoice_line.amount_currency + affect_base_amount_currency,
'tax_amount_currency': 0.0,
}
if not filter_to_apply or filter_to_apply(tax_values):
filtered_invoice_lines_tax_values_dict[invoice_line].append(tax_values)
# Initialize the results dict.
invoice_global_tax_details = {
'base_amount': 0.0,
'tax_amount': 0.0,
'base_amount_currency': 0.0,
'tax_amount_currency': 0.0,
'tax_details': defaultdict(lambda: {
'base_amount': 0.0,
'tax_amount': 0.0,
'base_amount_currency': 0.0,
'tax_amount_currency': 0.0,
'group_tax_details': [],
}),
'invoice_line_tax_details': defaultdict(lambda: {
'base_amount': 0.0,
'tax_amount': 0.0,
'base_amount_currency': 0.0,
'tax_amount_currency': 0.0,
'tax_details': defaultdict(lambda: {
'base_amount': 0.0,
'tax_amount': 0.0,
'base_amount_currency': 0.0,
'tax_amount_currency': 0.0,
'group_tax_details': [],
}),
}),
}
# Apply 'grouping_key_generator' to 'invoice_lines_tax_values_list' and add all values to the final results.
for invoice_line in invoice_lines:
tax_values_list = filtered_invoice_lines_tax_values_dict[invoice_line]
key_by_tax = {}
# Add to invoice global tax amounts.
invoice_global_tax_details['base_amount'] += invoice_line.balance
invoice_global_tax_details['base_amount_currency'] += invoice_line.amount_currency
for tax_values in tax_values_list:
grouping_key = grouping_key_generator(tax_values)
serialized_grouping_key = frozendict(grouping_key)
key_by_tax[tax_values['tax_id']] = serialized_grouping_key
# Add to invoice line global tax amounts.
if serialized_grouping_key not in invoice_global_tax_details['invoice_line_tax_details'][invoice_line]:
invoice_line_global_tax_details = invoice_global_tax_details['invoice_line_tax_details'][invoice_line]
invoice_line_global_tax_details.update({
'base_amount': invoice_line.balance,
'base_amount_currency': invoice_line.amount_currency,
})
else:
invoice_line_global_tax_details = invoice_global_tax_details['invoice_line_tax_details'][invoice_line]
self._add_edi_tax_values(invoice_global_tax_details, grouping_key, serialized_grouping_key, tax_values,
key_by_tax=key_by_tax if compute_mode == 'tax_details' else None)
self._add_edi_tax_values(invoice_line_global_tax_details, grouping_key, serialized_grouping_key, tax_values,
key_by_tax=key_by_tax if compute_mode == 'tax_details' else None)
return invoice_global_tax_details
def _prepare_edi_vals_to_export(self):
''' The purpose of this helper is to prepare values in order to export an invoice through the EDI system.
This includes the computation of the tax details for each invoice line that could be very difficult to
handle regarding the computation of the base amount.
:return: A python dict containing default pre-processed values.
'''
self.ensure_one()
res = {
'record': self,
'balance_multiplicator': -1 if self.is_inbound() else 1,
'invoice_line_vals_list': [],
}
# Invoice lines details.
for index, line in enumerate(self.invoice_line_ids.filtered(lambda line: not line.display_type), start=1):
line_vals = line._prepare_edi_vals_to_export()
line_vals['index'] = index
res['invoice_line_vals_list'].append(line_vals)
# Totals.
res.update({
'total_price_subtotal_before_discount': sum(x['price_subtotal_before_discount'] for x in res['invoice_line_vals_list']),
'total_price_discount': sum(x['price_discount'] for x in res['invoice_line_vals_list']),
})
return res
def _update_payments_edi_documents(self):
''' Update the edi documents linked to the current journal entries. These journal entries must be linked to an
account.payment of an account.bank.statement.line. This additional method is needed because the payment flow is
not the same as the invoice one. Indeed, the edi documents must be updated when the reconciliation with some
invoices is changing.
'''
edi_document_vals_list = []
for payment in self:
edi_formats = payment._get_reconciled_invoices().journal_id.edi_format_ids + payment.edi_document_ids.edi_format_id
edi_formats = self.env['account.edi.format'].browse(edi_formats.ids) # Avoid duplicates
for edi_format in edi_formats:
existing_edi_document = payment.edi_document_ids.filtered(lambda x: x.edi_format_id == edi_format)
if edi_format._is_required_for_payment(payment):
if existing_edi_document:
existing_edi_document.write({
'state': 'to_send',
'error': False,
'blocking_level': False,
})
else:
edi_document_vals_list.append({
'edi_format_id': edi_format.id,
'move_id': payment.id,
'state': 'to_send',
})
elif existing_edi_document:
existing_edi_document.write({
'state': False,
'error': False,
'blocking_level': False,
})
self.env['account.edi.document'].create(edi_document_vals_list)
self.edi_document_ids._process_documents_no_web_services()
def _is_ready_to_be_sent(self):
# OVERRIDE
# Prevent a mail to be sent to the customer if the EDI document is not sent.
res = super()._is_ready_to_be_sent()
if not res:
return False
edi_documents_to_send = self.edi_document_ids.filtered(lambda x: x.state == 'to_send')
return not bool(edi_documents_to_send)
def _post(self, soft=True):
# OVERRIDE
# Set the electronic document to be posted and post immediately for synchronous formats.
posted = super()._post(soft=soft)
edi_document_vals_list = []
for move in posted:
for edi_format in move.journal_id.edi_format_ids:
is_edi_needed = move.is_invoice(include_receipts=False) and edi_format._is_required_for_invoice(move)
if is_edi_needed:
errors = edi_format._check_move_configuration(move)
if errors:
raise UserError(_("Invalid invoice configuration:\n\n%s") % '\n'.join(errors))
existing_edi_document = move.edi_document_ids.filtered(lambda x: x.edi_format_id == edi_format)
if existing_edi_document:
existing_edi_document.write({
'state': 'to_send',
'attachment_id': False,
})
else:
edi_document_vals_list.append({
'edi_format_id': edi_format.id,
'move_id': move.id,
'state': 'to_send',
})
self.env['account.edi.document'].create(edi_document_vals_list)
posted.edi_document_ids._process_documents_no_web_services()
self.env.ref('account_edi.ir_cron_edi_network')._trigger()
return posted
def button_cancel(self):
# OVERRIDE
# Set the electronic document to be canceled and cancel immediately for synchronous formats.
res = super().button_cancel()
self.edi_document_ids.filtered(lambda doc: doc.state != 'sent').write({'state': 'cancelled', 'error': False, 'blocking_level': False})
self.edi_document_ids.filtered(lambda doc: doc.state == 'sent').write({'state': 'to_cancel', 'error': False, 'blocking_level': False})
self.edi_document_ids._process_documents_no_web_services()
self.env.ref('account_edi.ir_cron_edi_network')._trigger()
return res
def button_draft(self):
# OVERRIDE
for move in self:
if move.edi_show_cancel_button:
raise UserError(_(
"You can't edit the following journal entry %s because an electronic document has already been "
"sent. Please use the 'Request EDI Cancellation' button instead."
) % move.display_name)
res = super().button_draft()
self.edi_document_ids.write({'error': False, 'blocking_level': False})
return res
def button_cancel_posted_moves(self):
'''Mark the edi.document related to this move to be canceled.
'''
to_cancel_documents = self.env['account.edi.document']
for move in self:
move._check_fiscalyear_lock_date()
is_move_marked = False
for doc in move.edi_document_ids:
if doc.edi_format_id._needs_web_services() \
and doc.attachment_id \
and doc.state == 'sent' \
and move.is_invoice(include_receipts=True) \
and doc.edi_format_id._is_required_for_invoice(move):
to_cancel_documents |= doc
is_move_marked = True
if is_move_marked:
move.message_post(body=_("A cancellation of the EDI has been requested."))
to_cancel_documents.write({'state': 'to_cancel', 'error': False, 'blocking_level': False})
def button_abandon_cancel_posted_posted_moves(self):
'''Cancel the request for cancellation of the EDI.
'''
documents = self.env['account.edi.document']
for move in self:
is_move_marked = False
for doc in move.edi_document_ids:
if doc.state == 'to_cancel' \
and move.is_invoice(include_receipts=True) \
and doc.edi_format_id._is_required_for_invoice(move):
documents |= doc
is_move_marked = True
if is_move_marked:
move.message_post(body=_("A request for cancellation of the EDI has been called off."))
documents.write({'state': 'sent'})
def _get_edi_document(self, edi_format):
return self.edi_document_ids.filtered(lambda d: d.edi_format_id == edi_format)
def _get_edi_attachment(self, edi_format):
return self._get_edi_document(edi_format).attachment_id
####################################################
# Import Electronic Document
####################################################
def _get_create_invoice_from_attachment_decoders(self):
# OVERRIDE
res = super()._get_create_invoice_from_attachment_decoders()
res.append((10, self.env['account.edi.format'].search([])._create_invoice_from_attachment))
return res
def _get_update_invoice_from_attachment_decoders(self, invoice):
# OVERRIDE
res = super()._get_update_invoice_from_attachment_decoders(invoice)
res.append((10, self.env['account.edi.format'].search([])._update_invoice_from_attachment))
return res
####################################################
# Business operations
####################################################
def button_process_edi_web_services(self):
self.action_process_edi_web_services(with_commit=False)
def action_process_edi_web_services(self, with_commit=True):
docs = self.edi_document_ids.filtered(lambda d: d.state in ('to_send', 'to_cancel') and d.blocking_level != 'error')
docs._process_documents_web_services(with_commit=with_commit)
def _retry_edi_documents_error_hook(self):
''' Hook called when edi_documents are retried. For example, when it's needed to clean a field.
TO OVERRIDE
'''
return
def action_retry_edi_documents_error(self):
self._retry_edi_documents_error_hook()
self.edi_document_ids.write({'error': False, 'blocking_level': False})
self.action_process_edi_web_services()
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
####################################################
# Export Electronic Document
####################################################
def _prepare_edi_vals_to_export(self):
''' The purpose of this helper is the same as '_prepare_edi_vals_to_export' but for a single invoice line.
This includes the computation of the tax details for each invoice line or the management of the discount.
Indeed, in some EDI, we need to provide extra values depending the discount such as:
- the discount as an amount instead of a percentage.
- the price_unit but after subtraction of the discount.
:return: A python dict containing default pre-processed values.
'''
self.ensure_one()
if self.discount == 100.0:
gross_price_subtotal = self.currency_id.round(self.price_unit * self.quantity)
else:
gross_price_subtotal = self.currency_id.round(self.price_subtotal / (1 - self.discount / 100.0))
res = {
'line': self,
'price_unit_after_discount': self.currency_id.round(self.price_unit * (1 - (self.discount / 100.0))),
'price_subtotal_before_discount': gross_price_subtotal,
'price_subtotal_unit': self.currency_id.round(self.price_subtotal / self.quantity) if self.quantity else 0.0,
'price_total_unit': self.currency_id.round(self.price_total / self.quantity) if self.quantity else 0.0,
'price_discount': gross_price_subtotal - self.price_subtotal,
'price_discount_unit': (gross_price_subtotal - self.price_subtotal) / self.quantity if self.quantity else 0.0,
'gross_price_total_unit': self.currency_id.round(gross_price_subtotal / self.quantity) if self.quantity else 0.0,
'unece_uom_code': self.product_id.product_tmpl_id.uom_id._get_unece_code(),
}
return res
def reconcile(self):
# OVERRIDE
# In some countries, the payments must be sent to the government under some condition. One of them could be
# there is at least one reconciled invoice to the payment. Then, we need to update the state of the edi
# documents during the reconciliation.
all_lines = self + self.matched_debit_ids.debit_move_id + self.matched_credit_ids.credit_move_id
payments = all_lines.move_id.filtered(lambda move: move.payment_id or move.statement_line_id)
invoices_per_payment_before = {pay: pay._get_reconciled_invoices() for pay in payments}
res = super().reconcile()
invoices_per_payment_after = {pay: pay._get_reconciled_invoices() for pay in payments}
changed_payments = self.env['account.move']
for payment, invoices_after in invoices_per_payment_after.items():
invoices_before = invoices_per_payment_before[payment]
if set(invoices_after.ids) != set(invoices_before.ids):
changed_payments |= payment
changed_payments._update_payments_edi_documents()
return res
def remove_move_reconcile(self):
# OVERRIDE
# When a payment has been sent to the government, it usually contains some information about reconciled
# invoices. If the user breaks a reconciliation, the related payments must be cancelled properly and then, a new
# electronic document must be generated.
all_lines = self + self.matched_debit_ids.debit_move_id + self.matched_credit_ids.credit_move_id
payments = all_lines.move_id.filtered(lambda move: move.payment_id or move.statement_line_id)
invoices_per_payment_before = {pay: pay._get_reconciled_invoices() for pay in payments}
res = super().remove_move_reconcile()
invoices_per_payment_after = {pay: pay._get_reconciled_invoices() for pay in payments}
changed_payments = self.env['account.move']
for payment, invoices_after in invoices_per_payment_after.items():
invoices_before = invoices_per_payment_before[payment]
if set(invoices_after.ids) != set(invoices_before.ids):
changed_payments |= payment
changed_payments._update_payments_edi_documents()
return res
| 52.015299
| 37,399
|
29,434
|
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.pdf import OdooPdfFileReader, OdooPdfFileWriter
from odoo.osv import expression
from odoo.tools import html_escape
from odoo.exceptions import RedirectWarning
from lxml import etree
from struct import error as StructError
import base64
import io
import logging
import pathlib
import re
_logger = logging.getLogger(__name__)
class AccountEdiFormat(models.Model):
_name = 'account.edi.format'
_description = 'EDI format'
name = fields.Char()
code = fields.Char(required=True)
_sql_constraints = [
('unique_code', 'unique (code)', 'This code already exists')
]
####################################################
# Low-level methods
####################################################
@api.model_create_multi
def create(self, vals_list):
edi_formats = super().create(vals_list)
# activate by default on journal
if not self.pool.loaded:
# The registry is not totally loaded. We cannot yet recompute the field on jourals as
# The helper methods aren't yet overwritten by all installed `l10n_` modules.
# Delay it in the register hook
self.pool._delay_compute_edi_format_ids = True
else:
journals = self.env['account.journal'].search([])
journals._compute_edi_format_ids()
# activate cron
if any(edi_format._needs_web_services() for edi_format in edi_formats):
self.env.ref('account_edi.ir_cron_edi_network').active = True
return edi_formats
def _register_hook(self):
if hasattr(self.pool, "_delay_compute_edi_format_ids"):
del self.pool._delay_compute_edi_format_ids
journals = self.env['account.journal'].search([])
journals._compute_edi_format_ids()
return super()._register_hook()
####################################################
# Export method to override based on EDI Format
####################################################
def _get_invoice_edi_content(self, move):
''' Create a bytes literal of the file content representing the invoice - to be overridden by the EDI Format
:returns: bytes literal of the content generated (typically XML).
'''
return b''
def _get_payment_edi_content(self, move):
''' Create a bytes literal of the file content representing the payment - to be overridden by the EDI Format
:returns: bytes literal of the content generated (typically XML).
'''
return b''
def _is_required_for_invoice(self, invoice):
""" Indicate if this EDI must be generated for the invoice passed as parameter.
:param invoice: An account.move having the invoice type.
:returns: True if the EDI must be generated, False otherwise.
"""
# TO OVERRIDE
self.ensure_one()
return True
def _is_required_for_payment(self, payment):
""" Indicate if this EDI must be generated for the payment passed as parameter.
:param payment: An account.move linked to either an account.payment, either an account.bank.statement.line.
:returns: True if the EDI must be generated, False otherwise.
"""
# TO OVERRIDE
self.ensure_one()
return False
def _needs_web_services(self):
""" Indicate if the EDI must be generated asynchronously through to some web services.
:return: True if such a web service is available, False otherwise.
"""
self.ensure_one()
return False
def _is_compatible_with_journal(self, journal):
""" Indicate if the EDI format should appear on the journal passed as parameter to be selected by the user.
If True, this EDI format will appear on the journal.
:param journal: The journal.
:returns: True if this format can appear on the journal, False otherwise.
"""
# TO OVERRIDE
self.ensure_one()
return journal.type == 'sale'
def _is_enabled_by_default_on_journal(self, journal):
""" Indicate if the EDI format should be selected by default on the journal passed as parameter.
If True, this EDI format will be selected by default on the journal.
:param journal: The journal.
:returns: True if this format should be enabled by default on the journal, False otherwise.
"""
return True
def _is_embedding_to_invoice_pdf_needed(self):
""" Indicate if the EDI must be embedded inside the PDF report.
:returns: True if the documents need to be embedded, False otherwise.
"""
# TO OVERRIDE
return False
def _get_embedding_to_invoice_pdf_values(self, invoice):
""" Get the values to embed to pdf.
:returns: A dictionary {'name': name, 'datas': datas} or False if there are no values to embed.
* name: The name of the file.
* datas: The bytes ot the file.
To remove in master
"""
self.ensure_one()
attachment = invoice._get_edi_attachment(self)
if not attachment or not self._is_embedding_to_invoice_pdf_needed():
return False
datas = base64.b64decode(attachment.with_context(bin_size=False).datas)
return {'name': attachment.name, 'datas': datas}
def _support_batching(self, move, state, company):
""" Indicate if we can send multiple documents in the same time to the web services.
If True, the _post_%s_edi methods will get multiple documents in the same time.
Otherwise, these methods will be called with only one record at a time.
:param move: The move that we are trying to batch.
:param state: The EDI state of the move.
:param company: The company with which we are sending the EDI.
:returns: True if batching is supported, False otherwise.
"""
# TO OVERRIDE
return False
def _get_batch_key(self, move, state):
""" Returns a tuple that will be used as key to partitionnate the invoices/payments when creating batches
with multiple invoices/payments.
The type of move (invoice or payment), its company_id, its edi state and the edi_format are used by default, if
no further partition is needed for this format, this method should return (). It's not necessary to repeat those
fields in the custom key.
:param move: The move to batch.
:param state: The EDI state of the move.
:returns: The key to be used when partitionning the batches.
"""
move.ensure_one()
return ()
def _check_move_configuration(self, move):
""" Checks the move and relevant records for potential error (missing data, etc).
:param move: The move to check.
:returns: A list of error messages.
"""
# TO OVERRIDE
return []
def _post_invoice_edi(self, invoices):
""" Create the file content representing the invoice (and calls web services if necessary).
:param invoices: A list of invoices to post.
:returns: A dictionary with the invoice as key and as value, another dictionary:
* success: True if the edi was successfully posted.
* attachment: The attachment representing the invoice in this edi_format.
* error: An error if the edi was not successfully posted.
* blocking_level: (optional) How bad is the error (how should the edi flow be blocked ?)
"""
# TO OVERRIDE
self.ensure_one()
return {}
def _cancel_invoice_edi(self, invoices):
"""Calls the web services to cancel the invoice of this document.
:param invoices: A list of invoices to cancel.
:returns: A dictionary with the invoice as key and as value, another dictionary:
* success: True if the invoice was successfully cancelled.
* error: An error if the edi was not successfully cancelled.
* blocking_level: (optional) How bad is the error (how should the edi flow be blocked ?)
"""
# TO OVERRIDE
self.ensure_one()
return {invoice: {'success': True} for invoice in invoices} # By default, cancel succeeds doing nothing.
def _post_payment_edi(self, payments):
""" Create the file content representing the payment (and calls web services if necessary).
:param payments: The payments to post.
:returns: A dictionary with the payment as key and as value, another dictionary:
* attachment: The attachment representing the payment in this edi_format if the edi was successfully posted.
* error: An error if the edi was not successfully posted.
* blocking_level: (optional) How bad is the error (how should the edi flow be blocked ?)
"""
# TO OVERRIDE
self.ensure_one()
return {}
def _cancel_payment_edi(self, payments):
"""Calls the web services to cancel the payment of this document.
:param payments: A list of payments to cancel.
:returns: A dictionary with the payment as key and as value, another dictionary:
* success: True if the payment was successfully cancelled.
* error: An error if the edi was not successfully cancelled.
* blocking_level: (optional) How bad is the error (how should the edi flow be blocked ?)
"""
# TO OVERRIDE
self.ensure_one()
return {payment: {'success': True} for payment in payments} # By default, cancel succeeds doing nothing.
####################################################
# Import methods to override based on EDI Format
####################################################
def _create_invoice_from_xml_tree(self, filename, tree, journal=None):
""" Create a new invoice with the data inside the xml.
:param filename: The name of the xml.
:param tree: The tree of the xml to import.
:param journal: The journal on which importing the invoice.
:returns: The created invoice.
"""
# TO OVERRIDE
self.ensure_one()
return self.env['account.move']
def _update_invoice_from_xml_tree(self, filename, tree, invoice):
""" Update an existing invoice with the data inside the xml.
:param filename: The name of the xml.
:param tree: The tree of the xml to import.
:param invoice: The invoice to update.
:returns: The updated invoice.
"""
# TO OVERRIDE
self.ensure_one()
return self.env['account.move']
def _create_invoice_from_pdf_reader(self, filename, reader):
""" Create a new invoice with the data inside a pdf.
:param filename: The name of the pdf.
:param reader: The OdooPdfFileReader of the pdf to import.
:returns: The created invoice.
"""
# TO OVERRIDE
self.ensure_one()
return self.env['account.move']
def _update_invoice_from_pdf_reader(self, filename, reader, invoice):
""" Update an existing invoice with the data inside the pdf.
:param filename: The name of the pdf.
:param reader: The OdooPdfFileReader of the pdf to import.
:param invoice: The invoice to update.
:returns: The updated invoice.
"""
# TO OVERRIDE
self.ensure_one()
return self.env['account.move']
def _create_invoice_from_binary(self, filename, content, extension):
""" Create a new invoice with the data inside a binary file.
:param filename: The name of the file.
:param content: The content of the binary file.
:param extension: The extensions as a string.
:returns: The created invoice.
"""
# TO OVERRIDE
self.ensure_one()
return self.env['account.move']
def _update_invoice_from_binary(self, filename, content, extension, invoice):
""" Update an existing invoice with the data inside a binary file.
:param filename: The name of the file.
:param content: The content of the binary file.
:param extension: The extensions as a string.
:param invoice: The invoice to update.
:returns: The updated invoice.
"""
# TO OVERRIDE
self.ensure_one()
return self.env['account.move']
def _prepare_invoice_report(self, pdf_writer, edi_document):
"""
Prepare invoice report to be printed.
:param pdf_writer: The pdf writer with the invoice pdf content loaded.
:param edi_document: The edi document to be added to the pdf file.
"""
# TO OVERRIDE
self.ensure_one()
if self._is_embedding_to_invoice_pdf_needed() and edi_document.attachment_id:
pdf_writer.embed_odoo_attachment(edi_document.attachment_id)
####################################################
# Export Internal methods (not meant to be overridden)
####################################################
def _embed_edis_to_pdf(self, pdf_content, invoice):
""" Create the EDI document of the invoice and embed it in the pdf_content.
:param pdf_content: the bytes representing the pdf to add the EDIs to.
:param invoice: the invoice to generate the EDI from.
:returns: the same pdf_content with the EDI of the invoice embed in it.
"""
to_embed = invoice.edi_document_ids
# Add the attachments to the pdf file
if to_embed:
reader_buffer = io.BytesIO(pdf_content)
reader = OdooPdfFileReader(reader_buffer, strict=False)
writer = OdooPdfFileWriter()
writer.cloneReaderDocumentRoot(reader)
for edi_document in to_embed:
edi_document.edi_format_id._prepare_invoice_report(writer, edi_document)
buffer = io.BytesIO()
writer.write(buffer)
pdf_content = buffer.getvalue()
reader_buffer.close()
buffer.close()
return pdf_content
####################################################
# Import Internal methods (not meant to be overridden)
####################################################
def _decode_xml(self, filename, content):
"""Decodes an xml into a list of one dictionary representing an attachment.
:param filename: The name of the xml.
:param content: The bytes representing the xml.
:returns: A list with a dictionary.
* filename: The name of the attachment.
* content: The content of the attachment.
* type: The type of the attachment.
* xml_tree: The tree of the xml if type is xml.
"""
to_process = []
try:
xml_tree = etree.fromstring(content)
except Exception as e:
_logger.exception("Error when converting the xml content to etree: %s" % e)
return to_process
if len(xml_tree):
to_process.append({
'filename': filename,
'content': content,
'type': 'xml',
'xml_tree': xml_tree,
})
return to_process
def _decode_pdf(self, filename, content):
"""Decodes a pdf and unwrap sub-attachment into a list of dictionary each representing an attachment.
:param filename: The name of the pdf.
:param content: The bytes representing the pdf.
:returns: A list of dictionary for each attachment.
* filename: The name of the attachment.
* content: The content of the attachment.
* type: The type of the attachment.
* xml_tree: The tree of the xml if type is xml.
* pdf_reader: The pdf_reader if type is pdf.
"""
to_process = []
try:
buffer = io.BytesIO(content)
pdf_reader = OdooPdfFileReader(buffer, strict=False)
except Exception as e:
# Malformed pdf
_logger.exception("Error when reading the pdf: %s" % e)
return to_process
# Process embedded files.
try:
for xml_name, content in pdf_reader.getAttachments():
to_process.extend(self._decode_xml(xml_name, content))
except (NotImplementedError, StructError) as e:
_logger.warning("Unable to access the attachments of %s. Tried to decrypt it, but %s." % (filename, e))
# Process the pdf itself.
to_process.append({
'filename': filename,
'content': content,
'type': 'pdf',
'pdf_reader': pdf_reader,
})
return to_process
def _decode_binary(self, filename, content):
"""Decodes any file into a list of one dictionary representing an attachment.
This is a fallback for all files that are not decoded by other methods.
:param filename: The name of the file.
:param content: The bytes representing the file.
:returns: A list with a dictionary.
* filename: The name of the attachment.
* content: The content of the attachment.
* type: The type of the attachment.
"""
return [{
'filename': filename,
'extension': ''.join(pathlib.Path(filename).suffixes),
'content': content,
'type': 'binary',
}]
def _decode_attachment(self, attachment):
"""Decodes an ir.attachment and unwrap sub-attachment into a list of dictionary each representing an attachment.
:param attachment: An ir.attachment record.
:returns: A list of dictionary for each attachment.
* filename: The name of the attachment.
* content: The content of the attachment.
* type: The type of the attachment.
* xml_tree: The tree of the xml if type is xml.
* pdf_reader: The pdf_reader if type is pdf.
"""
content = base64.b64decode(attachment.with_context(bin_size=False).datas)
to_process = []
# XML attachments received by mail have a 'text/plain' mimetype (cfr. context key: 'attachments_mime_plainxml')
# Therefore, if content start with '<?xml', or if the filename ends with '.xml', it is considered as XML.
is_text_plain_xml = 'text/plain' in attachment.mimetype and (content.startswith(b'<?xml') or attachment.name.endswith('.xml'))
if 'pdf' in attachment.mimetype:
to_process.extend(self._decode_pdf(attachment.name, content))
elif attachment.mimetype.endswith('/xml') or is_text_plain_xml:
to_process.extend(self._decode_xml(attachment.name, content))
else:
to_process.extend(self._decode_binary(attachment.name, content))
return to_process
def _create_invoice_from_attachment(self, attachment):
"""Decodes an ir.attachment to create an invoice.
:param attachment: An ir.attachment record.
:returns: The invoice where to import data.
"""
for file_data in self._decode_attachment(attachment):
for edi_format in self:
res = False
try:
if file_data['type'] == 'xml':
res = edi_format.with_company(self.env.company)._create_invoice_from_xml_tree(file_data['filename'], file_data['xml_tree'])
elif file_data['type'] == 'pdf':
res = edi_format.with_company(self.env.company)._create_invoice_from_pdf_reader(file_data['filename'], file_data['pdf_reader'])
file_data['pdf_reader'].stream.close()
else:
res = edi_format._create_invoice_from_binary(file_data['filename'], file_data['content'], file_data['extension'])
except RedirectWarning as rw:
raise rw
except Exception as e:
_logger.exception("Error importing attachment \"%s\" as invoice with format \"%s\"", file_data['filename'], edi_format.name, exc_info=True)
if res:
return res
return self.env['account.move']
def _update_invoice_from_attachment(self, attachment, invoice):
"""Decodes an ir.attachment to update an invoice.
:param attachment: An ir.attachment record.
:returns: The invoice where to import data.
"""
for file_data in self._decode_attachment(attachment):
for edi_format in self:
res = False
try:
if file_data['type'] == 'xml':
res = edi_format.with_company(invoice.company_id)._update_invoice_from_xml_tree(file_data['filename'], file_data['xml_tree'], invoice)
elif file_data['type'] == 'pdf':
res = edi_format.with_company(invoice.company_id)._update_invoice_from_pdf_reader(file_data['filename'], file_data['pdf_reader'], invoice)
file_data['pdf_reader'].stream.close()
else: # file_data['type'] == 'binary'
res = edi_format._update_invoice_from_binary(file_data['filename'], file_data['content'], file_data['extension'], invoice)
except Exception as e:
_logger.exception("Error importing attachment \"%s\" as invoice with format \"%s\"", file_data['filename'], edi_format.name, exc_info=True)
if res:
return res
return self.env['account.move']
####################################################
# Import helpers
####################################################
def _find_value(self, xpath, xml_element, namespaces=None):
element = xml_element.xpath(xpath, namespaces=namespaces)
return element[0].text if element else None
@api.model
def _retrieve_partner_with_vat(self, vat, extra_domain):
if not vat:
return None
# Sometimes, the vat is specified with some whitespaces.
normalized_vat = vat.replace(' ', '')
country_prefix = re.match('^[a-zA-Z]{2}|^', vat).group()
partner = self.env['res.partner'].search(extra_domain + [('vat', 'in', (normalized_vat, vat))], limit=1)
# Try to remove the country code prefix from the vat.
if not partner and country_prefix:
partner = self.env['res.partner'].search(extra_domain + [
('vat', 'in', (normalized_vat[2:], vat[2:])),
('country_id.code', '=', country_prefix.upper()),
], limit=1)
# The country could be not specified on the partner.
if not partner:
partner = self.env['res.partner'].search(extra_domain + [
('vat', 'in', (normalized_vat[2:], vat[2:])),
('country_id', '=', False),
], limit=1)
# The vat could be a string of alphanumeric values without country code but with missing zeros at the
# beginning.
if not partner:
try:
vat_only_numeric = str(int(re.sub(r'^\D{2}', '', normalized_vat) or 0))
except ValueError:
vat_only_numeric = None
if vat_only_numeric:
query = self.env['res.partner']._where_calc(extra_domain + [('active', '=', True)])
tables, where_clause, where_params = query.get_sql()
if country_prefix:
vat_prefix_regex = f'({country_prefix})?'
else:
vat_prefix_regex = '([A-z]{2})?'
self._cr.execute(f'''
SELECT res_partner.id
FROM {tables}
WHERE {where_clause}
AND res_partner.vat ~ %s
LIMIT 1
''', where_params + ['^%s0*%s$' % (vat_prefix_regex, vat_only_numeric)])
partner_row = self._cr.fetchone()
if partner_row:
partner = self.env['res.partner'].browse(partner_row[0])
return partner
@api.model
def _retrieve_partner_with_phone_mail(self, phone, mail, extra_domain):
domains = []
if phone:
domains.append([('phone', '=', phone)])
domains.append([('mobile', '=', phone)])
if mail:
domains.append([('email', '=', mail)])
if not domains:
return None
domain = expression.OR(domains)
if extra_domain:
domain = expression.AND([domain, extra_domain])
return self.env['res.partner'].search(domain, limit=1)
@api.model
def _retrieve_partner_with_name(self, name, extra_domain):
if not name:
return None
return self.env['res.partner'].search([('name', 'ilike', name)] + extra_domain, limit=1)
def _retrieve_partner(self, name=None, phone=None, mail=None, vat=None, domain=None):
'''Search all partners and find one that matches one of the parameters.
:param name: The name of the partner.
:param phone: The phone or mobile of the partner.
:param mail: The mail of the partner.
:param vat: The vat number of the partner.
:returns: A partner or an empty recordset if not found.
'''
def search_with_vat(extra_domain):
return self._retrieve_partner_with_vat(vat, extra_domain)
def search_with_phone_mail(extra_domain):
return self._retrieve_partner_with_phone_mail(phone, mail, extra_domain)
def search_with_name(extra_domain):
return self._retrieve_partner_with_name(name, extra_domain)
def search_with_domain(extra_domain):
if not domain:
return None
return self.env['res.partner'].search(domain + extra_domain, limit=1)
for search_method in (search_with_vat, search_with_domain, search_with_phone_mail, search_with_name):
for extra_domain in ([('company_id', '=', self.env.company.id)], []):
partner = search_method(extra_domain)
if partner:
return partner
return self.env['res.partner']
def _retrieve_product(self, name=None, default_code=None, barcode=None):
'''Search all products and find one that matches one of the parameters.
:param name: The name of the product.
:param default_code: The default_code of the product.
:param barcode: The barcode of the product.
:returns: A product or an empty recordset if not found.
'''
if name and '\n' in name:
# cut Sales Description from the name
name = name.split('\n')[0]
domains = []
for value, domain in (
(name, ('name', 'ilike', name)),
(default_code, ('default_code', '=', default_code)),
(barcode, ('barcode', '=', barcode)),
):
if value is not None:
domains.append([domain])
domain = expression.AND([
expression.OR(domains),
[('company_id', 'in', [False, self.env.company.id])],
])
return self.env['product.product'].search(domain, limit=1)
def _retrieve_tax(self, amount, type_tax_use):
'''Search all taxes and find one that matches all of the parameters.
:param amount: The amount of the tax.
:param type_tax_use: The type of the tax.
:returns: A tax or an empty recordset if not found.
'''
domains = [
[('amount', '=', float(amount))],
[('type_tax_use', '=', type_tax_use)],
[('company_id', '=', self.env.company.id)]
]
return self.env['account.tax'].search(expression.AND(domains), order='sequence ASC', limit=1)
def _retrieve_currency(self, code):
'''Search all currencies and find one that matches the code.
:param code: The code of the currency.
:returns: A currency or an empty recordset if not found.
'''
return self.env['res.currency'].with_context(active_test=False).search([('name', '=', code.upper())], limit=1)
####################################################
# Other helpers
####################################################
@api.model
def _format_error_message(self, error_title, errors):
bullet_list_msg = ''.join('<li>%s</li>' % html_escape(msg) for msg in errors)
return '%s<ul>%s</ul>' % (error_title, bullet_list_msg)
def _is_account_edi_ubl_cii_available(self):
return hasattr(self, '_infer_xml_builder_from_tree')
| 42.596237
| 29,434
|
728
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'
def _post_pdf(self, save_in_attachment, pdf_content=None, res_ids=None):
# OVERRIDE to embed some EDI documents inside the PDF.
if self.model == 'account.move' and res_ids and len(res_ids) == 1 and pdf_content:
invoice = self.env['account.move'].browse(res_ids)
if invoice.is_sale_document() and invoice.state != 'draft':
pdf_content = invoice.journal_id.edi_format_ids._embed_edis_to_pdf(pdf_content, invoice)
return super(IrActionsReport, self)._post_pdf(save_in_attachment, pdf_content=pdf_content, res_ids=res_ids)
| 45.5
| 728
|
640
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, models, fields, _
from odoo.exceptions import UserError
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.ondelete(at_uninstall=False)
def _unlink_except_government_document(self):
linked_edi_documents = self.env['account.edi.document'].search([('attachment_id', 'in', self.ids)])
linked_edi_formats_ws = linked_edi_documents.edi_format_id.filtered(lambda edi_format: edi_format._needs_web_services())
if linked_edi_formats_ws:
raise UserError(_("You can't unlink an attachment being an EDI document sent to the government."))
| 45.714286
| 640
|
4,193
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields, _
from odoo.exceptions import UserError
from collections import defaultdict
class AccountJournal(models.Model):
_inherit = 'account.journal'
edi_format_ids = fields.Many2many(comodel_name='account.edi.format',
string='Electronic invoicing',
help='Send XML/EDI invoices',
domain="[('id', 'in', compatible_edi_ids)]",
compute='_compute_edi_format_ids',
readonly=False, store=True)
compatible_edi_ids = fields.Many2many(comodel_name='account.edi.format',
compute='_compute_compatible_edi_ids',
help='EDI format that support moves in this journal')
def write(self, vals):
# OVERRIDE
# Don't allow the user to deactivate an edi format having at least one document to be processed.
if vals.get('edi_format_ids'):
old_edi_format_ids = self.edi_format_ids
res = super().write(vals)
diff_edi_format_ids = old_edi_format_ids - self.edi_format_ids
documents = self.env['account.edi.document'].search([
('move_id.journal_id', 'in', self.ids),
('edi_format_id', 'in', diff_edi_format_ids.ids),
('state', 'in', ('to_cancel', 'to_send')),
])
# If the formats we are unchecking do not need a webservice, we don't need them to be correctly sent
if documents.filtered(lambda d: d.edi_format_id._needs_web_services()):
raise UserError(_('Cannot deactivate (%s) on this journal because not all documents are synchronized', ', '.join(documents.edi_format_id.mapped('display_name'))))
# remove these documents which: do not need a web service & are linked to the edi formats we are unchecking
if documents:
documents.unlink()
return res
else:
return super().write(vals)
@api.depends('type', 'company_id', 'company_id.account_fiscal_country_id')
def _compute_compatible_edi_ids(self):
edi_formats = self.env['account.edi.format'].search([])
for journal in self:
compatible_edis = edi_formats.filtered(lambda e: e._is_compatible_with_journal(journal))
journal.compatible_edi_ids = compatible_edis
@api.depends('type', 'company_id', 'company_id.account_fiscal_country_id')
def _compute_edi_format_ids(self):
edi_formats = self.env['account.edi.format'].search([])
journal_ids = self.ids
if journal_ids:
self._cr.execute('''
SELECT
move.journal_id,
ARRAY_AGG(doc.edi_format_id) AS edi_format_ids
FROM account_edi_document doc
JOIN account_move move ON move.id = doc.move_id
WHERE doc.state IN ('to_cancel', 'to_send')
AND move.journal_id IN %s
GROUP BY move.journal_id
''', [tuple(journal_ids)])
protected_edi_formats_per_journal = {r[0]: set(r[1]) for r in self._cr.fetchall()}
else:
protected_edi_formats_per_journal = defaultdict(set)
for journal in self:
enabled_edi_formats = edi_formats.filtered(lambda e: e._is_compatible_with_journal(journal) and
(e._is_enabled_by_default_on_journal(journal)
or (e in journal.edi_format_ids)))
# The existing edi formats that are already in use so we can't remove it.
protected_edi_format_ids = protected_edi_formats_per_journal.get(journal.id, set())
protected_edi_formats = journal.edi_format_ids.filtered(lambda e: e.id in protected_edi_format_ids)
journal.edi_format_ids = enabled_edi_formats + protected_edi_formats
| 50.518072
| 4,193
|
1,611
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, models
class MailTemplate(models.Model):
_inherit = "mail.template"
def _get_edi_attachments(self, document):
"""
Will return the information about the attachment of the edi document for adding the attachment in the mail.
Can be overridden where e.g. a zip-file needs to be sent with the individual files instead of the entire zip
:param document: an edi document
:return: list with a tuple with the name and base64 content of the attachment
"""
if not document.attachment_id:
return []
return [(document.attachment_id.name, document.attachment_id.datas)]
def generate_email(self, res_ids, fields):
res = super().generate_email(res_ids, fields)
multi_mode = True
if isinstance(res_ids, int):
res_ids = [res_ids]
multi_mode = False
if self.model not in ['account.move', 'account.payment']:
return res
records = self.env[self.model].browse(res_ids)
for record in records:
record_data = (res[record.id] if multi_mode else res)
for doc in record.edi_document_ids:
# The EDI format will be embedded directly inside the PDF and then, don't need to be added to the
# wizard.
if doc.edi_format_id._is_embedding_to_invoice_pdf_needed():
continue
record_data.setdefault('attachments', [])
record_data['attachments'] += self._get_edi_attachments(doc)
return res
| 37.465116
| 1,611
|
1,488
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class UoM(models.Model):
_inherit = 'uom.uom'
def _get_unece_code(self):
""" Returns the UNECE code used for international trading for corresponding to the UoM as per
https://unece.org/fileadmin/DAM/cefact/recommendations/rec20/rec20_rev3_Annex2e.pdf"""
mapping = {
'uom.product_uom_unit': 'C62',
'uom.product_uom_dozen': 'DZN',
'uom.product_uom_kgm': 'KGM',
'uom.product_uom_gram': 'GRM',
'uom.product_uom_day': 'DAY',
'uom.product_uom_hour': 'HUR',
'uom.product_uom_ton': 'TNE',
'uom.product_uom_meter': 'MTR',
'uom.product_uom_km': 'KTM',
'uom.product_uom_cm': 'CMT',
'uom.product_uom_litre': 'LTR',
'uom.product_uom_lb': 'LBR',
'uom.product_uom_oz': 'ONZ',
'uom.product_uom_inch': 'INH',
'uom.product_uom_foot': 'FOT',
'uom.product_uom_mile': 'SMI',
'uom.product_uom_floz': 'OZA',
'uom.product_uom_qt': 'QT',
'uom.product_uom_gal': 'GLL',
'uom.product_uom_cubic_meter': 'MTQ',
'uom.product_uom_cubic_inch': 'INQ',
'uom.product_uom_cubic_foot': 'FTQ',
}
xml_ids = self._get_external_ids().get(self.id, [])
matches = list(set(xml_ids) & set(mapping.keys()))
return matches and mapping[matches[0]] or 'C62'
| 39.157895
| 1,488
|
2,994
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
class AccountPayment(models.Model):
_inherit = 'account.payment'
edi_show_cancel_button = fields.Boolean(
compute='_compute_edi_show_cancel_button')
edi_show_abandon_cancel_button = fields.Boolean(
compute='_compute_edi_show_abandon_cancel_button')
@api.depends('state', 'edi_document_ids.state')
def _compute_edi_show_cancel_button(self):
for payment in self:
if payment.state != 'posted':
payment.edi_show_cancel_button = False
continue
payment.edi_show_cancel_button = any([doc.edi_format_id._needs_web_services()
and doc.state == 'sent'
for doc in payment.edi_document_ids])
@api.depends('state', 'edi_document_ids.state')
def _compute_edi_show_abandon_cancel_button(self):
for payment in self:
payment.edi_show_abandon_cancel_button = any(doc.edi_format_id._needs_web_services()
and doc.state == 'to_cancel'
for doc in payment.edi_document_ids)
def action_process_edi_web_services(self):
return self.move_id.action_process_edi_web_services()
def action_retry_edi_documents_error(self):
self.ensure_one()
return self.move_id.action_retry_edi_documents_error()
def button_cancel_posted_payments(self):
"""
Mark the edi.document related to this payment to be canceled.
"""
to_cancel_documents = self.env['account.edi.document']
for payment in self:
payment.move_id._check_fiscalyear_lock_date()
is_payment_marked = False
for doc in payment.edi_document_ids:
if doc.edi_format_id._needs_web_services() and doc.attachment_id and doc.state == 'sent':
to_cancel_documents |= doc
is_payment_marked = True
if is_payment_marked:
payment.message_post(body=_("A cancellation of the EDI has been requested."))
to_cancel_documents.write({'state': 'to_cancel', 'error': False, 'blocking_level': False})
def button_abandon_cancel_posted_payments(self):
'''Cancel the request for cancellation of the EDI.
'''
documents = self.env['account.edi.document']
for payment in self:
is_payment_marked = False
for doc in payment.edi_document_ids:
if doc.state == 'to_cancel':
documents |= doc
is_payment_marked = True
if is_payment_marked:
payment.message_post(body=_("A request for cancellation of the EDI has been called off."))
documents.write({'state': 'sent'})
| 43.391304
| 2,994
|
13,194
|
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
from psycopg2 import OperationalError
import base64
import logging
_logger = logging.getLogger(__name__)
DEFAULT_BLOCKING_LEVEL = 'error'
class AccountEdiDocument(models.Model):
_name = 'account.edi.document'
_description = 'Electronic Document for an account.move'
# == Stored fields ==
move_id = fields.Many2one('account.move', required=True, ondelete='cascade')
edi_format_id = fields.Many2one('account.edi.format', required=True)
attachment_id = fields.Many2one('ir.attachment', help='The file generated by edi_format_id when the invoice is posted (and this document is processed).')
state = fields.Selection([('to_send', 'To Send'), ('sent', 'Sent'), ('to_cancel', 'To Cancel'), ('cancelled', 'Cancelled')])
error = fields.Html(help='The text of the last error that happened during Electronic Invoice operation.')
blocking_level = fields.Selection(
selection=[('info', 'Info'), ('warning', 'Warning'), ('error', 'Error')],
help="Blocks the current operation of the document depending on the error severity:\n"
" * Info: the document is not blocked and everything is working as it should.\n"
" * Warning: there is an error that doesn't prevent the current Electronic Invoicing operation to succeed.\n"
" * Error: there is an error that blocks the current Electronic Invoicing operation.")
# == Not stored fields ==
name = fields.Char(related='attachment_id.name')
edi_format_name = fields.Char(string='Format Name', related='edi_format_id.name')
edi_content = fields.Binary(compute='_compute_edi_content', compute_sudo=True)
_sql_constraints = [
(
'unique_edi_document_by_move_by_format',
'UNIQUE(edi_format_id, move_id)',
'Only one edi document by move by format',
),
]
@api.depends('move_id', 'error', 'state')
def _compute_edi_content(self):
for doc in self:
res = b''
if doc.state in ('to_send', 'to_cancel'):
move = doc.move_id
config_errors = doc.edi_format_id._check_move_configuration(move)
if config_errors:
res = base64.b64encode('\n'.join(config_errors).encode('UTF-8'))
elif move.is_invoice(include_receipts=True) and doc.edi_format_id._is_required_for_invoice(move):
res = base64.b64encode(doc.edi_format_id._get_invoice_edi_content(doc.move_id))
elif move.payment_id and doc.edi_format_id._is_required_for_payment(move):
res = base64.b64encode(doc.edi_format_id._get_payment_edi_content(doc.move_id))
doc.edi_content = res
def action_export_xml(self):
self.ensure_one()
return {
'type': 'ir.actions.act_url',
'url': '/web/content/account.edi.document/%s/edi_content' % self.id
}
def _prepare_jobs(self):
"""Creates a list of jobs to be performed by '_process_job' for the documents in self.
Each document represent a job, BUT if multiple documents have the same state, edi_format_id,
doc_type (invoice or payment) and company_id AND the edi_format_id supports batching, they are grouped
into a single job.
:returns: A list of tuples (documents, doc_type)
* documents: The documents related to this job. If edi_format_id does not support batch, length is one
* doc_type: Are the moves of this job invoice or payments ?
"""
# Classify jobs by (edi_format, edi_doc.state, doc_type, move.company_id, custom_key)
to_process = {}
documents = self.filtered(lambda d: d.state in ('to_send', 'to_cancel') and d.blocking_level != 'error')
for edi_doc in documents:
move = edi_doc.move_id
edi_format = edi_doc.edi_format_id
if move.is_invoice(include_receipts=True):
doc_type = 'invoice'
elif move.payment_id or move.statement_line_id:
doc_type = 'payment'
else:
continue
custom_key = edi_format._get_batch_key(edi_doc.move_id, edi_doc.state)
key = (edi_format, edi_doc.state, doc_type, move.company_id, custom_key)
to_process.setdefault(key, self.env['account.edi.document'])
to_process[key] |= edi_doc
# Order payments/invoice and create batches.
invoices = []
payments = []
for key, documents in to_process.items():
edi_format, state, doc_type, company_id, custom_key = key
target = invoices if doc_type == 'invoice' else payments
batch = self.env['account.edi.document']
for doc in documents:
if edi_format._support_batching(move=doc.move_id, state=state, company=company_id):
batch |= doc
else:
target.append((doc, doc_type))
if batch:
target.append((batch, doc_type))
return invoices + payments
@api.model
def _process_job(self, documents, doc_type):
"""Post or cancel move_id (invoice or payment) by calling the related methods on edi_format_id.
Invoices are processed before payments.
:param documents: The documents related to this job. If edi_format_id does not support batch, length is one
:param doc_type: Are the moves of this job invoice or payments ?
"""
def _postprocess_post_edi_results(documents, edi_result):
attachments_to_unlink = self.env['ir.attachment']
for document in documents:
move = document.move_id
move_result = edi_result.get(move, {})
if move_result.get('attachment'):
old_attachment = document.attachment_id
document.attachment_id = move_result['attachment']
if not old_attachment.res_model or not old_attachment.res_id:
attachments_to_unlink |= old_attachment
if move_result.get('success') is True:
document.write({
'state': 'sent',
'error': False,
'blocking_level': False,
})
else:
document.write({
'error': move_result.get('error', False),
'blocking_level': move_result.get('blocking_level', DEFAULT_BLOCKING_LEVEL) if 'error' in move_result else False,
})
# Attachments that are not explicitly linked to a business model could be removed because they are not
# supposed to have any traceability from the user.
attachments_to_unlink.unlink()
def _postprocess_cancel_edi_results(documents, edi_result):
moves_to_cancel = self.env['account.move'] # Avoid duplicates
attachments_to_unlink = self.env['ir.attachment']
for document in documents:
move = document.move_id
move_result = edi_result.get(move, {})
if move_result.get('success') is True:
old_attachment = document.sudo().attachment_id
document.write({
'state': 'cancelled',
'error': False,
'attachment_id': False,
'blocking_level': False,
})
if move.state == 'posted':
# The user requested a cancellation of the EDI and it has been approved. Then, the invoice
# can be safely cancelled.
moves_to_cancel |= move
if not old_attachment.res_model or not old_attachment.res_id:
attachments_to_unlink |= old_attachment
else:
document.write({
'error': move_result.get('error', False),
'blocking_level': move_result.get('blocking_level', DEFAULT_BLOCKING_LEVEL) if move_result.get('error') else False,
})
if moves_to_cancel:
moves_to_cancel.button_draft()
moves_to_cancel.button_cancel()
# Attachments that are not explicitly linked to a business model could be removed because they are not
# supposed to have any traceability from the user.
attachments_to_unlink.sudo().unlink()
documents.edi_format_id.ensure_one() # All account.edi.document of a job should have the same edi_format_id
documents.move_id.company_id.ensure_one() # All account.edi.document of a job should be from the same company
if len(set(doc.state for doc in documents)) != 1:
raise ValueError('All account.edi.document of a job should have the same state')
edi_format = documents.edi_format_id
state = documents[0].state
if doc_type == 'invoice':
if state == 'to_send':
invoices = documents.move_id
with invoices._send_only_when_ready():
edi_result = edi_format._post_invoice_edi(invoices)
_postprocess_post_edi_results(documents, edi_result)
elif state == 'to_cancel':
edi_result = edi_format._cancel_invoice_edi(documents.move_id)
_postprocess_cancel_edi_results(documents, edi_result)
elif doc_type == 'payment':
if state == 'to_send':
edi_result = edi_format._post_payment_edi(documents.move_id)
_postprocess_post_edi_results(documents, edi_result)
elif state == 'to_cancel':
edi_result = edi_format._cancel_payment_edi(documents.move_id)
_postprocess_cancel_edi_results(documents, edi_result)
def _process_documents_no_web_services(self):
""" Post and cancel all the documents that don't need a web service.
"""
jobs = self.filtered(lambda d: not d.edi_format_id._needs_web_services())._prepare_jobs()
for documents, doc_type in jobs:
self._process_job(documents, doc_type)
def _process_documents_web_services(self, job_count=None, with_commit=True):
''' Post and cancel all the documents that need a web service.
:param job_count: The maximum number of jobs to process if specified.
:param with_commit: Flag indicating a commit should be made between each job.
:return: The number of remaining jobs to process.
'''
all_jobs = self.filtered(lambda d: d.edi_format_id._needs_web_services())._prepare_jobs()
jobs_to_process = all_jobs[0:job_count] if job_count else all_jobs
for documents, doc_type in jobs_to_process:
move_to_lock = documents.move_id
attachments_potential_unlink = documents.attachment_id.filtered(lambda a: not a.res_model and not a.res_id)
try:
with self.env.cr.savepoint(flush=False):
self._cr.execute('SELECT * FROM account_edi_document WHERE id IN %s FOR UPDATE NOWAIT', [tuple(documents.ids)])
self._cr.execute('SELECT * FROM account_move WHERE id IN %s FOR UPDATE NOWAIT', [tuple(move_to_lock.ids)])
# Locks the attachments that might be unlinked
if attachments_potential_unlink:
self._cr.execute('SELECT * FROM ir_attachment WHERE id IN %s FOR UPDATE NOWAIT', [tuple(attachments_potential_unlink.ids)])
except OperationalError as e:
if e.pgcode == '55P03':
_logger.debug('Another transaction already locked documents rows. Cannot process documents.')
if not with_commit:
raise UserError(_('This document is being sent by another process already. '))
continue
else:
raise e
self._process_job(documents, doc_type)
if with_commit and len(jobs_to_process) > 1:
self.env.cr.commit()
return len(all_jobs) - len(jobs_to_process)
@api.model
def _cron_process_documents_web_services(self, job_count=None):
''' Method called by the EDI cron processing all web-services.
:param job_count: Limit explicitely the number of web service calls. If not provided, process all.
'''
edi_documents = self.search([('state', 'in', ('to_send', 'to_cancel')), ('move_id.state', '=', 'posted')])
nb_remaining_jobs = edi_documents._process_documents_web_services(job_count=job_count)
# Mark the CRON to be triggered again asap since there is some remaining jobs to process.
if nb_remaining_jobs > 0:
self.env.ref('account_edi.ir_cron_edi_network')._trigger()
| 50.1673
| 13,194
|
3,047
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "Ecuadorian Accounting",
"version": "3.3",
"description": """
Functional
----------
This module adds accounting features for Ecuadorian localization, which
represent the minimum requirements to operate a business in Ecuador in compliance
with local regulation bodies such as the ecuadorian tax authority -SRI- and the
Superintendency of Companies -Super Intendencia de Compañías-
Follow the next configuration steps:
1. Go to your company and configure your country as Ecuador
2. Install the invoicing or accounting module, everything will be handled automatically
Highlights:
* Ecuadorian chart of accounts will be automatically installed, based on example provided by Super Intendencia de Compañías
* List of taxes (including withholds) will also be installed, you can switch off the ones your company doesn't use
* Fiscal position, document types, list of local banks, list of local states, etc, will also be installed
Technical
---------
Master Data:
* Chart of Accounts, based on recomendation by Super Cías
* Ecuadorian Taxes, Tax Tags, and Tax Groups
* Ecuadorian Fiscal Positions
* Document types (there are about 41 purchase documents types in Ecuador)
* Identification types
* Ecuador banks
* Partners: Consumidor Final, SRI, IESS, and also basic VAT validation
""",
"author": "OPA CONSULTING & TRESCLOUD",
"category": "Accounting/Localizations/Account Charts",
"maintainer": "OPA CONSULTING",
"website": "https://opa-consulting.com",
"license": "LGPL-3",
"depends": [
"base",
"base_iban",
"account",
"account_debit_note",
"l10n_latam_invoice_document",
"l10n_latam_base",
],
"data": [
# Chart of Accounts
"data/account_chart_template_data.xml",
"data/account_group_template_data.xml",
"data/account.account.template.csv",
"data/account_chart_template_setup_accounts.xml",
# Taxes
"data/account_tax_group_data.xml",
"data/account_tax_report_data.xml",
"data/account_tax_template_vat_data.xml",
"data/account_tax_template_withhold_profit_data.xml",
"data/account_tax_template_withhold_vat_data.xml",
"data/account_fiscal_position_template.xml",
# Partners data
"data/res.bank.csv",
"data/l10n_latam_identification_type_data.xml",
"data/res_partner_data.xml",
# Other data
"data/l10n_latam.document.type.csv",
"data/account_chart_template_configure_data.xml",
"data/l10n_ec.sri.payment.csv",
"views/account_tax_view.xml",
"views/l10n_latam_document_type_view.xml",
"views/l10n_ec_sri_payment.xml",
"views/account_journal_view.xml",
# Security
"security/ir.model.access.csv",
],
"demo": [
"demo/demo_company.xml",
],
"installable": True,
"auto_install": False,
"application": False,
}
| 37.097561
| 3,042
|
1,110
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class AccountChartTemplate(models.Model):
_inherit = "account.chart.template"
@api.model
def _get_demo_data_move(self):
ref = self.env.ref
cid = self.env.company.id
model, data = super()._get_demo_data_move()
if self.env.company.account_fiscal_country_id.code == 'EC':
document_type = ref('l10n_ec.ec_dt_18', False) and ref('l10n_ec.ec_dt_18').id or False
data[f'{cid}_demo_invoice_1']['l10n_latam_document_type_id'] = document_type
data[f'{cid}_demo_invoice_2']['l10n_latam_document_type_id'] = document_type
data[f'{cid}_demo_invoice_3']['l10n_latam_document_type_id'] = document_type
data[f'{cid}_demo_invoice_followup']['l10n_latam_document_type_id'] = document_type
data[f'{cid}_demo_invoice_5']['l10n_latam_document_number'] = '001-001-00001'
data[f'{cid}_demo_invoice_equipment_purchase']['l10n_latam_document_number'] = '001-001-00002'
return model, data
| 44.4
| 1,110
|
1,735
|
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 AccountTax(models.Model):
_inherit = "account.tax"
l10n_ec_code_base = fields.Char(
string="Code base",
help="Tax declaration code of the base amount prior to the calculation of the tax",
)
l10n_ec_code_applied = fields.Char(
string="Code applied",
help="Tax declaration code of the resulting amount after the calculation of the tax",
)
l10n_ec_code_ats = fields.Char(
string="Code ATS",
help="Tax Identification Code for the Simplified Transactional Annex",
)
class AccountTaxTemplate(models.Model):
_inherit = "account.tax.template"
def _get_tax_vals(self, company, tax_template_to_tax):
vals = super(AccountTaxTemplate, self)._get_tax_vals(
company, tax_template_to_tax
)
vals.update(
{
"l10n_ec_code_base": self.l10n_ec_code_base,
"l10n_ec_code_applied": self.l10n_ec_code_applied,
"l10n_ec_code_ats": self.l10n_ec_code_ats,
}
)
return vals
l10n_ec_code_base = fields.Char(
string="Code base",
help="Tax declaration code of the base amount prior to the calculation of the tax",
)
l10n_ec_code_applied = fields.Char(
string="Code applied",
help="Tax declaration code of the resulting amount after the calculation of the tax",
)
l10n_ec_code_ats = fields.Char(
string="Code ATS",
help="Tax Identification Code for the Simplified Transactional Annex",
)
| 31.735849
| 1,682
|
7,770
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
from odoo.addons.l10n_ec.models.res_partner import verify_final_consumer
_DOCUMENTS_MAPPING = {
"01": [
'ec_dt_01',
'ec_dt_02',
'ec_dt_04',
'ec_dt_05',
'ec_dt_08',
'ec_dt_09',
'ec_dt_11',
'ec_dt_12',
'ec_dt_20',
'ec_dt_21',
'ec_dt_41',
'ec_dt_42',
'ec_dt_43',
'ec_dt_45',
'ec_dt_47',
'ec_dt_48'
],
"02": [
'ec_dt_03',
'ec_dt_04',
'ec_dt_05',
'ec_dt_09',
'ec_dt_19',
'ec_dt_41',
'ec_dt_294',
'ec_dt_344'
],
"03": [
'ec_dt_03',
'ec_dt_04',
'ec_dt_05',
'ec_dt_09',
'ec_dt_15',
'ec_dt_19',
'ec_dt_41',
'ec_dt_45',
'ec_dt_294',
'ec_dt_344'
],
"04": [
'ec_dt_04',
'ec_dt_05',
'ec_dt_18',
'ec_dt_41',
'ec_dt_44',
'ec_dt_47',
'ec_dt_48',
'ec_dt_49',
'ec_dt_50',
'ec_dt_51',
'ec_dt_52',
'ec_dt_370',
'ec_dt_371',
'ec_dt_372',
'ec_dt_373'
],
"05": [
'ec_dt_04',
'ec_dt_05',
'ec_dt_18',
'ec_dt_41',
'ec_dt_44',
'ec_dt_47',
'ec_dt_48',
'ec_dt_370',
'ec_dt_371',
'ec_dt_372',
'ec_dt_373'
],
"06": [
'ec_dt_04',
'ec_dt_05',
'ec_dt_18',
'ec_dt_41',
'ec_dt_44',
'ec_dt_47',
'ec_dt_48',
'ec_dt_370',
'ec_dt_371',
'ec_dt_372',
'ec_dt_373'
],
"07": [
'ec_dt_04',
'ec_dt_05',
'ec_dt_18'
],
"09": [
'ec_dt_01',
'ec_dt_04',
'ec_dt_05',
'ec_dt_15',
'ec_dt_16',
'ec_dt_41',
'ec_dt_47',
'ec_dt_48',
],
"20": [
'ec_dt_01',
'ec_dt_04',
'ec_dt_05',
'ec_dt_15',
'ec_dt_16',
'ec_dt_41',
'ec_dt_47',
'ec_dt_48'
],
"21": [
'ec_dt_01',
'ec_dt_04',
'ec_dt_05',
'ec_dt_15',
'ec_dt_16',
'ec_dt_41',
'ec_dt_47',
'ec_dt_48'
],
}
class AccountMove(models.Model):
_inherit = "account.move"
l10n_ec_sri_payment_id = fields.Many2one(
comodel_name="l10n_ec.sri.payment",
string="Payment Method (SRI)",
)
def _get_l10n_ec_identification_type(self):
self.ensure_one()
move = self
it_ruc = self.env.ref("l10n_ec.ec_ruc", False)
it_dni = self.env.ref("l10n_ec.ec_dni", False)
it_passport = self.env.ref("l10n_ec.ec_passport", False)
is_final_consumer = verify_final_consumer(move.partner_id.commercial_partner_id.vat)
is_ruc = move.partner_id.commercial_partner_id.l10n_latam_identification_type_id.id == it_ruc.id
is_dni = move.partner_id.commercial_partner_id.l10n_latam_identification_type_id.id == it_dni.id
is_passport = move.partner_id.commercial_partner_id.l10n_latam_identification_type_id.id == it_passport.id
l10n_ec_is_exportation = move.partner_id.commercial_partner_id.country_id.code != 'EC'
identification_code = False
if move.move_type in ("in_invoice", "in_refund"):
if is_ruc:
identification_code = "01"
elif is_dni:
identification_code = "02"
else:
identification_code = "03"
elif move.move_type in ("out_invoice", "out_refund"):
if not l10n_ec_is_exportation:
if is_final_consumer:
identification_code = "07"
elif is_ruc:
identification_code = "04"
elif is_dni:
identification_code = "05"
elif is_passport:
identification_code = "06"
else:
if is_ruc:
identification_code = "20"
elif is_dni:
identification_code = "21"
else:
identification_code = "09"
return identification_code
@api.model
def _get_l10n_ec_documents_allowed(self, identification_code):
documents_allowed = self.env['l10n_latam.document.type']
for document_ref in _DOCUMENTS_MAPPING.get(identification_code, []):
document_allowed = self.env.ref('l10n_ec.%s' % document_ref, False)
if document_allowed:
documents_allowed |= document_allowed
return documents_allowed
def _get_l10n_ec_internal_type(self):
self.ensure_one()
internal_type = self.env.context.get("internal_type", "invoice")
if self.move_type in ("out_refund", "in_refund"):
internal_type = "credit_note"
if self.debit_origin_id:
internal_type = "debit_note"
return internal_type
def _get_l10n_latam_documents_domain(self):
self.ensure_one()
if self.journal_id.company_id.account_fiscal_country_id != self.env.ref('base.ec') or not \
self.journal_id.l10n_latam_use_documents:
return super()._get_l10n_latam_documents_domain()
domain = [
('country_id.code', '=', 'EC'),
('internal_type', 'in', ['invoice', 'debit_note', 'credit_note', 'invoice_in'])
]
internal_type = self._get_l10n_ec_internal_type()
allowed_documents = self._get_l10n_ec_documents_allowed(self._get_l10n_ec_identification_type())
if internal_type and allowed_documents:
domain.append(("id", "in", allowed_documents.filtered(lambda x: x.internal_type == internal_type).ids))
return domain
def _get_ec_formatted_sequence(self, number=0):
return "%s %s-%s-%09d" % (
self.l10n_latam_document_type_id.doc_code_prefix,
self.journal_id.l10n_ec_entity,
self.journal_id.l10n_ec_emission,
number,
)
def _get_starting_sequence(self):
"""If use documents then will create a new starting sequence using the document type code prefix and the
journal document number with a 8 padding number"""
if (
self.journal_id.l10n_latam_use_documents
and self.company_id.country_id.code == "EC"
):
if self.l10n_latam_document_type_id:
return self._get_ec_formatted_sequence()
return super()._get_starting_sequence()
def _get_last_sequence_domain(self, relaxed=False):
l10n_latam_document_type_model = self.env['l10n_latam.document.type']
where_string, param = super(AccountMove, self)._get_last_sequence_domain(relaxed)
if self.country_code == "EC" and self.l10n_latam_use_documents and self.move_type in (
"out_invoice",
"out_refund",
"in_invoice",
"in_refund",
):
where_string, param = super(AccountMove, self)._get_last_sequence_domain(False)
internal_type = self._get_l10n_ec_internal_type()
document_types = l10n_latam_document_type_model.search([
('internal_type', '=', internal_type),
('country_id.code', '=', 'EC'),
])
if document_types:
where_string += """
AND l10n_latam_document_type_id in %(l10n_latam_document_type_id)s
"""
param["l10n_latam_document_type_id"] = tuple(document_types.ids)
return where_string, param
| 31.45749
| 7,770
|
304
|
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 SriPayment(models.Model):
_name = "l10n_ec.sri.payment"
_description = "SRI Payment Method"
name = fields.Char("Name")
code = fields.Char("Code")
| 23.384615
| 304
|
805
|
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class AccountJournal(models.Model):
_inherit = "account.journal"
l10n_ec_entity = fields.Char(string="Emission Entity", size=3, default="001")
l10n_ec_emission = fields.Char(string="Emission Point", size=3, default="001")
l10n_ec_emission_address_id = fields.Many2one(
comodel_name="res.partner",
string="Emission address",
domain="['|', ('id', '=', company_partner_id), '&', ('id', 'child_of', company_partner_id), ('type', '!=', 'contact')]",
)
l10n_ec_emission_type = fields.Selection(
string="Emission type",
selection=[
("pre_printed", "Pre Printed"),
("auto_printer", "Auto Printer"),
("electronic", "Electronic"),
],
default="electronic",
)
| 33.541667
| 805
|
1,411
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import UserError
import re
class L10nLatamDocumentType(models.Model):
_inherit = "l10n_latam.document.type"
internal_type = fields.Selection(
selection_add=[
("purchase_liquidation", "Purchase Liquidation"),
]
)
l10n_ec_check_format = fields.Boolean(
string="Check Number Format EC", default=False
)
def _format_document_number(self, document_number):
self.ensure_one()
if self.country_id != self.env.ref("base.ec"):
return super()._format_document_number(document_number)
if not document_number:
return False
if self.l10n_ec_check_format:
document_number = re.sub(r'\s+', "", document_number) # remove any whitespace
num_match = re.match(r'(\d{1,3})-(\d{1,3})-(\d{1,9})', document_number)
if num_match:
# Fill each number group with zeroes (3, 3 and 9 respectively)
document_number = "-".join([n.zfill(3 if i < 2 else 9) for i, n in enumerate(num_match.groups())])
else:
raise UserError(
_(u"Ecuadorian Document %s must be like 001-001-123456789")
% (self.display_name)
)
return document_number
| 36.179487
| 1,411
|
775
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
_TYPE_EC = [
("vat12", "VAT 12%"),
("vat14", "VAT 14%"),
("zero_vat", "VAT 0%"),
("not_charged_vat", "VAT Not Charged"),
("exempt_vat", "VAT Exempt"),
("withhold_vat", "VAT Withhold"),
("withhold_income_tax", "Profit Withhold"),
("ice", "Special Consumptions Tax (ICE)"),
("irbpnr", "Plastic Bottles (IRBPNR)"),
("outflows_tax", "Exchange Outflows"),
("other", "Others"),
]
class AccountTaxGroup(models.Model):
_inherit = "account.tax.group"
l10n_ec_type = fields.Selection(
_TYPE_EC, string="Type Ecuadorian Tax", help="Ecuadorian taxes subtype"
)
| 28.807692
| 749
|
274
|
py
|
PYTHON
|
15.0
|
from odoo import models
class ResCompany(models.Model):
_inherit = "res.company"
def _localization_use_documents(self):
self.ensure_one()
return self.account_fiscal_country_id.code == "EC" or super(ResCompany, self)._localization_use_documents()
| 27.4
| 274
|
2,682
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import ValidationError
import logging
_logger = logging.getLogger(__name__)
def verify_final_consumer(vat):
all_number_9 = False
try:
all_number_9 = vat and all(int(number) == 9 for number in vat) or False
except ValueError as e:
_logger.debug('Vat is not only numbers %s', e)
return all_number_9 and len(vat) == 13
class ResPartner(models.Model):
_inherit = "res.partner"
@api.constrains("vat", "country_id", "l10n_latam_identification_type_id")
def check_vat(self):
it_ruc = self.env.ref("l10n_ec.ec_ruc", False)
it_dni = self.env.ref("l10n_ec.ec_dni", False)
ecuadorian_partners = self.filtered(
lambda x: x.country_id == self.env.ref("base.ec")
)
for partner in ecuadorian_partners:
if partner.vat:
if partner.l10n_latam_identification_type_id.id in (
it_ruc.id,
it_dni.id,
):
if partner.l10n_latam_identification_type_id.id == it_dni.id and len(partner.vat) != 10:
raise ValidationError(_('If your identification type is %s, it must be 10 digits')
% it_dni.display_name)
if partner.l10n_latam_identification_type_id.id == it_ruc.id and len(partner.vat) != 13:
raise ValidationError(_('If your identification type is %s, it must be 13 digits')
% it_ruc.display_name)
final_consumer = verify_final_consumer(partner.vat)
if final_consumer:
valid = True
else:
valid = self.is_valid_ruc_ec(partner.vat)
if not valid:
error_message = ""
if partner.l10n_latam_identification_type_id.id == it_dni.id:
error_message = _("VAT %s is not valid for an Ecuadorian DNI, "
"it must be like this form 0915068258") % partner.vat
if partner.l10n_latam_identification_type_id.id == it_ruc.id:
error_message = _("VAT %s is not valid for an Ecuadorian company, "
"it must be like this form 0993143790001") % partner.vat
raise ValidationError(error_message)
return super(ResPartner, self - ecuadorian_partners).check_vat()
| 47.052632
| 2,682
|
1,041
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Czech - Accounting',
'version': '1.0',
'author': '26HOUSE',
'website': 'http://www.26house.com',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Czech accounting chart and localization. With Chart of Accounts with taxes and basic fiscal positions.
Tento modul definuje:
- Českou účetní osnovu za rok 2020
- Základní sazby pro DPH z prodeje a nákupu
- Základní fiskální pozice pro českou legislativu
""",
'depends': [
'account',
'base_iban',
'base_vat',
],
'data': [
'data/l10n_cz_coa_data.xml',
'data/account.account.template.csv',
'data/account.group.template.csv',
'data/l10n_cz_coa_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_data.xml',
'data/account_fiscal_position_data.xml',
'data/account_chart_template_data.xml'
],
'demo': ['data/demo_company.xml'],
'license': 'LGPL-3',
}
| 27.810811
| 1,029
|
907
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name' : 'Analytic Accounting',
'version': '1.1',
'category': 'Accounting/Accounting',
'depends' : ['base', 'mail', 'uom'],
'description': """
Module for defining analytic accounting object.
===============================================
In Odoo, analytic accounts are linked to general accounts but are treated
totally independently. So, you can enter various different analytic operations
that have no counterpart in the general financial accounts.
""",
'data': [
'security/analytic_security.xml',
'security/ir.model.access.csv',
'views/analytic_account_views.xml',
],
'demo': [
'data/analytic_demo.xml',
'data/analytic_account_demo.xml',
],
'installable': True,
'auto_install': False,
'license': 'LGPL-3',
}
| 31.275862
| 907
|
348
|
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'
group_analytic_accounting = fields.Boolean(string='Analytic Accounting', implied_group='analytic.group_analytic_accounting')
| 38.666667
| 348
|
10,872
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import api, fields, models, _
from odoo.osv import expression
from odoo.exceptions import ValidationError
class AccountAnalyticDistribution(models.Model):
_name = 'account.analytic.distribution'
_description = 'Analytic Account Distribution'
_rec_name = 'account_id'
account_id = fields.Many2one('account.analytic.account', string='Analytic Account', required=True)
percentage = fields.Float(string='Percentage', required=True, default=100.0)
name = fields.Char(string='Name', related='account_id.name', readonly=False)
tag_id = fields.Many2one('account.analytic.tag', string="Parent tag", required=True)
_sql_constraints = [
('check_percentage', 'CHECK(percentage >= 0 AND percentage <= 100)',
'The percentage of an analytic distribution should be between 0 and 100.')
]
class AccountAnalyticTag(models.Model):
_name = 'account.analytic.tag'
_description = 'Analytic Tags'
name = fields.Char(string='Analytic Tag', index=True, required=True)
color = fields.Integer('Color Index')
active = fields.Boolean(default=True, help="Set active to false to hide the Analytic Tag without removing it.")
active_analytic_distribution = fields.Boolean('Analytic Distribution')
analytic_distribution_ids = fields.One2many('account.analytic.distribution', 'tag_id', string="Analytic Accounts")
company_id = fields.Many2one('res.company', string='Company')
class AccountAnalyticGroup(models.Model):
_name = 'account.analytic.group'
_description = 'Analytic Categories'
_parent_store = True
_rec_name = 'complete_name'
name = fields.Char(required=True)
description = fields.Text(string='Description')
parent_id = fields.Many2one('account.analytic.group', string="Parent", ondelete='cascade', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
parent_path = fields.Char(index=True)
children_ids = fields.One2many('account.analytic.group', 'parent_id', string="Childrens")
complete_name = fields.Char('Complete Name', compute='_compute_complete_name', recursive=True, store=True)
company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company)
@api.depends('name', 'parent_id.complete_name')
def _compute_complete_name(self):
for group in self:
if group.parent_id:
group.complete_name = '%s / %s' % (group.parent_id.complete_name, group.name)
else:
group.complete_name = group.name
class AccountAnalyticAccount(models.Model):
_name = 'account.analytic.account'
_inherit = ['mail.thread']
_description = 'Analytic Account'
_order = 'code, name asc'
_check_company_auto = True
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
"""
Override read_group to calculate the sum of the non-stored fields that depend on the user context
"""
res = super(AccountAnalyticAccount, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
accounts = self.env['account.analytic.account']
for line in res:
if '__domain' in line:
accounts = self.search(line['__domain'])
if 'balance' in fields:
line['balance'] = sum(accounts.mapped('balance'))
if 'debit' in fields:
line['debit'] = sum(accounts.mapped('debit'))
if 'credit' in fields:
line['credit'] = sum(accounts.mapped('credit'))
return res
@api.depends('line_ids.amount')
def _compute_debit_credit_balance(self):
Curr = self.env['res.currency']
analytic_line_obj = self.env['account.analytic.line']
domain = [
('account_id', 'in', self.ids),
('company_id', 'in', [False] + self.env.companies.ids)
]
if self._context.get('from_date', False):
domain.append(('date', '>=', self._context['from_date']))
if self._context.get('to_date', False):
domain.append(('date', '<=', self._context['to_date']))
if self._context.get('tag_ids'):
tag_domain = expression.OR([[('tag_ids', 'in', [tag])] for tag in self._context['tag_ids']])
domain = expression.AND([domain, tag_domain])
user_currency = self.env.company.currency_id
credit_groups = analytic_line_obj.read_group(
domain=domain + [('amount', '>=', 0.0)],
fields=['account_id', 'currency_id', 'amount'],
groupby=['account_id', 'currency_id'],
lazy=False,
)
data_credit = defaultdict(float)
for l in credit_groups:
data_credit[l['account_id'][0]] += Curr.browse(l['currency_id'][0])._convert(
l['amount'], user_currency, self.env.company, fields.Date.today())
debit_groups = analytic_line_obj.read_group(
domain=domain + [('amount', '<', 0.0)],
fields=['account_id', 'currency_id', 'amount'],
groupby=['account_id', 'currency_id'],
lazy=False,
)
data_debit = defaultdict(float)
for l in debit_groups:
data_debit[l['account_id'][0]] += Curr.browse(l['currency_id'][0])._convert(
l['amount'], user_currency, self.env.company, fields.Date.today())
for account in self:
account.debit = abs(data_debit.get(account.id, 0.0))
account.credit = data_credit.get(account.id, 0.0)
account.balance = account.credit - account.debit
name = fields.Char(string='Analytic Account', index=True, required=True, tracking=True)
code = fields.Char(string='Reference', index=True, tracking=True)
active = fields.Boolean('Active', help="If the active field is set to False, it will allow you to hide the account without removing it.", default=True)
group_id = fields.Many2one('account.analytic.group', string='Group', check_company=True)
line_ids = fields.One2many('account.analytic.line', 'account_id', string="Analytic Lines")
company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company)
# use auto_join to speed up name_search call
partner_id = fields.Many2one('res.partner', string='Customer', auto_join=True, tracking=True, check_company=True)
balance = fields.Monetary(compute='_compute_debit_credit_balance', string='Balance', groups='account.group_account_readonly')
debit = fields.Monetary(compute='_compute_debit_credit_balance', string='Debit', groups='account.group_account_readonly')
credit = fields.Monetary(compute='_compute_debit_credit_balance', string='Credit', groups='account.group_account_readonly')
currency_id = fields.Many2one(related="company_id.currency_id", string="Currency", readonly=True)
def name_get(self):
res = []
for analytic in self:
name = analytic.name
if analytic.code:
name = '[' + analytic.code + '] ' + name
if analytic.partner_id.commercial_partner_id.name:
name = name + ' - ' + analytic.partner_id.commercial_partner_id.name
res.append((analytic.id, name))
return res
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if operator not in ('ilike', 'like', '=', '=like', '=ilike', 'not ilike'):
return super(AccountAnalyticAccount, self)._name_search(name, args, operator, limit, name_get_uid=name_get_uid)
args = args or []
if operator == 'ilike' and not (name or '').strip():
domain = []
else:
# `partner_id` is in auto_join and the searches using ORs with auto_join fields doesn't work
# we have to cut the search in two searches ... https://github.com/odoo/odoo/issues/25175
partner_ids = self.env['res.partner']._search([('name', operator, name)], limit=limit, access_rights_uid=name_get_uid)
domain_operator = '&' if operator == 'not ilike' else '|'
partner_domain = [('partner_id', 'in', partner_ids)]
if operator == 'not ilike':
partner_domain = expression.OR([partner_domain, [('partner_id', '=', False)]])
domain = [domain_operator, domain_operator, ('code', operator, name), ('name', operator, name)] + partner_domain
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
class AccountAnalyticLine(models.Model):
_name = 'account.analytic.line'
_description = 'Analytic Line'
_order = 'date desc, id desc'
_check_company_auto = True
@api.model
def _default_user(self):
return self.env.context.get('user_id', self.env.user.id)
name = fields.Char('Description', required=True)
date = fields.Date('Date', required=True, index=True, default=fields.Date.context_today)
amount = fields.Monetary('Amount', required=True, default=0.0)
unit_amount = fields.Float('Quantity', default=0.0)
product_uom_id = fields.Many2one('uom.uom', string='Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_uom_id.category_id', string='UoM Category', readonly=True)
account_id = fields.Many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='restrict', index=True, check_company=True)
partner_id = fields.Many2one('res.partner', string='Partner', check_company=True)
user_id = fields.Many2one('res.users', string='User', default=_default_user)
tag_ids = fields.Many2many('account.analytic.tag', 'account_analytic_line_tag_rel', 'line_id', 'tag_id', string='Tags', copy=True, check_company=True)
company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company)
currency_id = fields.Many2one(related="company_id.currency_id", string="Currency", readonly=True, store=True, compute_sudo=True)
group_id = fields.Many2one('account.analytic.group', related='account_id.group_id', store=True, readonly=True, compute_sudo=True)
category = fields.Selection([('other', 'Other')], default='other')
@api.constrains('company_id', 'account_id')
def _check_company_id(self):
for line in self:
if line.account_id.company_id and line.company_id.id != line.account_id.company_id.id:
raise ValidationError(_('The selected account belongs to another company than the one you\'re trying to create an analytic item for'))
| 53.294118
| 10,872
|
1,436
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Newsletter Subscribe Button',
'summary': 'Attract visitors to subscribe to mailing lists',
'description': """
This module brings a new building block with a mailing list widget to drop on any page of your website.
On a simple click, your visitors can subscribe to mailing lists managed in the Email Marketing app.
""",
'version': '1.0',
'category': 'Website/Website',
'depends': ['website', 'mass_mailing', 'google_recaptcha'],
'data': [
'views/snippets/s_popup.xml',
'views/snippets_templates.xml',
],
'auto_install': ['website', 'mass_mailing'],
'assets': {
'web.assets_frontend': [
'website_mass_mailing/static/src/scss/website_mass_mailing_popup.scss',
'website_mass_mailing/static/src/js/website_mass_mailing.js',
],
'website.assets_wysiwyg': [
'website_mass_mailing/static/src/js/wysiwyg.js',
'website_mass_mailing/static/src/js/website_mass_mailing.editor.js',
'website_mass_mailing/static/src/scss/website_mass_mailing_edit_mode.scss',
],
'web.assets_tests': [
'website_mass_mailing/static/tests/**/*',
],
'web.assets_qweb': [
'website_mass_mailing/static/src/xml/*.xml',
],
},
'license': 'LGPL-3',
}
| 38.810811
| 1,436
|
736
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
import odoo.tests
@odoo.tests.common.tagged('post_install', '-at_install')
class TestSnippets(odoo.tests.HttpCase):
def test_01_newsletter_popup(self):
self.start_tour("/?enable_editor=1", "newsletter_popup_edition", login='admin')
self.start_tour("/", "newsletter_popup_use", login=None)
mailing_list = self.env['mailing.list'].search([], limit=1)
emails = mailing_list.contact_ids.mapped('email')
self.assertIn("hello@world.com", emails)
def test_02_newsletter_block_edition(self):
self.start_tour("/?enable_editor=1", "newsletter_block_edition", login='admin')
| 38.736842
| 736
|
849
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ResCompany(models.Model):
_inherit = "res.company"
def _get_social_media_links(self):
social_media_links = super()._get_social_media_links()
website_id = self.env['website'].get_current_website()
social_media_links.update({
'social_facebook': website_id.social_facebook or social_media_links.get('social_facebook'),
'social_linkedin': website_id.social_linkedin or social_media_links.get('social_linkedin'),
'social_twitter': website_id.social_twitter or social_media_links.get('social_twitter'),
'social_instagram': website_id.social_instagram or social_media_links.get('social_instagram')
})
return social_media_links
| 44.684211
| 849
|
2,361
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _
from odoo.http import route, request
from odoo.addons.mass_mailing.controllers import main
class MassMailController(main.MassMailController):
@route('/website_mass_mailing/is_subscriber', type='json', website=True, auth="public")
def is_subscriber(self, list_id, **post):
email = None
if not request.env.user._is_public():
email = request.env.user.email
elif request.session.get('mass_mailing_email'):
email = request.session['mass_mailing_email']
is_subscriber = False
if email:
contacts_count = request.env['mailing.contact.subscription'].sudo().search_count([('list_id', 'in', [int(list_id)]), ('contact_id.email', '=', email), ('opt_out', '=', False)])
is_subscriber = contacts_count > 0
return {'is_subscriber': is_subscriber, 'email': email}
@route('/website_mass_mailing/subscribe', type='json', website=True, auth="public")
def subscribe(self, list_id, email, **post):
if not request.env['ir.http']._verify_request_recaptcha_token('website_mass_mailing_subscribe'):
return {
'toast_type': 'danger',
'toast_content': _("Suspicious activity detected by Google reCaptcha."),
}
ContactSubscription = request.env['mailing.contact.subscription'].sudo()
Contacts = request.env['mailing.contact'].sudo()
name, email = Contacts.get_name_email(email)
subscription = ContactSubscription.search([('list_id', '=', int(list_id)), ('contact_id.email', '=', email)], limit=1)
if not subscription:
# inline add_to_list as we've already called half of it
contact_id = Contacts.search([('email', '=', email)], limit=1)
if not contact_id:
contact_id = Contacts.create({'name': name, 'email': email})
ContactSubscription.create({'contact_id': contact_id.id, 'list_id': int(list_id)})
elif subscription.opt_out:
subscription.opt_out = False
# add email to session
request.session['mass_mailing_email'] = email
return {
'toast_type': 'success',
'toast_content': _("Thanks for subscribing!"),
}
| 46.294118
| 2,361
|
1,881
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'pos_sale',
'version': '1.1',
'category': 'Hidden',
'sequence': 6,
'summary': 'Link module between Point of Sale and Sales',
'description': """
This module adds a custom Sales Team for the Point of Sale. This enables you to view and manage your point of sale sales with more ease.
""",
'depends': ['point_of_sale', 'sale_management'],
'data': [
'data/pos_sale_data.xml',
'security/pos_sale_security.xml',
'security/ir.model.access.csv',
'views/point_of_sale_report.xml',
'views/sale_order_views.xml',
'views/pos_order_views.xml',
'views/sales_team_views.xml',
'views/pos_config_views.xml',
'views/stock_template.xml',
],
'installable': True,
'auto_install': True,
'assets': {
'point_of_sale.assets': [
'pos_sale/static/src/css/pos_sale.css',
'pos_sale/static/src/js/models.js',
'pos_sale/static/src/js/SetSaleOrderButton.js',
'pos_sale/static/src/js/OrderManagementScreen/MobileSaleOrderManagementScreen.js',
'pos_sale/static/src/js/OrderManagementScreen/SaleOrderFetcher.js',
'pos_sale/static/src/js/OrderManagementScreen/SaleOrderList.js',
'pos_sale/static/src/js/OrderManagementScreen/SaleOrderManagementControlPanel.js',
'pos_sale/static/src/js/OrderManagementScreen/SaleOrderManagementScreen.js',
'pos_sale/static/src/js/OrderManagementScreen/SaleOrderRow.js',
'pos_sale/static/src/js/ProductScreen.js',
],
'web.assets_qweb': [
'pos_sale/static/src/xml/**/*',
],
'web.assets_tests': [
'pos_sale/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 37.62
| 1,881
|
3,402
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
from odoo.addons.point_of_sale.tests.common import TestPoSCommon
@odoo.tests.tagged('post_install', '-at_install')
class TestPoSSaleReport(TestPoSCommon):
def setUp(self):
super(TestPoSSaleReport, self).setUp()
self.config = self.basic_config
self.product0 = self.create_product('Product 0', self.categ_basic, 0.0, 0.0)
def test_weight_and_volume(self):
self.product0.product_tmpl_id.weight = 3
self.product0.product_tmpl_id.volume = 4
self.open_new_session()
session = self.pos_session
orders = []
# Process two orders
orders.append(self.create_ui_order_data([(self.product0, 3)]))
orders.append(self.create_ui_order_data([(self.product0, 1)]))
self.env['pos.order'].create_from_ui(orders)
# Duplicate the first line of the first order
session.order_ids[0].lines.copy()
session.action_pos_session_closing_control()
# PoS Orders have negative IDs to avoid conflict, so reports[0] will correspond to the newest order
reports = self.env['sale.report'].sudo().search([('product_id', '=', self.product0.id)], order='id', limit=2)
self.assertEqual(reports[0].weight, 3)
self.assertEqual(reports[0].volume, 4)
self.assertEqual(reports[1].weight, 18)
self.assertEqual(reports[1].volume, 24)
def test_weight_and_volume_product_variant(self):
colors = ['red', 'blue']
prod_attr = self.env['product.attribute'].create({'name': 'Color', 'create_variant': 'dynamic'})
prod_attr_values = self.env['product.attribute.value'].create([{'name': color, 'attribute_id': prod_attr.id, 'sequence': 1} for color in colors])
uom_unit = self.env.ref('uom.product_uom_unit')
product_template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': prod_attr.id,
'value_ids': [(6, 0, prod_attr_values.ids)]
})]
})
prod_tmpl_attrs = self.env['product.template.attribute.value'].search([
('attribute_line_id', '=', product_template.attribute_line_ids.id),
('product_attribute_value_id', 'in', prod_attr_values.ids)
])
product_1 = product_template._create_product_variant(prod_tmpl_attrs[0])
product_1.weight = 1
product_1.volume = 1
product_2 = product_template._create_product_variant(prod_tmpl_attrs[1])
product_2.weight = 2
product_2.volume = 2
self.open_new_session()
session = self.pos_session
order = self.create_ui_order_data([(product_1, 3), (product_2, 3)])
self.env['pos.order'].create_from_ui([order])
session.action_pos_session_closing_control()
report = self.env['sale.report'].sudo().search([('product_id', '=', product_1.id)], order='id', limit=1)
self.assertEqual(report.weight, 3)
self.assertEqual(report.weight, 3)
report = self.env['sale.report'].sudo().search([('product_id', '=', product_2.id)], order='id', limit=1)
self.assertEqual(report.weight, 6)
self.assertEqual(report.weight, 6)
| 41.487805
| 3,402
|
12,020
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon
from odoo.tests.common import Form
@odoo.tests.tagged('post_install', '-at_install')
class TestPoSSale(TestPointOfSaleHttpCommon):
def test_settle_order_with_kit(self):
if not self.env["ir.module.module"].search([("name", "=", "mrp"), ("state", "=", "installed")]):
self.skipTest("mrp module is required for this test")
self.kit = self.env['product.product'].create({
'name': 'Pizza Chicken',
'available_in_pos': True,
'type': 'product',
'lst_price': 10.0,
})
self.component_a = self.env['product.product'].create({
'name': 'Chicken',
'type': 'product',
'available_in_pos': True,
'uom_id': self.env.ref('uom.product_uom_gram').id,
'uom_po_id': self.env.ref('uom.product_uom_gram').id,
'lst_price': 10.0,
})
self.env['stock.quant']._update_available_quantity(self.component_a, self.env['sale.order']._default_warehouse_id().lot_stock_id, 100000)
bom_product_form = Form(self.env['mrp.bom'])
bom_product_form.product_id = self.kit
bom_product_form.product_tmpl_id = self.kit.product_tmpl_id
bom_product_form.product_qty = 1.0
bom_product_form.type = 'phantom'
with bom_product_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.component_a
bom_line.product_qty = 300.0
self.bom_a = bom_product_form.save()
sale_order = self.env['sale.order'].create({
'partner_id': self.env.ref('base.res_partner_2').id,
'order_line': [(0, 0, {
'product_id': self.kit.id,
'name': self.kit.name,
'product_uom_qty': 10,
'product_uom': self.kit.uom_id.id,
'price_unit': self.kit.lst_price,
})],
})
sale_order.action_confirm()
picking = sale_order.picking_ids
picking.move_lines.quantity_done = 300
action = picking.button_validate()
wizard = Form(self.env[action['res_model']].with_context(action['context']))
wizard.save().process()
self.assertEqual(sale_order.order_line.qty_delivered, 1)
self.main_pos_config.open_session_cb()
self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PosSettleOrder', login="accountman")
#assert that sales order qty are correctly updated
self.assertEqual(sale_order.order_line.qty_delivered, 3)
self.assertEqual(sale_order.picking_ids[0].move_lines.product_qty, 2100) # 7 left to deliver => 300 * 7 = 2100
self.assertEqual(sale_order.picking_ids[0].move_lines.quantity_done, 0)
self.assertEqual(sale_order.picking_ids[1].move_lines.product_qty, 300)
self.assertEqual(sale_order.picking_ids[1].move_lines.quantity_done, 300) # 1 delivered => 300 * 2 = 600
def test_settle_order_with_different_product(self):
"""This test create an order and settle it in the PoS. But only one of the product is delivered.
And we need to make sure the quantity are correctly updated on the sale order.
"""
#create 2 products
product_a = self.env['product.product'].create({
'name': 'Product A',
'available_in_pos': True,
'type': 'product',
'lst_price': 10.0,
})
product_b = self.env['product.product'].create({
'name': 'Product B',
'available_in_pos': True,
'type': 'product',
'lst_price': 10.0,
})
#create a sale order with 2 lines
sale_order = self.env['sale.order'].create({
'partner_id': self.env.ref('base.res_partner_2').id,
'order_line': [(0, 0, {
'product_id': product_a.id,
'name': product_a.name,
'product_uom_qty': 1,
'product_uom': product_a.uom_id.id,
'price_unit': product_a.lst_price,
}), (0, 0, {
'product_id': product_b.id,
'name': product_b.name,
'product_uom_qty': 1,
'product_uom': product_b.uom_id.id,
'price_unit': product_b.lst_price,
})],
})
sale_order.action_confirm()
self.assertEqual(sale_order.order_line[0].qty_delivered, 0)
self.assertEqual(sale_order.order_line[1].qty_delivered, 0)
self.main_pos_config.open_session_cb()
self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PosSettleOrder2', login="accountman")
self.assertEqual(sale_order.order_line[0].qty_delivered, 1)
self.assertEqual(sale_order.order_line[1].qty_delivered, 0)
orderline_product_a = sale_order.order_line.filtered(lambda l: l.product_id.id == product_a.id)
orderline_product_b = sale_order.order_line.filtered(lambda l: l.product_id.id == product_b.id)
# nothing to deliver for product a because already handled in pos.
self.assertEqual(orderline_product_a.move_ids.product_uom_qty, 0)
# 1 item to deliver for product b.
self.assertEqual(orderline_product_b.move_ids.product_uom_qty, 1)
def test_settle_order_with_promotions(self):
if not self.env["ir.module.module"].search([("name", "=", "pos_coupon"), ("state", "=", "installed")]):
self.skipTest("pos_coupon module is required for this test")
if not self.env["ir.module.module"].search([("name", "=", "sale_coupon"), ("state", "=", "installed")]):
self.skipTest("sale_coupon module is required for this test")
self.promotion_program = self.env['coupon.program'].create({
'name': '50% on current order',
'program_type': 'promotion_program',
'promo_code_usage': 'no_code_needed',
'reward_type': 'discount',
'discount_type': 'percentage',
'discount_percentage': 50,
'discount_apply_on': 'on_order',
})
self.product = self.env['product.product'].create({
'name': 'Product',
'available_in_pos': True,
'type': 'product',
'lst_price': 200.0,
'taxes_id': False,
})
sale_order = self.env['sale.order'].create({
'partner_id': self.env.ref('base.res_partner_2').id,
'order_line': [(0, 0, {
'product_id': self.product.id,
'name': self.product.name,
'product_uom_qty': 1,
'product_uom': self.env.ref('uom.product_uom_unit').id,
'price_unit': self.product.lst_price,
})],
})
#validate the sale order
sale_order.recompute_coupon_lines()
sale_order.action_confirm()
#add the promo program to the pos config
self.main_pos_config.write({
'use_coupon_programs': True,
'promo_program_ids': [(6, 0, [self.promotion_program.id])],
})
self.main_pos_config.open_session_cb()
self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PosSettleOrderWithPromotions', login="accountman")
def test_settle_order_unreserve_order_lines(self):
#create a product category that use the closest location for the removal strategy
self.removal_strategy = self.env['product.removal'].search([('method', '=', 'closest')], limit=1)
self.product_category = self.env['product.category'].create({
'name': 'Product Category',
'removal_strategy_id': self.removal_strategy.id,
})
self.product = self.env['product.product'].create({
'name': 'Product',
'available_in_pos': True,
'type': 'product',
'lst_price': 10.0,
'taxes_id': False,
'categ_id': self.product_category.id,
})
#create 2 stock location Shelf 1 and Shelf 2
self.warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
self.shelf_1 = self.env['stock.location'].create({
'name': 'Shelf 1',
'usage': 'internal',
'location_id': self.warehouse.lot_stock_id.id,
})
self.shelf_2 = self.env['stock.location'].create({
'name': 'Shelf 2',
'usage': 'internal',
'location_id': self.warehouse.lot_stock_id.id,
})
quants = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product.id,
'inventory_quantity': 2,
'location_id': self.shelf_1.id,
})
quants |= self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product.id,
'inventory_quantity': 5,
'location_id': self.shelf_2.id,
})
quants.action_apply_inventory()
sale_order = self.env['sale.order'].create({
'partner_id': self.env.ref('base.res_partner_2').id,
'order_line': [(0, 0, {
'product_id': self.product.id,
'name': self.product.name,
'product_uom_qty': 4,
'price_unit': self.product.lst_price,
})],
})
sale_order.action_confirm()
self.assertEqual(sale_order.order_line.move_ids.move_line_ids[0].product_qty, 2)
self.assertEqual(sale_order.order_line.move_ids.move_line_ids[0].location_id.id, self.shelf_1.id)
self.assertEqual(sale_order.order_line.move_ids.move_line_ids[1].product_qty, 2)
self.assertEqual(sale_order.order_line.move_ids.move_line_ids[1].location_id.id, self.shelf_2.id)
self.config = self.env['res.config.settings'].create({
'update_stock_quantities': 'real',
})
self.config.execute()
self.main_pos_config.open_session_cb()
self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PosSettleOrderRealTime', login="accountman")
pos_order = self.env['pos.order'].search([], order='id desc', limit=1)
self.assertEqual(pos_order.picking_ids.move_line_ids[0].qty_done, 2)
self.assertEqual(pos_order.picking_ids.move_line_ids[0].location_id.id, self.shelf_1.id)
self.assertEqual(pos_order.picking_ids.move_line_ids[1].qty_done, 2)
self.assertEqual(pos_order.picking_ids.move_line_ids[1].location_id.id, self.shelf_2.id)
self.assertEqual(sale_order.order_line.move_ids.move_lines_count, 0)
def test_downpayment_refund(self):
#create a sale order
sale_order = self.env['sale.order'].create({
'partner_id': self.env.ref('base.res_partner_2').id,
'order_line': [(0, 0, {
'product_id': self.product_a.id,
'name': self.product_a.name,
'product_uom_qty': 1,
'price_unit': 100,
'product_uom': self.product_a.uom_id.id
})],
})
sale_order.action_confirm()
#set downpayment product in pos config
self.downpayment_product = self.env['product.product'].create({
'name': 'Down Payment',
'available_in_pos': True,
'type': 'service',
})
self.main_pos_config.write({
'down_payment_product_id': self.downpayment_product.id,
})
self.main_pos_config.open_session_cb()
self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PosRefundDownpayment', login="accountman")
self.assertEqual(len(sale_order.order_line), 3)
self.assertEqual(sale_order.order_line[1].qty_invoiced, 1)
self.assertEqual(sale_order.order_line[2].qty_invoiced, -1)
| 44.684015
| 12,020
|
1,376
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from datetime import datetime
import pytz
class CrmTeam(models.Model):
_inherit = 'crm.team'
pos_config_ids = fields.One2many('pos.config', 'crm_team_id', string="Point of Sales")
pos_sessions_open_count = fields.Integer(string='Open POS Sessions', compute='_compute_pos_sessions_open_count')
pos_order_amount_total = fields.Float(string="Session Sale Amount", compute='_compute_pos_order_amount_total')
def _compute_pos_sessions_open_count(self):
for team in self:
team.pos_sessions_open_count = self.env['pos.session'].search_count([('config_id.crm_team_id', '=', team.id), ('state', '=', 'opened')])
def _compute_pos_order_amount_total(self):
data = self.env['report.pos.order'].read_group([
('session_id.state', '=', 'opened'),
('config_id.crm_team_id', 'in', self.ids),
], ['price_total:sum', 'config_id'], ['config_id'])
rg_results = dict((d['config_id'][0], d['price_total']) for d in data)
for team in self:
team.pos_order_amount_total = sum([
rg_results.get(config.id, 0.0)
for config in team.pos_config_ids
])
| 44.387097
| 1,376
|
4,887
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
pos_order_line_ids = fields.One2many('pos.order.line', 'sale_order_origin_id', string="Order lines Transfered to Point of Sale", readonly=True, groups="point_of_sale.group_pos_user")
pos_order_count = fields.Integer(string='Pos Order Count', compute='_count_pos_order', readonly=True, groups="point_of_sale.group_pos_user")
def _count_pos_order(self):
for order in self:
linked_orders = order.pos_order_line_ids.mapped('order_id')
order.pos_order_count = len(linked_orders)
def action_view_pos_order(self):
self.ensure_one()
linked_orders = self.pos_order_line_ids.mapped('order_id')
return {
'type': 'ir.actions.act_window',
'name': _('Linked POS Orders'),
'res_model': 'pos.order',
'view_mode': 'tree,form',
'domain': [('id', 'in', linked_orders.ids)],
}
def get_order_amount_unpaid(self):
order_amount_unpaid = {}
for sale_order in self:
total_invoice_paid = sum(sale_order.order_line.filtered(lambda l: not l.display_type).mapped('invoice_lines').filtered(lambda l: l.parent_state != 'cancel').mapped('price_total'))
total_pos_paid = sum(sale_order.order_line.filtered(lambda l: not l.display_type).mapped('pos_order_line_ids.price_subtotal_incl'))
order_amount_unpaid[sale_order.id] = sale_order.amount_total - (total_invoice_paid + total_pos_paid)
return order_amount_unpaid
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
pos_order_line_ids = fields.One2many('pos.order.line', 'sale_order_line_id', string="Order lines Transfered to Point of Sale", readonly=True, groups="point_of_sale.group_pos_user")
@api.depends('pos_order_line_ids.qty')
def _compute_qty_delivered(self):
super()._compute_qty_delivered()
for sale_line in self:
sale_line.qty_delivered += sum([self._convert_qty(sale_line, pos_line.qty, 'p2s') for pos_line in sale_line.pos_order_line_ids if sale_line.product_id.type != 'service'], 0)
@api.depends('pos_order_line_ids.qty')
def _compute_qty_invoiced(self):
super()._compute_qty_invoiced()
for sale_line in self:
sale_line.qty_invoiced += sum([self._convert_qty(sale_line, pos_line.qty, 'p2s') for pos_line in sale_line.pos_order_line_ids], 0)
def read_converted(self):
field_names = ["product_id", "name", "price_unit", "product_uom_qty", "tax_id", "qty_delivered", "qty_invoiced", "discount", "qty_to_invoice", "price_total"]
results = []
for sale_line in self:
if sale_line.product_type:
product_uom = sale_line.product_id.uom_id
sale_line_uom = sale_line.product_uom
item = sale_line.read(field_names)[0]
if sale_line.product_id.tracking != 'none':
item['lot_names'] = sale_line.move_ids.move_line_ids.lot_id.mapped('name')
if product_uom == sale_line_uom:
results.append(item)
continue
item['product_uom_qty'] = self._convert_qty(sale_line, item['product_uom_qty'], 's2p')
item['qty_delivered'] = self._convert_qty(sale_line, item['qty_delivered'], 's2p')
item['qty_invoiced'] = self._convert_qty(sale_line, item['qty_invoiced'], 's2p')
item['qty_to_invoice'] = self._convert_qty(sale_line, item['qty_to_invoice'], 's2p')
item['price_unit'] = sale_line_uom._compute_price(item['price_unit'], product_uom)
results.append(item)
elif sale_line.display_type == 'line_note':
if results:
results[-1]['customer_note'] = sale_line.name
return results
@api.model
def _convert_qty(self, sale_line, qty, direction):
"""Converts the given QTY based on the given SALE_LINE and DIR.
if DIR='s2p': convert from sale line uom to product uom
if DIR='p2s': convert from product uom to sale line uom
"""
product_uom = sale_line.product_id.uom_id
sale_line_uom = sale_line.product_uom
if direction == 's2p':
return sale_line_uom._compute_quantity(qty, product_uom, False)
elif direction == 'p2s':
return product_uom._compute_quantity(qty, sale_line_uom, False)
def unlink(self):
# do not delete downpayment lines created from pos
pos_downpayment_lines = self.filtered(lambda line: line.is_downpayment and line.sudo().pos_order_line_ids)
return super(SaleOrderLine, self - pos_downpayment_lines).unlink()
| 50.381443
| 4,887
|
311
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class PosSession(models.Model):
_inherit = 'pos.session'
crm_team_id = fields.Many2one('crm.team', related='config_id.crm_team_id', string="Sales Team", readonly=True)
| 31.1
| 311
|
1,088
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
from odoo.exceptions import AccessError
class PosConfig(models.Model):
_inherit = 'pos.config'
crm_team_id = fields.Many2one(
'crm.team', string="Sales Team", ondelete="set null",
help="This Point of sale's sales will be related to this Sales Team.")
down_payment_product_id = fields.Many2one('product.product',
string="Down Payment Product",
help="This product will be used as down payment on a sale order.")
@api.onchange('company_id')
def _get_default_pos_team(self):
default_sale_team = self.env.ref('sales_team.pos_sales_team', raise_if_not_found=False)
if default_sale_team and (not default_sale_team.company_id or default_sale_team.company_id == self.company_id):
self.crm_team_id = default_sale_team
else:
self.crm_team_id = self.env['crm.team'].search(['|', ('company_id', '=', self.company_id.id), ('company_id', '=', False)], limit=1)
| 43.52
| 1,088
|
781
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class StockPicking(models.Model):
_inherit = 'stock.picking'
def _create_move_from_pos_order_lines(self, lines):
lines_to_unreserve = self.env['pos.order.line']
for line in lines:
if line.order_id.to_ship:
continue
if any(wh != line.order_id.config_id.warehouse_id for wh in line.sale_order_line_id.move_ids.location_id.warehouse_id):
continue
lines_to_unreserve |= line
lines_to_unreserve.sale_order_line_id.move_ids.filtered(lambda ml: ml.state not in ['cancel', 'done'])._do_unreserve()
return super()._create_move_from_pos_order_lines(lines)
| 41.105263
| 781
|
6,991
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.tools import float_compare, float_is_zero
class PosOrder(models.Model):
_inherit = 'pos.order'
currency_rate = fields.Float(compute='_compute_currency_rate', store=True, digits=0, readonly=True)
crm_team_id = fields.Many2one('crm.team', string="Sales Team", ondelete="set null")
sale_order_count = fields.Integer(string='Sale Order Count', compute='_count_sale_order', readonly=True, groups="sales_team.group_sale_salesman")
def _count_sale_order(self):
for order in self:
order.sale_order_count = len(order.lines.mapped('sale_order_origin_id'))
@api.model
def _complete_values_from_session(self, session, values):
values = super(PosOrder, self)._complete_values_from_session(session, values)
values.setdefault('crm_team_id', session.config_id.crm_team_id.id)
return values
@api.depends('pricelist_id.currency_id', 'date_order', 'company_id')
def _compute_currency_rate(self):
for order in self:
date_order = order.date_order or fields.Datetime.now()
order.currency_rate = self.env['res.currency']._get_conversion_rate(order.company_id.currency_id, order.pricelist_id.currency_id, order.company_id, date_order)
def _prepare_invoice_vals(self):
invoice_vals = super(PosOrder, self)._prepare_invoice_vals()
invoice_vals['team_id'] = self.crm_team_id
addr = self.partner_id.address_get(['delivery'])
invoice_vals['partner_shipping_id'] = addr['delivery']
sale_orders = self.lines.mapped('sale_order_origin_id')
if sale_orders and sale_orders[0].payment_term_id:
invoice_vals['invoice_payment_term_id'] = sale_orders[0].payment_term_id.id,
return invoice_vals
@api.model
def create_from_ui(self, orders, draft=False):
order_ids = super(PosOrder, self).create_from_ui(orders, draft)
for order in self.sudo().browse([o['id'] for o in order_ids]):
for line in order.lines.filtered(lambda l: l.product_id == order.config_id.down_payment_product_id and l.qty != 0 and (l.sale_order_origin_id or l.refunded_orderline_id.sale_order_origin_id)):
sale_lines = line.sale_order_origin_id.order_line or line.refunded_orderline_id.sale_order_origin_id.order_line
sale_order_origin = line.sale_order_origin_id or line.refunded_orderline_id.sale_order_origin_id
sale_line = self.env['sale.order.line'].create({
'order_id': sale_order_origin.id,
'product_id': line.product_id.id,
'price_unit': line.price_unit,
'product_uom_qty': 0,
'tax_id': [(6, 0, line.tax_ids.ids)],
'is_downpayment': True,
'discount': line.discount,
'sequence': sale_lines and sale_lines[-1].sequence + 1 or 10,
})
sale_line._compute_tax_id()
line.sale_order_line_id = sale_line
so_lines = order.lines.mapped('sale_order_line_id')
# confirm the unconfirmed sale orders that are linked to the sale order lines
sale_orders = so_lines.mapped('order_id')
for sale_order in sale_orders.filtered(lambda so: so.state in ['draft', 'sent']):
sale_order.action_confirm()
# update the demand qty in the stock moves related to the sale order line
# flush the qty_delivered to make sure the updated qty_delivered is used when
# updating the demand value
so_lines.flush(['qty_delivered'])
# track the waiting pickings
waiting_picking_ids = set()
for so_line in so_lines:
so_line_stock_move_ids = so_line.move_ids.group_id.stock_move_ids
for stock_move in so_line.move_ids:
picking = stock_move.picking_id
if not picking.state in ['waiting', 'confirmed', 'assigned']:
continue
new_qty = so_line.product_uom_qty - so_line.qty_delivered
if float_compare(new_qty, 0, precision_rounding=stock_move.product_uom.rounding) <= 0:
new_qty = 0
stock_move.product_uom_qty = so_line.compute_uom_qty(new_qty, stock_move, False)
#If the product is delivered with more than one step, we need to update the quantity of the other steps
for move in so_line_stock_move_ids.filtered(lambda m: m.state in ['waiting', 'confirmed'] and m.product_id == stock_move.product_id):
move.product_uom_qty = stock_move.product_uom_qty
waiting_picking_ids.add(picking.id)
def is_product_uom_qty_zero(move):
return float_is_zero(move.product_uom_qty, precision_rounding=move.product_uom.rounding)
# cancel the waiting pickings if each product_uom_qty of move is zero
for picking in self.env['stock.picking'].browse(waiting_picking_ids):
if all(is_product_uom_qty_zero(move) for move in picking.move_lines):
picking.action_cancel()
return order_ids
def action_view_sale_order(self):
self.ensure_one()
linked_orders = self.lines.mapped('sale_order_origin_id')
return {
'type': 'ir.actions.act_window',
'name': _('Linked Sale Orders'),
'res_model': 'sale.order',
'view_mode': 'tree,form',
'domain': [('id', 'in', linked_orders.ids)],
}
class PosOrderLine(models.Model):
_inherit = 'pos.order.line'
sale_order_origin_id = fields.Many2one('sale.order', string="Linked Sale Order")
sale_order_line_id = fields.Many2one('sale.order.line', string="Source Sale Order Line")
down_payment_details = fields.Text(string="Down Payment Details")
def _export_for_ui(self, orderline):
result = super()._export_for_ui(orderline)
# NOTE We are not exporting 'sale_order_line_id' because it is being used in any views in the POS App.
result['down_payment_details'] = bool(orderline.down_payment_details) and orderline.down_payment_details
result['sale_order_origin_id'] = bool(orderline.sale_order_origin_id) and orderline.sale_order_origin_id.read(fields=['name'])[0]
return result
def _order_line_fields(self, line, session_id):
result = super()._order_line_fields(line, session_id)
vals = result[2]
if vals.get('sale_order_origin_id', False):
vals['sale_order_origin_id'] = vals['sale_order_origin_id']['id']
if vals.get('sale_order_line_id', False):
vals['sale_order_line_id'] = vals['sale_order_line_id']['id']
return result
| 52.962121
| 6,991
|
5,285
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import tools
from odoo import api, fields, models
class SaleReport(models.Model):
_inherit = "sale.report"
@api.model
def _get_done_states(self):
done_states = super(SaleReport, self)._get_done_states()
done_states.extend(['pos_done', 'invoiced'])
return done_states
state = fields.Selection(selection_add=[('pos_draft', 'New'),
('paid', 'Paid'),
('pos_done', 'Posted'),
('invoiced', 'Invoiced')], string='Status', readonly=True)
def _select_pos(self, fields=None):
if not fields:
fields = {}
select_ = '''
-MIN(l.id) AS id,
l.product_id AS product_id,
t.uom_id AS product_uom,
sum(l.qty) AS product_uom_qty,
sum(l.qty) AS qty_delivered,
0 as qty_to_deliver,
CASE WHEN pos.state = 'invoiced' THEN sum(l.qty) ELSE 0 END AS qty_invoiced,
CASE WHEN pos.state != 'invoiced' THEN sum(l.qty) ELSE 0 END AS qty_to_invoice,
SUM(l.price_subtotal_incl) / MIN(CASE COALESCE(pos.currency_rate, 0) WHEN 0 THEN 1.0 ELSE pos.currency_rate END) AS price_total,
SUM(l.price_subtotal) / MIN(CASE COALESCE(pos.currency_rate, 0) WHEN 0 THEN 1.0 ELSE pos.currency_rate END) AS price_subtotal,
(CASE WHEN pos.state != 'invoiced' THEN SUM(l.price_subtotal) ELSE 0 END) / MIN(CASE COALESCE(pos.currency_rate, 0) WHEN 0 THEN 1.0 ELSE pos.currency_rate END) AS amount_to_invoice,
(CASE WHEN pos.state = 'invoiced' THEN SUM(l.price_subtotal) ELSE 0 END) / MIN(CASE COALESCE(pos.currency_rate, 0) WHEN 0 THEN 1.0 ELSE pos.currency_rate END) AS amount_invoiced,
count(*) AS nbr,
pos.name AS name,
pos.date_order AS date,
CASE WHEN pos.state = 'draft' THEN 'pos_draft' WHEN pos.state = 'done' THEN 'pos_done' else pos.state END AS state,
pos.partner_id AS partner_id,
pos.user_id AS user_id,
pos.company_id AS company_id,
NULL AS campaign_id,
NULL AS medium_id,
NULL AS source_id,
extract(epoch from avg(date_trunc('day',pos.date_order)-date_trunc('day',pos.create_date)))/(24*60*60)::decimal(16,2) AS delay,
t.categ_id AS categ_id,
pos.pricelist_id AS pricelist_id,
NULL AS analytic_account_id,
pos.crm_team_id AS team_id,
p.product_tmpl_id,
partner.country_id AS country_id,
partner.industry_id AS industry_id,
partner.commercial_partner_id AS commercial_partner_id,
(sum(p.weight) * l.qty / u.factor) AS weight,
(sum(p.volume) * l.qty / u.factor) AS volume,
l.discount as discount,
sum((l.price_unit * l.discount * l.qty / 100.0 / CASE COALESCE(pos.currency_rate, 0) WHEN 0 THEN 1.0 ELSE pos.currency_rate END)) as discount_amount,
NULL as order_id
'''
for value in fields.values():
select_ += value
return select_
def _from_pos(self):
from_ = '''
pos_order_line l
join pos_order pos on (l.order_id=pos.id)
left join res_partner partner ON (pos.partner_id = partner.id OR pos.partner_id = NULL)
left join product_product p on (l.product_id=p.id)
left join product_template t on (p.product_tmpl_id=t.id)
LEFT JOIN uom_uom u ON (u.id=t.uom_id)
LEFT JOIN pos_session session ON (session.id = pos.session_id)
LEFT JOIN pos_config config ON (config.id = session.config_id)
left join product_pricelist pp on (pos.pricelist_id = pp.id)
'''
return from_
def _where_pos(self):
where_ = 'l.sale_order_line_id is NULL'
return where_
def _group_by_pos(self):
groupby_ = '''
l.order_id,
l.product_id,
l.price_unit,
l.discount,
l.qty,
t.uom_id,
t.categ_id,
pos.name,
pos.date_order,
pos.partner_id,
pos.user_id,
pos.state,
pos.company_id,
pos.pricelist_id,
p.product_tmpl_id,
partner.country_id,
partner.industry_id,
partner.commercial_partner_id,
u.factor,
pos.crm_team_id
'''
return groupby_
def _query(self, with_clause='', fields=None, groupby='', from_clause=''):
if not fields:
fields = {}
res = super()._query(with_clause, fields, groupby, from_clause)
sale_fields = self._select_additional_fields(fields)
for key in sale_fields:
fields[key] = ', NULL as %s' % (key)
current = '(SELECT %s FROM %s WHERE %s GROUP BY %s)' % \
(self._select_pos(fields), self._from_pos(), self._where_pos(), self._group_by_pos())
return '%s UNION ALL %s' % (res, current)
| 43.677686
| 5,285
|
2,058
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Sales',
'version': '1.0',
'category': 'Sales/Sales',
'sequence': 5,
'summary': 'From quotations to invoices',
'description': """
Manage sales quotations and orders
==================================
This application allows you to manage your sales goals in an effective and efficient manner by keeping track of all sales orders and history.
It handles the full sales workflow:
* **Quotation** -> **Sales order** -> **Invoice**
Preferences (only with Warehouse Management installed)
------------------------------------------------------
If you also installed the Warehouse Management, you can deal with the following preferences:
* Shipping: Choice of delivery at once or partial delivery
* Invoicing: choose how invoices will be paid
* Incoterms: International Commercial terms
With this module you can personnalize the sales order and invoice report with
categories, subtotals or page-breaks.
The Dashboard for the Sales Manager will include
------------------------------------------------
* My Quotations
* Monthly Turnover (Graph)
""",
'website': 'https://www.odoo.com/app/sales',
'depends': ['sale', 'digest'],
'data': [
'security/sale_management_security.xml',
'data/digest_data.xml',
'views/sale_portal_templates.xml',
'views/sale_order_template_views.xml',
'security/ir.model.access.csv',
'views/res_config_settings_views.xml',
'data/digest_data.xml',
'views/sale_management_views.xml',
'views/digest_views.xml',
'views/sale_order_views.xml',
'report/sale_report_templates.xml',
],
'demo': [
'data/sale_order_template_demo.xml',
],
'application': True,
'uninstall_hook': 'uninstall_hook',
'post_init_hook': 'post_init_hook',
'assets': {
'web.assets_frontend': [
'sale_management/static/src/js/**/*',
],
},
'license': 'LGPL-3',
}
| 31.661538
| 2,058
|
14,107
|
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 Form, tagged
@tagged('-at_install', 'post_install')
class TestSaleOrder(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
Pricelist = cls.env['product.pricelist']
Product = cls.env['product.product']
SaleOrder = cls.env['sale.order']
SaleOrderTemplate = cls.env['sale.order.template']
SaleOrderTemplateLine = cls.env['sale.order.template.line']
SaleOrderTemplateOption = cls.env['sale.order.template.option']
# some variables to ease asserts in tests
cls.pub_product_price = 100.0
cls.pl_product_price = 80.0
cls.tpl_discount = 10.0
cls.pl_discount = (cls.pub_product_price - cls.pl_product_price) * 100 / cls.pub_product_price
cls.merged_discount = 100.0 - (100.0 - cls.pl_discount) * (100.0 - cls.tpl_discount) / 100.0
cls.pub_option_price = 200.0
cls.pl_option_price = 100.0
cls.tpl_option_discount = 20.0
cls.pl_option_discount = (cls.pub_option_price - cls.pl_option_price) * 100 / cls.pub_option_price
cls.merged_option_discount = 100.0 - (100.0 - cls.pl_option_discount) * (100.0 - cls.tpl_option_discount) / 100.0
# create some products
cls.product_1 = Product.create({
'name': 'Product 1',
'lst_price': cls.pub_product_price,
})
cls.optional_product = Product.create({
'name': 'Optional product',
'lst_price': cls.pub_option_price,
})
# create some quotation templates
cls.quotation_template_no_discount = SaleOrderTemplate.create({
'name': 'A quotation template without discount'
})
SaleOrderTemplateLine.create({
'name': 'Product 1',
'sale_order_template_id': cls.quotation_template_no_discount.id,
'product_id': cls.product_1.id,
'product_uom_id': cls.product_1.uom_id.id
})
SaleOrderTemplateOption.create({
'name': 'Optional product 1',
'sale_order_template_id': cls.quotation_template_no_discount.id,
'product_id': cls.optional_product.id,
'uom_id': cls.optional_product.uom_id.id
})
# create some pricelists
cls.discount_included_price_list = Pricelist.create({
'name': 'Discount included Pricelist',
'discount_policy': 'with_discount',
'item_ids': [
(0, 0, {
'name': 'Product 1 premium price',
'applied_on': '1_product',
'product_tmpl_id': cls.product_1.product_tmpl_id.id,
'compute_price': 'fixed',
'fixed_price': cls.pl_product_price
}),
(0, 0, {
'name': 'Optional product premium price',
'applied_on': '1_product',
'product_tmpl_id': cls.optional_product.product_tmpl_id.id,
'compute_price': 'fixed',
'fixed_price': cls.pl_option_price
})]
})
cls.discount_excluded_price_list = Pricelist.create({
'name': 'Discount excluded Pricelist',
'discount_policy': 'without_discount',
'item_ids': [
(0, 0, {
'name': 'Product 1 premium price',
'applied_on': '1_product',
'product_tmpl_id': cls.product_1.product_tmpl_id.id,
'compute_price': 'fixed',
'fixed_price': cls.pl_product_price
}),
(0, 0, {
'name': 'Optional product premium price',
'applied_on': '1_product',
'product_tmpl_id': cls.optional_product.product_tmpl_id.id,
'compute_price': 'fixed',
'fixed_price': cls.pl_option_price
})]
})
# create some sale orders
cls.sale_order = SaleOrder.create({
'partner_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
cls.sale_order_no_price_list = SaleOrder.create({
'partner_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
def test_01_template_without_pricelist(self):
"""
This test checks that without any price list, the public price
of the product is used in the sale order after selecting a
quotation template.
"""
# first case, without discount in the quotation template
self.sale_order_no_price_list.write({
'sale_order_template_id': self.quotation_template_no_discount.id
})
self.sale_order_no_price_list.onchange_sale_order_template_id()
self.assertEqual(
len(self.sale_order_no_price_list.order_line),
1,
"The sale order shall contains the same number of products as"
"the quotation template.")
self.assertEqual(
self.sale_order_no_price_list.order_line[0].product_id.id,
self.product_1.id,
"The sale order shall contains the same products as the"
"quotation template.")
self.assertEqual(
self.sale_order_no_price_list.order_line[0].price_unit,
self.pub_product_price,
"Without any price list and discount, the public price of"
"the product shall be used.")
self.assertEqual(
len(self.sale_order_no_price_list.sale_order_option_ids),
1,
"The sale order shall contains the same number of optional products as"
"the quotation template.")
self.assertEqual(
self.sale_order_no_price_list.sale_order_option_ids[0].product_id.id,
self.optional_product.id,
"The sale order shall contains the same optional products as the"
"quotation template.")
self.assertEqual(
self.sale_order_no_price_list.sale_order_option_ids[0].price_unit,
self.pub_option_price,
"Without any price list and discount, the public price of"
"the optional product shall be used.")
# add the option to the order
self.sale_order_no_price_list.sale_order_option_ids[0].button_add_to_order()
self.assertEqual(
len(self.sale_order_no_price_list.order_line),
2,
"When an option is added, a new order line is created")
self.assertEqual(
self.sale_order_no_price_list.order_line[1].product_id.id,
self.optional_product.id,
"The sale order shall contains the same products as the"
"quotation template.")
self.assertEqual(
self.sale_order_no_price_list.order_line[1].price_unit,
self.pub_option_price,
"Without any price list and discount, the public price of"
"the optional product shall be used.")
def test_02_template_with_discount_included_pricelist(self):
"""
This test checks that with a 'discount included' price list,
the price used in the sale order is computed according to the
price list.
"""
# first case, without discount in the quotation template
self.sale_order.write({
'pricelist_id': self.discount_included_price_list.id,
'sale_order_template_id': self.quotation_template_no_discount.id
})
self.sale_order.onchange_sale_order_template_id()
self.assertEqual(
self.sale_order.order_line[0].price_unit,
self.pl_product_price,
"If a pricelist is set, the product price shall be computed"
"according to it.")
self.assertEqual(
self.sale_order.sale_order_option_ids[0].price_unit,
self.pl_option_price,
"If a pricelist is set, the optional product price shall"
"be computed according to it.")
# add the option to the order
self.sale_order.sale_order_option_ids[0].button_add_to_order()
self.assertEqual(
self.sale_order.order_line[1].price_unit,
self.pl_option_price,
"If a pricelist is set, the optional product price shall"
"be computed according to it.")
def test_03_template_with_discount_excluded_pricelist(self):
"""
This test checks that with a 'discount excluded' price list,
the price used in the sale order is the product public price and
the discount is computed according to the price list.
"""
self.sale_order.write({
'pricelist_id': self.discount_excluded_price_list.id,
'sale_order_template_id': self.quotation_template_no_discount.id
})
self.sale_order.onchange_sale_order_template_id()
self.assertEqual(
self.sale_order.order_line[0].price_unit,
self.pub_product_price,
"If a pricelist is set without discount included, the unit "
"price shall be the public product price.")
self.assertEqual(
self.sale_order.order_line[0].price_subtotal,
self.pl_product_price,
"If a pricelist is set without discount included, the subtotal "
"price shall be the price computed according to the price list.")
self.assertEqual(
self.sale_order.order_line[0].discount,
self.pl_discount,
"If a pricelist is set without discount included, the discount "
"shall be computed according to the price unit and the subtotal."
"price")
self.assertEqual(
self.sale_order.sale_order_option_ids[0].price_unit,
self.pub_option_price,
"If a pricelist is set without discount included, the unit "
"price shall be the public optional product price.")
self.assertEqual(
self.sale_order.sale_order_option_ids[0].discount,
self.pl_option_discount,
"If a pricelist is set without discount included, the discount "
"shall be computed according to the optional price unit and"
"the subtotal price.")
# add the option to the order
self.sale_order.sale_order_option_ids[0].button_add_to_order()
self.assertEqual(
self.sale_order.order_line[1].price_unit,
self.pub_option_price,
"If a pricelist is set without discount included, the unit "
"price shall be the public optional product price.")
self.assertEqual(
self.sale_order.order_line[1].price_subtotal,
self.pl_option_price,
"If a pricelist is set without discount included, the subtotal "
"price shall be the price computed according to the price list.")
self.assertEqual(
self.sale_order.order_line[1].discount,
self.pl_option_discount,
"If a pricelist is set without discount included, the discount "
"shall be computed according to the price unit and the subtotal."
"price")
def test_04_update_pricelist_option_line(self):
"""
This test checks that option line's values are correctly
updated after a pricelist update
"""
# Necessary for _onchange_discount() check
self.env.user.write({
'groups_id': [(4, self.env.ref('product.group_discount_per_so_line').id)],
})
self.sale_order.write({
'sale_order_template_id': self.quotation_template_no_discount.id
})
self.sale_order.onchange_sale_order_template_id()
self.assertEqual(
self.sale_order.sale_order_option_ids[0].price_unit,
self.pub_option_price,
"If no pricelist is set, the unit price shall be the option's product price.")
self.assertEqual(
self.sale_order.sale_order_option_ids[0].discount, 0,
"If no pricelist is set, the discount should be 0.")
self.sale_order.write({
'pricelist_id': self.discount_included_price_list.id,
})
self.sale_order.update_prices()
self.assertEqual(
self.sale_order.sale_order_option_ids[0].price_unit,
self.pl_option_price,
"If a pricelist is set with discount included,"
" the unit price shall be the option's product discounted price.")
self.assertEqual(
self.sale_order.sale_order_option_ids[0].discount, 0,
"If a pricelist is set with discount included,"
" the discount should be 0.")
self.sale_order.write({
'pricelist_id': self.discount_excluded_price_list.id,
})
self.sale_order.update_prices()
self.assertEqual(
self.sale_order.sale_order_option_ids[0].price_unit,
self.pub_option_price,
"If a pricelist is set without discount included,"
" the unit price shall be the option's product sale price.")
self.assertEqual(
self.sale_order.sale_order_option_ids[0].discount,
self.pl_option_discount,
"If a pricelist is set without discount included,"
" the discount should be correctly computed.")
def test_option_creation(self):
"""Make sure the product uom is automatically added to the option when the product is specified"""
order_form = Form(self.sale_order)
with order_form.sale_order_option_ids.new() as option:
option.product_id = self.product_1
self.assertTrue(bool(option.uom_id))
| 40.305714
| 14,107
|
290
|
py
|
PYTHON
|
15.0
|
import odoo.tests
# Part of Odoo. See LICENSE file for full copyright and licensing details.
@odoo.tests.tagged('post_install', '-at_install')
class TestUi(odoo.tests.HttpCase):
def test_01_sale_tour(self):
self.start_tour("/web", 'sale_tour', login="admin", step_delay=100)
| 32.222222
| 290
|
1,387
|
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_all_sale_total = fields.Boolean('All Sales')
kpi_all_sale_total_value = fields.Monetary(compute='_compute_kpi_sale_total_value')
def _compute_kpi_sale_total_value(self):
if not self.env.user.has_group('sales_team.group_sale_salesman_all_leads'):
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()
all_channels_sales = self.env['sale.report'].read_group([
('date', '>=', start),
('date', '<', end),
('state', 'not in', ['draft', 'cancel', 'sent']),
('company_id', '=', company.id)], ['price_total'], ['company_id'])
record.kpi_all_sale_total_value = sum([channel_sale['price_total'] for channel_sale in all_channels_sales])
def _compute_kpis_actions(self, company, user):
res = super(Digest, self)._compute_kpis_actions(company, user)
res['kpi_all_sale_total'] = 'sale.report_all_channels_sales_action&menu_id=%s' % self.env.ref('sale.sale_menu_root').id
return res
| 47.827586
| 1,387
|
9,677
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
class SaleOrderTemplate(models.Model):
_name = "sale.order.template"
_description = "Quotation Template"
def _get_default_require_signature(self):
return self.env.company.portal_confirmation_sign
def _get_default_require_payment(self):
return self.env.company.portal_confirmation_pay
name = fields.Char('Quotation Template', required=True)
sale_order_template_line_ids = fields.One2many('sale.order.template.line', 'sale_order_template_id', 'Lines', copy=True)
note = fields.Html('Terms and conditions', translate=True)
sale_order_template_option_ids = fields.One2many('sale.order.template.option', 'sale_order_template_id', 'Optional Products', copy=True)
number_of_days = fields.Integer('Quotation Duration',
help='Number of days for the validity date computation of the quotation')
require_signature = fields.Boolean('Online Signature', default=_get_default_require_signature, help='Request a online signature to the customer in order to confirm orders automatically.')
require_payment = fields.Boolean('Online Payment', default=_get_default_require_payment, help='Request an online payment to the customer in order to confirm orders automatically.')
mail_template_id = fields.Many2one(
'mail.template', 'Confirmation Mail',
domain=[('model', '=', 'sale.order')],
help="This e-mail template will be sent on confirmation. Leave empty to send nothing.")
active = fields.Boolean(default=True, help="If unchecked, it will allow you to hide the quotation template without removing it.")
company_id = fields.Many2one('res.company', string='Company')
@api.constrains('company_id', 'sale_order_template_line_ids', 'sale_order_template_option_ids')
def _check_company_id(self):
for template in self:
companies = template.mapped('sale_order_template_line_ids.product_id.company_id') | template.mapped('sale_order_template_option_ids.product_id.company_id')
if len(companies) > 1:
raise ValidationError(_("Your template cannot contain products from multiple companies."))
elif companies and companies != template.company_id:
raise ValidationError(_(
"Your template contains products from company %(product_company)s whereas your template belongs to company %(template_company)s. \n Please change the company of your template or remove the products from other companies.",
product_company=', '.join(companies.mapped('display_name')),
template_company=template.company_id.display_name,
))
@api.onchange('sale_order_template_line_ids', 'sale_order_template_option_ids')
def _onchange_template_line_ids(self):
companies = self.mapped('sale_order_template_option_ids.product_id.company_id') | self.mapped('sale_order_template_line_ids.product_id.company_id')
if companies and self.company_id not in companies:
self.company_id = companies[0]
@api.model_create_multi
def create(self, vals_list):
records = super(SaleOrderTemplate, self).create(vals_list)
records._update_product_translations()
return records
def write(self, vals):
if 'active' in vals and not vals.get('active'):
companies = self.env['res.company'].sudo().search([('sale_order_template_id', 'in', self.ids)])
companies.sale_order_template_id = None
result = super(SaleOrderTemplate, self).write(vals)
self._update_product_translations()
return result
def _update_product_translations(self):
languages = self.env['res.lang'].search([('active', '=', 'true')])
for lang in languages:
for line in self.sale_order_template_line_ids:
if line.name == line.product_id.get_product_multiline_description_sale():
self.create_or_update_translations(model_name='sale.order.template.line,name', lang_code=lang.code,
res_id=line.id,src=line.name,
value=line.product_id.with_context(lang=lang.code).get_product_multiline_description_sale())
for option in self.sale_order_template_option_ids:
if option.name == option.product_id.get_product_multiline_description_sale():
self.create_or_update_translations(model_name='sale.order.template.option,name', lang_code=lang.code,
res_id=option.id,src=option.name,
value=option.product_id.with_context(lang=lang.code).get_product_multiline_description_sale())
def create_or_update_translations(self, model_name, lang_code, res_id, src, value):
data = {
'type': 'model',
'name': model_name,
'lang': lang_code,
'res_id': res_id,
'src': src,
'value': value,
'state': 'inprogress',
}
existing_trans = self.env['ir.translation'].search([('name', '=', model_name),
('res_id', '=', res_id),
('lang', '=', lang_code)])
if not existing_trans:
self.env['ir.translation'].create(data)
else:
existing_trans.write(data)
class SaleOrderTemplateLine(models.Model):
_name = "sale.order.template.line"
_description = "Quotation Template Line"
_order = 'sale_order_template_id, sequence, id'
sequence = fields.Integer('Sequence', help="Gives the sequence order when displaying a list of sale quote lines.",
default=10)
sale_order_template_id = fields.Many2one(
'sale.order.template', 'Quotation Template Reference',
required=True, ondelete='cascade', index=True)
company_id = fields.Many2one('res.company', related='sale_order_template_id.company_id', store=True, index=True)
name = fields.Text('Description', required=True, translate=True)
product_id = fields.Many2one(
'product.product', 'Product', check_company=True,
domain=[('sale_ok', '=', True)])
product_uom_qty = fields.Float('Quantity', required=True, digits='Product Unit of Measure', default=1)
product_uom_id = fields.Many2one('uom.uom', 'Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id', readonly=True)
display_type = fields.Selection([
('line_section', "Section"),
('line_note', "Note")], default=False, help="Technical field for UX purpose.")
@api.onchange('product_id')
def _onchange_product_id(self):
self.ensure_one()
if self.product_id:
self.product_uom_id = self.product_id.uom_id.id
self.name = self.product_id.get_product_multiline_description_sale()
@api.model
def create(self, values):
if values.get('display_type', self.default_get(['display_type'])['display_type']):
values.update(product_id=False, product_uom_qty=0, product_uom_id=False)
return super(SaleOrderTemplateLine, self).create(values)
def write(self, values):
if 'display_type' in values and self.filtered(lambda line: line.display_type != values.get('display_type')):
raise UserError(_("You cannot change the type of a sale quote line. Instead you should delete the current line and create a new line of the proper type."))
return super(SaleOrderTemplateLine, self).write(values)
_sql_constraints = [
('accountable_product_id_required',
"CHECK(display_type IS NOT NULL OR (product_id IS NOT NULL AND product_uom_id IS NOT NULL))",
"Missing required product and UoM on accountable sale quote line."),
('non_accountable_fields_null',
"CHECK(display_type IS NULL OR (product_id IS NULL AND product_uom_qty = 0 AND product_uom_id IS NULL))",
"Forbidden product, unit price, quantity, and UoM on non-accountable sale quote line"),
]
class SaleOrderTemplateOption(models.Model):
_name = "sale.order.template.option"
_description = "Quotation Template Option"
_check_company_auto = True
sale_order_template_id = fields.Many2one('sale.order.template', 'Quotation Template Reference', ondelete='cascade',
index=True, required=True)
company_id = fields.Many2one('res.company', related='sale_order_template_id.company_id', store=True, index=True)
name = fields.Text('Description', required=True, translate=True)
product_id = fields.Many2one(
'product.product', 'Product', domain=[('sale_ok', '=', True)],
required=True, check_company=True)
uom_id = fields.Many2one('uom.uom', 'Unit of Measure ', required=True, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id', readonly=True)
quantity = fields.Float('Quantity', required=True, digits='Product Unit of Measure', default=1)
@api.onchange('product_id')
def _onchange_product_id(self):
if not self.product_id:
return
self.uom_id = self.product_id.uom_id
self.name = self.product_id.get_product_multiline_description_sale()
| 55.936416
| 9,677
|
13,129
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo import SUPERUSER_ID, api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import is_html_empty
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.model
def default_get(self, fields_list):
default_vals = super(SaleOrder, self).default_get(fields_list)
if "sale_order_template_id" in fields_list and not default_vals.get("sale_order_template_id"):
company_id = default_vals.get('company_id', False)
company = self.env["res.company"].browse(company_id) if company_id else self.env.company
default_vals['sale_order_template_id'] = company.sale_order_template_id.id
return default_vals
sale_order_template_id = fields.Many2one(
'sale.order.template', 'Quotation Template',
readonly=True, check_company=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
sale_order_option_ids = fields.One2many(
'sale.order.option', 'order_id', 'Optional Products Lines',
copy=True, readonly=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})
@api.constrains('company_id', 'sale_order_option_ids')
def _check_optional_product_company_id(self):
for order in self:
companies = order.sale_order_option_ids.product_id.company_id
if companies and companies != order.company_id:
bad_products = order.sale_order_option_ids.product_id.filtered(lambda p: p.company_id and p.company_id != order.company_id)
raise ValidationError(_(
"Your quotation contains products from company %(product_company)s whereas your quotation belongs to company %(quote_company)s. \n Please change the company of your quotation or remove the products from other companies (%(bad_products)s).",
product_company=', '.join(companies.mapped('display_name')),
quote_company=order.company_id.display_name,
bad_products=', '.join(bad_products.mapped('display_name')),
))
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
if self.sale_order_template_id and self.sale_order_template_id.number_of_days > 0:
default = dict(default or {})
default['validity_date'] = fields.Date.context_today(self) + timedelta(self.sale_order_template_id.number_of_days)
return super(SaleOrder, self).copy(default=default)
@api.onchange('partner_id')
def onchange_partner_id(self):
super(SaleOrder, self).onchange_partner_id()
template = self.sale_order_template_id.with_context(lang=self.partner_id.lang)
self.note = template.note if not is_html_empty(template.note) else self.note
def _compute_line_data_for_template_change(self, line):
return {
'display_type': line.display_type,
'name': line.name,
'state': 'draft',
}
def _compute_option_data_for_template_change(self, option):
price = option.product_id.lst_price
discount = 0
if self.pricelist_id:
pricelist_price = self.pricelist_id.with_context(uom=option.uom_id.id).get_product_price(option.product_id, 1, False)
if self.pricelist_id.discount_policy == 'without_discount' and price:
discount = max(0, (price - pricelist_price) * 100 / price)
else:
price = pricelist_price
return {
'product_id': option.product_id.id,
'name': option.name,
'quantity': option.quantity,
'uom_id': option.uom_id.id,
'price_unit': price,
'discount': discount
}
def update_prices(self):
self.ensure_one()
res = super().update_prices()
self.sale_order_option_ids._update_price_and_discount()
return res
@api.onchange('sale_order_template_id')
def onchange_sale_order_template_id(self):
if not self.sale_order_template_id:
self.require_signature = self._get_default_require_signature()
self.require_payment = self._get_default_require_payment()
return
template = self.sale_order_template_id.with_context(lang=self.partner_id.lang)
# --- first, process the list of products from the template
order_lines = [(5, 0, 0)]
for line in template.sale_order_template_line_ids:
data = self._compute_line_data_for_template_change(line)
if line.product_id:
price = line.product_id.lst_price
discount = 0
if self.pricelist_id:
pricelist_price = self.pricelist_id.with_context(uom=line.product_uom_id.id).get_product_price(line.product_id, 1, False)
if self.pricelist_id.discount_policy == 'without_discount' and price:
discount = max(0, (price - pricelist_price) * 100 / price)
else:
price = pricelist_price
data.update({
'price_unit': price,
'discount': discount,
'product_uom_qty': line.product_uom_qty,
'product_id': line.product_id.id,
'product_uom': line.product_uom_id.id,
'customer_lead': self._get_customer_lead(line.product_id.product_tmpl_id),
})
order_lines.append((0, 0, data))
# set first line to sequence -99, so a resequence on first page doesn't cause following page
# lines (that all have sequence 10 by default) to get mixed in the first page
if len(order_lines) >= 2:
order_lines[1][2]['sequence'] = -99
self.order_line = order_lines
self.order_line._compute_tax_id()
# then, process the list of optional products from the template
option_lines = [(5, 0, 0)]
for option in template.sale_order_template_option_ids:
data = self._compute_option_data_for_template_change(option)
option_lines.append((0, 0, data))
self.sale_order_option_ids = option_lines
if template.number_of_days > 0:
self.validity_date = fields.Date.context_today(self) + timedelta(template.number_of_days)
self.require_signature = template.require_signature
self.require_payment = template.require_payment
if not is_html_empty(template.note):
self.note = template.note
def action_confirm(self):
res = super(SaleOrder, self).action_confirm()
if self.env.su:
self = self.with_user(SUPERUSER_ID)
for order in self:
if order.sale_order_template_id and order.sale_order_template_id.mail_template_id:
order.sale_order_template_id.mail_template_id.send_mail(order.id)
return res
def get_access_action(self, access_uid=None):
""" Instead of the classic form view, redirect to the online quote if it exists. """
self.ensure_one()
user = access_uid and self.env['res.users'].sudo().browse(access_uid) or self.env.user
if not self.sale_order_template_id or (not user.share and not self.env.context.get('force_website')):
return super(SaleOrder, self).get_access_action(access_uid)
return {
'type': 'ir.actions.act_url',
'url': self.get_portal_url(),
'target': 'self',
'res_id': self.id,
}
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
_description = "Sales Order Line"
sale_order_option_ids = fields.One2many('sale.order.option', 'line_id', 'Optional Products Lines')
# Take the description on the order template if the product is present in it
@api.onchange('product_id')
def product_id_change(self):
domain = super(SaleOrderLine, self).product_id_change()
if self.product_id and self.order_id.sale_order_template_id:
for line in self.order_id.sale_order_template_id.sale_order_template_line_ids:
if line.product_id == self.product_id:
lang = self.order_id.partner_id.lang
self.name = line.with_context(lang=lang).name + self.with_context(lang=lang)._get_sale_order_line_multiline_description_variants()
break
return domain
class SaleOrderOption(models.Model):
_name = "sale.order.option"
_description = "Sale Options"
_order = 'sequence, id'
is_present = fields.Boolean(string="Present on Quotation",
help="This field will be checked if the option line's product is "
"already present in the quotation.",
compute="_compute_is_present", search="_search_is_present")
order_id = fields.Many2one('sale.order', 'Sales Order Reference', ondelete='cascade', index=True)
line_id = fields.Many2one('sale.order.line', ondelete="set null", copy=False)
name = fields.Text('Description', required=True)
product_id = fields.Many2one('product.product', 'Product', required=True, domain=[('sale_ok', '=', True)])
price_unit = fields.Float('Unit Price', required=True, digits='Product Price')
discount = fields.Float('Discount (%)', digits='Discount')
uom_id = fields.Many2one('uom.uom', 'Unit of Measure ', required=True, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id', readonly=True)
quantity = fields.Float('Quantity', required=True, digits='Product Unit of Measure', default=1)
sequence = fields.Integer('Sequence', help="Gives the sequence order when displaying a list of optional products.")
def _update_price_and_discount(self):
for option in self:
if not option.product_id:
continue
# To compute the discount a so line is created in cache
values = option._get_values_to_add_to_order()
new_sol = option.env['sale.order.line'].new(values)
new_sol._onchange_discount()
option.discount = new_sol.discount
if option.order_id.pricelist_id and option.order_id.partner_id:
product = option.product_id.with_context(
partner=option.order_id.partner_id,
quantity=option.quantity,
date=option.order_id.date_order,
pricelist=option.order_id.pricelist_id.id,
uom=option.uom_id.id,
fiscal_position=option.env.context.get('fiscal_position')
)
option.price_unit = new_sol._get_display_price(product)
@api.depends('line_id', 'order_id.order_line', 'product_id')
def _compute_is_present(self):
# NOTE: this field cannot be stored as the line_id is usually removed
# through cascade deletion, which means the compute would be false
for option in self:
option.is_present = bool(option.order_id.order_line.filtered(lambda l: l.product_id == option.product_id))
def _search_is_present(self, operator, value):
if (operator, value) in [('=', True), ('!=', False)]:
return [('line_id', '=', False)]
return [('line_id', '!=', False)]
@api.onchange('product_id', 'uom_id', 'quantity')
def _onchange_product_id(self):
if not self.product_id:
return
product = self.product_id.with_context(
lang=self.order_id.partner_id.lang,
)
self.uom_id = self.uom_id or product.uom_id
self.name = product.get_product_multiline_description_sale()
self._update_price_and_discount()
def button_add_to_order(self):
self.add_option_to_order()
def add_option_to_order(self):
self.ensure_one()
sale_order = self.order_id
if sale_order.state not in ['draft', 'sent']:
raise UserError(_('You cannot add options to a confirmed order.'))
values = self._get_values_to_add_to_order()
order_line = self.env['sale.order.line'].create(values)
order_line._compute_tax_id()
self.write({'line_id': order_line.id})
if sale_order:
sale_order.add_option_to_order_with_taxcloud()
def _get_values_to_add_to_order(self):
self.ensure_one()
return {
'order_id': self.order_id.id,
'price_unit': self.price_unit,
'name': self.name,
'product_id': self.product_id.id,
'product_uom_qty': self.quantity,
'product_uom': self.uom_id.id,
'discount': self.discount,
'company_id': self.order_id.company_id.id,
}
| 44.656463
| 13,129
|
447
|
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 ResCompany(models.Model):
_inherit = "res.company"
_check_company_auto = True
sale_order_template_id = fields.Many2one(
"sale.order.template", string="Default Sale Template",
domain="['|', ('company_id', '=', False), ('company_id', '=', id)]",
check_company=True,
)
| 29.8
| 447
|
1,169
|
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 ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
group_sale_order_template = fields.Boolean(
"Quotation Templates", implied_group='sale_management.group_sale_order_template')
company_so_template_id = fields.Many2one(
related="company_id.sale_order_template_id", string="Default Template", readonly=False,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
module_sale_quotation_builder = fields.Boolean("Quotation Builder")
@api.onchange('group_sale_order_template')
def _onchange_group_sale_order_template(self):
if not self.group_sale_order_template:
self.module_sale_quotation_builder = False
def set_values(self):
if not self.group_sale_order_template:
self.company_so_template_id = None
self.env['res.company'].sudo().search([]).write({
'sale_order_template_id': False,
})
return super(ResConfigSettings, self).set_values()
| 41.75
| 1,169
|
2,006
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from functools import partial
from odoo import http
from odoo.tools import formatLang
from odoo.exceptions import AccessError, MissingError
from odoo.http import request
from odoo.addons.sale.controllers import portal
class CustomerPortal(portal.CustomerPortal):
@http.route(['/my/orders/<int:order_id>/update_line_dict'], type='json', auth="public", website=True)
def update_line_dict(self, line_id, remove=False, unlink=False, order_id=None, access_token=None, input_quantity=False, **kwargs):
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return request.redirect('/my')
if order_sudo.state not in ('draft', 'sent'):
return False
order_line = request.env['sale.order.line'].sudo().browse(int(line_id))
if order_line.order_id != order_sudo:
return False
if input_quantity is not False:
quantity = input_quantity
else:
number = -1 if remove else 1
quantity = order_line.product_uom_qty + number
if unlink or quantity <= 0:
order_line.unlink()
return
order_line.write({'product_uom_qty': quantity})
@http.route(["/my/orders/<int:order_id>/add_option/<int:option_id>"], type='json', auth="public", website=True)
def add(self, order_id, option_id, access_token=None, **post):
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token=access_token)
except (AccessError, MissingError):
return request.redirect('/my')
option_sudo = request.env['sale.order.option'].sudo().browse(option_id)
if order_sudo != option_sudo.order_id:
return request.redirect(order_sudo.get_portal_url())
option_sudo.add_option_to_order()
| 38.576923
| 2,006
|
893
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Mail Tests (Full)',
'version': '1.0',
'category': 'Hidden',
'sequence': 9876,
'summary': 'Mail Tests: performances and tests specific to mail with all sub-modules',
'description': """This module contains tests related to various mail features
and mail-related sub modules. Those tests are present in a separate module as it
contains models used only to perform tests independently to functional aspects of
real applications. """,
'depends': [
'test_mail',
'test_mass_mailing',
'mail',
'mail_bot',
# 'snailmail',
'mass_mailing',
'mass_mailing_sms', # adds portal
'phone_validation',
'sms',
],
'data': [
'security/ir.model.access.csv',
],
'demo': [
],
'installable': True,
'application': False,
'license': 'LGPL-3',
}
| 27.90625
| 893
|
3,802
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_mail_full.tests.common import TestMailFullCommon, TestMailFullRecipients
class TestPhoneBlacklist(TestMailFullCommon, TestMailFullRecipients):
""" TODO """
@classmethod
def setUpClass(cls):
super(TestPhoneBlacklist, cls).setUpClass()
cls._test_body = 'VOID CONTENT'
cls.test_record = cls.env['mail.test.sms.bl'].with_context(**cls._test_context).create({
'name': 'Test',
'customer_id': cls.partner_1.id,
'mobile_nbr': cls.test_numbers[0],
'phone_nbr': cls.test_numbers[1],
})
cls.test_record = cls._reset_mail_context(cls.test_record)
def test_phone_blacklist_internals(self):
with self.with_user('employee'):
test_record = self.env['mail.test.sms.bl'].browse(self.test_record.id)
self.assertEqual(test_record.phone_sanitized, self.test_numbers_san[1])
self.assertFalse(test_record.phone_sanitized_blacklisted)
bl_record = self.env['phone.blacklist'].sudo().create([{'number': self.test_numbers_san[1]}])
test_record.invalidate_cache()
self.assertTrue(test_record.phone_sanitized_blacklisted)
self.env['phone.blacklist'].sudo().remove(self.test_numbers_san[1])
self.assertFalse(bl_record.active)
test_record.invalidate_cache()
self.assertFalse(test_record.phone_sanitized_blacklisted)
self.env['phone.blacklist'].sudo().add(self.test_numbers_san[1])
self.assertTrue(bl_record.active)
test_record.invalidate_cache()
self.assertTrue(test_record.phone_sanitized_blacklisted)
bl_record_2 = self.env['phone.blacklist'].sudo().create([{'number': self.test_numbers_san[1]}])
self.assertEqual(bl_record, bl_record_2)
rec = self.env['mail.test.sms.bl'].search([('phone_sanitized_blacklisted', '=', True)])
self.assertEqual(rec, test_record)
bl_record.unlink()
rec = self.env['mail.test.sms.bl'].search([('phone_sanitized_blacklisted', '=', True)])
self.assertEqual(rec, self.env['mail.test.sms.bl'])
def test_phone_sanitize_api(self):
with self.with_user('employee'):
test_record = self.env['mail.test.sms.bl'].browse(self.test_record.id)
self.assertFalse(test_record.phone_sanitized_blacklisted)
test_record._phone_set_blacklisted()
test_record.invalidate_cache()
self.assertTrue(test_record.phone_sanitized_blacklisted)
test_record._phone_reset_blacklisted()
test_record.invalidate_cache()
self.assertFalse(test_record.phone_sanitized_blacklisted)
def test_phone_sanitize_internals(self):
with self.with_user('employee'):
test_record = self.env['mail.test.sms.bl'].browse(self.test_record.id)
self.assertEqual(test_record.phone_nbr, self.test_numbers[1])
self.assertEqual(test_record.phone_sanitized, self.test_numbers_san[1])
test_record.write({'phone_nbr': 'incorrect'})
self.assertEqual(test_record.phone_nbr, 'incorrect')
self.assertEqual(test_record.phone_sanitized, self.test_numbers_san[0])
test_record.write({'mobile_nbr': 'incorrect'})
self.assertEqual(test_record.mobile_nbr, 'incorrect')
self.assertEqual(test_record.phone_sanitized, False)
test_record.write({'phone_nbr': self.test_numbers[1]})
self.assertEqual(test_record.phone_nbr, self.test_numbers[1])
self.assertEqual(test_record.phone_sanitized, self.test_numbers_san[1])
| 46.365854
| 3,802
|
9,753
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_mail_full.tests.common import TestMailFullCommon, TestMailFullRecipients
from odoo.tests import tagged
from odoo.tools import mute_logger
class TestSMSActionsCommon(TestMailFullCommon, TestMailFullRecipients):
@classmethod
def setUpClass(cls):
super(TestSMSActionsCommon, cls).setUpClass()
cls.test_record = cls.env['mail.test.sms'].with_context(**cls._test_context).create({
'name': 'Test',
'customer_id': cls.partner_1.id,
})
cls.test_record = cls._reset_mail_context(cls.test_record)
cls.msg = cls.test_record.message_post(body='TEST BODY', author_id=cls.partner_employee.id)
cls.sms_p1 = cls.env['sms.sms'].create({
'body': 'TEST BODY',
'failure_type': 'sms_number_format',
'mail_message_id': cls.msg.id,
'number': cls.partner_1.mobile,
'partner_id': cls.partner_1.id,
'state': 'error',
})
cls.notif_p1 = cls.env['mail.notification'].create({
'mail_message_id': cls.msg.id,
'res_partner_id': cls.partner_1.id,
'sms_id': cls.sms_p1.id,
'sms_number': cls.partner_1.mobile,
'notification_type': 'sms',
'notification_status': 'exception',
'failure_type': 'sms_number_format',
})
cls.sms_p2 = cls.env['sms.sms'].create({
'body': 'TEST BODY',
'failure_type': 'sms_credit',
'mail_message_id': cls.msg.id,
'number': cls.partner_2.mobile,
'partner_id': cls.partner_2.id,
'state': 'error',
})
cls.notif_p2 = cls.env['mail.notification'].create({
'mail_message_id': cls.msg.id,
'res_partner_id': cls.partner_2.id,
'sms_id': cls.sms_p2.id,
'sms_number': cls.partner_2.mobile,
'notification_type': 'sms',
'notification_status': 'exception',
'failure_type': 'sms_credit',
})
@tagged('sms_management')
class TestSMSActions(TestSMSActionsCommon):
def test_sms_set_cancel(self):
self._reset_bus()
self.sms_p1.action_set_canceled()
self.assertEqual(self.sms_p1.state, 'canceled')
self.assertMessageBusNotifications(self.msg)
self.assertSMSNotification([
{'partner': self.partner_1, 'number': self.notif_p1.sms_number, 'state': 'canceled', 'failure_type': 'sms_number_format'},
{'partner': self.partner_2, 'number': self.notif_p2.sms_number, 'state': 'exception', 'failure_type': 'sms_credit'}
], 'TEST BODY', self.msg, check_sms=False) # do not check new sms as they already exist
self._reset_bus()
self.sms_p2.with_context(sms_skip_msg_notification=True).action_set_canceled()
self.assertEqual(self.sms_p2.state, 'canceled')
self.assertEqual(self.env['bus.bus'].search([]), self.env['bus.bus'], 'SMS: no bus notifications unless asked')
self.assertSMSNotification([
{'partner': self.partner_1, 'number': self.notif_p1.sms_number, 'state': 'canceled', 'failure_type': 'sms_number_format'},
{'partner': self.partner_2, 'number': self.notif_p2.sms_number, 'state': 'canceled', 'failure_type': 'sms_credit'}
], 'TEST BODY', self.msg, check_sms=False) # do not check new sms as they already exist
def test_sms_set_error(self):
self._reset_bus()
(self.sms_p1 + self.sms_p2).with_context(sms_skip_msg_notification=True).action_set_canceled()
self.assertEqual(self.sms_p1.state, 'canceled')
self.assertEqual(self.sms_p2.state, 'canceled')
self.assertEqual(self.env['bus.bus'].search([]), self.env['bus.bus'], 'SMS: no bus notifications unless asked')
(self.sms_p1 + self.sms_p2).action_set_error('sms_server')
self.assertEqual(self.sms_p1.state, 'error')
self.assertEqual(self.sms_p2.state, 'error')
self.assertMessageBusNotifications(self.msg)
self.assertSMSNotification([
{'partner': self.partner_1, 'number': self.notif_p1.sms_number, 'state': 'exception', 'failure_type': 'sms_server'},
{'partner': self.partner_2, 'number': self.notif_p2.sms_number, 'state': 'exception', 'failure_type': 'sms_server'}
], 'TEST BODY', self.msg, check_sms=False) # do not check new sms as they already exist
def test_sms_set_outgoing(self):
self._reset_bus()
(self.sms_p1 + self.sms_p2).action_set_outgoing()
self.assertEqual(self.sms_p1.state, 'outgoing')
self.assertEqual(self.sms_p2.state, 'outgoing')
self.assertMessageBusNotifications(self.msg)
self.assertSMSNotification([
{'partner': self.partner_1, 'number': self.notif_p1.sms_number, 'state': 'ready'},
{'partner': self.partner_2, 'number': self.notif_p2.sms_number, 'state': 'ready'}
], 'TEST BODY', self.msg, check_sms=False) # do not check new sms as they already exist
@tagged('sms_management')
class TestSMSWizards(TestSMSActionsCommon):
@mute_logger('odoo.addons.sms.models.sms_sms')
def test_sms_resend(self):
self._reset_bus()
with self.with_user('employee'):
wizard = self.env['sms.resend'].with_context(default_mail_message_id=self.msg.id).create({})
wizard.write({'recipient_ids': [(1, r.id, {'resend': True}) for r in wizard.recipient_ids]})
with self.mockSMSGateway():
wizard.action_resend()
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'sent'},
{'partner': self.partner_2, 'state': 'sent'}
], 'TEST BODY', self.msg, check_sms=True)
self.assertMessageBusNotifications(self.msg)
@mute_logger('odoo.addons.sms.models.sms_sms')
def test_sms_resend_update_number(self):
self._reset_bus()
with self.with_user('employee'):
wizard = self.env['sms.resend'].with_context(default_mail_message_id=self.msg.id).create({})
wizard.write({'recipient_ids': [(1, r.id, {'resend': True, 'sms_number': self.random_numbers[idx]}) for idx, r in enumerate(wizard.recipient_ids.sorted())]})
with self.mockSMSGateway():
wizard.action_resend()
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'sent', 'number': self.random_numbers_san[0]},
{'partner': self.partner_2, 'state': 'sent', 'number': self.random_numbers_san[1]}
], 'TEST BODY', self.msg, check_sms=True)
self.assertMessageBusNotifications(self.msg)
def test_sms_resend_cancel(self):
self._reset_bus()
with self.with_user('employee'):
wizard = self.env['sms.resend'].with_context(default_mail_message_id=self.msg.id).create({})
with self.mockSMSGateway():
wizard.action_cancel()
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'canceled', 'number': self.notif_p1.sms_number, 'failure_type': 'sms_number_format'},
{'partner': self.partner_2, 'state': 'canceled', 'number': self.notif_p2.sms_number, 'failure_type': 'sms_credit'}
], 'TEST BODY', self.msg, check_sms=False)
self.assertMessageBusNotifications(self.msg)
@mute_logger('odoo.addons.sms.models.sms_sms')
def test_sms_resend_internals(self):
self._reset_bus()
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'exception', 'number': self.notif_p1.sms_number, 'failure_type': 'sms_number_format'},
{'partner': self.partner_2, 'state': 'exception', 'number': self.notif_p2.sms_number, 'failure_type': 'sms_credit'}
], 'TEST BODY', self.msg, check_sms=False)
with self.with_user('employee'):
wizard = self.env['sms.resend'].with_context(default_mail_message_id=self.msg.id).create({})
self.assertTrue(wizard.has_insufficient_credit)
self.assertEqual(set(wizard.mapped('recipient_ids.partner_name')), set((self.partner_1 | self.partner_2).mapped('display_name')))
wizard.write({'recipient_ids': [(1, r.id, {'resend': True}) for r in wizard.recipient_ids]})
with self.mockSMSGateway():
wizard.action_resend()
@mute_logger('odoo.addons.sms.models.sms_sms')
def test_sms_resend_w_cancel(self):
self._reset_bus()
with self.with_user('employee'):
wizard = self.env['sms.resend'].with_context(default_mail_message_id=self.msg.id).create({})
wizard.write({'recipient_ids': [(1, r.id, {'resend': True if r.partner_id == self.partner_1 else False}) for r in wizard.recipient_ids]})
with self.mockSMSGateway():
wizard.action_resend()
self.assertSMSNotification([{'partner': self.partner_1, 'state': 'sent'}], 'TEST BODY', self.msg, check_sms=True)
self.assertSMSNotification([{'partner': self.partner_2, 'state': 'canceled', 'number': self.notif_p2.sms_number, 'failure_type': 'sms_credit'}], 'TEST BODY', self.msg, check_sms=False)
self.assertMessageBusNotifications(self.msg)
def test_sms_cancel(self):
self._reset_bus()
with self.mockSMSGateway(), self.with_user('employee'):
wizard = self.env['sms.cancel'].with_context(default_model=self.msg.model).create({})
wizard.action_cancel()
self.assertEqual((self.notif_p1 | self.notif_p2).mapped('notification_status'), ['canceled', 'canceled'])
self.assertMessageBusNotifications(self.msg)
| 49.01005
| 9,753
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.