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
|
|---|---|---|---|---|---|---|
6,299
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.tests import tagged
from odoo.tools import mute_logger
@tagged("odoobot")
class TestOdoobot(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestOdoobot, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
cls.odoobot = cls.env.ref("base.partner_root")
cls.message_post_default_kwargs = {
'body': '',
'attachment_ids': [],
'message_type': 'comment',
'partner_ids': [],
'subtype_xmlid': 'mail.mt_comment'
}
cls.odoobot_ping_body = '<a href="http://odoo.com/web#model=res.partner&id=%s" class="o_mail_redirect" data-oe-id="%s" data-oe-model="res.partner" target="_blank">@OdooBot</a>' % (cls.odoobot.id, cls.odoobot.id)
cls.test_record_employe = cls.test_record.with_user(cls.user_employee)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_fetch_listener(self):
channel = self.env['mail.channel'].with_user(self.user_employee).init_odoobot()
partners = self.env['mail.channel'].channel_fetch_listeners(channel.uuid)
odoobot = self.env.ref("base.partner_root")
odoobot_in_fetch_listeners = [partner for partner in partners if partner['id'] == odoobot.id]
self.assertEqual(len(odoobot_in_fetch_listeners), 1, 'odoobot should appear only once in channel_fetch_listeners')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_odoobot_ping(self):
kwargs = self.message_post_default_kwargs.copy()
kwargs.update({'body': self.odoobot_ping_body, 'partner_ids': [self.odoobot.id, self.user_admin.partner_id.id]})
with patch('random.choice', lambda x: x[0]):
self.assertNextMessage(
self.test_record_employe.with_context({'mail_post_autofollow': True}).message_post(**kwargs),
sender=self.odoobot,
answer=False
)
# Odoobot should not be a follower but user_employee and user_admin should
follower = self.test_record.message_follower_ids.mapped('partner_id')
self.assertNotIn(self.odoobot, follower)
self.assertIn(self.user_employee.partner_id, follower)
self.assertIn(self.user_admin.partner_id, follower)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_onboarding_flow(self):
kwargs = self.message_post_default_kwargs.copy()
channel = self.env['mail.channel'].with_user(self.user_employee).init_odoobot()
kwargs['body'] = 'tagada 😊'
last_message = self.assertNextMessage(
channel.message_post(**kwargs),
sender=self.odoobot,
answer=("help",)
)
channel.execute_command_help()
self.assertNextMessage(
last_message, # no message will be post with command help, use last odoobot message instead
sender=self.odoobot,
answer=("@OdooBot",)
)
kwargs['body'] = ''
kwargs['partner_ids'] = [self.env['ir.model.data']._xmlid_to_res_id("base.partner_root")]
self.assertNextMessage(
channel.message_post(**kwargs),
sender=self.odoobot,
answer=("attachment",)
)
kwargs['body'] = ''
attachment = self.env['ir.attachment'].with_user(self.user_employee).create({
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'name': 'picture_of_your_dog.doc',
'res_model': 'mail.compose.message',
})
kwargs['attachment_ids'] = [attachment.id]
# For the end of the flow, we only test that the state changed, but not to which
# one since it depends on the intalled apps, which can add more steps (like livechat)
channel.message_post(**kwargs)
self.assertNotEqual(self.user_employee.odoobot_state, 'onboarding_attachement')
# Test miscellaneous messages
self.user_employee.odoobot_state = "idle"
kwargs['partner_ids'] = []
kwargs['body'] = "I love you"
self.assertNextMessage(
channel.message_post(**kwargs),
sender=self.odoobot,
answer=("too human for me",)
)
kwargs['body'] = "Go fuck yourself"
self.assertNextMessage(
channel.message_post(**kwargs),
sender=self.odoobot,
answer=("I have feelings",)
)
kwargs['body'] = "help me"
self.assertNextMessage(
channel.message_post(**kwargs),
sender=self.odoobot,
answer=("If you need help",)
)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_odoobot_no_default_answer(self):
kwargs = self.message_post_default_kwargs.copy()
kwargs.update({'body': "I'm not talking to @odoobot right now", 'partner_ids': []})
self.assertNextMessage(
self.test_record_employe.message_post(**kwargs),
answer=False
)
def assertNextMessage(self, message, answer=None, sender=None):
last_message = self.env['mail.message'].search([('id', '=', message.id + 1)])
if last_message:
body = last_message.body.replace('<p>', '').replace('</p>', '')
else:
self.assertFalse(answer, "No last message found when an answer was expect")
if answer is not None:
if answer and not last_message:
self.assertTrue(False, "No last message found")
if isinstance(answer, list):
self.assertIn(body, answer)
elif isinstance(answer, tuple):
for elem in answer:
self.assertIn(elem, body)
elif not answer:
self.assertFalse(last_message, "No answer should have been post")
return
else:
self.assertEqual(body, answer)
if sender:
self.assertEqual(sender, last_message.author_id)
return last_message
| 44.027972
| 6,296
|
9,280
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug
from unittest.mock import patch
from unittest.mock import DEFAULT
from odoo import exceptions
from odoo.addons.link_tracker.tests.common import MockLinkTracker
from odoo.addons.sms.models.sms_sms import SmsSms as SmsSms
from odoo.addons.test_mail_full.tests.common import TestMailFullCommon
class TestSMSPost(TestMailFullCommon, MockLinkTracker):
def setUp(self):
super(TestSMSPost, self).setUp()
self._web_base_url = 'https://test.odoo.com'
self.env['ir.config_parameter'].sudo().set_param('web.base.url', self._web_base_url)
@classmethod
def setUpClass(cls):
super(TestSMSPost, cls).setUpClass()
cls._test_body = 'VOID CONTENT'
cls.sms_all = cls.env['sms.sms']
for x in range(10):
cls.sms_all |= cls.env['sms.sms'].create({
'number': '+324560000%s%s' % (x, x),
'body': cls._test_body,
})
# tracking info
cls.utm_c = cls.env.ref('utm.utm_campaign_fall_drive')
cls.utm_m = cls.env.ref('mass_mailing_sms.utm_medium_sms')
cls.tracker_values = {
'campaign_id': cls.utm_c.id,
'medium_id': cls.utm_m.id,
}
def test_body_link_shorten(self):
link = 'http://www.example.com'
self.env['link.tracker'].search([('url', '=', link)]).unlink()
new_body = self.env['mail.render.mixin']._shorten_links_text('Welcome to %s !' % link, self.tracker_values)
self.assertNotIn(link, new_body)
self.assertLinkShortenedText(new_body, (link, True), {'utm_campaign': self.utm_c.name, 'utm_medium': self.utm_m.name})
link = self.env['link.tracker'].search([('url', '=', link)])
self.assertIn(link.short_url, new_body)
link = f'{self._web_base_url}/my/super_page?test[0]=42&toto=áâà#title3'
self.env['link.tracker'].search([('url', '=', link)]).unlink()
new_body = self.env['mail.render.mixin']._shorten_links_text('Welcome to %s !' % link, self.tracker_values)
self.assertNotIn(link, new_body)
self.assertLinkShortenedText(new_body, (link, True), {
'utm_campaign': self.utm_c.name,
'utm_medium': self.utm_m.name,
'test[0]': '42',
'toto': 'áâà',
})
link = self.env['link.tracker'].search([('url', '=', link)])
self.assertIn(link.short_url, new_body)
# Bugfix: ensure void content convert does not crash
new_body = self.env['mail.render.mixin']._shorten_links_text(False, self.tracker_values)
self.assertFalse(new_body)
def test_body_link_shorten_wshort(self):
link = f'{self._web_base_url}/r/RAOUL'
self.env['link.tracker'].search([('url', '=', link)]).unlink()
new_body = self.env['mail.render.mixin']._shorten_links_text('Welcome to %s !' % link, self.tracker_values)
self.assertIn(link, new_body)
self.assertFalse(self.env['link.tracker'].search([('url', '=', link)]))
def test_body_link_shorten_wunsubscribe(self):
link = f'{self._web_base_url}/sms/3/'
self.env['link.tracker'].search([('url', '=', link)]).unlink()
new_body = self.env['mail.render.mixin']._shorten_links_text('Welcome to %s !' % link, self.tracker_values)
self.assertIn(link, new_body)
self.assertFalse(self.env['link.tracker'].search([('url', '=', link)]))
def test_sms_body_link_shorten_suffix(self):
mailing = self.env['mailing.mailing'].create({
'subject': 'Minimal mailing',
'mailing_model_id': self.env['ir.model']._get('mail.test.sms').id,
'mailing_type': 'sms',
})
sms_0 = self.env['sms.sms'].create({
'body': f'Welcome to {self._web_base_url}',
'number': '10',
'mailing_id': mailing.id,
})
sms_1 = self.env['sms.sms'].create({
'body': f'Welcome to {self._web_base_url}/r/RAOUL',
'number': '11',
})
sms_2 = self.env['sms.sms'].create({
'body': f'Welcome to {self._web_base_url}/r/RAOUL',
'number': '12',
'mailing_id': mailing.id,
})
sms_3 = self.env['sms.sms'].create({
'body': f'Welcome to {self._web_base_url}/leodagan/r/RAOUL',
'number': '13',
'mailing_id': mailing.id,
})
sms_4 = self.env['sms.sms'].create({
'body': f'Welcome to {self._web_base_url}/r/RAOUL\nAnd again,\n'
f'{self._web_base_url}/r/RAOUL',
'number': '14',
'mailing_id': mailing.id,
})
res = (sms_0 | sms_1 | sms_2 | sms_3 | sms_4)._update_body_short_links()
self.assertEqual(res[sms_0.id], f'Welcome to {self._web_base_url}')
self.assertEqual(res[sms_1.id], f'Welcome to {self._web_base_url}/r/RAOUL')
self.assertEqual(res[sms_2.id], f'Welcome to {self._web_base_url}/r/RAOUL/s/%s' % sms_2.id)
self.assertEqual(res[sms_3.id], f'Welcome to {self._web_base_url}/leodagan/r/RAOUL')
self.assertEqual(
res[sms_4.id],
f'Welcome to {self._web_base_url}/r/RAOUL/s/{sms_4.id}\nAnd again,\n{self._web_base_url}/r/RAOUL/s/{sms_4.id}')
def test_sms_send_batch_size(self):
self.count = 0
def _send(sms_self, unlink_failed=False, unlink_sent=True, raise_exception=False):
self.count += 1
return DEFAULT
self.env['ir.config_parameter'].set_param('sms.session.batch.size', '3')
with patch.object(SmsSms, '_send', autospec=True, side_effect=_send) as send_mock:
self.env['sms.sms'].browse(self.sms_all.ids).send()
self.assertEqual(self.count, 4)
def test_sms_send_crash_employee(self):
with self.assertRaises(exceptions.AccessError):
self.env['sms.sms'].with_user(self.user_employee).browse(self.sms_all.ids).send()
def test_sms_send_delete_all(self):
with self.mockSMSGateway(sms_allow_unlink=True, sim_error='jsonrpc_exception'):
self.env['sms.sms'].browse(self.sms_all.ids).send(unlink_failed=True, unlink_sent=True, raise_exception=False)
self.assertFalse(len(self.sms_all.exists()))
def test_sms_send_delete_default(self):
""" Test default send behavior: keep failed SMS, remove sent. """
with self.mockSMSGateway(sms_allow_unlink=True, nbr_t_error={
'+32456000011': 'wrong_number_format',
'+32456000022': 'credit',
'+32456000033': 'server_error',
'+32456000044': 'unregistered',
}):
self.env['sms.sms'].browse(self.sms_all.ids).send(raise_exception=False)
remaining = self.sms_all.exists()
self.assertEqual(len(remaining), 4)
self.assertTrue(all(sms.state == 'error') for sms in remaining)
def test_sms_send_delete_failed(self):
with self.mockSMSGateway(sms_allow_unlink=True, nbr_t_error={
'+32456000011': 'wrong_number_format',
'+32456000022': 'wrong_number_format',
}):
self.env['sms.sms'].browse(self.sms_all.ids).send(unlink_failed=True, unlink_sent=False, raise_exception=False)
remaining = self.sms_all.exists()
self.assertEqual(len(remaining), 8)
self.assertTrue(all(sms.state == 'sent') for sms in remaining)
def test_sms_send_delete_none(self):
with self.mockSMSGateway(sms_allow_unlink=True, nbr_t_error={
'+32456000011': 'wrong_number_format',
'+32456000022': 'wrong_number_format',
}):
self.env['sms.sms'].browse(self.sms_all.ids).send(unlink_failed=False, unlink_sent=False, raise_exception=False)
self.assertEqual(len(self.sms_all.exists()), 10)
success_sms = self.sms_all[:1] + self.sms_all[3:]
error_sms = self.sms_all[1:3]
self.assertTrue(all(sms.state == 'sent') for sms in success_sms)
self.assertTrue(all(sms.state == 'error') for sms in error_sms)
def test_sms_send_delete_sent(self):
with self.mockSMSGateway(sms_allow_unlink=True, nbr_t_error={
'+32456000011': 'wrong_number_format',
'+32456000022': 'wrong_number_format',
}):
self.env['sms.sms'].browse(self.sms_all.ids).send(unlink_failed=False, unlink_sent=True, raise_exception=False)
remaining = self.sms_all.exists()
self.assertEqual(len(remaining), 2)
self.assertTrue(all(sms.state == 'error') for sms in remaining)
def test_sms_send_raise(self):
with self.assertRaises(exceptions.AccessError):
with self.mockSMSGateway(sim_error='jsonrpc_exception'):
self.env['sms.sms'].browse(self.sms_all.ids).send(raise_exception=True)
self.assertEqual(set(self.sms_all.mapped('state')), set(['outgoing']))
def test_sms_send_raise_catch(self):
with self.mockSMSGateway(sim_error='jsonrpc_exception'):
self.env['sms.sms'].browse(self.sms_all.ids).send(raise_exception=False)
self.assertEqual(set(self.sms_all.mapped('state')), set(['error']))
| 46.603015
| 9,274
|
6,421
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sms.tests import common as sms_common
from odoo.addons.test_mail.tests.test_performance import BaseMailPerformance
from odoo.tests.common import users, warmup
from odoo.tests import tagged
from odoo.tools import mute_logger
@tagged('mail_performance', 'post_install', '-at_install')
class TestSMSPerformance(BaseMailPerformance, sms_common.SMSCase):
def setUp(self):
super(TestSMSPerformance, self).setUp()
self.user_employee.write({
'login': 'employee',
'country_id': self.env.ref('base.be').id,
})
self.admin = self.env.user
self.customer = self.env['res.partner'].with_context(self._quick_create_ctx).create({
'name': 'Test Customer',
'email': 'test@example.com',
'mobile': '0456123456',
'country_id': self.env.ref('base.be').id,
})
self.test_record = self.env['mail.test.sms'].with_context(self._quick_create_ctx).create({
'name': 'Test',
'customer_id': self.customer.id,
'phone_nbr': '0456999999',
})
# prepare recipients to test for more realistic workload
Partners = self.env['res.partner'].with_context(self._quick_create_ctx)
self.partners = self.env['res.partner']
for x in range(0, 10):
self.partners |= Partners.create({
'name': 'Test %s' % x,
'email': 'test%s@example.com' % x,
'mobile': '0456%s%s0000' % (x, x),
'country_id': self.env.ref('base.be').id,
})
self._init_mail_gateway()
@mute_logger('odoo.addons.sms.models.sms_sms')
@users('employee')
@warmup
def test_message_sms_record_1_partner(self):
record = self.test_record.with_user(self.env.user)
pids = self.customer.ids
with self.mockSMSGateway(sms_allow_unlink=True), self.assertQueryCount(employee=26): # test_mail_enterprise: 26
messages = record._message_sms(
body='Performance Test',
partner_ids=pids,
)
self.assertEqual(record.message_ids[0].body, '<p>Performance Test</p>')
self.assertSMSNotification([{'partner': self.customer}], 'Performance Test', messages, sent_unlink=True)
@mute_logger('odoo.addons.sms.models.sms_sms')
@users('employee')
@warmup
def test_message_sms_record_10_partners(self):
record = self.test_record.with_user(self.env.user)
pids = self.partners.ids
with self.mockSMSGateway(sms_allow_unlink=True), self.assertQueryCount(employee=44):
messages = record._message_sms(
body='Performance Test',
partner_ids=pids,
)
self.assertEqual(record.message_ids[0].body, '<p>Performance Test</p>')
self.assertSMSNotification([{'partner': partner} for partner in self.partners], 'Performance Test', messages, sent_unlink=True)
@mute_logger('odoo.addons.sms.models.sms_sms')
@users('employee')
@warmup
def test_message_sms_record_default(self):
record = self.test_record.with_user(self.env.user)
with self.mockSMSGateway(sms_allow_unlink=True), self.assertQueryCount(employee=28):
messages = record._message_sms(
body='Performance Test',
)
self.assertEqual(record.message_ids[0].body, '<p>Performance Test</p>')
self.assertSMSNotification([{'partner': self.customer}], 'Performance Test', messages, sent_unlink=True)
@tagged('mail_performance', 'post_install', '-at_install')
class TestSMSMassPerformance(BaseMailPerformance, sms_common.MockSMS):
def setUp(self):
super(TestSMSMassPerformance, self).setUp()
be_country_id = self.env.ref('base.be').id,
self.user_employee.write({
'login': 'employee',
'country_id': be_country_id,
})
self.admin = self.env.user
self.admin.write({
'country_id': be_country_id,
})
self._test_body = 'MASS SMS'
records = self.env['mail.test.sms']
partners = self.env['res.partner']
for x in range(50):
partners += self.env['res.partner'].with_context(**self._quick_create_ctx).create({
'name': 'Partner_%s' % (x),
'email': '_test_partner_%s@example.com' % (x),
'country_id': be_country_id,
'mobile': '047500%02d%02d' % (x, x)
})
records += self.env['mail.test.sms'].with_context(**self._quick_create_ctx).create({
'name': 'Test_%s' % (x),
'customer_id': partners[x].id,
})
self.partners = partners
self.records = records
self.sms_template = self.env['sms.template'].create({
'name': 'Test Template',
'model_id': self.env['ir.model']._get('mail.test.sms').id,
'body': 'Dear {{ object.display_name }} this is an SMS.',
})
self._init_mail_gateway()
@mute_logger('odoo.addons.sms.models.sms_sms')
@users('employee')
@warmup
def test_composer_mass_active_domain(self):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
default_use_active_domain=True,
active_domain=[('id', 'in', self.records.ids)],
).create({
'body': self._test_body,
'mass_keep_log': False,
})
with self.mockSMSGateway(sms_allow_unlink=True), self.assertQueryCount(employee=106):
composer.action_send_sms()
@mute_logger('odoo.addons.sms.models.sms_sms')
@users('employee')
@warmup
def test_composer_mass_active_domain_w_log(self):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
default_use_active_domain=True,
active_domain=[('id', 'in', self.records.ids)],
).create({
'body': self._test_body,
'mass_keep_log': True,
})
with self.mockSMSGateway(sms_allow_unlink=True), self.assertQueryCount(employee=157):
composer.action_send_sms()
| 39.152439
| 6,421
|
4,171
|
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 TestSmsTemplate(TestMailFullCommon, TestMailFullRecipients):
@classmethod
def setUpClass(cls):
super(TestSmsTemplate, 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.body_en = 'Dear {{ object.display_name }} this is an SMS.'
cls.body_fr = u"Hello {{ object.display_name }} ceci est en français."
cls.sms_template = cls._create_sms_template('mail.test.sms', body=cls.body_en)
def test_sms_template_render(self):
rendered_body = self.sms_template._render_template(self.sms_template.body, self.sms_template.model, self.test_record.ids)
self.assertEqual(rendered_body[self.test_record.id], 'Dear %s this is an SMS.' % self.test_record.display_name)
rendered_body = self.sms_template._render_field('body', self.test_record.ids)
self.assertEqual(rendered_body[self.test_record.id], 'Dear %s this is an SMS.' % self.test_record.display_name)
def test_sms_template_lang(self):
self.env['res.lang']._activate_lang('fr_FR')
self.user_admin.write({'lang': 'en_US'})
self.env['ir.translation'].create({
'type': 'model',
'name': 'sms.template,body',
'lang': 'fr_FR',
'res_id': self.sms_template.id,
'src': self.sms_template.body,
'value': self.body_fr,
})
# set template to try to use customer lang
self.sms_template.write({
'lang': '{{ object.customer_id.lang }}',
})
# create a second record linked to a customer in another language
self.partner_2.write({
'lang': 'fr_FR',
})
test_record_2 = self.env['mail.test.sms'].create({
'name': 'Test',
'customer_id': self.partner_2.id,
})
self.assertEqual(self.sms_template.body, self.body_en)
self.assertEqual(self.sms_template.with_context(lang='fr_FR').body, self.body_fr)
rid_to_lang = self.sms_template._render_lang((self.test_record | test_record_2).ids)
self.assertEqual(set(rid_to_lang.keys()), set((self.test_record | test_record_2).ids))
for rid, lang in rid_to_lang.items():
# TDE FIXME: False or en_US ?
if rid == self.test_record.id:
self.assertEqual(lang, 'en_US')
elif rid == test_record_2.id:
self.assertEqual(lang, 'fr_FR')
else:
self.assertTrue(False)
tpl_to_rids = self.sms_template._classify_per_lang((self.test_record | test_record_2).ids)
for lang, (tpl, rids) in tpl_to_rids.items():
# TDE FIXME: False or en_US ?
if lang == 'en_US':
self.assertEqual(rids, self.test_record.ids)
elif lang == 'fr_FR':
self.assertEqual(rids, test_record_2.ids)
else:
self.assertTrue(False, 'Should not return lang %s' % lang)
def test_sms_template_create_and_unlink_sidebar_action(self):
ActWindow = self.env['ir.actions.act_window']
self.sms_template.action_create_sidebar_action()
action_id = self.sms_template.sidebar_action_id.id
self.assertNotEqual(action_id, False)
self.assertEqual(ActWindow.search_count([('id', '=', action_id)]), 1)
self.sms_template.action_unlink_sidebar_action()
self.assertEqual(ActWindow.search_count([('id', '=', action_id)]), 0)
def test_sms_template_unlink_with_action(self):
ActWindow = self.env['ir.actions.act_window']
self.sms_template.action_create_sidebar_action()
action_id = self.sms_template.sidebar_action_id.id
self.sms_template.unlink()
self.assertEqual(ActWindow.search_count([('id', '=', action_id)]), 0)
| 44.361702
| 4,170
|
5,636
|
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, users
@tagged('mail_thread')
class TestMailThreadPhone(TestMailFullCommon, TestMailFullRecipients):
""" Test mail.thread.phone mixin, its tools and API """
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.test_phone_records, cls.test_phone_partners = cls._create_records_for_batch(
'mail.test.sms.bl',
5,
)
cls.test_phone_records += cls.env['mail.test.sms.bl'].create([
{
'phone_nbr': '+32475110505',
'mobile_nbr': '+32475000505',
}, {
'phone_nbr': '0032475110606',
'mobile_nbr': '0032475000606',
}, {
'phone_nbr': '0032475110707',
'mobile_nbr': False,
}, {
'phone_nbr': False,
'mobile_nbr': False,
},
])
def test_initial_data(self):
""" Test initial data for this class, allowing to be sure of I/O of tests. """
self.assertEqual(
self.test_phone_records.mapped('mobile_nbr'),
['0475000000', '0475000101', '0475000202', '0475000303', '0475000404',
'+32475000505', '0032475000606',
False, False,
]
)
self.assertEqual(
self.test_phone_records.mapped('phone_nbr'),
[False] * 5 + ['+32475110505', '0032475110606', '0032475110707', False]
)
@users('employee')
def test_search_phone_mobile_search_boolean(self):
test_phone_records = self.test_phone_records.with_env(self.env)
# test Falsy -> is set / is not set
for test_values in [False, '', ' ']:
# test is not set -> both fields should be not set
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '=', test_values)])
self.assertEqual(results, test_phone_records[-1],
'Search on phone_mobile_search: = False: record with two void values')
# test is set -> at least one field should be set
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '!=', test_values)])
self.assertEqual(results, test_phone_records[:-1],
'Search on phone_mobile_search: != False: record at least one value set')
# test Truthy -> is set / is not set
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '=', True)])
self.assertEqual(results, test_phone_records[:-1],
'Search on phone_mobile_search: = True: record at least one value set')
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '!=', True)])
self.assertEqual(results, test_phone_records[-1],
'Search on phone_mobile_search: != True: record with two void values')
@users('employee')
def test_search_phone_mobile_search_equal(self):
""" Test searching by phone/mobile with direct search """
test_phone_records = self.test_phone_records.with_env(self.env)
# test "=" search
# Currently not suported, returning results for "ilike"
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '=', '0475')])
self.assertFalse(results, 'Search on phone_mobile_search: = should return only matching results')
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '=', '0475000000')])
self.assertEqual(results, test_phone_records[0])
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '=', '0032475110606')])
self.assertEqual(results, test_phone_records[6])
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', '=', '+32475110606')])
self.assertEqual(results, test_phone_records[6])
@users('employee')
def test_search_phone_mobile_search_ilike(self):
""" Test searching by phone/mobile on various ilike combinations """
test_phone_records = self.test_phone_records.with_env(self.env)
# test ilike search
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', 'ilike', '0475')])
self.assertEqual(results, test_phone_records[:5])
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', 'ilike', '101')])
self.assertEqual(results, test_phone_records[1])
# test search using +32/0032
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', 'ilike', '+32475')])
self.assertEqual(results, test_phone_records[5:8],
'Search on phone_mobile_search: +32/0032 likeliness')
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', 'ilike', '0032475')])
self.assertEqual(results, test_phone_records[5:8],
'Search on phone_mobile_search: +32/0032 likeliness')
# test inverse ilike search
# Currently not supported, returning results for "ilike"
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', 'not ilike', '0475')])
self.assertEqual(results, test_phone_records - test_phone_records[:5])
results = self.env['mail.test.sms.bl'].search([('phone_mobile_search', 'not ilike', '101')])
self.assertEqual(results, test_phone_records - test_phone_records[1])
| 50.321429
| 5,636
|
3,068
|
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 TestServerAction(TestMailFullCommon, TestMailFullRecipients):
@classmethod
def setUpClass(cls):
super(TestServerAction, 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_2 = cls.env['mail.test.sms'].with_context(**cls._test_context).create({
'name': 'Test Record 2',
'customer_id': False,
'phone_nbr': cls.test_numbers[0],
})
cls.sms_template = cls._create_sms_template('mail.test.sms')
cls.action = cls.env['ir.actions.server'].create({
'name': 'Test SMS Action',
'model_id': cls.env['ir.model']._get('mail.test.sms').id,
'state': 'sms',
'sms_template_id': cls.sms_template.id,
'groups_id': cls.env.ref('base.group_user'),
})
def test_action_sms(self):
context = {
'active_model': 'mail.test.sms',
'active_ids': (self.test_record | self.test_record_2).ids,
}
with self.with_user('employee'), self.mockSMSGateway():
self.action.with_user(self.env.user).with_context(**context).run()
self.assertSMSOutgoing(self.test_record.customer_id, None, content='Dear %s this is an SMS.' % self.test_record.display_name)
self.assertSMSOutgoing(self.env['res.partner'], self.test_numbers_san[0], content='Dear %s this is an SMS.' % self.test_record_2.display_name)
def test_action_sms_single(self):
context = {
'active_model': 'mail.test.sms',
'active_id': self.test_record.id,
}
with self.with_user('employee'), self.mockSMSGateway():
self.action.with_user(self.env.user).with_context(**context).run()
self.assertSMSOutgoing(self.test_record.customer_id, None, content='Dear %s this is an SMS.' % self.test_record.display_name)
def test_action_sms_w_log(self):
self.action.sms_mass_keep_log = True
context = {
'active_model': 'mail.test.sms',
'active_ids': (self.test_record | self.test_record_2).ids,
}
with self.with_user('employee'), self.mockSMSGateway():
self.action.with_user(self.env.user).with_context(**context).run()
self.assertSMSOutgoing(self.test_record.customer_id, None, content='Dear %s this is an SMS.' % self.test_record.display_name)
self.assertSMSLogged(self.test_record, 'Dear %s this is an SMS.' % self.test_record.display_name)
self.assertSMSOutgoing(self.env['res.partner'], self.test_numbers_san[0], content='Dear %s this is an SMS.' % self.test_record_2.display_name)
self.assertSMSLogged(self.test_record_2, 'Dear %s this is an SMS.' % self.test_record_2.display_name)
| 45.791045
| 3,068
|
2,285
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.phone_validation.tools import phone_validation
from odoo.addons.mass_mailing_sms.tests.common import MassSMSCommon
from odoo.addons.test_mail.tests import common
from odoo.addons.test_mass_mailing.tests.common import TestMassMailCommon
class TestMailFullCommon(TestMassMailCommon, MassSMSCommon):
@classmethod
def setUpClass(cls):
super(TestMailFullCommon, cls).setUpClass()
cls.mailing_sms = cls.env['mailing.mailing'].with_user(cls.user_marketing).create({
'name': 'XMas SMS',
'subject': 'Xmas SMS for {object.name}',
'mailing_model_id': cls.env['ir.model']._get('mail.test.sms').id,
'mailing_type': 'sms',
'mailing_domain': '%s' % repr([('name', 'ilike', 'MassSMSTest')]),
'body_plaintext': 'Dear {{object.display_name}} this is a mass SMS with two links http://www.odoo.com/smstest and http://www.odoo.com/smstest/{{object.id}}',
'sms_force_send': True,
'sms_allow_unsubscribe': True,
})
@classmethod
def _create_mailing_sms_test_records(cls, model='mail.test.sms', partners=None, count=1):
""" Helper to create data. Currently simple, to be improved. """
Model = cls.env[model]
phone_field = 'phone_nbr' if 'phone_nbr' in Model else 'phone'
partner_field = 'customer_id' if 'customer_id' in Model else 'partner_id'
vals_list = []
for idx in range(count):
vals = {
'name': 'MassSMSTestRecord_%02d' % idx,
phone_field: '045600%02d%02d' % (idx, idx)
}
if partners:
vals[partner_field] = partners[idx % len(partners)]
vals_list.append(vals)
return cls.env[model].create(vals_list)
class TestMailFullRecipients(common.TestRecipients):
@classmethod
def setUpClass(cls):
super(TestMailFullRecipients, cls).setUpClass()
cls.partner_numbers = [
phone_validation.phone_format(partner.mobile, partner.country_id.code, partner.country_id.phone_code, force_format='E164')
for partner in (cls.partner_1 | cls.partner_2)
]
| 40.803571
| 2,285
|
27,218
|
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 TestSMSComposerComment(TestMailFullCommon, TestMailFullRecipients):
""" TODO LIST
* add test for default_res_model / default_res_id and stuff like that;
* add test for comment put in queue;
* add test for language support (set template lang context);
* add test for sanitized / wrong numbers;
"""
@classmethod
def setUpClass(cls):
super(TestSMSComposerComment, cls).setUpClass()
cls._test_body = 'VOID CONTENT'
cls.test_record = cls.env['mail.test.sms'].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)
cls.sms_template = cls.env['sms.template'].create({
'name': 'Test Template',
'model_id': cls.env['ir.model']._get('mail.test.sms').id,
'body': 'Dear {{ object.display_name }} this is an SMS.',
})
def test_composer_comment_not_mail_thread(self):
with self.with_user('employee'):
record = self.env['test_performance.base'].create({'name': 'TestBase'})
composer = self.env['sms.composer'].with_context(
active_model='test_performance.base', active_id=record.id
).create({
'body': self._test_body,
'numbers': ','.join(self.random_numbers),
})
with self.mockSMSGateway():
composer._action_send_sms()
# use sms.api directly, does not create sms.sms
self.assertNoSMS()
self.assertSMSIapSent(self.random_numbers_san, self._test_body)
def test_composer_comment_default(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
active_model='mail.test.sms', active_id=self.test_record.id
).create({
'body': self._test_body,
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
self.assertSMSNotification([{'partner': self.test_record.customer_id, 'number': self.test_numbers_san[1]}], self._test_body, messages)
def test_composer_comment_field_1(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
active_model='mail.test.sms', active_id=self.test_record.id,
).create({
'body': self._test_body,
'number_field_name': 'mobile_nbr',
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
self.assertSMSNotification([{'partner': self.test_record.customer_id, 'number': self.test_numbers_san[0]}], self._test_body, messages)
def test_composer_comment_field_2(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
active_model='mail.test.sms', active_id=self.test_record.id,
).create({
'body': self._test_body,
'number_field_name': 'phone_nbr',
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
self.assertSMSNotification([{'partner': self.test_record.customer_id, 'number': self.test_numbers_san[1]}], self._test_body, messages)
def test_composer_comment_field_w_numbers(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
active_model='mail.test.sms', active_id=self.test_record.id,
default_number_field_name='mobile_nbr',
).create({
'body': self._test_body,
'numbers': ','.join(self.random_numbers),
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
self.assertSMSNotification([
{'partner': self.test_record.customer_id, 'number': self.test_record.mobile_nbr},
{'number': self.random_numbers_san[0]}, {'number': self.random_numbers_san[1]}], self._test_body, messages)
def test_composer_comment_field_w_template(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
active_model='mail.test.sms', active_id=self.test_record.id,
default_template_id=self.sms_template.id,
default_number_field_name='mobile_nbr',
).create({})
with self.mockSMSGateway():
messages = composer._action_send_sms()
self.assertSMSNotification([{'partner': self.test_record.customer_id, 'number': self.test_record.mobile_nbr}], 'Dear %s this is an SMS.' % self.test_record.display_name, messages)
def test_composer_comment_nofield(self):
""" Test the Send Message in SMS Composer when a Model does not contain any phone number related field """
test_record = self.env['mail.test.sms.partner'].create({'name': 'Test'})
sms_composer = self.env['sms.composer'].create({
'body': self._test_body,
'recipient_single_number_itf': self.random_numbers_san[0],
'res_id': test_record.id,
'res_model': 'mail.test.sms.partner'
})
with self.mockSMSGateway():
sms_composer._action_send_sms()
self.assertSMSNotification([{'number': self.random_numbers_san[0]}], self._test_body)
def test_composer_default_recipient(self):
self.test_record.write({
'phone_nbr': '0123456789',
})
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_res_model='mail.test.sms', default_res_id=self.test_record.id,
).create({
'body': self._test_body,
'number_field_name': 'phone_nbr',
})
self.assertFalse(composer.recipient_single_valid)
self.assertEqual(composer.recipient_single_description, self.test_record.customer_id.display_name)
def test_composer_internals(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_res_model='mail.test.sms', default_res_id=self.test_record.id,
).create({
'body': self._test_body,
'number_field_name': 'phone_nbr',
})
self.assertEqual(composer.res_model, self.test_record._name)
self.assertEqual(composer.res_id, self.test_record.id)
self.assertEqual(composer.number_field_name, 'phone_nbr')
self.assertTrue(composer.comment_single_recipient)
self.assertEqual(composer.recipient_single_description, self.test_record.customer_id.display_name)
self.assertEqual(composer.recipient_single_number, self.test_numbers[1])
self.assertEqual(composer.recipient_single_number_itf, self.test_numbers[1])
self.assertTrue(composer.recipient_single_valid)
self.assertEqual(composer.recipient_valid_count, 1)
self.assertEqual(composer.recipient_invalid_count, 0)
with self.with_user('employee'):
composer.update({'recipient_single_number_itf': '0123456789'})
self.assertFalse(composer.recipient_single_valid)
with self.with_user('employee'):
composer.update({'recipient_single_number_itf': self.random_numbers[0]})
self.assertTrue(composer.recipient_single_valid)
with self.with_user('employee'):
with self.mockSMSGateway():
composer.action_send_sms()
self.test_record.flush()
self.assertEqual(self.test_record.phone_nbr, self.random_numbers[0])
def test_composer_comment_wo_partner_wo_value_update(self):
""" Test record without partner and without phone values: should allow updating first found phone field """
self.test_record.write({
'customer_id': False,
'phone_nbr': False,
'mobile_nbr': False,
})
default_field_name = self.env['mail.test.sms']._sms_get_number_fields()[0]
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
active_model='mail.test.sms', active_id=self.test_record.id,
default_composition_mode='comment',
).create({
'body': self._test_body,
})
self.assertFalse(composer.recipient_single_number_itf)
self.assertFalse(composer.recipient_single_number)
self.assertEqual(composer.number_field_name, default_field_name)
composer.write({
'recipient_single_number_itf': self.random_numbers_san[0],
})
self.assertEqual(composer.recipient_single_number_itf, self.random_numbers_san[0])
self.assertFalse(composer.recipient_single_number)
with self.mockSMSGateway():
messages = composer._action_send_sms()
self.assertEqual(self.test_record[default_field_name], self.random_numbers_san[0])
self.assertSMSNotification([{'partner': self.env['res.partner'], 'number': self.random_numbers_san[0]}], self._test_body, messages)
def test_composer_numbers_no_model(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='numbers'
).create({
'body': self._test_body,
'numbers': ','.join(self.random_numbers),
})
with self.mockSMSGateway():
composer._action_send_sms()
# use sms.api directly, does not create sms.sms
self.assertNoSMS()
self.assertSMSIapSent(self.random_numbers_san, self._test_body)
class TestSMSComposerBatch(TestMailFullCommon):
@classmethod
def setUpClass(cls):
super(TestSMSComposerBatch, cls).setUpClass()
cls._test_body = 'Hello {{ object.name }} zizisse an SMS.'
cls._create_records_for_batch('mail.test.sms', 3)
cls.sms_template = cls._create_sms_template('mail.test.sms')
def test_composer_batch_active_domain(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='comment',
default_res_model='mail.test.sms',
default_use_active_domain=True,
active_domain=[('id', 'in', self.records.ids)],
).create({
'body': self._test_body,
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
for record, message in zip(self.records, messages):
self.assertSMSNotification(
[{'partner': record.customer_id}],
'Hello %s zizisse an SMS.' % record.name,
message
)
def test_composer_batch_active_ids(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='comment',
default_res_model='mail.test.sms',
active_ids=self.records.ids
).create({
'body': self._test_body,
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
for record, message in zip(self.records, messages):
self.assertSMSNotification(
[{'partner': record.customer_id}],
'Hello %s zizisse an SMS.' % record.name,
message
)
def test_composer_batch_domain(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='comment',
default_res_model='mail.test.sms',
default_use_active_domain=True,
default_active_domain=repr([('id', 'in', self.records.ids)]),
).create({
'body': self._test_body,
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
for record, message in zip(self.records, messages):
self.assertSMSNotification(
[{'partner': record.customer_id}],
'Hello %s zizisse an SMS.' % record.name,
message
)
def test_composer_batch_res_ids(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='comment',
default_res_model='mail.test.sms',
default_res_ids=repr(self.records.ids),
).create({
'body': self._test_body,
})
with self.mockSMSGateway():
messages = composer._action_send_sms()
for record, message in zip(self.records, messages):
self.assertSMSNotification(
[{'partner': record.customer_id}],
'Hello %s zizisse an SMS.' % record.name,
message
)
class TestSMSComposerMass(TestMailFullCommon):
@classmethod
def setUpClass(cls):
super(TestSMSComposerMass, cls).setUpClass()
cls._test_body = 'Hello {{ object.name }} zizisse an SMS.'
cls._create_records_for_batch('mail.test.sms', 10)
cls.sms_template = cls._create_sms_template('mail.test.sms')
def test_composer_mass_active_domain(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
default_use_active_domain=True,
active_domain=[('id', 'in', self.records.ids)],
).create({
'body': self._test_body,
'mass_keep_log': False,
})
with self.mockSMSGateway():
composer.action_send_sms()
for record in self.records:
self.assertSMSOutgoing(
record.customer_id, None,
content='Hello %s zizisse an SMS.' % record.name
)
def test_composer_mass_active_domain_w_template(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
default_use_active_domain=True,
active_domain=[('id', 'in', self.records.ids)],
default_template_id=self.sms_template.id,
).create({
'mass_keep_log': False,
})
with self.mockSMSGateway():
composer.action_send_sms()
for record in self.records:
self.assertSMSOutgoing(
record.customer_id, None,
content='Dear %s this is an SMS.' % record.display_name
)
def test_composer_mass_active_ids(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
).create({
'body': self._test_body,
'mass_keep_log': False,
})
with self.mockSMSGateway():
composer.action_send_sms()
for partner, record in zip(self.partners, self.records):
self.assertSMSOutgoing(
partner, None,
content='Hello %s zizisse an SMS.' % record.name
)
def test_composer_mass_active_ids_w_blacklist(self):
self.env['phone.blacklist'].create([{
'number': p.phone_sanitized,
'active': True,
} for p in self.partners[:5]])
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
).create({
'body': self._test_body,
'mass_keep_log': False,
'mass_use_blacklist': True,
})
with self.mockSMSGateway():
composer.action_send_sms()
for partner, record in zip(self.partners[5:], self.records[5:]):
self.assertSMSOutgoing(
partner, partner.phone_sanitized,
content='Hello %s zizisse an SMS.' % record.name
)
for partner, record in zip(self.partners[:5], self.records[:5]):
self.assertSMSCanceled(
partner, partner.phone_sanitized,
failure_type='sms_blacklist',
content='Hello %s zizisse an SMS.' % record.name
)
def test_composer_mass_active_ids_wo_blacklist(self):
self.env['phone.blacklist'].create([{
'number': p.phone_sanitized,
'active': True,
} for p in self.partners[:5]])
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
).create({
'body': self._test_body,
'mass_keep_log': False,
'mass_use_blacklist': False,
})
with self.mockSMSGateway():
composer.action_send_sms()
for partner, record in zip(self.partners, self.records):
self.assertSMSOutgoing(
partner, partner.phone_sanitized,
content='Hello %s zizisse an SMS.' % record.name
)
def test_composer_mass_active_ids_w_blacklist_and_done(self):
""" Create some duplicates + blacklist. record[5] will have duplicated
number on 6 and 7. """
self.env['phone.blacklist'].create([{
'number': p.phone_sanitized,
'active': True,
} for p in self.partners[:5]])
for p in self.partners[5:8]:
p.mobile = self.partners[5].mobile
self.assertEqual(p.phone_sanitized, self.partners[5].phone_sanitized)
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
).create({
'body': self._test_body,
'mass_keep_log': False,
'mass_use_blacklist': True,
})
with self.mockSMSGateway():
composer.action_send_sms()
self.assertSMSOutgoing(
self.partners[5], self.partners[5].phone_sanitized,
content='Hello %s zizisse an SMS.' % self.records[5].name
)
for partner, record in zip(self.partners[8:], self.records[8:]):
self.assertSMSOutgoing(
partner, partner.phone_sanitized,
content='Hello %s zizisse an SMS.' % record.name
)
# duplicates
for partner, record in zip(self.partners[6:8], self.records[6:8]):
self.assertSMSCanceled(
partner, partner.phone_sanitized,
failure_type='sms_duplicate',
content='Hello %s zizisse an SMS.' % record.name
)
# blacklist
for partner, record in zip(self.partners[:5], self.records[:5]):
self.assertSMSCanceled(
partner, partner.phone_sanitized,
failure_type='sms_blacklist',
content='Hello %s zizisse an SMS.' % record.name
)
def test_composer_mass_active_ids_w_template(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
default_template_id=self.sms_template.id,
).create({
'mass_keep_log': False,
})
with self.mockSMSGateway():
composer.action_send_sms()
for record in self.records:
self.assertSMSOutgoing(
record.customer_id, None,
content='Dear %s this is an SMS.' % record.display_name
)
def test_composer_mass_active_ids_w_template_and_lang(self):
self.env['res.lang']._activate_lang('fr_FR')
self.env['ir.translation'].create({
'type': 'model',
'name': 'sms.template,body',
'lang': 'fr_FR',
'res_id': self.sms_template.id,
'src': self.sms_template.body,
'value': 'Cher·e· {{ object.display_name }} ceci est un SMS.',
})
# set template to try to use customer lang
self.sms_template.write({
'lang': '{{ object.customer_id.lang }}',
})
# set one customer as french speaking
self.partners[2].write({'lang': 'fr_FR'})
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
default_template_id=self.sms_template.id,
).create({
'mass_keep_log': False,
})
with self.mockSMSGateway():
composer.action_send_sms()
for record in self.records:
if record.customer_id == self.partners[2]:
self.assertSMSOutgoing(
record.customer_id, None,
content='Cher·e· %s ceci est un SMS.' % record.display_name
)
else:
self.assertSMSOutgoing(
record.customer_id, None,
content='Dear %s this is an SMS.' % record.display_name
)
def test_composer_mass_active_ids_w_template_and_log(self):
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
default_composition_mode='mass',
default_res_model='mail.test.sms',
active_ids=self.records.ids,
default_template_id=self.sms_template.id,
).create({
'mass_keep_log': True,
})
with self.mockSMSGateway():
composer.action_send_sms()
for record in self.records:
self.assertSMSOutgoing(
record.customer_id, None,
content='Dear %s this is an SMS.' % record.display_name
)
self.assertSMSLogged(record, 'Dear %s this is an SMS.' % record.display_name)
def test_composer_template_context_action(self):
""" Test the context action from a SMS template (Add context action button)
and the usage with the sms composer """
# Create the lang info
self.env['res.lang']._activate_lang('fr_FR')
self.env['ir.translation'].create({
'type': 'model',
'name': 'sms.template,body',
'lang': 'fr_FR',
'res_id': self.sms_template.id,
'src': self.sms_template.body,
'value': "Hello {{ object.display_name }} ceci est en français.",
})
# set template to try to use customer lang
self.sms_template.write({
'lang': '{{ object.customer_id.lang }}',
})
# create a second record linked to a customer in another language
self.partners[2].write({'lang': 'fr_FR'})
test_record_2 = self.env['mail.test.sms'].create({
'name': 'Test',
'customer_id': self.partners[2].id,
})
test_record_1 = self.env['mail.test.sms'].create({
'name': 'Test',
'customer_id': self.partners[1].id,
})
# Composer creation with context from a template context action (simulate) - comment (single recipient)
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
sms_composition_mode='guess',
default_res_ids=[test_record_2.id],
default_res_id=test_record_2.id,
active_ids=[test_record_2.id],
active_id=test_record_2.id,
active_model='mail.test.sms',
default_template_id=self.sms_template.id,
).create({
'mass_keep_log': False,
})
self.assertEqual(composer.composition_mode, "comment")
self.assertEqual(composer.body, "Hello %s ceci est en français." % test_record_2.display_name)
with self.mockSMSGateway():
messages = composer._action_send_sms()
number = self.partners[2].phone_get_sanitized_number()
self.assertSMSNotification(
[{'partner': test_record_2.customer_id, 'number': number}],
"Hello %s ceci est en français." % test_record_2.display_name, messages
)
# Composer creation with context from a template context action (simulate) - mass (multiple recipient)
with self.with_user('employee'):
composer = self.env['sms.composer'].with_context(
sms_composition_mode='guess',
default_res_ids=[test_record_1.id, test_record_2.id],
default_res_id=test_record_1.id,
active_ids=[test_record_1.id, test_record_2.id],
active_id=test_record_1.id,
active_model='mail.test.sms',
default_template_id=self.sms_template.id,
).create({
'mass_keep_log': True,
})
self.assertEqual(composer.composition_mode, "mass")
# In english because by default but when sinding depending of record
self.assertEqual(composer.body, "Dear {{ object.display_name }} this is an SMS.")
with self.mockSMSGateway():
composer.action_send_sms()
self.assertSMSOutgoing(
test_record_1.customer_id, None,
content='Dear %s this is an SMS.' % test_record_1.display_name
)
self.assertSMSOutgoing(
test_record_2.customer_id, None,
content="Hello %s ceci est en français." % test_record_2.display_name
)
| 40.551416
| 27,210
|
17,017
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from odoo.addons.phone_validation.tools import phone_validation
from odoo.addons.test_mail_full.tests.common import TestMailFullCommon
from odoo import exceptions
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.tools import mute_logger
@tagged('mass_mailing')
class TestMassSMSCommon(TestMailFullCommon):
@classmethod
def setUpClass(cls):
super(TestMassSMSCommon, cls).setUpClass()
cls._test_body = 'Mass SMS in your face'
records = cls.env['mail.test.sms']
partners = cls.env['res.partner']
country_be_id = cls.env.ref('base.be').id,
country_us_id = cls.env.ref('base.us').id,
for x in range(10):
partners += cls.env['res.partner'].with_context(**cls._test_context).create({
'name': 'Partner_%s' % (x),
'email': '_test_partner_%s@example.com' % (x),
'country_id': country_be_id,
'mobile': '045600%s%s99' % (x, x)
})
records += cls.env['mail.test.sms'].with_context(**cls._test_context).create({
'name': 'MassSMSTest_%s' % (x),
'customer_id': partners[x].id,
'phone_nbr': '045600%s%s44' % (x, x)
})
cls.records = cls._reset_mail_context(records)
cls.records_numbers = [phone_validation.phone_format(r.phone_nbr, 'BE', '32', force_format='E164') for r in cls.records]
cls.partners = partners
cls.sms_template = cls.env['sms.template'].create({
'name': 'Test Template',
'model_id': cls.env['ir.model']._get('mail.test.sms').id,
'body': 'Dear {{ object.display_name }} this is a mass SMS.',
})
cls.partner_numbers = [
phone_validation.phone_format(partner.mobile, partner.country_id.code, partner.country_id.phone_code, force_format='E164')
for partner in partners
]
@tagged('mass_mailing')
class TestMassSMSInternals(TestMassSMSCommon):
@users('user_marketing')
def test_mass_sms_domain(self):
mailing = self.env['mailing.mailing'].create({
'name': 'Xmas Spam',
'subject': 'Xmas Spam',
'mailing_model_id': self.env['ir.model']._get('mail.test.sms').id,
'mailing_type': 'sms',
})
self.assertEqual(literal_eval(mailing.mailing_domain), [])
mailing = self.env['mailing.mailing'].create({
'name': 'Xmas Spam',
'subject': 'Xmas Spam',
'mailing_model_id': self.env['ir.model']._get('mail.test.sms.bl').id,
'mailing_type': 'sms',
})
self.assertEqual(literal_eval(mailing.mailing_domain), [('phone_sanitized_blacklisted', '=', False)])
@users('user_marketing')
def test_mass_sms_internals(self):
with self.with_user('user_marketing'):
mailing = self.env['mailing.mailing'].create({
'name': 'Xmas Spam',
'subject': 'Xmas Spam',
'mailing_model_id': self.env['ir.model']._get('mail.test.sms').id,
'mailing_type': 'sms',
'mailing_domain': '%s' % repr([('name', 'ilike', 'MassSMSTest')]),
'sms_template_id': self.sms_template.id,
'sms_allow_unsubscribe': False,
})
self.assertEqual(mailing.mailing_model_real, 'mail.test.sms')
self.assertEqual(mailing.medium_id, self.env.ref('mass_mailing_sms.utm_medium_sms'))
self.assertEqual(mailing.body_plaintext, self.sms_template.body)
remaining_res_ids = mailing._get_remaining_recipients()
self.assertEqual(set(remaining_res_ids), set(self.records.ids))
with self.mockSMSGateway():
mailing.action_send_sms()
self.assertSMSTraces(
[{'partner': record.customer_id,
'number': self.records_numbers[i],
'content': 'Dear %s this is a mass SMS.' % record.display_name
} for i, record in enumerate(self.records)],
mailing, self.records,
)
@users('user_marketing')
def test_mass_sms_internals_errors(self):
# same customer, specific different number on record -> should be valid
new_record_1 = self.env['mail.test.sms'].create({
'name': 'MassSMSTest_nr1',
'customer_id': self.partners[0].id,
'phone_nbr': '0456999999',
})
void_record = self.env['mail.test.sms'].create({
'name': 'MassSMSTest_void',
'customer_id': False,
'phone_nbr': '',
})
falsy_record_1 = self.env['mail.test.sms'].create({
'name': 'MassSMSTest_falsy_1',
'customer_id': False,
'phone_nbr': 'abcd',
})
falsy_record_2 = self.env['mail.test.sms'].create({
'name': 'MassSMSTest_falsy_2',
'customer_id': False,
'phone_nbr': '04561122',
})
bl_record_1 = self.env['mail.test.sms'].create({
'name': 'MassSMSTest_bl_1',
'customer_id': False,
'phone_nbr': '0456110011',
})
self.env['phone.blacklist'].sudo().create({'number': '0456110011'})
# new customer, number already on record -> should be ignored
country_be_id = self.env.ref('base.be').id
nr2_partner = self.env['res.partner'].create({
'name': 'Partner_nr2',
'country_id': country_be_id,
'mobile': '0456449999',
})
new_record_2 = self.env['mail.test.sms'].create({
'name': 'MassSMSTest_nr2',
'customer_id': nr2_partner.id,
'phone_nbr': self.records[0].phone_nbr,
})
records_numbers = self.records_numbers + ['+32456999999']
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
mailing.write({'sms_force_send': False}) # force outgoing sms, not sent
with self.with_user('user_marketing'):
with self.mockSMSGateway():
mailing.action_send_sms()
self.assertSMSTraces(
[{'partner': record.customer_id, 'number': records_numbers[i],
'content': 'Dear %s this is a mass SMS' % record.display_name}
for i, record in enumerate(self.records | new_record_1)],
mailing, self.records | new_record_1,
)
# duplicates
self.assertSMSTraces(
[{'partner': new_record_2.customer_id, 'number': self.records_numbers[0],
'content': 'Dear %s this is a mass SMS' % new_record_2.display_name, 'trace_status': 'cancel',
'failure_type': 'sms_duplicate'}],
mailing, new_record_2,
)
# blacklist
self.assertSMSTraces(
[{'partner': self.env['res.partner'], 'number': phone_validation.phone_format(bl_record_1.phone_nbr, 'BE', '32', force_format='E164'),
'content': 'Dear %s this is a mass SMS' % bl_record_1.display_name, 'trace_status': 'cancel',
'failure_type': 'sms_blacklist'}],
mailing, bl_record_1,
)
# missing number
self.assertSMSTraces(
[{'partner': self.env['res.partner'], 'number': False,
'content': 'Dear %s this is a mass SMS' % void_record.display_name, 'trace_status': 'cancel',
'failure_type': 'sms_number_missing'}],
mailing, void_record,
)
# wrong values
self.assertSMSTraces(
[{'partner': self.env['res.partner'], 'number': record.phone_nbr,
'content': 'Dear %s this is a mass SMS' % record.display_name, 'trace_status': 'cancel',
'failure_type': 'sms_number_format'}
for record in falsy_record_1 + falsy_record_2],
mailing, falsy_record_1 + falsy_record_2,
)
@users('user_marketing')
def test_mass_sms_internals_done_ids(self):
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
mailing.write({'sms_force_send': False}) # check with outgoing traces, not already sent
with self.with_user('user_marketing'):
with self.mockSMSGateway():
mailing.action_send_sms(res_ids=self.records[:5].ids)
traces = self.env['mailing.trace'].search([('mass_mailing_id', 'in', mailing.ids)])
self.assertEqual(len(traces), 5)
# new traces generated
self.assertSMSTraces(
[{'partner': record.customer_id, 'number': self.records_numbers[i],
'content': 'Dear %s this is a mass SMS' % record.display_name}
for i, record in enumerate(self.records[:5])],
mailing, self.records[:5],
)
with self.with_user('user_marketing'):
with self.mockSMSGateway():
mailing.action_send_sms(res_ids=self.records.ids)
# delete old traces (for testing purpose: ease check by deleting old ones)
traces.unlink()
# new failed traces generated for duplicates
self.assertSMSTraces(
[{'partner': record.customer_id, 'number': self.records_numbers[i],
'content': 'Dear %s this is a mass SMS' % record.display_name, 'trace_status': 'cancel',
'failure_type': 'sms_duplicate'}
for i, record in enumerate(self.records[:5])],
mailing, self.records[:5],
)
# new traces generated
self.assertSMSTraces(
[{'partner': record.customer_id, 'number': self.records_numbers[i+5],
'content': 'Dear %s this is a mass SMS' % record.display_name}
for i, record in enumerate(self.records[5:])],
mailing, self.records[5:],
)
@mute_logger('odoo.addons.mail.models.mail_render_mixin')
def test_mass_sms_test_button(self):
mailing = self.env['mailing.mailing'].create({
'name': 'TestButton',
'subject': 'Subject {{ object.name }}',
'preview': 'Preview {{ object.name }}',
'state': 'draft',
'mailing_type': 'sms',
'body_plaintext': 'Hello {{ object.name }}',
'mailing_model_id': self.env['ir.model']._get('res.partner').id,
})
mailing_test = self.env['mailing.sms.test'].with_user(self.user_marketing).create({
'numbers': '+32456001122',
'mailing_id': mailing.id,
})
with self.with_user('user_marketing'):
with self.mockSMSGateway():
mailing_test.action_send_sms()
# Test if bad inline_template in the body raises an error
mailing.write({
'body_plaintext': 'Hello {{ object.name_id.id }}',
})
with self.with_user('user_marketing'):
with self.mock_mail_gateway(), self.assertRaises(Exception):
mailing_test.action_send_sms()
@tagged('mass_mailing', 'mass_mailing_sms')
class TestMassSMS(TestMassSMSCommon):
@users('user_marketing')
def test_mass_sms_links(self):
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
mailing.write({
'body_plaintext': 'Dear {{ object.display_name }} this is a mass SMS with two links http://www.odoo.com/smstest and http://www.odoo.com/smstest/{{ object.name }}',
'sms_template_id': False,
'sms_force_send': True,
'sms_allow_unsubscribe': True,
})
with self.mockSMSGateway():
mailing.action_send_sms()
self.assertSMSTraces(
[{'partner': record.customer_id,
'number': self.records_numbers[i],
'trace_status': 'sent',
'content': 'Dear %s this is a mass SMS with two links' % record.display_name
} for i, record in enumerate(self.records)],
mailing, self.records,
sms_links_info=[[
('http://www.odoo.com/smstest', True, {}),
('http://www.odoo.com/smstest/%s' % record.name, True, {}),
# unsubscribe is not shortened and parsed at sending
('unsubscribe', False, {}),
] for record in self.records],
)
@users('user_marketing')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mass_sms_partner_only(self):
""" Check sending SMS marketing on models having only a partner_id fields
set is working. """
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
mailing.write({
'mailing_model_id': self.env['ir.model']._get('mail.test.sms.partner').id,
})
records = self.env['mail.test.sms.partner'].create([
{'name': 'MassSMSTest on %s' % partner.name,
'customer_id': partner.id,
} for partner in self.partners
])
with self.mockSMSGateway():
mailing.action_send_sms()
self.assertEqual(len(mailing.mailing_trace_ids), 10)
self.assertSMSTraces(
[{'partner': record.customer_id,
'number': record.customer_id.phone_sanitized,
'trace_status': 'sent',
'content': 'Dear %s this is a mass SMS with two links' % record.display_name
} for record in records],
mailing, records,
sms_links_info=[[
('http://www.odoo.com/smstest', True, {}),
('http://www.odoo.com/smstest/%s' % record.id, True, {}),
# unsubscribe is not shortened and parsed at sending
('unsubscribe', False, {}),
] for record in records],
)
# add a new record, send -> sent list should not resend traces
new_record = self.env['mail.test.sms.partner'].create([
{'name': 'Duplicate SMS on %s' % self.partners[0].name,
'customer_id': self.partners[0].id,
}
])
with self.mockSMSGateway():
mailing.action_send_sms()
self.assertEqual(len(mailing.mailing_trace_ids), 11)
self.assertSMSTraces(
[{'partner': new_record.customer_id,
'number': new_record.customer_id.phone_sanitized,
'trace_status': 'sent',
'content': 'Dear %s this is a mass SMS with two links' % new_record.display_name
}],
mailing, new_record,
sms_links_info=[[
('http://www.odoo.com/smstest', True, {}),
('http://www.odoo.com/smstest/%s' % new_record.id, True, {}),
# unsubscribe is not shortened and parsed at sending
('unsubscribe', False, {}),
]],
)
@users('user_marketing')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mass_sms_partner_only_m2m(self):
""" Check sending SMS marketing on models having only a m2m to partners
is currently not suppored. """
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
mailing.write({
'mailing_model_id': self.env['ir.model']._get('mail.test.sms.partner.2many').id,
})
self.env['mail.test.sms.partner.2many'].create([
{'name': 'MassSMSTest on %s' % partner.name,
'customer_ids': [(4, partner.id)],
} for partner in self.partners
])
with self.assertRaises(exceptions.UserError), self.mockSMSGateway():
mailing.action_send_sms()
@users('user_marketing')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mass_sms_w_opt_out(self):
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
recipients = self._create_mailing_sms_test_records(model='mail.test.sms.bl.optout', count=5)
# optout records 0 and 1
(recipients[0] | recipients[1]).write({'opt_out': True})
# blacklist records 4
# TDE FIXME: sudo should not be necessary
self.env['phone.blacklist'].sudo().create({'number': recipients[4].phone_nbr})
mailing.write({
'mailing_model_id': self.env['ir.model']._get('mail.test.sms.bl.optout'),
'mailing_domain': [('id', 'in', recipients.ids)],
})
with self.mockSMSGateway():
mailing.action_send_sms()
self.assertSMSTraces(
[{'number': '+32456000000', 'trace_status': 'cancel', 'failure_type': 'sms_optout'},
{'number': '+32456000101', 'trace_status': 'cancel', 'failure_type': 'sms_optout'},
{'number': '+32456000202', 'trace_status': 'sent'},
{'number': '+32456000303', 'trace_status': 'sent'},
{'number': '+32456000404', 'trace_status': 'cancel', 'failure_type': 'sms_blacklist'}],
mailing, recipients
)
self.assertEqual(mailing.canceled, 3)
| 42.330846
| 17,017
|
5,817
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.urls import url_parse, url_decode
import json
from odoo import http
from odoo.addons.test_mail_full.tests.common import TestMailFullCommon, TestMailFullRecipients
from odoo.tests import tagged, users
from odoo.tests.common import HttpCase
@tagged('portal')
class TestPortal(HttpCase, TestMailFullCommon, TestMailFullRecipients):
def setUp(self):
super(TestPortal, self).setUp()
self.record_portal = self.env['mail.test.portal'].create({
'partner_id': self.partner_1.id,
'name': 'Test Portal Record',
})
self.record_portal._portal_ensure_token()
@tagged('-at_install', 'post_install', 'portal')
class TestPortalControllers(TestPortal):
def test_redirect_to_records(self):
""" Test redirection of portal-enabled records """
# Test Case 0: as anonymous, cannot access, redirect to web/login
response = self.url_open('/mail/view?model=%s&res_id=%s' % (
self.record_portal._name,
self.record_portal.id), timeout=15)
path = url_parse(response.url).path
self.assertEqual(path, '/web/login')
# Test Case 1: as admin, can access record
self.authenticate(self.user_admin.login, self.user_admin.login)
response = self.url_open('/mail/view?model=%s&res_id=%s' % (
self.record_portal._name,
self.record_portal.id), timeout=15)
self.assertEqual(response.status_code, 200)
fragment = url_parse(response.url).fragment
params = url_decode(fragment)
self.assertEqual(params['cids'], '%s' % self.user_admin.company_id.id)
self.assertEqual(params['id'], '%s' % self.record_portal.id)
self.assertEqual(params['model'], self.record_portal._name)
def test_redirect_to_records_norecord(self):
""" Check specific use case of missing model, should directly redirect
to login page. """
for model, res_id in [
(False, self.record_portal.id),
('', self.record_portal.id),
(self.record_portal._name, False),
(self.record_portal._name, ''),
(False, False),
('wrong.model', self.record_portal.id),
(self.record_portal._name, -4),
]:
response = self.url_open(
'/mail/view?model=%s&res_id=%s' % (model, res_id),
timeout=15
)
path = url_parse(response.url).path
self.assertEqual(
path, '/web/login',
'Failed with %s - %s' % (model, res_id)
)
def test_portal_message_fetch(self):
"""Test retrieving chatter messages through the portal controller"""
self.authenticate(None, None)
message_fetch_url = '/mail/chatter_fetch'
payload = json.dumps({
'jsonrpc': '2.0',
'method': 'call',
'id': 0,
'params': {
'res_model': 'mail.test.portal',
'res_id': self.record_portal.id,
'token': self.record_portal.access_token,
},
})
def get_chatter_message_count():
res = self.url_open(
url=message_fetch_url,
data=payload,
headers={'Content-Type': 'application/json'}
)
return res.json().get('result', {}).get('message_count', 0)
self.assertEqual(get_chatter_message_count(), 0)
for _ in range(8):
self.record_portal.message_post(
body='Test',
author_id=self.partner_1.id,
message_type='comment',
subtype_id=self.env.ref('mail.mt_comment').id,
)
self.assertEqual(get_chatter_message_count(), 8)
# Empty the body of a few messages
for i in (2, 5, 6):
self.record_portal.message_ids[i].body = ""
# Empty messages should be ignored
self.assertEqual(get_chatter_message_count(), 5)
def test_portal_share_comment(self):
""" Test posting through portal controller allowing to use a hash to
post wihtout access rights. """
self.authenticate(None, None)
post_url = f"{self.record_portal.get_base_url()}/mail/chatter_post"
# test as not logged
self.opener.post(
url=post_url,
json={
'params': {
'csrf_token': http.WebRequest.csrf_token(self),
'hash': self.record_portal._sign_token(self.partner_2.id),
'message': 'Test',
'pid': self.partner_2.id,
'redirect': '/',
'res_model': self.record_portal._name,
'res_id': self.record_portal.id,
'token': self.record_portal.access_token,
},
},
)
message = self.record_portal.message_ids[0]
self.assertIn('Test', message.body)
self.assertEqual(message.author_id, self.partner_2)
@tagged('portal')
class TestPortalMixin(TestPortal):
@users('employee')
def test_portal_mixin(self):
""" Test internals of portal mixin """
customer = self.partner_1.with_env(self.env)
record_portal = self.env['mail.test.portal'].create({
'partner_id': customer.id,
'name': 'Test Portal Record',
})
self.assertFalse(record_portal.access_token)
self.assertEqual(record_portal.access_url, '/my/test_portal/%s' % record_portal.id)
record_portal._portal_ensure_token()
self.assertTrue(record_portal.access_token)
| 35.687117
| 5,817
|
23,530
|
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 TestSMSPost(TestMailFullCommon, TestMailFullRecipients):
""" TODO
* add tests for new mail.message and mail.thread fields;
"""
@classmethod
def setUpClass(cls):
super(TestSMSPost, cls).setUpClass()
cls._test_body = 'VOID CONTENT'
cls.test_record = cls.env['mail.test.sms'].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_message_sms_internals_body(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms('<p>Mega SMS<br/>Top moumoutte</p>', partner_ids=self.partner_1.ids)
self.assertEqual(messages.body, '<p>Mega SMS<br>Top moumoutte</p>')
self.assertEqual(messages.subtype_id, self.env.ref('mail.mt_note'))
self.assertSMSNotification([{'partner': self.partner_1}], 'Mega SMS\nTop moumoutte', messages)
def test_message_sms_internals_check_existing(self):
with self.with_user('employee'), self.mockSMSGateway(sim_error='wrong_number_format'):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=self.partner_1.ids)
self.assertSMSNotification([{'partner': self.partner_1, 'state': 'exception', 'failure_type': 'sms_number_format'}], self._test_body, messages)
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
test_record._notify_record_by_sms(messages, [{'id': self.partner_1.id, 'notif': 'sms'}], check_existing=True)
self.assertSMSNotification([{'partner': self.partner_1}], self._test_body, messages)
def test_message_sms_internals_sms_numbers(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=self.partner_1.ids, sms_numbers=self.random_numbers)
self.assertSMSNotification([{'partner': self.partner_1}, {'number': self.random_numbers_san[0]}, {'number': self.random_numbers_san[1]}], self._test_body, messages)
def test_message_sms_internals_subtype(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms('<p>Mega SMS<br/>Top moumoutte</p>', subtype_id=self.env.ref('mail.mt_comment').id, partner_ids=self.partner_1.ids)
self.assertEqual(messages.body, '<p>Mega SMS<br>Top moumoutte</p>')
self.assertEqual(messages.subtype_id, self.env.ref('mail.mt_comment'))
self.assertSMSNotification([{'partner': self.partner_1}], 'Mega SMS\nTop moumoutte', messages)
def test_message_sms_internals_pid_to_number(self):
pid_to_number = {
self.partner_1.id: self.random_numbers[0],
self.partner_2.id: self.random_numbers[1],
}
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2).ids, sms_pid_to_number=pid_to_number)
self.assertSMSNotification([
{'partner': self.partner_1, 'number': self.random_numbers_san[0]},
{'partner': self.partner_2, 'number': self.random_numbers_san[1]}],
self._test_body, messages)
def test_message_sms_model_partner(self):
with self.with_user('employee'), self.mockSMSGateway():
messages = self.partner_1._message_sms(self._test_body)
messages |= self.partner_2._message_sms(self._test_body)
self.assertSMSNotification([{'partner': self.partner_1}, {'partner': self.partner_2}], self._test_body, messages)
def test_message_sms_model_partner_fallback(self):
self.partner_1.write({'mobile': False, 'phone': self.random_numbers[0]})
with self.mockSMSGateway():
messages = self.partner_1._message_sms(self._test_body)
messages |= self.partner_2._message_sms(self._test_body)
self.assertSMSNotification([{'partner': self.partner_1, 'number': self.random_numbers_san[0]}, {'partner': self.partner_2}], self._test_body, messages)
def test_message_sms_model_w_partner_only(self):
with self.with_user('employee'):
record = self.env['mail.test.sms.partner'].create({'customer_id': self.partner_1.id})
with self.mockSMSGateway():
messages = record._message_sms(self._test_body)
self.assertSMSNotification([{'partner': self.partner_1}], self._test_body, messages)
def test_message_sms_model_w_partner_only_void(self):
with self.with_user('employee'):
record = self.env['mail.test.sms.partner'].create({'customer_id': False})
with self.mockSMSGateway():
messages = record._message_sms(self._test_body)
# should not crash but have a failed notification
self.assertSMSNotification([{'partner': self.env['res.partner'], 'number': False, 'state': 'exception', 'failure_type': 'sms_number_missing'}], self._test_body, messages)
def test_message_sms_model_w_partner_m2m_only(self):
with self.with_user('employee'):
record = self.env['mail.test.sms.partner.2many'].create({'customer_ids': [(4, self.partner_1.id)]})
with self.mockSMSGateway():
messages = record._message_sms(self._test_body)
self.assertSMSNotification([{'partner': self.partner_1}], self._test_body, messages)
# TDE: should take first found one according to partner ordering
with self.with_user('employee'):
record = self.env['mail.test.sms.partner.2many'].create({'customer_ids': [(4, self.partner_1.id), (4, self.partner_2.id)]})
with self.mockSMSGateway():
messages = record._message_sms(self._test_body)
self.assertSMSNotification([{'partner': self.partner_2}], self._test_body, messages)
def test_message_sms_on_field_w_partner(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, number_field='mobile_nbr')
self.assertSMSNotification([{'partner': self.partner_1, 'number': self.test_record.mobile_nbr}], self._test_body, messages)
def test_message_sms_on_field_wo_partner(self):
self.test_record.write({'customer_id': False})
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, number_field='mobile_nbr')
self.assertSMSNotification([{'number': self.test_record.mobile_nbr}], self._test_body, messages)
def test_message_sms_on_field_wo_partner_wo_value(self):
""" Test record without a partner and without phone values. """
self.test_record.write({
'customer_id': False,
'phone_nbr': False,
'mobile_nbr': False,
})
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body)
# should not crash but have a failed notification
self.assertSMSNotification([{'partner': self.env['res.partner'], 'number': False, 'state': 'exception', 'failure_type': 'sms_number_missing'}], self._test_body, messages)
def test_message_sms_on_field_wo_partner_default_field(self):
self.test_record.write({'customer_id': False})
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body)
self.assertSMSNotification([{'number': self.test_numbers_san[1]}], self._test_body, messages)
def test_message_sms_on_field_wo_partner_default_field_2(self):
self.test_record.write({'customer_id': False, 'phone_nbr': False})
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body)
self.assertSMSNotification([{'number': self.test_numbers_san[0]}], self._test_body, messages)
def test_message_sms_on_numbers(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, sms_numbers=self.random_numbers_san)
self.assertSMSNotification([{'number': self.random_numbers_san[0]}, {'number': self.random_numbers_san[1]}], self._test_body, messages)
def test_message_sms_on_numbers_sanitization(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, sms_numbers=self.random_numbers)
self.assertSMSNotification([{'number': self.random_numbers_san[0]}, {'number': self.random_numbers_san[1]}], self._test_body, messages)
def test_message_sms_on_partner_ids(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2).ids)
self.assertSMSNotification([{'partner': self.partner_1}, {'partner': self.partner_2}], self._test_body, messages)
def test_message_sms_on_partner_ids_default(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body)
self.assertSMSNotification([{'partner': self.test_record.customer_id, 'number': self.test_numbers_san[1]}], self._test_body, messages)
def test_message_sms_on_partner_ids_w_numbers(self):
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=self.partner_1.ids, sms_numbers=self.random_numbers[:1])
self.assertSMSNotification([{'partner': self.partner_1}, {'number': self.random_numbers_san[0]}], self._test_body, messages)
def test_message_sms_with_template(self):
sms_template = self.env['sms.template'].create({
'name': 'Test Template',
'model_id': self.env['ir.model']._get('mail.test.sms').id,
'body': 'Dear {{ object.display_name }} this is an SMS.',
})
with self.with_user('employee'):
with self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms_with_template(template=sms_template)
self.assertSMSNotification([{'partner': self.partner_1, 'number': self.test_numbers_san[1]}], 'Dear %s this is an SMS.' % self.test_record.display_name, messages)
def test_message_sms_with_template_fallback(self):
with self.with_user('employee'):
with self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms_with_template(template_xmlid='test_mail_full.this_should_not_exists', template_fallback='Fallback for {{ object.id }}')
self.assertSMSNotification([{'partner': self.partner_1, 'number': self.test_numbers_san[1]}], 'Fallback for %s' % self.test_record.id, messages)
def test_message_sms_with_template_xmlid(self):
sms_template = self.env['sms.template'].create({
'name': 'Test Template',
'model_id': self.env['ir.model']._get('mail.test.sms').id,
'body': 'Dear {{ object.display_name }} this is an SMS.',
})
self.env['ir.model.data'].create({
'name': 'this_should_exists',
'module': 'test_mail_full',
'model': sms_template._name,
'res_id': sms_template.id,
})
with self.with_user('employee'):
with self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms_with_template(template_xmlid='test_mail_full.this_should_exists')
self.assertSMSNotification([{'partner': self.partner_1, 'number': self.test_numbers_san[1]}], 'Dear %s this is an SMS.' % self.test_record.display_name, messages)
class TestSMSPostException(TestMailFullCommon, TestMailFullRecipients):
@classmethod
def setUpClass(cls):
super(TestSMSPostException, cls).setUpClass()
cls._test_body = 'VOID CONTENT'
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.partner_3 = cls.env['res.partner'].with_context({
'mail_create_nolog': True,
'mail_create_nosubscribe': True,
'mail_notrack': True,
'no_reset_password': True,
}).create({
'name': 'Ernestine Loubine',
'email': 'ernestine.loubine@agrolait.com',
'country_id': cls.env.ref('base.be').id,
'mobile': '0475556644',
})
def test_message_sms_w_numbers_invalid(self):
random_numbers = self.random_numbers + ['6988754']
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, sms_numbers=random_numbers)
# invalid numbers are still given to IAP currently as they are
self.assertSMSNotification([{'number': self.random_numbers_san[0]}, {'number': self.random_numbers_san[1]}, {'number': random_numbers[2]}], self._test_body, messages)
def test_message_sms_w_partners_nocountry(self):
self.test_record.customer_id.write({
'mobile': self.random_numbers[0],
'phone': self.random_numbers[1],
'country_id': False,
})
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=self.test_record.customer_id.ids)
self.assertSMSNotification([{'partner': self.test_record.customer_id}], self._test_body, messages)
def test_message_sms_w_partners_falsy(self):
# TDE FIXME: currently sent to IAP
self.test_record.customer_id.write({
'mobile': 'youpie',
'phone': 'youpla',
})
with self.with_user('employee'), self.mockSMSGateway():
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=self.test_record.customer_id.ids)
# self.assertSMSNotification({self.test_record.customer_id: {}}, {}, self._test_body, messages)
def test_message_sms_w_numbers_sanitization_duplicate(self):
pass
# TDE FIXME: not sure
# random_numbers = self.random_numbers + [self.random_numbers[1]]
# random_numbers_san = self.random_numbers_san + [self.random_numbers_san[1]]
# with self.with_user('employee'), self.mockSMSGateway():
# messages = self.test_record._message_sms(self._test_body, sms_numbers=random_numbers)
# self.assertSMSNotification({}, {random_numbers_san[0]: {}, random_numbers_san[1]: {}, random_numbers_san[2]: {}}, self._test_body, messages)
def test_message_sms_crash_credit(self):
with self.with_user('employee'), self.mockSMSGateway(sim_error='credit'):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'exception', 'failure_type': 'sms_credit'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_credit'},
], self._test_body, messages)
def test_message_sms_crash_credit_single(self):
with self.with_user('employee'), self.mockSMSGateway(nbr_t_error={self.partner_2.phone_get_sanitized_number(): 'credit'}):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2 | self.partner_3).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'sent'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_credit'},
{'partner': self.partner_3, 'state': 'sent'},
], self._test_body, messages)
def test_message_sms_crash_server_crash(self):
with self.with_user('employee'), self.mockSMSGateway(sim_error='jsonrpc_exception'):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2 | self.partner_3).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'exception', 'failure_type': 'sms_server'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_server'},
{'partner': self.partner_3, 'state': 'exception', 'failure_type': 'sms_server'},
], self._test_body, messages)
def test_message_sms_crash_unregistered(self):
with self.with_user('employee'), self.mockSMSGateway(sim_error='unregistered'):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'exception', 'failure_type': 'sms_acc'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_acc'},
], self._test_body, messages)
def test_message_sms_crash_unregistered_single(self):
with self.with_user('employee'), self.mockSMSGateway(nbr_t_error={self.partner_2.phone_get_sanitized_number(): 'unregistered'}):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2 | self.partner_3).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'sent'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_acc'},
{'partner': self.partner_3, 'state': 'sent'},
], self._test_body, messages)
def test_message_sms_crash_wrong_number(self):
with self.with_user('employee'), self.mockSMSGateway(sim_error='wrong_number_format'):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'exception', 'failure_type': 'sms_number_format'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_number_format'},
], self._test_body, messages)
def test_message_sms_crash_wrong_number_single(self):
with self.with_user('employee'), self.mockSMSGateway(nbr_t_error={self.partner_2.phone_get_sanitized_number(): 'wrong_number_format'}):
test_record = self.env['mail.test.sms'].browse(self.test_record.id)
messages = test_record._message_sms(self._test_body, partner_ids=(self.partner_1 | self.partner_2 | self.partner_3).ids)
self.assertSMSNotification([
{'partner': self.partner_1, 'state': 'sent'},
{'partner': self.partner_2, 'state': 'exception', 'failure_type': 'sms_number_format'},
{'partner': self.partner_3, 'state': 'sent'},
], self._test_body, messages)
class TestSMSApi(TestMailFullCommon):
@classmethod
def setUpClass(cls):
super(TestSMSApi, cls).setUpClass()
cls._test_body = 'Zizisse an SMS.'
cls._create_records_for_batch('mail.test.sms', 3)
cls.sms_template = cls._create_sms_template('mail.test.sms')
def test_message_schedule_sms(self):
with self.with_user('employee'):
with self.mockSMSGateway():
self.env['mail.test.sms'].browse(self.records.ids)._message_sms_schedule_mass(body=self._test_body, mass_keep_log=False)
for record in self.records:
self.assertSMSOutgoing(record.customer_id, None, content=self._test_body)
def test_message_schedule_sms_w_log(self):
with self.with_user('employee'):
with self.mockSMSGateway():
self.env['mail.test.sms'].browse(self.records.ids)._message_sms_schedule_mass(body=self._test_body, mass_keep_log=True)
for record in self.records:
self.assertSMSOutgoing(record.customer_id, None, content=self._test_body)
self.assertSMSLogged(record, self._test_body)
def test_message_schedule_sms_w_template(self):
with self.with_user('employee'):
with self.mockSMSGateway():
self.env['mail.test.sms'].browse(self.records.ids)._message_sms_schedule_mass(template=self.sms_template, mass_keep_log=False)
for record in self.records:
self.assertSMSOutgoing(record.customer_id, None, content='Dear %s this is an SMS.' % record.display_name)
def test_message_schedule_sms_w_template_and_log(self):
with self.with_user('employee'):
with self.mockSMSGateway():
self.env['mail.test.sms'].browse(self.records.ids)._message_sms_schedule_mass(template=self.sms_template, mass_keep_log=True)
for record in self.records:
self.assertSMSOutgoing(record.customer_id, None, content='Dear %s this is an SMS.' % record.display_name)
self.assertSMSLogged(record, 'Dear %s this is an SMS.' % record.display_name)
| 53.844394
| 23,530
|
3,322
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import html
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.test_mail_full.tests.test_mass_sms import TestMassSMSCommon
from odoo.tests.common import users
from odoo.tests import tagged
from odoo.tools import formataddr, mute_logger
@tagged('digest', 'mass_mailing')
class TestMailingStatistics(TestMassSMSCommon):
@classmethod
def setUpClass(cls):
super(TestMailingStatistics, cls).setUpClass()
cls.user_marketing_2 = mail_new_test_user(
cls.env,
groups='base.group_user,base.group_partner_manager,mass_mailing.group_mass_mailing_user',
login='user_marketing_2',
name='Marie Marketing',
signature='--\nMarie'
)
@users('user_marketing')
@mute_logger('odoo.addons.mass_mailing_sms.models.mailing_mailing', 'odoo.addons.mail.models.mail_mail', 'odoo.addons.mail.models.mail_thread')
def test_mailing_statistics_sms(self):
mailing = self.env['mailing.mailing'].browse(self.mailing_sms.ids)
target_records = self.env['mail.test.sms'].browse(self.records.ids)
mailing.write({'mailing_domain': [('id', 'in', target_records.ids)], 'user_id': self.user_marketing_2.id})
mailing.action_put_in_queue()
with self.mockSMSGateway():
mailing.action_send_sms()
# simulate some replies and clicks
self.gateway_sms_click(mailing, target_records[0])
self.gateway_sms_click(mailing, target_records[2])
self.gateway_sms_click(mailing, target_records[3])
# check mailing statistics
self.assertEqual(mailing.clicked, 3)
self.assertEqual(mailing.delivered, 10)
self.assertEqual(mailing.opened, 3)
self.assertEqual(mailing.opened_ratio, 30)
self.assertEqual(mailing.sent, 10)
with self.mock_mail_gateway(mail_unlink_sent=True):
mailing._action_send_statistics()
self.assertEqual(len(self._new_mails), 1, "Mailing: a mail should have been created for statistics")
mail = self._new_mails[0]
# test email values
self.assertEqual(mail.author_id, self.user_marketing_2.partner_id)
self.assertEqual(mail.email_from, self.user_marketing_2.email_formatted)
self.assertEqual(mail.email_to, self.user_marketing_2.email_formatted)
self.assertEqual(mail.reply_to, self.company_admin.partner_id.email_formatted)
self.assertEqual(mail.state, 'outgoing')
# test body content: KPIs
body_html = html.fromstring(mail.body_html)
kpi_values = body_html.xpath('//div[@data-field="sms"]//*[hasclass("kpi_value")]/text()')
self.assertEqual(
[t.strip().strip('%') for t in kpi_values],
['100', str(mailing.opened_ratio), str(mailing.replied_ratio)]
)
# test body content: clicks (a bit hackish but hey we are in stable)
kpi_click_values = body_html.xpath('//div[hasclass("global_layout")]/table//tr[contains(@style,"color: #888888")]/td[contains(@style,"width: 30%")]/text()')
first_link_value = int(kpi_click_values[0].strip().split()[1].strip('()'))
self.assertEqual(first_link_value, mailing.clicked)
| 46.788732
| 3,322
|
6,261
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug
from odoo.addons.test_mail_full.tests.common import TestMailFullCommon
from odoo.tests.common import users
from odoo.tools import mute_logger
from odoo.tests import tagged
@tagged('mass_mailing')
class TestMassMailing(TestMailFullCommon):
@users('user_marketing')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mailing_w_blacklist_opt_out(self):
mailing = self.env['mailing.mailing'].browse(self.mailing_bl.ids)
mailing.write({'mailing_model_id': self.env['ir.model']._get('mailing.test.optout').id})
recipients = self._create_mailing_test_records(model='mailing.test.optout', count=10)
# optout records 1 and 2
(recipients[1] | recipients[2]).write({'opt_out': True})
# blacklist records 3 and 4
self.env['mail.blacklist'].create({'email': recipients[3].email_normalized})
self.env['mail.blacklist'].create({'email': recipients[4].email_normalized})
# have a duplicate email for 9
recipient_dup_1 = recipients[9].copy()
# have a void mail
recipient_void_1 = self.env['mailing.test.optout'].create({'name': 'TestRecord_void_1'})
# have a falsy mail
recipient_falsy_1 = self.env['mailing.test.optout'].create({
'name': 'TestRecord_falsy_1',
'email_from': 'falsymail'
})
recipients_all = recipients + recipient_dup_1 + recipient_void_1 + recipient_falsy_1
mailing.write({'mailing_domain': [('id', 'in', recipients_all.ids)]})
mailing.action_put_in_queue()
with self.mock_mail_gateway(mail_unlink_sent=False):
mailing.action_send_mail()
for recipient in recipients_all:
recipient_info = {
'email': recipient.email_normalized,
'content': 'Hello %s' % recipient.name}
# opt-out: cancel (cancel mail)
if recipient in recipients[1] | recipients[2]:
recipient_info['trace_status'] = "cancel"
recipient_info['failure_type'] = "mail_optout"
# blacklisted: cancel (cancel mail)
elif recipient in recipients[3] | recipients[4]:
recipient_info['trace_status'] = "cancel"
recipient_info['failure_type'] = "mail_bl"
# duplicates: cancel (cancel mail)
elif recipient == recipient_dup_1:
recipient_info['trace_status'] = "cancel"
recipient_info['failure_type'] = "mail_dup"
# void: error (failed mail)
elif recipient == recipient_void_1:
recipient_info['trace_status'] = 'cancel'
recipient_info['failure_type'] = "mail_email_missing"
# falsy: error (failed mail)
elif recipient == recipient_falsy_1:
recipient_info['trace_status'] = "cancel"
recipient_info['failure_type'] = "mail_email_invalid"
recipient_info['email'] = recipient.email_from # normalized is False but email should be falsymail
else:
email = self._find_sent_mail_wemail(recipient.email_normalized)
# preview correctly integrated rendered qweb
self.assertIn(
'Hi %s :)' % recipient.name,
email['body'])
# rendered unsubscribe
self.assertIn(
'%s/mail/mailing/%s/unsubscribe' % (mailing.get_base_url(), mailing.id),
email['body'])
unsubscribe_href = self._get_href_from_anchor_id(email['body'], "url6")
unsubscribe_url = werkzeug.urls.url_parse(unsubscribe_href)
unsubscribe_params = unsubscribe_url.decode_query().to_dict(flat=True)
self.assertEqual(int(unsubscribe_params['res_id']), recipient.id)
self.assertEqual(unsubscribe_params['email'], recipient.email_normalized)
self.assertEqual(
mailing._unsubscribe_token(unsubscribe_params['res_id'], (unsubscribe_params['email'])),
unsubscribe_params['token']
)
# rendered view
self.assertIn(
'%s/mailing/%s/view' % (mailing.get_base_url(), mailing.id),
email['body'])
view_href = self._get_href_from_anchor_id(email['body'], "url6")
view_url = werkzeug.urls.url_parse(view_href)
view_params = view_url.decode_query().to_dict(flat=True)
self.assertEqual(int(view_params['res_id']), recipient.id)
self.assertEqual(view_params['email'], recipient.email_normalized)
self.assertEqual(
mailing._unsubscribe_token(view_params['res_id'], (view_params['email'])),
view_params['token']
)
self.assertMailTraces(
[recipient_info], mailing, recipient,
mail_links_info=[[
('url0', 'https://www.odoo.tz/my/%s' % recipient.name, True, {}),
('url1', 'https://www.odoo.be', True, {}),
('url2', 'https://www.odoo.com', True, {}),
('url3', 'https://www.odoo.eu', True, {}),
('url4', 'https://www.example.com/foo/bar?baz=qux', True, {'baz': 'qux'}),
('url5', '%s/event/dummy-event-0' % mailing.get_base_url(), True, {}),
# view is not shortened and parsed at sending
('url6', '%s/view' % mailing.get_base_url(), False, {}),
('url7', 'mailto:test@odoo.com', False, {}),
# unsubscribe is not shortened and parsed at sending
('url8', '%s/unsubscribe_from_list' % mailing.get_base_url(), False, {}),
]],
check_mail=True,)
# sent: 13, 2 bl, 2 opt-out, 3 invalid -> 6 remaining
# ignored: 2 bl + 2 optout + 2 invalid + 1 duplicate; failed: 0
self.assertMailingStatistics(mailing, expected=13, delivered=6, sent=6, canceled=7, failed=0)
| 51.743802
| 6,261
|
5,266
|
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 MailTestPortal(models.Model):
""" A model intheriting from mail.thread with some fields used for portal
sharing, like a partner, ..."""
_description = 'Chatter Model for Portal'
_name = 'mail.test.portal'
_inherit = [
'mail.thread',
'portal.mixin',
]
name = fields.Char()
partner_id = fields.Many2one('res.partner', 'Customer')
def _compute_access_url(self):
self.access_url = False
for record in self.filtered('id'):
record.access_url = '/my/test_portal/%s' % self.id
class MailTestSMS(models.Model):
""" A model inheriting from mail.thread with some fields used for SMS
gateway, like a partner, a specific mobile phone, ... """
_description = 'Chatter Model for SMS Gateway'
_name = 'mail.test.sms'
_inherit = ['mail.thread']
_mailing_enabled = True
_order = 'name asc, id asc'
name = fields.Char()
subject = fields.Char()
email_from = fields.Char()
phone_nbr = fields.Char()
mobile_nbr = fields.Char()
customer_id = fields.Many2one('res.partner', 'Customer')
def _sms_get_partner_fields(self):
return ['customer_id']
def _sms_get_number_fields(self):
return ['phone_nbr', 'mobile_nbr']
class MailTestSMSBL(models.Model):
""" A model inheriting from mail.thread.phone allowing to test auto formatting
of phone numbers, blacklist, ... """
_description = 'SMS Mailing Blacklist Enabled'
_name = 'mail.test.sms.bl'
_inherit = ['mail.thread.phone']
_mailing_enabled = True
_order = 'name asc, id asc'
name = fields.Char()
subject = fields.Char()
email_from = fields.Char()
phone_nbr = fields.Char(compute='_compute_phone_nbr', readonly=False, store=True)
mobile_nbr = fields.Char(compute='_compute_mobile_nbr', readonly=False, store=True)
customer_id = fields.Many2one('res.partner', 'Customer')
@api.depends('customer_id')
def _compute_mobile_nbr(self):
for phone_record in self.filtered(lambda rec: not rec.mobile_nbr and rec.customer_id):
phone_record.mobile_nbr = phone_record.customer_id.mobile
@api.depends('customer_id')
def _compute_phone_nbr(self):
for phone_record in self.filtered(lambda rec: not rec.phone_nbr and rec.customer_id):
phone_record.phone_nbr = phone_record.customer_id.phone
def _sms_get_partner_fields(self):
return ['customer_id']
def _phone_get_number_fields(self):
return ['phone_nbr', 'mobile_nbr']
class MailTestSMSOptout(models.Model):
""" Model using blacklist mechanism and a hijacked opt-out mechanism for
mass mailing features. """
_description = 'SMS Mailing Blacklist / Optout Enabled'
_name = 'mail.test.sms.bl.optout'
_inherit = ['mail.thread.phone']
_mailing_enabled = True
_order = 'name asc, id asc'
name = fields.Char()
subject = fields.Char()
email_from = fields.Char()
phone_nbr = fields.Char()
mobile_nbr = fields.Char()
customer_id = fields.Many2one('res.partner', 'Customer')
opt_out = fields.Boolean()
def _mailing_get_opt_out_list_sms(self, mailing):
res_ids = mailing._get_recipients()
return self.search([
('id', 'in', res_ids),
('opt_out', '=', True)
]).ids
def _sms_get_partner_fields(self):
return ['customer_id']
def _sms_get_number_fields(self):
# TDE note: should override _phone_get_number_fields but ok as sms in dependencies
return ['phone_nbr', 'mobile_nbr']
class MailTestSMSPartner(models.Model):
""" A model like sale order having only a customer, not specific phone
or mobile fields. """
_description = 'Chatter Model for SMS Gateway (Partner only)'
_name = 'mail.test.sms.partner'
_inherit = ['mail.thread']
_mailing_enabled = True
name = fields.Char()
customer_id = fields.Many2one('res.partner', 'Customer')
opt_out = fields.Boolean()
def _mailing_get_opt_out_list_sms(self, mailing):
res_ids = mailing._get_recipients()
return self.search([
('id', 'in', res_ids),
('opt_out', '=', True)
]).ids
def _sms_get_partner_fields(self):
return ['customer_id']
def _sms_get_number_fields(self):
return []
class MailTestSMSPartner2Many(models.Model):
""" A model like sale order having only a customer, not specific phone
or mobile fields. """
_description = 'Chatter Model for SMS Gateway (M2M Partners only)'
_name = 'mail.test.sms.partner.2many'
_inherit = ['mail.thread']
_mailing_enabled = True
name = fields.Char()
customer_ids = fields.Many2many('res.partner', string='Customers')
opt_out = fields.Boolean()
def _mailing_get_opt_out_list_sms(self, mailing):
res_ids = mailing._get_recipients()
return self.search([
('id', 'in', res_ids),
('opt_out', '=', True)
]).ids
def _sms_get_partner_fields(self):
return ['customer_ids']
def _sms_get_number_fields(self):
return []
| 32.306748
| 5,266
|
813
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Debit Notes',
'version': '1.0',
'category': 'Accounting/Accounting',
'summary': 'Debit Notes',
'description': """
In a lot of countries, a debit note is used as an increase of the amounts of an existing invoice
or in some specific cases to cancel a credit note.
It is like a regular invoice, but we need to keep track of the link with the original invoice.
The wizard used is similar as the one for the credit note.
""",
'depends': ['account'],
'data': [
'wizard/account_debit_note_view.xml',
'views/account_move_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'auto_install': False,
'license': 'LGPL-3',
}
| 33.875
| 813
|
2,453
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo import fields
@tagged('post_install', '-at_install')
class TestAccountDebitNote(AccountTestInvoicingCommon):
def test_00_debit_note_out_invoice(self):
""" Debit Note of a regular Customer Invoice"""
invoice = self.init_invoice('out_invoice', products=self.product_a+self.product_b)
invoice.action_post()
move_debit_note_wiz = self.env['account.debit.note'].with_context(active_model="account.move",
active_ids=invoice.ids).create({
'date': fields.Date.from_string('2019-02-01'),
'reason': 'no reason',
'copy_lines': True,
})
move_debit_note_wiz.create_debit()
# Search for the original invoice
debit_note = self.env['account.move'].search([('debit_origin_id', '=', invoice.id)])
debit_note.ensure_one()
self.assertEqual(len(debit_note.invoice_line_ids), 2, "Should have copied the invoice lines")
self.assertEqual(debit_note.move_type, 'out_invoice', 'Type of debit note should be the same as the original invoice')
self.assertEqual(debit_note.state, 'draft', 'We should create debit notes in draft state')
def test_10_debit_note_in_refund(self):
""" Debit Note of a vendor refund (is a regular vendor bill) """
invoice = self.init_invoice('in_refund', products=self.product_a+self.product_b)
invoice.action_post()
move_debit_note_wiz = self.env['account.debit.note'].with_context(active_model="account.move",
active_ids=invoice.ids).create({
'date': fields.Date.from_string('2019-02-01'),
'reason': 'in order to cancel refund',
})
move_debit_note_wiz.create_debit()
# Search for the original invoice
debit_note = self.env['account.move'].search([('debit_origin_id', '=', invoice.id)])
debit_note.ensure_one()
self.assertFalse(debit_note.invoice_line_ids, 'We should not copy lines by default on debit notes')
self.assertEqual(debit_note.move_type, 'in_invoice', 'Type of debit note should not be refund anymore')
self.assertEqual(debit_note.state, 'draft', 'We should create debit notes in draft state')
| 53.326087
| 2,453
|
4,450
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.tools.translate import _
from odoo.exceptions import UserError
class AccountDebitNote(models.TransientModel):
"""
Add Debit Note wizard: when you want to correct an invoice with a positive amount.
Opposite of a Credit Note, but different from a regular invoice as you need the link to the original invoice.
In some cases, also used to cancel Credit Notes
"""
_name = 'account.debit.note'
_description = 'Add Debit Note wizard'
move_ids = fields.Many2many('account.move', 'account_move_debit_move', 'debit_id', 'move_id',
domain=[('state', '=', 'posted')])
date = fields.Date(string='Debit Note Date', default=fields.Date.context_today, required=True)
reason = fields.Char(string='Reason')
journal_id = fields.Many2one('account.journal', string='Use Specific Journal',
help='If empty, uses the journal of the journal entry to be debited.')
copy_lines = fields.Boolean("Copy Lines",
help="In case you need to do corrections for every line, it can be in handy to copy them. "
"We won't copy them for debit notes from credit notes. ")
# computed fields
move_type = fields.Char(compute="_compute_from_moves")
journal_type = fields.Char(compute="_compute_from_moves")
country_code = fields.Char(related='move_ids.company_id.country_id.code')
@api.model
def default_get(self, fields):
res = super(AccountDebitNote, self).default_get(fields)
move_ids = self.env['account.move'].browse(self.env.context['active_ids']) if self.env.context.get('active_model') == 'account.move' else self.env['account.move']
if any(move.state != "posted" for move in move_ids):
raise UserError(_('You can only debit posted moves.'))
res['move_ids'] = [(6, 0, move_ids.ids)]
return res
@api.depends('move_ids')
def _compute_from_moves(self):
for record in self:
move_ids = record.move_ids
record.move_type = move_ids[0].move_type if len(move_ids) == 1 or not any(m.move_type != move_ids[0].move_type for m in move_ids) else False
record.journal_type = record.move_type in ['in_refund', 'in_invoice'] and 'purchase' or 'sale'
def _prepare_default_values(self, move):
if move.move_type in ('in_refund', 'out_refund'):
type = 'in_invoice' if move.move_type == 'in_refund' else 'out_invoice'
else:
type = move.move_type
default_values = {
'ref': '%s, %s' % (move.name, self.reason) if self.reason else move.name,
'date': self.date or move.date,
'invoice_date': move.is_invoice(include_receipts=True) and (self.date or move.date) or False,
'journal_id': self.journal_id and self.journal_id.id or move.journal_id.id,
'invoice_payment_term_id': None,
'debit_origin_id': move.id,
'move_type': type,
}
if not self.copy_lines or move.move_type in [('in_refund', 'out_refund')]:
default_values['line_ids'] = [(5, 0, 0)]
return default_values
def create_debit(self):
self.ensure_one()
new_moves = self.env['account.move']
for move in self.move_ids.with_context(include_business_fields=True): #copy sale/purchase links
default_values = self._prepare_default_values(move)
new_move = move.copy(default=default_values)
move_msg = _(
"This debit note was created from:") + " <a href=# data-oe-model=account.move data-oe-id=%d>%s</a>" % (
move.id, move.name)
new_move.message_post(body=move_msg)
new_moves |= new_move
action = {
'name': _('Debit Notes'),
'type': 'ir.actions.act_window',
'res_model': 'account.move',
'context': {'default_move_type': default_values['move_type']},
}
if len(new_moves) == 1:
action.update({
'view_mode': 'form',
'res_id': new_moves.id,
})
else:
action.update({
'view_mode': 'tree,form',
'domain': [('id', 'in', new_moves.ids)],
})
return action
| 48.369565
| 4,450
|
1,353
|
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 AccountMove(models.Model):
_inherit = "account.move"
debit_origin_id = fields.Many2one('account.move', 'Original Invoice Debited', readonly=True, copy=False)
debit_note_ids = fields.One2many('account.move', 'debit_origin_id', 'Debit Notes',
help="The debit notes created for this invoice")
debit_note_count = fields.Integer('Number of Debit Notes', compute='_compute_debit_count')
@api.depends('debit_note_ids')
def _compute_debit_count(self):
debit_data = self.env['account.move'].read_group([('debit_origin_id', 'in', self.ids)],
['debit_origin_id'], ['debit_origin_id'])
data_map = {datum['debit_origin_id'][0]: datum['debit_origin_id_count'] for datum in debit_data}
for inv in self:
inv.debit_note_count = data_map.get(inv.id, 0.0)
def action_view_debit_notes(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': _('Debit Notes'),
'res_model': 'account.move',
'view_mode': 'tree,form',
'domain': [('debit_origin_id', '=', self.id)],
}
| 45.1
| 1,353
|
535
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Event CRM Sale',
'version': '1.0',
'category': 'Marketing/Events',
'website': 'https://www.odoo.com/app/events',
'description': "Add information of sale order linked to the registration for the creation of the lead.",
'depends': ['event_crm', 'event_sale'],
'data': [
'views/event_lead_rule_views.xml',
],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 31.470588
| 535
|
2,365
|
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 models
class EventRegistration(models.Model):
_inherit = 'event.registration'
def _get_lead_grouping(self, rules, rule_to_new_regs):
""" Override to support sale-order based grouping and update.
When checking for groups for rules, we search for existing leads linked
to same group (based on sale_order_id) and rule. Each rule can therefore
update an existing lead or create a new one, for each sale order that
makes the group. """
so_registrations = self.filtered(lambda reg: reg.sale_order_id)
grouping_res = super(EventRegistration, self - so_registrations)._get_lead_grouping(rules, rule_to_new_regs)
if so_registrations:
# find existing leads in batch to put them in cache and avoid multiple search / queries
related_registrations = self.env['event.registration'].search([
('sale_order_id', 'in', so_registrations.sale_order_id.ids)
])
related_leads = self.env['crm.lead'].search([
('event_lead_rule_id', 'in', rules.ids),
('registration_ids', 'in', related_registrations.ids)
])
for rule in rules:
rule_new_regs = rule_to_new_regs[rule]
# for each group (sale_order), find its linked registrations
so_to_regs = defaultdict(lambda: self.env['event.registration'])
for registration in rule_new_regs & so_registrations:
so_to_regs[registration.sale_order_id] |= registration
# for each grouped registrations, prepare result with group and existing lead
so_res = []
for sale_order, registrations in so_to_regs.items():
registrations = registrations.sorted('id') # as an OR was used, re-ensure order
leads = related_leads.filtered(lambda lead: lead.event_lead_rule_id == rule and lead.registration_ids.sale_order_id == sale_order)
so_res.append((leads, sale_order, registrations))
if so_res:
grouping_res[rule] = grouping_res.get(rule, list()) + so_res
return grouping_res
| 48.265306
| 2,365
|
854
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'POS Six',
'version': '1.0',
'category': 'Sales/Point Of Sale',
'sequence': 6,
'summary': 'Integrate your POS with a Six payment terminal',
'description': '',
'data': [
'views/pos_payment_method_views.xml',
],
'depends': ['point_of_sale'],
'installable': True,
'license': 'LGPL-3',
'assets': {
'point_of_sale.assets': [
'pos_six/static/lib/six_timapi/timapi.js',
'pos_six/static/src/js/BalanceButton.js',
'pos_six/static/src/js/Chrome.js',
'pos_six/static/src/js/models.js',
'pos_six/static/src/js/payment_six.js',
],
'web.assets_qweb': [
'pos_six/static/src/xml/**/*',
],
}
}
| 30.5
| 854
|
497
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class PosConfig(models.Model):
_inherit = 'pos.config'
def _force_http(self):
enforce_https = self.env['ir.config_parameter'].sudo().get_param('point_of_sale.enforce_https')
if not enforce_https and self.payment_method_ids.filtered(lambda pm: pm.use_payment_terminal == 'six'):
return True
return super(PosConfig, self)._force_http()
| 35.5
| 497
|
400
|
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 PosPaymentMethod(models.Model):
_inherit = 'pos.payment.method'
def _get_payment_terminal_selection(self):
return super(PosPaymentMethod, self)._get_payment_terminal_selection() + [('six', 'SIX')]
six_terminal_ip = fields.Char('Six Terminal IP')
| 30.769231
| 400
|
798
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Online Event Ticketing",
'category': 'Website/Website',
'summary': "Sell event tickets online",
'description': """
Sell event tickets through eCommerce app.
""",
'depends': ['website_event', 'event_sale', 'website_sale'],
'data': [
'data/event_data.xml',
'views/event_event_views.xml',
'views/website_event_templates.xml',
'views/website_sale_templates.xml',
'security/ir.model.access.csv',
'security/website_event_sale_security.xml',
],
'auto_install': True,
'assets': {
'web.assets_tests': [
'website_event_sale/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 29.555556
| 798
|
3,297
|
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.fields import Datetime
from odoo.tests.common import TransactionCase
class TestWebsiteEventSaleCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestWebsiteEventSaleCommon, cls).setUpClass()
cls.zero_tax = cls.env['account.tax'].sudo().create({
'name': 'Tax 0',
'amount': 0,
})
cls.product_event = cls.env['product.product'].create({
'base_unit_price': 100,
'detailed_type': 'event',
'name': 'Event Registration No Company Assigned',
'taxes_id': [(6, 0, cls.zero_tax.ids)],
})
cls.event = cls.env['event.event'].create({
'date_begin': (Datetime.today() + timedelta(days=5)).strftime('%Y-%m-%d 07:00:00'),
'date_end': (Datetime.today() + timedelta(days=5)).strftime('%Y-%m-%d 16:30:00'),
'name': 'Pycon',
'user_id': cls.env.ref('base.user_admin').id,
'website_published': True,
})
cls.ticket = cls.env['event.event.ticket'].create([{
'event_id': cls.event.id,
'name': 'Standard',
'product_id': cls.product_event.id,
'price': 100,
}])
cls.currency_test = cls.env['res.currency'].create({
'name': 'eventX',
'rounding': 0.01,
'symbol': 'EX',
})
cls.partner = cls.env['res.partner'].create({'name': 'test'})
cls.env['res.currency.rate'].search([]).unlink()
cls.rate = cls.env['res.currency.rate'].create({
'company_id': cls.env.company.id,
'currency_id': cls.currency_test.id,
'name': '2022-01-01',
'rate': 10,
})
cls.current_website = cls.env['website'].get_current_website()
cls.pricelist = cls.current_website.get_current_pricelist()
cls.so = cls.env['sale.order'].create({
'company_id': cls.env.company.id,
'partner_id': cls.partner.id,
'pricelist_id': cls.pricelist.id,
})
def create_pricelist(currency, name, policy):
return cls.env['product.pricelist'].create({
'currency_id': currency.id,
'discount_policy': policy,
'item_ids': [(5, 0, 0), (0, 0, {
'applied_on': '3_global',
'compute_price': 'percentage',
'percent_price': 10,
})],
'name': name,
'selectable': True,
})
cls.pricelist_with_discount = create_pricelist(currency=cls.env.company.currency_id, name='EUR With Discount Included', policy='with_discount')
cls.pricelist_without_discount = create_pricelist(currency=cls.env.company.currency_id, name='EUR Without Discount Included', policy='without_discount')
cls.ex_pricelist_with_discount = create_pricelist(currency=cls.currency_test, name='EX With Discount Included', policy='with_discount')
cls.ex_pricelist_without_discount = create_pricelist(currency=cls.currency_test, name='EX Without Discount Included', policy='without_discount')
| 41.2125
| 3,297
|
3,924
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
from datetime import timedelta
from odoo.addons.base.tests.common import HttpCaseWithUserDemo
from odoo.addons.website_event_sale.tests.common import TestWebsiteEventSaleCommon
from odoo.fields import Datetime
@odoo.tests.common.tagged('post_install', '-at_install')
class TestUi(HttpCaseWithUserDemo, TestWebsiteEventSaleCommon):
def setUp(self):
super().setUp()
self.event_2 = self.env['event.event'].create({
'name': 'Conference for Architects TEST',
'user_id': self.env.ref('base.user_admin').id,
'date_begin': (Datetime.today() + timedelta(days=5)).strftime('%Y-%m-%d 07:00:00'),
'date_end': (Datetime.today() + timedelta(days=5)).strftime('%Y-%m-%d 16:30:00'),
'website_published': True,
})
self.env['event.event.ticket'].create([{
'name': 'Standard',
'event_id': self.event_2.id,
'product_id': self.env.ref('event_sale.product_product_event').id,
'start_sale_datetime': (Datetime.today() - timedelta(days=5)).strftime('%Y-%m-%d 07:00:00'),
'end_sale_datetime': (Datetime.today() + timedelta(90)).strftime('%Y-%m-%d'),
'price': 1000.0,
}, {
'name': 'VIP',
'event_id': self.event_2.id,
'product_id': self.env.ref('event_sale.product_product_event').id,
'end_sale_datetime': (Datetime.today() + timedelta(90)).strftime('%Y-%m-%d'),
'price': 1500.0,
}])
self.event_3 = self.env['event.event'].create({
'name': 'Last ticket test',
'user_id': self.env.ref('base.user_admin').id,
'date_begin': (Datetime.today() + timedelta(days=5)).strftime('%Y-%m-%d 07:00:00'),
'date_end': (Datetime.today() + timedelta(days=5)).strftime('%Y-%m-%d 16:30:00'),
'website_published': True,
})
self.env['event.event.ticket'].create([{
'name': 'VIP',
'event_id': self.event_3.id,
'product_id': self.env.ref('event_sale.product_product_event').id,
'end_sale_datetime': (Datetime.today() + timedelta(90)).strftime('%Y-%m-%d'),
'price': 1500.0,
'seats_max': 2,
}])
# flush event to ensure having tickets available in the tests
self.event_2.flush()
self.event_3.flush()
(self.env.ref('base.partner_admin') + self.partner_demo).write({
'street': '215 Vine St',
'city': 'Scranton',
'zip': '18503',
'country_id': self.env.ref('base.us').id,
'state_id': self.env.ref('base.state_us_39').id,
'phone': '+1 555-555-5555',
'email': 'admin@yourcompany.example.com',
})
self.env['account.journal'].create({'name': 'Cash - Test', 'type': 'cash', 'code': 'CASH - Test'})
def test_admin(self):
# Seen that:
# - this test relies on demo data that are entirely in USD (pricelists)
# - that main demo company is gelocated in US
# - that this test awaits for hardcoded USDs amount
# we have to force company currency as USDs only for this test
self.cr.execute("UPDATE res_company SET currency_id = %s WHERE id = %s", [self.env.ref('base.USD').id, self.env.ref('base.main_company').id])
self.start_tour("/", 'event_buy_tickets', login="admin")
def test_demo(self):
self.start_tour("/", 'event_buy_tickets', login="demo")
def test_buy_last_ticket(self):
self.start_tour("/", 'event_buy_last_ticket')
def test_pricelists_different_currencies(self):
self.start_tour("/", 'event_sale_pricelists_different_currencies')
# TO DO - add public test with new address when convert to web.tour format.
| 42.193548
| 3,924
|
3,082
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_sale.controllers.main import WebsiteSale
from odoo.addons.website.tools import MockRequest
from odoo.addons.website_event_sale.tests.common import TestWebsiteEventSaleCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestWebsiteEventPriceList(TestWebsiteEventSaleCommon):
@classmethod
def setUpClass(cls):
super(TestWebsiteEventPriceList, cls).setUpClass()
cls.WebsiteSaleController = WebsiteSale()
def test_pricelist_different_currency(self):
so_line = self.env['sale.order.line'].create({
'event_id': self.event.id,
'event_ticket_id': self.ticket.id,
'name': self.event.name,
'order_id': self.so.id,
'product_id': self.ticket.product_id.id,
'product_uom_qty': 1,
})
# set pricelist to 0 - currency: company
self.pricelist.write({
'currency_id': self.env.company.currency_id.id,
'discount_policy': 'with_discount',
'item_ids': [(5, 0, 0), (0, 0, {
'applied_on': '3_global',
'compute_price': 'percentage',
'percent_price': 0,
})],
'name': 'With Discount Included',
})
with MockRequest(self.env, sale_order_id=self.so.id, website=self.current_website):
self.WebsiteSaleController.pricelist('With Discount Included')
self.so._cart_update(line_id=so_line.id, product_id=self.ticket.product_id.id, set_qty=1)
self.assertEqual(so_line.price_reduce, 100)
# set pricelist to 10% - without discount
self.pricelist.write({
'currency_id': self.currency_test.id,
'discount_policy': 'without_discount',
'item_ids': [(5, 0, 0), (0, 0, {
'applied_on': '3_global',
'compute_price': 'percentage',
'percent_price': 10,
})],
'name': 'Without Discount Included',
})
with MockRequest(self.env, sale_order_id=self.so.id, website=self.current_website):
self.WebsiteSaleController.pricelist('Without Discount Included')
self.so._cart_update(line_id=so_line.id, product_id=self.ticket.product_id.id, set_qty=1)
self.assertEqual(so_line.price_reduce, 900, 'Incorrect amount based on the pricelist and its currency.')
# set pricelist to 10% - with discount
self.pricelist.write({
'discount_policy': 'with_discount',
'name': 'With Discount Included',
})
with MockRequest(self.env, sale_order_id=self.so.id, website=self.current_website):
self.WebsiteSaleController.pricelist('With Discount Included')
self.so._cart_update(line_id=so_line.id, product_id=self.ticket.product_id.id, set_qty=1)
self.assertEqual(so_line.price_reduce, 900, 'Incorrect amount based on the pricelist and its currency.')
| 44.666667
| 3,082
|
1,066
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import _, api, models
class PricelistItem(models.Model):
_inherit = "product.pricelist.item"
@api.onchange('applied_on', 'product_id', 'product_tmpl_id', 'min_quantity')
def _onchange_event_sale_warning(self):
if self.min_quantity > 0:
msg = ''
if self.applied_on == '3_global' or self.applied_on == '2_product_category':
msg = _("A pricelist item with a positive min. quantity will not be applied to the event tickets products.")
elif ((self.applied_on == '1_product' and self.product_tmpl_id.detailed_type == 'event') or
(self.applied_on == '0_product_variant' and self.product_id.detailed_type == 'event')):
msg = _("A pricelist item with a positive min. quantity cannot be applied to this event tickets product.")
if msg:
return {'warning':
{
'title': _("Warning"),
'message': msg
}
}
| 46.347826
| 1,066
|
7,192
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.osv import expression
class SaleOrder(models.Model):
_inherit = "sale.order"
def _cart_find_product_line(self, product_id=None, line_id=None, **kwargs):
self.ensure_one()
lines = super(SaleOrder, self)._cart_find_product_line(product_id, line_id, **kwargs)
if line_id:
return lines
domain = [('id', 'in', lines.ids)]
if self.env.context.get("event_ticket_id"):
domain.append(('event_ticket_id', '=', self.env.context.get("event_ticket_id")))
return self.env['sale.order.line'].sudo().search(domain)
def _website_product_id_change(self, order_id, product_id, qty=0, **kwargs):
order = self.env['sale.order'].sudo().browse(order_id)
if self._context.get('pricelist') != order.pricelist_id.id:
self = self.with_context(pricelist=order.pricelist_id.id)
values = super(SaleOrder, self)._website_product_id_change(order_id, product_id, qty=qty, **kwargs)
event_ticket_id = None
if self.env.context.get("event_ticket_id"):
event_ticket_id = self.env.context.get("event_ticket_id")
else:
product = self.env['product.product'].browse(product_id)
if product.event_ticket_ids:
event_ticket_id = product.event_ticket_ids[0].id
if event_ticket_id:
ticket = self.env['event.event.ticket'].browse(event_ticket_id)
if product_id != ticket.product_id.id:
raise UserError(_("The ticket doesn't match with this product."))
values['product_id'] = ticket.product_id.id
values['event_id'] = ticket.event_id.id
values['event_ticket_id'] = ticket.id
discount = 0
ticket_currency = ticket.product_id.currency_id
pricelist_currency = order.pricelist_id.currency_id
price_reduce = ticket.price_reduce
if ticket_currency != pricelist_currency:
price_reduce = ticket_currency._convert(
price_reduce,
pricelist_currency,
order.company_id,
order.date_order or fields.Datetime.now()
)
if order.pricelist_id.discount_policy == 'without_discount':
price = ticket.price
if price != 0:
if ticket_currency != pricelist_currency:
price = ticket_currency._convert(
price,
pricelist_currency,
order.company_id,
order.date_order or fields.Datetime.now()
)
discount = (price - price_reduce) / price * 100
price_unit = price
if discount < 0:
discount = 0
price_unit = price_reduce
else:
price_unit = price_reduce
else:
price_unit = price_reduce
if order.pricelist_id and order.partner_id:
order_line = order._cart_find_product_line(ticket.product_id.id)
if order_line:
price_unit = self.env['account.tax']._fix_tax_included_price_company(price_unit, ticket.product_id.taxes_id, order_line[0].tax_id, self.company_id)
values.update(
discount=discount,
name=ticket._get_ticket_multiline_description(),
price_unit=price_unit,
)
# avoid writing related values that end up locking the product record
values.pop('event_ok', None)
return values
def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
OrderLine = self.env['sale.order.line']
try:
if add_qty:
add_qty = float(add_qty)
except ValueError:
add_qty = 1
try:
if set_qty:
set_qty = float(set_qty)
except ValueError:
set_qty = 0
if line_id:
line = OrderLine.browse(line_id)
ticket = line.event_ticket_id
old_qty = int(line.product_uom_qty)
if ticket.id:
self = self.with_context(event_ticket_id=ticket.id, fixed_price=1)
else:
ticket_domain = [('product_id', '=', product_id)]
if self.env.context.get("event_ticket_id"):
ticket_domain = expression.AND([ticket_domain, [('id', '=', self.env.context['event_ticket_id'])]])
ticket = self.env['event.event.ticket'].search(ticket_domain, limit=1)
old_qty = 0
new_qty = set_qty if set_qty else (add_qty or 0 + old_qty)
# case: buying tickets for a sold out ticket
values = {}
increased_quantity = new_qty > old_qty
if ticket and ticket.seats_limited and ticket.seats_available <= 0 and increased_quantity:
values['warning'] = _('Sorry, The %(ticket)s tickets for the %(event)s event are sold out.') % {
'ticket': ticket.name,
'event': ticket.event_id.name}
new_qty, set_qty, add_qty = 0, 0, -old_qty
# case: buying tickets, too much attendees
elif ticket and ticket.seats_limited and new_qty > ticket.seats_available and increased_quantity:
values['warning'] = _('Sorry, only %(remaining_seats)d seats are still available for the %(ticket)s ticket for the %(event)s event.') % {
'remaining_seats': ticket.seats_available,
'ticket': ticket.name,
'event': ticket.event_id.name}
new_qty, set_qty, add_qty = ticket.seats_available, ticket.seats_available, 0
values.update(super(SaleOrder, self)._cart_update(product_id, line_id, add_qty, set_qty, **kwargs))
# removing attendees
if ticket and new_qty < old_qty:
attendees = self.env['event.registration'].search([
('state', '!=', 'cancel'),
('sale_order_id', 'in', self.ids), # To avoid break on multi record set
('event_ticket_id', '=', ticket.id),
], offset=new_qty, limit=(old_qty - new_qty), order='create_date asc')
attendees.action_cancel()
# adding attendees
elif ticket and new_qty > old_qty:
# do not do anything, attendees will be created at SO confirmation if not given previously
pass
return values
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
@api.depends('product_id.display_name', 'event_ticket_id.display_name')
def _compute_name_short(self):
""" If the sale order line concerns a ticket, we don't want the product name, but the ticket name instead.
"""
super(SaleOrderLine, self)._compute_name_short()
for record in self:
if record.event_ticket_id:
record.name_short = record.event_ticket_id.display_name
| 44.670807
| 7,192
|
536
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
# defined for access rules
class Product(models.Model):
_inherit = 'product.product'
event_ticket_ids = fields.One2many('event.event.ticket', 'product_id', string='Event Tickets')
def _is_add_to_cart_allowed(self):
# Allow adding event tickets to the cart regardless of product's rules
self.ensure_one()
res = super()._is_add_to_cart_allowed()
return res or any(event.website_published for event in self.event_ticket_ids.event_id)
| 33.5
| 536
|
348
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class Website(models.Model):
_inherit = 'website'
def sale_product_domain(self):
# remove product event from the website content grid and list view (not removed in detail view)
return ['&'] + super(Website, self).sale_product_domain() + [('detailed_type', '!=', 'event')]
| 31.636364
| 348
|
3,368
|
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_event.controllers.main import WebsiteEventController
from odoo.http import request
class WebsiteEventSaleController(WebsiteEventController):
@http.route()
def event_register(self, event, **post):
event = event.with_context(pricelist=request.website.id)
if not request.context.get('pricelist'):
pricelist = request.website.get_current_pricelist()
if pricelist:
event = event.with_context(pricelist=pricelist.id)
return super(WebsiteEventSaleController, self).event_register(event, **post)
def _process_tickets_form(self, event, form_details):
""" Add price information on ticket order """
res = super(WebsiteEventSaleController, self)._process_tickets_form(event, form_details)
for item in res:
item['price'] = item['ticket']['price'] if item['ticket'] else 0
return res
def _create_attendees_from_registration_post(self, event, registration_data):
# we have at least one registration linked to a ticket -> sale mode activate
if any(info.get('event_ticket_id') for info in registration_data):
order = request.website.sale_get_order(force_create=1)
for info in [r for r in registration_data if r.get('event_ticket_id')]:
ticket = request.env['event.event.ticket'].sudo().browse(info['event_ticket_id'])
cart_values = order.with_context(event_ticket_id=ticket.id, fixed_price=True)._cart_update(product_id=ticket.product_id.id, add_qty=1)
info['sale_order_id'] = order.id
info['sale_order_line_id'] = cart_values.get('line_id')
return super(WebsiteEventSaleController, self)._create_attendees_from_registration_post(event, registration_data)
@http.route()
def registration_confirm(self, event, **post):
res = super(WebsiteEventSaleController, self).registration_confirm(event, **post)
registrations = self._process_attendees_form(event, post)
# we have at least one registration linked to a ticket -> sale mode activate
if any(info['event_ticket_id'] for info in registrations):
order = request.website.sale_get_order(force_create=False)
if order.amount_total:
return request.redirect("/shop/checkout")
# free tickets -> order with amount = 0: auto-confirm, no checkout
elif order:
order.action_confirm() # tde notsure: email sending ?
request.website.sale_reset()
return res
def _prepare_event_values(self, name, event_start, event_end, address_values=None):
values = super(WebsiteEventSaleController, self)._prepare_event_values(name, event_start, event_end, address_values)
product = request.env.ref('event_sale.product_product_event', raise_if_not_found=False)
if product:
values.update({
'event_ticket_ids': [[0, 0, {
'name': _('Registration'),
'product_id': product.id,
'end_sale_datetime': False,
'seats_max': 1000,
'price': 0,
}]]
})
return values
| 47.43662
| 3,368
|
1,143
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Contact Form',
'category': 'Website/Website',
'sequence': 54,
'summary': 'Generate leads from a contact form',
'version': '2.1',
'description': """
Add capability to your website forms to generate leads or opportunities in the CRM app.
Forms has to be customized inside the *Website Builder* in order to generate leads.
This module includes contact phone and mobile numbers validation.""",
'depends': ['website', 'crm'],
'data': [
'security/ir.model.access.csv',
'data/ir_actions_data.xml',
'data/ir_model_data.xml',
'views/crm_lead_views.xml',
'views/res_config_settings_views.xml',
'views/website_visitor_views.xml',
'views/website_templates_contactus.xml',
],
'installable': True,
'auto_install': True,
'assets': {
'website.assets_editor': [
'website_crm/static/src/**/*',
],
'web.assets_tests': [
'website_crm/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 31.75
| 1,143
|
1,884
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
@odoo.tests.tagged('post_install', '-at_install')
class TestWebsiteCrm(odoo.tests.HttpCase):
def test_tour(self):
# change action to create opportunity
self.start_tour("/", 'website_crm_pre_tour', login='admin')
self.start_tour("/", 'website_crm_tour')
# check result
record = self.env['crm.lead'].search([('description', '=', '### TOUR DATA ###')])
self.assertEqual(len(record), 1)
self.assertEqual(record.contact_name, 'John Smith')
self.assertEqual(record.email_from, 'john@smith.com')
self.assertEqual(record.partner_name, 'Odoo S.A.')
def test_catch_logged_partner_info_tour(self):
user_login = 'admin'
user_partner = self.env['res.users'].search([('login', '=', user_login)]).partner_id
partner_email = user_partner.email
partner_phone = user_partner.phone
# no edit on prefilled data from logged partner : propagate partner_id on created lead
self.start_tour("/", 'website_crm_pre_tour', login=user_login)
self.start_tour("/", "website_crm_catch_logged_partner_info_tour", login=user_login)
created_lead = self.env['crm.lead'].search([('description', '=', '### TOUR DATA PREFILL ###')])
self.assertEqual(created_lead.partner_id, user_partner)
# edited contact us partner info : do not propagate partner_id on lead
self.start_tour("/", "website_crm_tour", login=user_login)
created_lead = self.env['crm.lead'].search([('description', '=', '### TOUR DATA ###')])
self.assertFalse(created_lead.partner_id)
# check partner has not been changed
self.assertEqual(user_partner.email, partner_email)
self.assertEqual(user_partner.phone, partner_phone)
| 47.1
| 1,884
|
2,783
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.tests.common import users
class TestWebsiteVisitor(TestCrmCommon):
def setUp(self):
super(TestWebsiteVisitor, self).setUp()
self.test_partner = self.env['res.partner'].create({
'name': 'Test Customer',
'email': '"Test Customer" <test@test.example.com>',
'country_id': self.env.ref('base.be').id,
'mobile': '+32456001122'
})
@users('user_sales_manager')
def test_compute_email_phone(self):
visitor_sudo = self.env['website.visitor'].sudo().create({
'name': 'Mega Visitor',
})
visitor = visitor_sudo.with_user(self.env.user) # as of 13.0 salesmen cannot create visitors, only read them
customer = self.test_partner.with_user(self.env.user)
self.assertFalse(visitor.email)
self.assertFalse(visitor.mobile)
# partner information copied on visitor -> behaves like related
visitor_sudo.write({'partner_id': self.test_partner.id})
self.assertEqual(visitor.email, customer.email_normalized)
self.assertEqual(visitor.mobile, customer.mobile)
# if reset -> behaves like a related, also reset on visitor
visitor_sudo.write({'partner_id': False})
self.assertFalse(visitor.email)
self.assertFalse(visitor.mobile)
# first lead created -> updates email
lead_1 = self.env['crm.lead'].create({
'name': 'Test Lead 1',
'email_from': 'Rambeau Fort <beaufort@test.example.com',
'visitor_ids': [(4, visitor.id)],
})
self.assertEqual(visitor.email, lead_1.email_normalized)
self.assertFalse(visitor.mobile)
# second lead created -> keep first email but takes mobile as not defined before
lead_2 = self.env['crm.lead'].create({
'name': 'Test Lead 1',
'email_from': 'Martino Brie <brie@test.example.com',
'country_id': self.env.ref('base.be').id,
'mobile': '+32456001122',
'visitor_ids': [(4, visitor.id)],
})
self.assertEqual(visitor.email, lead_1.email_normalized)
self.assertEqual(visitor.mobile, lead_2.mobile)
# partner win on leads
visitor_sudo.write({'partner_id': self.test_partner.id})
self.assertEqual(visitor.email, customer.email_normalized)
self.assertEqual(visitor.mobile, customer.mobile)
# partner updated -> fallback on leads
customer.write({'mobile': False})
self.assertEqual(visitor.email, customer.email_normalized)
self.assertEqual(visitor.mobile, lead_2.mobile)
| 41.537313
| 2,783
|
1,687
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.test_crm_lead_merge import TestLeadMergeCommon
from odoo.tests.common import tagged, users
@tagged('lead_manage')
class TestLeadVisitorMerge(TestLeadMergeCommon):
@users('user_sales_manager')
def test_merge_method_dependencies(self):
""" Test if dependences for leads are not lost while merging leads. In
this test leads are ordered as
lead_w_contact -----------lead---seq=30
lead_w_email -------------lead---seq=3
lead_1 -------------------lead---seq=1
lead_w_partner_company ---lead---seq=1----------------visitor
lead_w_partner -----------lead---seq=False------------visitor
"""
TestLeadMergeCommon.merge_fields.append('visitor_ids')
visitors = self.env['website.visitor'].sudo().create([
{'name': 'Visitor 1',
'lead_ids': [(4, self.lead_w_partner_company.id)],
},
{'name': 'Visitor 2',
'lead_ids': [(4, self.lead_w_partner.id)],
}
])
self.assertEqual(self.lead_w_partner_company.visitor_ids, visitors[0])
self.assertEqual(self.lead_w_partner.visitor_ids, visitors[1])
leads = self.env['crm.lead'].browse(self.leads.ids)._sort_by_confidence_level(reverse=True)
with self.assertLeadMerged(self.lead_w_contact, leads,
name=self.lead_w_contact.name,
visitor_ids=visitors
):
leads._merge_opportunity(auto_unlink=False, max_length=None)
| 42.175
| 1,687
|
994
|
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'
def _get_crm_default_team_domain(self):
if not self.env.user.has_group('crm.group_use_lead'):
return [('use_opportunities', '=', True)]
return [('use_leads', '=', True)]
crm_default_team_id = fields.Many2one(
'crm.team', string='Default Sales Team', related='website_id.crm_default_team_id', readonly=False,
domain=lambda self: self._get_crm_default_team_domain(),
help='Default Sales Team for new leads created through the Contact Us form.')
crm_default_user_id = fields.Many2one(
'res.users', string='Default Salesperson', related='website_id.crm_default_user_id', domain=[('share', '=', False)], readonly=False,
help='Default salesperson for new leads created through the Contact Us form.')
| 49.7
| 994
|
920
|
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 Website(models.Model):
_inherit = 'website'
def _get_crm_default_team_domain(self):
if not self.env.user.has_group('crm.group_use_lead'):
return [('use_opportunities', '=', True)]
return [('use_leads', '=', True)]
crm_default_team_id = fields.Many2one(
'crm.team', string='Default Sales Teams',
default=lambda self: self.env['crm.team'].search([], limit=1),
domain=lambda self: self._get_crm_default_team_domain(),
help='Default Sales Team for new leads created through the Contact Us form.')
crm_default_user_id = fields.Many2one(
'res.users', string='Default Salesperson', domain=[('share', '=', False)],
help='Default salesperson for new leads created through the Contact Us form.')
| 41.818182
| 920
|
2,905
|
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, SUPERUSER_ID
class Lead(models.Model):
_inherit = 'crm.lead'
visitor_ids = fields.Many2many('website.visitor', string="Web Visitors")
visitor_page_count = fields.Integer('# Page Views', compute="_compute_visitor_page_count")
@api.depends('visitor_ids.page_ids')
def _compute_visitor_page_count(self):
mapped_data = {}
if self.ids:
self.flush(['visitor_ids'])
sql = """ SELECT l.id as lead_id, count(*) as page_view_count
FROM crm_lead l
JOIN crm_lead_website_visitor_rel lv ON l.id = lv.crm_lead_id
JOIN website_visitor v ON v.id = lv.website_visitor_id
JOIN website_track p ON p.visitor_id = v.id
WHERE l.id in %s AND v.active = TRUE
GROUP BY l.id"""
self.env.cr.execute(sql, (tuple(self.ids),))
page_data = self.env.cr.dictfetchall()
mapped_data = {data['lead_id']: data['page_view_count'] for data in page_data}
for lead in self:
lead.visitor_page_count = mapped_data.get(lead.id, 0)
def action_redirect_to_page_views(self):
visitors = self.visitor_ids
action = self.env["ir.actions.actions"]._for_xml_id("website.website_visitor_page_action")
action['domain'] = [('visitor_id', 'in', visitors.ids)]
# avoid grouping if only few records
if len(visitors.website_track_ids) > 15 and len(visitors.website_track_ids.page_id) > 1:
action['context'] = {'search_default_group_by_page': '1'}
return action
def _merge_get_fields_specific(self):
fields_info = super(Lead, self)._merge_get_fields_specific()
# add all the visitors from all lead to merge
fields_info['visitor_ids'] = lambda fname, leads: [(6, 0, leads.visitor_ids.ids)]
return fields_info
def website_form_input_filter(self, request, values):
values['medium_id'] = values.get('medium_id') or \
self.default_get(['medium_id']).get('medium_id') or \
self.sudo().env.ref('utm.utm_medium_website').id
values['team_id'] = values.get('team_id') or \
request.website.crm_default_team_id.id
values['user_id'] = values.get('user_id') or \
request.website.crm_default_user_id.id
if values.get('team_id'):
values['type'] = 'lead' if self.env['crm.team'].sudo().browse(values['team_id']).use_leads else 'opportunity'
else:
values['type'] = 'lead' if self.with_user(SUPERUSER_ID).env['res.users'].has_group('crm.group_use_lead') else 'opportunity'
return values
| 49.237288
| 2,905
|
2,712
|
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 WebsiteVisitor(models.Model):
_inherit = 'website.visitor'
lead_ids = fields.Many2many('crm.lead', string='Leads', groups="sales_team.group_sale_salesman")
lead_count = fields.Integer('# Leads', compute="_compute_lead_count", groups="sales_team.group_sale_salesman")
@api.depends('lead_ids')
def _compute_lead_count(self):
for visitor in self:
visitor.lead_count = len(visitor.lead_ids)
@api.depends('partner_id.email_normalized', 'partner_id.mobile', 'lead_ids.email_normalized', 'lead_ids.mobile')
def _compute_email_phone(self):
super(WebsiteVisitor, self)._compute_email_phone()
self.flush()
left_visitors = self.filtered(lambda visitor: not visitor.email or not visitor.mobile)
leads = left_visitors.mapped('lead_ids').sorted('create_date', reverse=True)
visitor_to_lead_ids = dict((visitor.id, visitor.lead_ids.ids) for visitor in left_visitors)
for visitor in left_visitors:
visitor_leads = leads.filtered(lambda lead: lead.id in visitor_to_lead_ids[visitor.id])
if not visitor.email:
visitor.email = next((lead.email_normalized for lead in visitor_leads if lead.email_normalized), False)
if not visitor.mobile:
visitor.mobile = next((lead.mobile or lead.phone for lead in visitor_leads if lead.mobile or lead.phone), False)
def _check_for_message_composer(self):
check = super(WebsiteVisitor, self)._check_for_message_composer()
if not check and self.lead_ids:
sorted_leads = self.lead_ids._sort_by_confidence_level(reverse=True)
partners = sorted_leads.mapped('partner_id')
if not partners:
main_lead = self.lead_ids[0]
main_lead._handle_partner_assignment(create_missing=True)
self.partner_id = main_lead.partner_id.id
return True
return check
def _prepare_message_composer_context(self):
if not self.partner_id and self.lead_ids:
sorted_leads = self.lead_ids._sort_by_confidence_level(reverse=True)
lead_partners = sorted_leads.mapped('partner_id')
partner = lead_partners[0] if lead_partners else False
if partner:
return {
'default_model': 'crm.lead',
'default_res_id': sorted_leads[0].id,
'default_partner_ids': partner.ids,
}
return super(WebsiteVisitor, self)._prepare_message_composer_context()
| 47.578947
| 2,712
|
5,502
|
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.addons.phone_validation.tools import phone_validation
from odoo.addons.website.controllers import form
from odoo.http import request
class WebsiteForm(form.WebsiteForm):
def _get_country(self):
visitor_partner = request.env['website.visitor']._get_visitor_from_request().partner_id
if visitor_partner:
# match same behaviour as in partner._phone_format()
country = visitor_partner.country_id or request.env.company.country_id
if country:
return country
country_code = request.session.geoip and request.session.geoip.get('country_code') or False
if country_code:
return request.env['res.country'].sudo().search([('code', '=', country_code)], limit=1)
return request.env['res.country']
def _get_phone_fields_to_validate(self):
return ['phone', 'mobile']
# Check and insert values from the form on the model <model> + validation phone fields
def _handle_website_form(self, model_name, **kwargs):
model_record = request.env['ir.model'].sudo().search([('model', '=', model_name), ('website_form_access', '=', True)])
if model_record and hasattr(request.env[model_name], '_phone_format') or hasattr(request.env[model_name], 'phone_get_sanitized_number'):
# filter on either custom _phone_format method, either phone_get_sanitized_number but directly
# call phone_format from phone validation herebelow to simplify things as we don't have real
# records but a dictionary of value at this point (record.phone_get_sanitized_number would
# not work)
try:
data = self.extract_data(model_record, request.params)
except:
# no specific management, super will do it
pass
else:
record = data.get('record', {})
phone_fields = self._get_phone_fields_to_validate()
country = request.env['res.country'].browse(record.get('country_id'))
contact_country = country if country.exists() else self._get_country()
for phone_field in phone_fields:
if not record.get(phone_field):
continue
number = record[phone_field]
fmt_number = phone_validation.phone_format(
number, contact_country.code if contact_country else None,
contact_country.phone_code if contact_country else None,
force_format='INTERNATIONAL',
raise_exception=False
)
request.params.update({phone_field: fmt_number})
if model_name == 'crm.lead' and not request.params.get('state_id'):
geoip_country_code = request.session.get('geoip', {}).get('country_code')
geoip_state_code = request.session.get('geoip', {}).get('region')
if geoip_country_code and geoip_state_code:
state = request.env['res.country.state'].search([('code', '=', geoip_state_code), ('country_id.code', '=', geoip_country_code)])
if state:
request.params['state_id'] = state.id
return super(WebsiteForm, self)._handle_website_form(model_name, **kwargs)
def insert_record(self, request, model, values, custom, meta=None):
is_lead_model = model.model == 'crm.lead'
if is_lead_model:
values_email_normalized = tools.email_normalize(values.get('email_from'))
visitor_sudo = request.env['website.visitor']._get_visitor_from_request()
visitor_partner = visitor_sudo.partner_id
if values_email_normalized and visitor_partner and visitor_partner.email_normalized == values_email_normalized:
# Here, 'phone' in values has already been formatted, see _handle_website_form.
values_phone = values.get('phone')
# We write partner id on crm only if no phone exists on partner or in input,
# or if both numbers (after formating) are the same. This way we get additional phone
# if possible, without modifying an existing one. (see inverse function on model crm.lead)
if values_phone and visitor_partner.phone:
if visitor_partner._phone_format(visitor_partner.phone) == values_phone:
values['partner_id'] = visitor_partner.id
else:
values['partner_id'] = visitor_partner.id
if 'company_id' not in values:
values['company_id'] = request.website.company_id.id
lang = request.context.get('lang', False)
values['lang_id'] = values.get('lang_id') or request.env['res.lang']._lang_get_id(lang)
result = super(WebsiteForm, self).insert_record(request, model, values, custom, meta=meta)
if is_lead_model and visitor_sudo and result:
lead_sudo = request.env['crm.lead'].browse(result).sudo()
if lead_sudo.exists():
vals = {'lead_ids': [(4, result)]}
if not visitor_sudo.lead_ids and not visitor_sudo.partner_id:
vals['name'] = lead_sudo.contact_name
visitor_sudo.write(vals)
return result
| 56.721649
| 5,502
|
1,083
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Members',
'version': '1.0',
'category': 'Sales/Sales',
'description': """
This module allows you to manage all operations for managing memberships.
=========================================================================
It supports different kind of members:
--------------------------------------
* Free member
* Associated member (e.g.: a group subscribes to a membership for all subsidiaries)
* Paid members
* Special member prices
It is integrated with sales and accounting to allow you to automatically
invoice and send propositions for membership renewal.
""",
'depends': ['account'],
'data': [
'security/ir.model.access.csv',
'wizard/membership_invoice_views.xml',
'data/membership_data.xml',
'views/product_views.xml',
'views/partner_views.xml',
'report/report_membership_views.xml',
],
'website': 'https://www.odoo.com/app/forum',
'license': 'LGPL-3',
}
| 31.852941
| 1,083
|
7,033
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import datetime
from dateutil.relativedelta import relativedelta
from unittest.mock import patch
import time
from odoo.addons.membership.tests.common import TestMembershipCommon
from odoo.tests import tagged
from odoo import fields
@tagged('post_install', '-at_install')
class TestMembership(TestMembershipCommon):
def test_none_membership(self):
self.membership_1.write({
'membership_date_from': datetime.date.today() + relativedelta(years=-2),
'membership_date_to': datetime.date.today() + relativedelta(years=-1),
})
self.partner_1.create_membership_invoice(self.membership_1, 75.0)
self.assertEqual(
self.partner_1.membership_state, 'none',
'membership: outdated non paid subscription should keep in non-member state')
def test_old_membership(self):
self.membership_1.write({
'membership_date_from': datetime.date.today() + relativedelta(years=-2),
'membership_date_to': datetime.date.today() + relativedelta(years=-1),
})
self.partner_1.create_membership_invoice(self.membership_1, 75.0)
self.assertEqual(
self.partner_1.membership_state, 'none',
'membership: outdated non paid subscription should keep in non-member state')
# subscribes to a membership
self.partner_1.create_membership_invoice(self.membership_1, 75.0)
# checks for invoices
invoice = self.env['account.move'].search([('partner_id', '=', self.partner_1.id)], limit=1)
self.assertEqual(
invoice.state, 'draft',
'membership: new subscription should create a draft invoice')
self.assertEqual(
invoice.invoice_line_ids[0].product_id, self.membership_1,
'membership: new subscription should create a line with the membership as product')
self.assertEqual(
invoice.invoice_line_ids[0].price_unit, 75.0,
'membership: new subscription should create a line with the given price instead of product price')
self.assertEqual(
self.partner_1.membership_state, 'none',
'membership: old membership unpaid should be in non-member state')
# the invoice is open -> customer goes to invoiced status
invoice.action_post()
self.assertEqual(
self.partner_1.membership_state, 'none',
'membership: after opening the invoice for old membership, it should remain in non paid status')
# payment process
payment = self.env['account.payment'].create({
'destination_account_id': invoice.line_ids.account_id.filtered(lambda account: account.internal_type == 'receivable').id,
'payment_method_line_id': self.inbound_payment_method_line.id,
'payment_type': 'inbound',
'partner_type': 'customer',
'partner_id': invoice.partner_id.id,
'amount': 500,
'company_id': self.env.company.id,
'currency_id': self.env.company.currency_id.id,
})
payment.action_post()
inv1_receivable = invoice.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable')
pay_receivable = payment.move_id.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable')
(inv1_receivable + pay_receivable).reconcile()
# the invoice is paid -> customer goes to paid status
self.assertEqual(
self.partner_1.membership_state, 'old',
'membership: after paying the invoice, customer should be in old status')
# check second partner then associate them
self.assertEqual(
self.partner_2.membership_state, 'free',
'membership: free member customer should be in free state')
self.partner_2.write({'free_member': False, 'associate_member': self.partner_1.id})
self.assertEqual(
self.partner_2.membership_state, 'old',
'membership: associated customer should be in old state')
def test_paid_membership(self):
self.assertEqual(
self.partner_1.membership_state, 'none',
'membership: default membership status of partners should be None')
# subscribes to a membership
invoice = self.partner_1.create_membership_invoice(self.membership_1, 75.0)
self.assertEqual(
invoice.state, 'draft',
'membership: new subscription should create a draft invoice')
self.assertEqual(
invoice.invoice_line_ids[0].product_id, self.membership_1,
'membership: new subscription should create a line with the membership as product')
self.assertEqual(
invoice.invoice_line_ids[0].price_unit, 75.0,
'membership: new subscription should create a line with the given price instead of product price')
self.assertEqual(
self.partner_1.membership_state, 'waiting',
'membership: new membership should be in waiting state')
# the invoice is open -> customer goes to invoiced status
invoice.action_post()
self.assertEqual(
self.partner_1.membership_state, 'invoiced',
'membership: after opening the invoice, customer should be in invoiced status')
# the invoice is paid -> customer goes to paid status
payment = self.env['account.payment.register']\
.with_context(active_model='account.move', active_ids=invoice.ids)\
.create({
'amount': 86.25,
'payment_method_line_id': self.inbound_payment_method_line.id,
})\
._create_payments()
self.assertEqual(
self.partner_1.membership_state, 'paid',
'membership: after paying the invoice, customer should be in paid status')
# check second partner then associate them
self.assertEqual(
self.partner_2.membership_state, 'free',
'membership: free member customer should be in free state')
self.partner_2.write({'free_member': False, 'associate_member': self.partner_1.id})
self.assertEqual(
self.partner_2.membership_state, 'paid',
'membership: associated customer should be in paid state')
def test_cancel_membership(self):
self.assertEqual(
self.partner_1.membership_state, 'none',
'membership: default membership status of partners should be None')
# subscribes to a membership
invoice = self.partner_1.create_membership_invoice(self.membership_1, 75.0)
def patched_today(*args, **kwargs):
return fields.Date.to_date('2019-01-01')
with patch.object(fields.Date, 'today', patched_today):
invoice.button_cancel()
self.partner_1._compute_membership_state()
self.assertEqual(invoice.state, 'cancel')
self.assertEqual(self.partner_1.membership_state, 'canceled')
| 43.68323
| 7,033
|
1,032
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import datetime
from dateutil.relativedelta import relativedelta
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
class TestMembershipCommon(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# Test memberships
cls.membership_1 = cls.env['product.product'].create({
'membership': True,
'membership_date_from': datetime.date.today() + relativedelta(days=-2),
'membership_date_to': datetime.date.today() + relativedelta(months=1),
'name': 'Basic Limited',
'type': 'service',
'list_price': 100.00,
})
# Test people
cls.partner_1 = cls.env['res.partner'].create({
'name': 'Ignasse Reblochon',
})
cls.partner_2 = cls.env['res.partner'].create({
'name': 'Martine Poulichette',
'free_member': True,
})
| 32.25
| 1,032
|
1,519
|
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 MembershipInvoice(models.TransientModel):
_name = "membership.invoice"
_description = "Membership Invoice"
product_id = fields.Many2one('product.product', string='Membership', required=True)
member_price = fields.Float(string='Member Price', digits='Product Price', required=True)
@api.onchange('product_id')
def onchange_product(self):
"""This function returns value of product's member price based on product id.
"""
price_dict = self.product_id.price_compute('list_price')
self.member_price = price_dict.get(self.product_id.id) or False
def membership_invoice(self):
invoice_list = self.env['res.partner'].browse(self._context.get('active_ids')).create_membership_invoice(self.product_id, self.member_price)
search_view_ref = self.env.ref('account.view_account_invoice_filter', False)
form_view_ref = self.env.ref('account.view_move_form', False)
tree_view_ref = self.env.ref('account.view_move_tree', False)
return {
'domain': [('id', 'in', invoice_list.ids)],
'name': 'Membership Invoices',
'res_model': 'account.move',
'type': 'ir.actions.act_window',
'views': [(tree_view_ref.id, 'tree'), (form_view_ref.id, 'form')],
'search_view_id': search_view_ref and [search_view_ref.id],
}
| 43.4
| 1,519
|
4,509
|
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 datetime import date
class AccountMove(models.Model):
_inherit = 'account.move'
def button_draft(self):
# OVERRIDE to update the cancel date.
res = super(AccountMove, self).button_draft()
for move in self:
if move.move_type == 'out_invoice':
self.env['membership.membership_line'].search([
('account_invoice_line', 'in', move.mapped('invoice_line_ids').ids)
]).write({'date_cancel': False})
return res
def button_cancel(self):
# OVERRIDE to update the cancel date.
res = super(AccountMove, self).button_cancel()
for move in self:
if move.move_type == 'out_invoice':
self.env['membership.membership_line'].search([
('account_invoice_line', 'in', move.mapped('invoice_line_ids').ids)
]).write({'date_cancel': fields.Date.today()})
return res
def write(self, vals):
# OVERRIDE to write the partner on the membership lines.
res = super(AccountMove, self).write(vals)
if 'partner_id' in vals:
self.env['membership.membership_line'].search([
('account_invoice_line', 'in', self.mapped('invoice_line_ids').ids)
]).write({'partner': vals['partner_id']})
return res
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def write(self, vals):
# OVERRIDE
res = super(AccountMoveLine, self).write(vals)
to_process = self.filtered(lambda line: line.move_id.move_type == 'out_invoice' and line.product_id.membership)
# Nothing to process, break.
if not to_process:
return res
existing_memberships = self.env['membership.membership_line'].search([
('account_invoice_line', 'in', to_process.ids)])
to_process = to_process - existing_memberships.mapped('account_invoice_line')
# All memberships already exist, break.
if not to_process:
return res
memberships_vals = []
for line in to_process:
date_from = line.product_id.membership_date_from
date_to = line.product_id.membership_date_to
if (date_from and date_from < (line.move_id.invoice_date or date.min) < (date_to or date.min)):
date_from = line.move_id.invoice_date
memberships_vals.append({
'partner': line.move_id.partner_id.id,
'membership_id': line.product_id.id,
'member_price': line.price_unit,
'date': fields.Date.today(),
'date_from': date_from,
'date_to': date_to,
'account_invoice_line': line.id,
})
self.env['membership.membership_line'].create(memberships_vals)
return res
@api.model_create_multi
def create(self, vals_list):
# OVERRIDE
lines = super(AccountMoveLine, self).create(vals_list)
to_process = lines.filtered(lambda line: line.move_id.move_type == 'out_invoice' and line.product_id.membership)
# Nothing to process, break.
if not to_process:
return lines
existing_memberships = self.env['membership.membership_line'].search([
('account_invoice_line', 'in', to_process.ids)])
to_process = to_process - existing_memberships.mapped('account_invoice_line')
# All memberships already exist, break.
if not to_process:
return lines
memberships_vals = []
for line in to_process:
date_from = line.product_id.membership_date_from
date_to = line.product_id.membership_date_to
if (date_from and date_from < (line.move_id.invoice_date or date.min) < (date_to or date.min)):
date_from = line.move_id.invoice_date
memberships_vals.append({
'partner': line.move_id.partner_id.id,
'membership_id': line.product_id.id,
'member_price': line.price_unit,
'date': fields.Date.today(),
'date_from': date_from,
'date_to': date_to,
'account_invoice_line': line.id,
})
self.env['membership.membership_line'].create(memberships_vals)
return lines
| 39.208696
| 4,509
|
6,083
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from . import membership
class Partner(models.Model):
_inherit = 'res.partner'
associate_member = fields.Many2one('res.partner', string='Associate Member',
help="A member with whom you want to associate your membership."
"It will consider the membership state of the associated member.")
member_lines = fields.One2many('membership.membership_line', 'partner', string='Membership')
free_member = fields.Boolean(string='Free Member',
help="Select if you want to give free membership.")
membership_amount = fields.Float(string='Membership Amount', digits=(16, 2),
help='The price negotiated by the partner')
membership_state = fields.Selection(membership.STATE, compute='_compute_membership_state',
string='Current Membership Status', store=True, recursive=True,
help='It indicates the membership state.\n'
'-Non Member: A partner who has not applied for any membership.\n'
'-Cancelled Member: A member who has cancelled his membership.\n'
'-Old Member: A member whose membership date has expired.\n'
'-Waiting Member: A member who has applied for the membership and whose invoice is going to be created.\n'
'-Invoiced Member: A member whose invoice has been created.\n'
'-Paying member: A member who has paid the membership fee.')
membership_start = fields.Date(compute='_compute_membership_state',
string ='Membership Start Date', store=True,
help="Date from which membership becomes active.")
membership_stop = fields.Date(compute='_compute_membership_state',
string ='Membership End Date', store=True,
help="Date until which membership remains active.")
membership_cancel = fields.Date(compute='_compute_membership_state',
string ='Cancel Membership Date', store=True,
help="Date on which membership has been cancelled")
@api.depends('member_lines.account_invoice_line',
'member_lines.account_invoice_line.move_id.state',
'member_lines.account_invoice_line.move_id.payment_state',
'member_lines.account_invoice_line.move_id.partner_id',
'free_member',
'member_lines.date_to', 'member_lines.date_from',
'associate_member', 'associate_member.membership_state')
def _compute_membership_state(self):
today = fields.Date.today()
for partner in self:
partner.membership_start = self.env['membership.membership_line'].search([
('partner', '=', partner.associate_member.id or partner.id), ('date_cancel', '=', False)
], limit=1, order='date_from').date_from
partner.membership_stop = self.env['membership.membership_line'].search([
('partner', '=', partner.associate_member.id or partner.id), ('date_cancel', '=', False)
], limit=1, order='date_to desc').date_to
partner.membership_cancel = self.env['membership.membership_line'].search([
('partner', '=', partner.id)
], limit=1, order='date_cancel').date_cancel
if partner.associate_member:
partner.membership_state = partner.associate_member.membership_state
continue
if partner.free_member and partner.membership_state != 'paid':
partner.membership_state = 'free'
continue
for mline in partner.member_lines:
if (mline.date_to or date.min) >= today and (mline.date_from or date.min) <= today:
partner.membership_state = mline.state
break
elif ((mline.date_from or date.min) < today and (mline.date_to or date.min) <= today and \
(mline.date_from or date.min) < (mline.date_to or date.min)):
if mline.account_invoice_id and mline.account_invoice_id.payment_state in ('in_payment', 'paid'):
partner.membership_state = 'old'
elif mline.account_invoice_id and mline.account_invoice_id.state == 'cancel':
partner.membership_state = 'canceled'
break
else:
partner.membership_state = 'none'
@api.constrains('associate_member')
def _check_recursion_associate_member(self):
for partner in self:
level = 100
while partner:
partner = partner.associate_member
if not level:
raise ValidationError(_('You cannot create recursive associated members.'))
level -= 1
@api.model
def _cron_update_membership(self):
partners = self.search([('membership_state', 'in', ['invoiced', 'paid'])])
# mark the field to be recomputed, and recompute it
self.env.add_to_compute(self._fields['membership_state'], partners)
def create_membership_invoice(self, product, amount):
""" Create Customer Invoice of Membership for partners.
"""
invoice_vals_list = []
for partner in self:
addr = partner.address_get(['invoice'])
if partner.free_member:
raise UserError(_("Partner is a free Member."))
if not addr.get('invoice', False):
raise UserError(_("Partner doesn't have an address to make the invoice."))
invoice_vals_list.append({
'move_type': 'out_invoice',
'partner_id': partner.id,
'invoice_line_ids': [
(0, None, {'product_id': product.id, 'quantity': 1, 'price_unit': amount, 'tax_ids': [(6, 0, product.taxes_id.ids)]})
]
})
return self.env['account.move'].create(invoice_vals_list)
| 51.991453
| 6,083
|
1,244
|
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 Product(models.Model):
_inherit = 'product.template'
membership = fields.Boolean(help='Check if the product is eligible for membership.')
membership_date_from = fields.Date(string='Membership Start Date',
help='Date from which membership becomes active.')
membership_date_to = fields.Date(string='Membership End Date',
help='Date until which membership remains active.')
_sql_constraints = [
('membership_date_greater', 'check(membership_date_to >= membership_date_from)', 'Error ! Ending Date cannot be set before Beginning Date.')
]
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
if self._context.get('product') == 'membership_product':
if view_type == 'form':
view_id = self.env.ref('membership.membership_products_form').id
else:
view_id = self.env.ref('membership.membership_products_tree').id
return super(Product, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
| 46.074074
| 1,244
|
3,571
|
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
STATE = [
('none', 'Non Member'),
('canceled', 'Cancelled Member'),
('old', 'Old Member'),
('waiting', 'Waiting Member'),
('invoiced', 'Invoiced Member'),
('free', 'Free Member'),
('paid', 'Paid Member'),
]
class MembershipLine(models.Model):
_name = 'membership.membership_line'
_rec_name = 'partner'
_order = 'id desc'
_description = 'Membership Line'
partner = fields.Many2one('res.partner', string='Partner', ondelete='cascade', index=True)
membership_id = fields.Many2one('product.product', string="Membership", required=True)
date_from = fields.Date(string='From', readonly=True)
date_to = fields.Date(string='To', readonly=True)
date_cancel = fields.Date(string='Cancel date')
date = fields.Date(string='Join Date',
help="Date on which member has joined the membership")
member_price = fields.Float(string='Membership Fee',
digits='Product Price', required=True,
help='Amount for the membership')
account_invoice_line = fields.Many2one('account.move.line', string='Account Invoice line', readonly=True, ondelete='cascade')
account_invoice_id = fields.Many2one('account.move', related='account_invoice_line.move_id', string='Invoice', readonly=True)
company_id = fields.Many2one('res.company', related='account_invoice_line.move_id.company_id', string="Company", readonly=True, store=True)
state = fields.Selection(STATE, compute='_compute_state', string='Membership Status', store=True,
help="It indicates the membership status.\n"
"-Non Member: A member who has not applied for any membership.\n"
"-Cancelled Member: A member who has cancelled his membership.\n"
"-Old Member: A member whose membership date has expired.\n"
"-Waiting Member: A member who has applied for the membership and whose invoice is going to be created.\n"
"-Invoiced Member: A member whose invoice has been created.\n"
"-Paid Member: A member who has paid the membership amount.")
@api.depends('account_invoice_id.state',
'account_invoice_id.amount_residual',
'account_invoice_id.payment_state')
def _compute_state(self):
"""Compute the state lines """
if not self:
return
self._cr.execute('''
SELECT reversed_entry_id, COUNT(id)
FROM account_move
WHERE reversed_entry_id IN %s
GROUP BY reversed_entry_id
''', [tuple(self.mapped('account_invoice_id.id'))])
reverse_map = dict(self._cr.fetchall())
for line in self:
move_state = line.account_invoice_id.state
payment_state = line.account_invoice_id.payment_state
line.state = 'none'
if move_state == 'draft':
line.state = 'waiting'
elif move_state == 'posted':
if payment_state == 'paid':
if reverse_map.get(line.account_invoice_id.id):
line.state = 'canceled'
else:
line.state = 'paid'
elif payment_state == 'in_payment':
line.state = 'paid'
elif payment_state in ('not_paid', 'partial'):
line.state = 'invoiced'
elif move_state == 'cancel':
line.state = 'canceled'
| 45.782051
| 3,571
|
4,172
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools
STATE = [
('none', 'Non Member'),
('canceled', 'Cancelled Member'),
('old', 'Old Member'),
('waiting', 'Waiting Member'),
('invoiced', 'Invoiced Member'),
('free', 'Free Member'),
('paid', 'Paid Member'),
]
class ReportMembership(models.Model):
'''Membership Analysis'''
_name = 'report.membership'
_description = 'Membership Analysis'
_auto = False
_rec_name = 'start_date'
start_date = fields.Date(string='Start Date', readonly=True)
date_to = fields.Date(string='End Date', readonly=True, help="End membership date")
num_waiting = fields.Integer(string='# Waiting', readonly=True)
num_invoiced = fields.Integer(string='# Invoiced', readonly=True)
num_paid = fields.Integer(string='# Paid', readonly=True)
tot_pending = fields.Float(string='Pending Amount', digits=0, readonly=True)
tot_earned = fields.Float(string='Earned Amount', digits=0, readonly=True)
partner_id = fields.Many2one('res.partner', string='Member', readonly=True)
associate_member_id = fields.Many2one('res.partner', string='Associate Member', readonly=True)
membership_id = fields.Many2one('product.product', string='Membership Product', readonly=True)
membership_state = fields.Selection(STATE, string='Current Membership State', readonly=True)
user_id = fields.Many2one('res.users', string='Salesperson', readonly=True)
company_id = fields.Many2one('res.company', string='Company', readonly=True)
quantity = fields.Integer(readonly=True)
def init(self):
'''Create the view'''
tools.drop_view_if_exists(self._cr, self._table)
self._cr.execute("""
CREATE OR REPLACE VIEW %s AS (
SELECT
MIN(id) AS id,
partner_id,
count(membership_id) as quantity,
user_id,
membership_state,
associate_member_id,
membership_amount,
date_to,
start_date,
COUNT(num_waiting) AS num_waiting,
COUNT(num_invoiced) AS num_invoiced,
COUNT(num_paid) AS num_paid,
SUM(tot_pending) AS tot_pending,
SUM(tot_earned) AS tot_earned,
membership_id,
company_id
FROM
(SELECT
MIN(p.id) AS id,
p.id AS partner_id,
p.user_id AS user_id,
p.membership_state AS membership_state,
p.associate_member AS associate_member_id,
p.membership_amount AS membership_amount,
p.membership_stop AS date_to,
p.membership_start AS start_date,
CASE WHEN ml.state = 'waiting' THEN ml.id END AS num_waiting,
CASE WHEN ml.state = 'invoiced' THEN ml.id END AS num_invoiced,
CASE WHEN ml.state = 'paid' THEN ml.id END AS num_paid,
CASE WHEN ml.state IN ('waiting', 'invoiced') THEN SUM(aml.price_subtotal) ELSE 0 END AS tot_pending,
CASE WHEN ml.state = 'paid' OR p.membership_state = 'old' THEN SUM(aml.price_subtotal) ELSE 0 END AS tot_earned,
ml.membership_id AS membership_id,
p.company_id AS company_id
FROM res_partner p
LEFT JOIN membership_membership_line ml ON (ml.partner = p.id)
LEFT JOIN account_move_line aml ON (ml.account_invoice_line = aml.id)
LEFT JOIN account_move am ON (aml.move_id = am.id)
WHERE p.membership_state != 'none' and p.active = 'true'
GROUP BY
p.id,
p.user_id,
p.membership_state,
p.associate_member,
p.membership_amount,
p.membership_start,
ml.membership_id,
p.company_id,
ml.state,
ml.id
) AS foo
GROUP BY
start_date,
date_to,
partner_id,
user_id,
membership_id,
company_id,
membership_state,
associate_member_id,
membership_amount
)""" % (self._table,))
| 39.358491
| 4,172
|
1,510
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'WMS Accounting',
'version': '1.1',
'summary': 'Inventory, Logistic, Valuation, Accounting',
'description': """
WMS Accounting module
======================
This module makes the link between the 'stock' and 'account' modules and allows you to create accounting entries to value your stock movements
Key Features
------------
* Stock Valuation (periodical or automatic)
* Invoice from Picking
Dashboard / Reports for Warehouse Management includes:
------------------------------------------------------
* Stock Inventory Value at given date (support dates in the past)
""",
'depends': ['stock', 'account'],
'category': 'Hidden',
'sequence': 16,
'data': [
'security/stock_account_security.xml',
'security/ir.model.access.csv',
'data/stock_account_data.xml',
'views/stock_account_views.xml',
'views/res_config_settings_views.xml',
'data/product_data.xml',
'views/product_views.xml',
'views/stock_quant_views.xml',
'views/report_invoice.xml',
'views/stock_valuation_layer_views.xml',
'wizard/stock_request_count.xml',
'wizard/stock_valuation_layer_revaluation_views.xml',
'report/report_stock_forecasted.xml',
],
'test': [
],
'installable': True,
'auto_install': True,
'post_init_hook': '_configure_journals',
'license': 'LGPL-3',
}
| 32.826087
| 1,510
|
54,401
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
""" Implementation of "INVENTORY VALUATION TESTS (With valuation layers)" spreadsheet. """
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
from odoo.tests import Form, tagged
from odoo.tests.common import TransactionCase
class TestStockValuationCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestStockValuationCommon, cls).setUpClass()
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.supplier_location = cls.env.ref('stock.stock_location_suppliers')
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.product1 = cls.env['product.product'].create({
'name': 'product1',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.picking_type_in = cls.env.ref('stock.picking_type_in')
cls.picking_type_out = cls.env.ref('stock.picking_type_out')
cls.env.ref('base.EUR').active = True
def setUp(self):
super(TestStockValuationCommon, self).setUp()
# Counter automatically incremented by `_make_in_move` and `_make_out_move`.
self.days = 0
def _make_in_move(self, product, quantity, unit_cost=None, create_picking=False, loc_dest=None, pick_type=None):
""" Helper to create and validate a receipt move.
"""
unit_cost = unit_cost or product.standard_price
loc_dest = loc_dest or self.stock_location
pick_type = pick_type or self.picking_type_in
in_move = self.env['stock.move'].create({
'name': 'in %s units @ %s per unit' % (str(quantity), str(unit_cost)),
'product_id': product.id,
'location_id': self.supplier_location.id,
'location_dest_id': loc_dest.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': quantity,
'price_unit': unit_cost,
'picking_type_id': pick_type.id,
})
if create_picking:
picking = self.env['stock.picking'].create({
'picking_type_id': in_move.picking_type_id.id,
'location_id': in_move.location_id.id,
'location_dest_id': in_move.location_dest_id.id,
})
in_move.write({'picking_id': picking.id})
in_move._action_confirm()
in_move._action_assign()
in_move.move_line_ids.qty_done = quantity
in_move._action_done()
self.days += 1
return in_move.with_context(svl=True)
def _make_out_move(self, product, quantity, force_assign=None, create_picking=False, loc_src=None, pick_type=None):
""" Helper to create and validate a delivery move.
"""
loc_src = loc_src or self.stock_location
pick_type = pick_type or self.picking_type_out
out_move = self.env['stock.move'].create({
'name': 'out %s units' % str(quantity),
'product_id': product.id,
'location_id': loc_src.id,
'location_dest_id': self.customer_location.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': quantity,
'picking_type_id': pick_type.id,
})
if create_picking:
picking = self.env['stock.picking'].create({
'picking_type_id': out_move.picking_type_id.id,
'location_id': out_move.location_id.id,
'location_dest_id': out_move.location_dest_id.id,
})
out_move.write({'picking_id': picking.id})
out_move._action_confirm()
out_move._action_assign()
if force_assign:
self.env['stock.move.line'].create({
'move_id': out_move.id,
'product_id': out_move.product_id.id,
'product_uom_id': out_move.product_uom.id,
'location_id': out_move.location_id.id,
'location_dest_id': out_move.location_dest_id.id,
})
out_move.move_line_ids.qty_done = quantity
out_move._action_done()
self.days += 1
return out_move.with_context(svl=True)
def _make_dropship_move(self, product, quantity, unit_cost=None):
dropshipped = self.env['stock.move'].create({
'name': 'dropship %s units' % str(quantity),
'product_id': product.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.customer_location.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': quantity,
'picking_type_id': self.picking_type_out.id,
})
if unit_cost:
dropshipped.price_unit = unit_cost
dropshipped._action_confirm()
dropshipped._action_assign()
dropshipped.move_line_ids.qty_done = quantity
dropshipped._action_done()
return dropshipped
def _make_return(self, move, quantity_to_return):
stock_return_picking = Form(self.env['stock.return.picking']\
.with_context(active_ids=[move.picking_id.id], active_id=move.picking_id.id, active_model='stock.picking'))
stock_return_picking = stock_return_picking.save()
stock_return_picking.product_return_moves.quantity = quantity_to_return
stock_return_picking_action = stock_return_picking.create_returns()
return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_pick.move_lines[0].move_line_ids[0].qty_done = quantity_to_return
return_pick._action_done()
return return_pick.move_lines
class TestStockValuationStandard(TestStockValuationCommon):
def setUp(self):
super(TestStockValuationStandard, self).setUp()
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.standard_price = 10
def test_normal_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 15)
self.assertEqual(self.product1.value_svl, 50)
self.assertEqual(self.product1.quantity_svl, 5)
def test_change_in_past_increase_in_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 15)
move1.move_line_ids.qty_done = 15
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
def test_change_in_past_decrease_in_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 15)
move1.move_line_ids.qty_done = 5
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
def test_change_in_past_add_ml_in_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 15)
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 5,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
def test_change_in_past_increase_out_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_out_move(self.product1, 1)
move2.move_line_ids.qty_done = 5
self.assertEqual(self.product1.value_svl, 50)
self.assertEqual(self.product1.quantity_svl, 5)
def test_change_in_past_decrease_out_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_out_move(self.product1, 5)
move2.move_line_ids.qty_done = 1
self.assertEqual(self.product1.value_svl, 90)
self.assertEqual(self.product1.quantity_svl, 9)
def test_change_standard_price_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 15)
# change cost from 10 to 15
self.product1.standard_price = 15.0
self.assertEqual(self.product1.value_svl, 75)
self.assertEqual(self.product1.quantity_svl, 5)
self.assertEqual(self.product1.stock_valuation_layer_ids.sorted()[-1].description, 'Product value manually modified (from 10.0 to 15.0)')
def test_negative_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_out_move(self.product1, 15)
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 10,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})
self.assertEqual(self.product1.value_svl, 50)
self.assertEqual(self.product1.quantity_svl, 5)
def test_dropship_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_dropship_move(self.product1, 10)
valuation_layers = self.product1.stock_valuation_layer_ids
self.assertEqual(len(valuation_layers), 2)
self.assertEqual(valuation_layers[0].value, 100)
self.assertEqual(valuation_layers[1].value, -100)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
def test_change_in_past_increase_dropship_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_dropship_move(self.product1, 10)
move1.move_line_ids.qty_done = 15
valuation_layers = self.product1.stock_valuation_layer_ids
self.assertEqual(len(valuation_layers), 4)
self.assertEqual(valuation_layers[0].value, 100)
self.assertEqual(valuation_layers[1].value, -100)
self.assertEqual(valuation_layers[2].value, 50)
self.assertEqual(valuation_layers[3].value, -50)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
def test_empty_stock_move_valorisation(self):
product1 = self.env['product.product'].create({
'name': 'p1',
'type': 'product',
})
product2 = self.env['product.product'].create({
'name': 'p2',
'type': 'product',
})
picking = self.env['stock.picking'].create({
'picking_type_id': self.picking_type_in.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
})
for product in (product1, product2):
product.standard_price = 10
in_move = self.env['stock.move'].create({
'name': 'in %s units @ %s per unit' % (2, str(10)),
'product_id': product.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2,
'price_unit': 10,
'picking_type_id': self.picking_type_in.id,
'picking_id': picking.id
})
picking.action_confirm()
# set quantity done only on one move
in_move.move_line_ids.qty_done = 2
res_dict = picking.button_validate()
wizard = self.env[(res_dict.get('res_model'))].with_context(res_dict.get('context')).browse(res_dict.get('res_id'))
res_dict_for_back_order = wizard.process()
self.assertTrue(product2.stock_valuation_layer_ids)
self.assertFalse(product1.stock_valuation_layer_ids)
def test_currency_precision_and_standard_svl_value(self):
currency = self.env['res.currency'].create({
'name': 'Odoo',
'symbol': 'O',
'rounding': 1,
})
new_company = self.env['res.company'].create({
'name': 'Super Company',
'currency_id': currency.id,
})
old_company = self.env.user.company_id
try:
self.env.user.company_id = new_company
warehouse = self.env['stock.warehouse'].search([('company_id', '=', new_company.id)])
product = self.product1.with_company(new_company)
product.standard_price = 3
self._make_in_move(product, 0.5, loc_dest=warehouse.lot_stock_id, pick_type=warehouse.in_type_id)
self._make_out_move(product, 0.5, loc_src=warehouse.lot_stock_id, pick_type=warehouse.out_type_id)
self.assertEqual(product.value_svl, 0.0)
finally:
self.env.user.company_id = old_company
class TestStockValuationAVCO(TestStockValuationCommon):
def setUp(self):
super(TestStockValuationAVCO, self).setUp()
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
def test_normal_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
self.assertEqual(self.product1.standard_price, 10)
self.assertEqual(move1.stock_valuation_layer_ids.value, 100)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
self.assertEqual(self.product1.standard_price, 15)
self.assertEqual(move2.stock_valuation_layer_ids.value, 200)
move3 = self._make_out_move(self.product1, 15)
self.assertEqual(self.product1.standard_price, 15)
self.assertEqual(move3.stock_valuation_layer_ids.value, -225)
self.assertEqual(self.product1.value_svl, 75)
self.assertEqual(self.product1.quantity_svl, 5)
def test_change_in_past_increase_in_1(self):
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
move1.move_line_ids.qty_done = 15
self.assertEqual(self.product1.value_svl, 125)
self.assertEqual(self.product1.quantity_svl, 10)
def test_change_in_past_decrease_in_1(self):
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
move1.move_line_ids.qty_done = 5
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
def test_change_in_past_add_ml_in_1(self):
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 5,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})
self.assertEqual(self.product1.value_svl, 125)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.standard_price, 12.5)
def test_change_in_past_add_move_in_1(self):
move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
self.env['stock.move.line'].create({
'product_id': move1.product_id.id,
'qty_done': 5,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
'state': 'done',
'picking_id': move1.picking_id.id,
})
self.assertEqual(self.product1.value_svl, 150)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.standard_price, 15)
def test_change_in_past_increase_out_1(self):
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
move3.move_line_ids.qty_done = 20
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.standard_price, 15)
def test_change_in_past_decrease_out_1(self):
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
move3.move_line_ids.qty_done = 10
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 10)
self.assertEqual(self.product1.value_svl, 150)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.standard_price, 15)
def test_negative_1(self):
""" Ensures that, in AVCO, the `remaining_qty` field is computed and the vacuum is ran
when necessary.
"""
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 30)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, -10)
move4 = self._make_in_move(self.product1, 10, unit_cost=30)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 0)
move5 = self._make_in_move(self.product1, 10, unit_cost=40)
self.assertEqual(self.product1.value_svl, 400)
self.assertEqual(self.product1.quantity_svl, 10)
def test_negative_2(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.product1.standard_price = 10
move1 = self._make_out_move(self.product1, 1, force_assign=True)
move2 = self._make_in_move(self.product1, 1, unit_cost=15)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
def test_negative_3(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_out_move(self.product1, 2, force_assign=True)
self.assertEqual(move1.stock_valuation_layer_ids.value, 0)
move2 = self._make_in_move(self.product1, 20, unit_cost=3.33)
self.assertEqual(move1.stock_valuation_layer_ids[1].value, -6.66)
self.assertEqual(self.product1.standard_price, 3.33)
self.assertEqual(self.product1.value_svl, 59.94)
self.assertEqual(self.product1.quantity_svl, 18)
def test_return_receipt_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10, create_picking=True)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
move4 = self._make_return(move1, 1)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.standard_price, 15)
def test_return_delivery_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_out_move(self.product1, 1, create_picking=True)
move4 = self._make_return(move3, 1)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.product1.quantity_svl, 2)
self.assertEqual(self.product1.standard_price, 15)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 2)
def test_rereturn_receipt_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10, create_picking=True)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
move4 = self._make_return(move1, 1) # -15, current avco
move5 = self._make_return(move4, 1) # +10, original move's price unit
self.assertEqual(self.product1.value_svl, 15)
self.assertEqual(self.product1.quantity_svl, 1)
self.assertEqual(self.product1.standard_price, 15)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 1)
def test_rereturn_delivery_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_out_move(self.product1, 1, create_picking=True)
move4 = self._make_return(move3, 1)
move5 = self._make_return(move4, 1)
self.assertEqual(self.product1.value_svl, 15)
self.assertEqual(self.product1.quantity_svl, 1)
self.assertEqual(self.product1.standard_price, 15)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 1)
def test_dropship_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_dropship_move(self.product1, 1, unit_cost=10)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.product1.quantity_svl, 2)
self.assertEqual(self.product1.standard_price, 15)
def test_rounding_slv_1(self):
self._make_in_move(self.product1, 1, unit_cost=1.00)
self._make_in_move(self.product1, 1, unit_cost=1.00)
self._make_in_move(self.product1, 1, unit_cost=1.01)
self.assertAlmostEqual(self.product1.value_svl, 3.01)
move_out = self._make_out_move(self.product1, 3, create_picking=True)
self.assertIn('Rounding Adjustment: -0.01', move_out.stock_valuation_layer_ids.description)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.standard_price, 1.00)
def test_rounding_slv_2(self):
self._make_in_move(self.product1, 1, unit_cost=1.02)
self._make_in_move(self.product1, 1, unit_cost=1.00)
self._make_in_move(self.product1, 1, unit_cost=1.00)
self.assertAlmostEqual(self.product1.value_svl, 3.02)
move_out = self._make_out_move(self.product1, 3, create_picking=True)
self.assertIn('Rounding Adjustment: +0.01', move_out.stock_valuation_layer_ids.description)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.standard_price, 1.01)
def test_rounding_svl_3(self):
self._make_in_move(self.product1, 1000, unit_cost=0.17)
self._make_in_move(self.product1, 800, unit_cost=0.23)
self.assertEqual(self.product1.standard_price, 0.20)
self._make_out_move(self.product1, 1000, create_picking=True)
self._make_out_move(self.product1, 800, create_picking=True)
self.assertEqual(self.product1.value_svl, 0)
def test_rounding_svl_4(self):
"""
The first 2 In moves result in a rounded standard_price at 3.4943, which is rounded at 3.49.
This test ensures that no rounding error is generated with small out quantities.
"""
self.product1.categ_id.property_cost_method = 'average'
self._make_in_move(self.product1, 2, unit_cost=4.63)
self._make_in_move(self.product1, 5, unit_cost=3.04)
self.assertEqual(self.product1.standard_price, 3.49)
for _ in range(70):
self._make_out_move(self.product1, 0.1)
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.value_svl, 0)
def test_return_delivery_2(self):
self.product1.write({"standard_price": 1})
move1 = self._make_out_move(self.product1, 10, create_picking=True, force_assign=True)
self._make_in_move(self.product1, 10, unit_cost=2)
self._make_return(move1, 10)
self.assertEqual(self.product1.value_svl, 20)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.standard_price, 2)
class TestStockValuationFIFO(TestStockValuationCommon):
def setUp(self):
super(TestStockValuationFIFO, self).setUp()
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
def test_normal_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 15)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 5)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 5)
def test_negative_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 30)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, -10)
move4 = self._make_in_move(self.product1, 10, unit_cost=30)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 0)
move5 = self._make_in_move(self.product1, 10, unit_cost=40)
self.assertEqual(self.product1.value_svl, 400)
self.assertEqual(self.product1.quantity_svl, 10)
def test_change_in_past_decrease_in_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 20, unit_cost=10)
move2 = self._make_out_move(self.product1, 10)
move1.move_line_ids.qty_done = 10
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(self.product1.quantity_svl, 0)
def test_change_in_past_decrease_in_2(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 20, unit_cost=10)
move2 = self._make_out_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 10)
move1.move_line_ids.qty_done = 10
move4 = self._make_in_move(self.product1, 20, unit_cost=15)
self.assertEqual(self.product1.value_svl, 150)
self.assertEqual(self.product1.quantity_svl, 10)
def test_change_in_past_increase_in_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=15)
move3 = self._make_out_move(self.product1, 20)
move1.move_line_ids.qty_done = 20
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
def test_change_in_past_increase_in_2(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=12)
move3 = self._make_out_move(self.product1, 15)
move4 = self._make_out_move(self.product1, 20)
move5 = self._make_in_move(self.product1, 100, unit_cost=15)
move1.move_line_ids.qty_done = 20
self.assertEqual(self.product1.value_svl, 1375)
self.assertEqual(self.product1.quantity_svl, 95)
def test_change_in_past_increase_out_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 20, unit_cost=10)
move2 = self._make_out_move(self.product1, 10)
move3 = self._make_in_move(self.product1, 20, unit_cost=15)
move2.move_line_ids.qty_done = 25
self.assertEqual(self.product1.value_svl, 225)
self.assertEqual(self.product1.quantity_svl, 15)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 15)
def test_change_in_past_decrease_out_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 20, unit_cost=10)
move2 = self._make_out_move(self.product1, 15)
move3 = self._make_in_move(self.product1, 20, unit_cost=15)
move2.move_line_ids.qty_done = 5
self.assertEqual(self.product1.value_svl, 450)
self.assertEqual(self.product1.quantity_svl, 35)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 35)
def test_change_in_past_add_ml_out_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 20, unit_cost=10)
move2 = self._make_out_move(self.product1, 10)
move3 = self._make_in_move(self.product1, 20, unit_cost=15)
self.env['stock.move.line'].create({
'move_id': move2.id,
'product_id': move2.product_id.id,
'qty_done': 5,
'product_uom_id': move2.product_uom.id,
'location_id': move2.location_id.id,
'location_dest_id': move2.location_dest_id.id,
})
self.assertEqual(self.product1.value_svl, 350)
self.assertEqual(self.product1.quantity_svl, 25)
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 25)
def test_return_delivery_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_out_move(self.product1, 10, create_picking=True)
move3 = self._make_in_move(self.product1, 10, unit_cost=20)
move4 = self._make_return(move2, 10)
self.assertEqual(self.product1.value_svl, 300)
self.assertEqual(self.product1.quantity_svl, 20)
def test_return_receipt_1(self):
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10, create_picking=True)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_return(move1, 2)
self.assertEqual(self.product1.value_svl, 280)
self.assertEqual(self.product1.quantity_svl, 18)
def test_rereturn_receipt_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10, create_picking=True)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
move4 = self._make_return(move1, 1)
move5 = self._make_return(move4, 1)
self.assertEqual(self.product1.value_svl, 20)
self.assertEqual(self.product1.quantity_svl, 1)
def test_rereturn_delivery_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_out_move(self.product1, 1, create_picking=True)
move4 = self._make_return(move3, 1)
move5 = self._make_return(move4, 1)
self.assertEqual(self.product1.value_svl, 10)
self.assertEqual(self.product1.quantity_svl, 1)
def test_dropship_1(self):
move1 = self._make_in_move(self.product1, 1, unit_cost=10)
move2 = self._make_in_move(self.product1, 1, unit_cost=20)
move3 = self._make_dropship_move(self.product1, 1, unit_cost=10)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.product1.quantity_svl, 2)
self.assertAlmostEqual(self.product1.standard_price, 10)
def test_return_delivery_2(self):
self._make_in_move(self.product1, 1, unit_cost=10)
self.product1.standard_price = 0
self._make_in_move(self.product1, 1, unit_cost=0)
self._make_out_move(self.product1, 1)
out_move02 = self._make_out_move(self.product1, 1, create_picking=True)
returned = self._make_return(out_move02, 1)
self.assertEqual(returned.stock_valuation_layer_ids.value, 0)
def test_return_delivery_3(self):
self.product1.write({"standard_price": 1})
move1 = self._make_out_move(self.product1, 10, create_picking=True, force_assign=True)
self._make_in_move(self.product1, 10, unit_cost=2)
self._make_return(move1, 10)
self.assertEqual(self.product1.value_svl, 20)
self.assertEqual(self.product1.quantity_svl, 10)
def test_currency_precision_and_fifo_svl_value(self):
currency = self.env['res.currency'].create({
'name': 'Odoo',
'symbol': 'O',
'rounding': 1,
})
new_company = self.env['res.company'].create({
'name': 'Super Company',
'currency_id': currency.id,
})
old_company = self.env.user.company_id
try:
self.env.user.company_id = new_company
product = self.product1.with_company(new_company)
product.product_tmpl_id.categ_id.property_cost_method = 'fifo'
warehouse = self.env['stock.warehouse'].search([('company_id', '=', new_company.id)])
self._make_in_move(product, 0.5, loc_dest=warehouse.lot_stock_id, pick_type=warehouse.in_type_id, unit_cost=3)
self._make_out_move(product, 0.5, loc_src=warehouse.lot_stock_id, pick_type=warehouse.out_type_id)
self.assertEqual(product.value_svl, 0.0)
finally:
self.env.user.company_id = old_company
class TestStockValuationChangeCostMethod(TestStockValuationCommon):
def test_standard_to_fifo_1(self):
""" The accounting impact of this cost method change is neutral.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 1)
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.assertEqual(self.product1.value_svl, 190)
self.assertEqual(self.product1.quantity_svl, 19)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 5)
for svl in self.product1.stock_valuation_layer_ids.sorted()[-2:]:
self.assertEqual(svl.description, 'Costing method change for product category All: from standard to fifo.')
def test_standard_to_fifo_2(self):
""" We want the same result as `test_standard_to_fifo_1` but by changing the category of
`self.product1` to another one, not changing the current one.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 1)
cat2 = self.env['product.category'].create({'name': 'fifo'})
cat2.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id = cat2
self.assertEqual(self.product1.value_svl, 190)
self.assertEqual(self.product1.quantity_svl, 19)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 5)
def test_avco_to_fifo(self):
""" The accounting impact of this cost method change is neutral.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.assertEqual(self.product1.value_svl, 285)
self.assertEqual(self.product1.quantity_svl, 19)
def test_fifo_to_standard(self):
""" The accounting impact of this cost method change is not neutral as we will use the last
fifo price as the new standard price.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.assertEqual(self.product1.value_svl, 380)
self.assertEqual(self.product1.quantity_svl, 19)
def test_fifo_to_avco(self):
""" The accounting impact of this cost method change is not neutral as we will use the last
fifo price as the new AVCO.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self.assertEqual(self.product1.value_svl, 380)
self.assertEqual(self.product1.quantity_svl, 19)
def test_avco_to_standard(self):
""" The accounting impact of this cost method change is neutral.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
move1 = self._make_in_move(self.product1, 10, unit_cost=10)
move2 = self._make_in_move(self.product1, 10, unit_cost=20)
move3 = self._make_out_move(self.product1, 1)
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.assertEqual(self.product1.value_svl, 285)
self.assertEqual(self.product1.quantity_svl, 19)
def test_standard_to_avco(self):
""" The accounting impact of this cost method change is neutral.
"""
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
move2 = self._make_in_move(self.product1, 10)
move3 = self._make_out_move(self.product1, 1)
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self.assertEqual(self.product1.value_svl, 190)
self.assertEqual(self.product1.quantity_svl, 19)
@tagged('post_install', '-at_install')
class TestStockValuationChangeValuation(TestStockValuationCommon):
@classmethod
def setUpClass(cls):
super(TestStockValuationChangeValuation, cls).setUpClass()
cls.stock_input_account, cls.stock_output_account, cls.stock_valuation_account, cls.expense_account, cls.stock_journal = _create_accounting_data(cls.env)
cls.product1.categ_id.property_valuation = 'real_time'
cls.product1.write({
'property_account_expense_id': cls.expense_account.id,
})
cls.product1.categ_id.write({
'property_stock_account_input_categ_id': cls.stock_input_account.id,
'property_stock_account_output_categ_id': cls.stock_output_account.id,
'property_stock_valuation_account_id': cls.stock_valuation_account.id,
'property_stock_journal': cls.stock_journal.id,
})
def test_standard_manual_to_auto_1(self):
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 0)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 1)
self.product1.product_tmpl_id.categ_id.write({
'property_valuation': 'real_time',
'property_stock_account_input_categ_id': self.stock_input_account.id,
'property_stock_account_output_categ_id': self.stock_output_account.id,
'property_stock_valuation_account_id': self.stock_valuation_account.id,
})
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
# An accounting entry should only be created for the replenish now that the category is perpetual.
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 1)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 3)
for svl in self.product1.stock_valuation_layer_ids.sorted()[-2:]:
self.assertEqual(svl.description, 'Valuation method change for product category All: from manual_periodic to real_time.')
def test_standard_manual_to_auto_2(self):
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 0)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 1)
cat2 = self.env['product.category'].create({'name': 'standard auto'})
cat2.property_cost_method = 'standard'
cat2.property_valuation = 'real_time'
cat2.write({
'property_stock_account_input_categ_id': self.stock_input_account.id,
'property_stock_account_output_categ_id': self.stock_output_account.id,
'property_stock_valuation_account_id': self.stock_valuation_account.id,
'property_stock_journal': self.stock_journal.id,
})
# Try to change the product category with a `default_detailed_type` key in the context and
# check it doesn't break the account move generation.
self.product1.with_context(default_detailed_type='product').categ_id = cat2
self.assertEqual(self.product1.categ_id, cat2)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
# An accounting entry should only be created for the replenish now that the category is perpetual.
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 1)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 3)
def test_standard_auto_to_manual_1(self):
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 1)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 1)
self.product1.product_tmpl_id.categ_id.property_valuation = 'manual_periodic'
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
# An accounting entry should only be created for the emptying now that the category is manual.
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 2)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 3)
def test_standard_auto_to_manual_2(self):
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time'
self.product1.product_tmpl_id.standard_price = 10
move1 = self._make_in_move(self.product1, 10)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 1)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 1)
cat2 = self.env['product.category'].create({'name': 'fifo'})
cat2.property_cost_method = 'standard'
cat2.property_valuation = 'manual_periodic'
self.product1.with_context(debug=True).categ_id = cat2
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
# An accounting entry should only be created for the emptying now that the category is manual.
self.assertEqual(len(self.product1.stock_valuation_layer_ids.mapped('account_move_id')), 2)
self.assertEqual(len(self.product1.stock_valuation_layer_ids), 3)
@tagged('post_install', '-at_install')
class TestAngloSaxonAccounting(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.env.ref('base.EUR').active = True
cls.company_data['company'].anglo_saxon_accounting = True
cls.stock_location = cls.env['stock.location'].create({
'name': 'stock location',
'usage': 'internal',
})
cls.customer_location = cls.env['stock.location'].create({
'name': 'customer location',
'usage': 'customer',
})
cls.supplier_location = cls.env['stock.location'].create({
'name': 'supplier location',
'usage': 'supplier',
})
cls.warehouse_in = cls.env['stock.warehouse'].create({
'name': 'warehouse in',
'company_id': cls.company_data['company'].id,
'code': '1',
})
cls.warehouse_out = cls.env['stock.warehouse'].create({
'name': 'warehouse out',
'company_id': cls.company_data['company'].id,
'code': '2',
})
cls.picking_type_in = cls.env['stock.picking.type'].create({
'name': 'pick type in',
'sequence_code': '1',
'code': 'incoming',
'company_id': cls.company_data['company'].id,
'warehouse_id': cls.warehouse_in.id,
})
cls.picking_type_out = cls.env['stock.picking.type'].create({
'name': 'pick type in',
'sequence_code': '2',
'code': 'outgoing',
'company_id': cls.company_data['company'].id,
'warehouse_id': cls.warehouse_out.id,
})
cls.stock_input_account = cls.env['account.account'].create({
'name': 'Stock Input',
'code': 'StockIn',
'user_type_id': cls.env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
cls.stock_output_account = cls.env['account.account'].create({
'name': 'Stock Output',
'code': 'StockOut',
'user_type_id': cls.env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
cls.stock_valuation_account = cls.env['account.account'].create({
'name': 'Stock Valuation',
'code': 'Stock Valuation',
'user_type_id': cls.env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
cls.expense_account = cls.env['account.account'].create({
'name': 'Expense Account',
'code': 'Expense Account',
'user_type_id': cls.env.ref('account.data_account_type_expenses').id,
'reconcile': True,
})
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.product1 = cls.env['product.product'].create({
'name': 'product1',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
'property_account_expense_id': cls.expense_account.id,
})
cls.product1.categ_id.write({
'property_valuation': 'real_time',
'property_stock_account_input_categ_id': cls.stock_input_account.id,
'property_stock_account_output_categ_id': cls.stock_output_account.id,
'property_stock_valuation_account_id': cls.stock_valuation_account.id,
'property_stock_journal': cls.company_data['default_journal_misc'].id,
})
def _make_in_move(self, product, quantity, unit_cost=None, create_picking=False, loc_dest=None, pick_type=None):
""" Helper to create and validate a receipt move.
"""
unit_cost = unit_cost or product.standard_price
loc_dest = loc_dest or self.stock_location
pick_type = pick_type or self.picking_type_in
in_move = self.env['stock.move'].create({
'name': 'in %s units @ %s per unit' % (str(quantity), str(unit_cost)),
'product_id': product.id,
'location_id': self.supplier_location.id,
'location_dest_id': loc_dest.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': quantity,
'price_unit': unit_cost,
'picking_type_id': pick_type.id,
})
if create_picking:
picking = self.env['stock.picking'].create({
'picking_type_id': in_move.picking_type_id.id,
'location_id': in_move.location_id.id,
'location_dest_id': in_move.location_dest_id.id,
})
in_move.write({'picking_id': picking.id})
in_move._action_confirm()
in_move._action_assign()
in_move.move_line_ids.qty_done = quantity
in_move._action_done()
return in_move.with_context(svl=True)
def test_avco_and_credit_note(self):
"""
When reversing an invoice that contains some anglo-saxo AML, the new anglo-saxo AML should have the same value
"""
self.product1.categ_id.property_cost_method = 'average'
self._make_in_move(self.product1, 2, unit_cost=10)
invoice_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice'))
invoice_form.partner_id = self.env['res.partner'].create({'name': 'Super Client'})
with invoice_form.invoice_line_ids.new() as invoice_line_form:
invoice_line_form.product_id = self.product1
invoice_line_form.quantity = 2
invoice_line_form.price_unit = 25
invoice_line_form.account_id = self.company_data['default_journal_purchase'].default_account_id
invoice_line_form.tax_ids.clear()
invoice = invoice_form.save()
invoice.action_post()
self._make_in_move(self.product1, 2, unit_cost=20)
self.assertEqual(self.product1.standard_price, 15)
refund_wizard = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=invoice.ids).create({
'refund_method': 'refund',
'journal_id': invoice.journal_id.id,
})
action = refund_wizard.reverse_moves()
reverse_invoice = self.env['account.move'].browse(action['res_id'])
with Form(reverse_invoice) as reverse_invoice_form:
with reverse_invoice_form.invoice_line_ids.edit(0) as line:
line.quantity = 1
reverse_invoice.action_post()
anglo_lines = reverse_invoice.line_ids.filtered(lambda l: l.is_anglo_saxon_line)
self.assertEqual(len(anglo_lines), 2)
self.assertEqual(abs(anglo_lines[0].balance), 10)
self.assertEqual(abs(anglo_lines[1].balance), 10)
| 46.61611
| 54,401
|
6,081
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo import fields
@tagged('-at_install', 'post_install')
class ValuationReconciliationTestCommon(AccountTestInvoicingCommon):
""" Base class for tests checking interim accounts reconciliation works
in anglosaxon accounting. It sets up everything we need in the tests, and is
extended in both sale_stock and purchase modules to run the 'true' tests.
"""
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.stock_account_product_categ = cls.env['product.category'].create({
'name': 'Test category',
'property_valuation': 'real_time',
'property_cost_method': 'fifo',
'property_stock_valuation_account_id': cls.company_data['default_account_stock_valuation'].id,
'property_stock_account_input_categ_id': cls.company_data['default_account_stock_in'].id,
'property_stock_account_output_categ_id': cls.company_data['default_account_stock_out'].id,
})
uom_unit = cls.env.ref('uom.product_uom_unit')
cls.test_product_order = cls.env['product.product'].create({
'name': "Test product template invoiced on order",
'standard_price': 42.0,
'type': 'product',
'categ_id': cls.stock_account_product_categ.id,
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
})
cls.test_product_delivery = cls.env['product.product'].create({
'name': 'Test product template invoiced on delivery',
'standard_price': 42.0,
'type': 'product',
'categ_id': cls.stock_account_product_categ.id,
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
})
@classmethod
def setup_company_data(cls, company_name, chart_template=None, **kwargs):
company_data = super().setup_company_data(company_name, chart_template=chart_template, **kwargs)
# Create stock config.
company_data.update({
'default_account_stock_in': cls.env['account.account'].create({
'name': 'default_account_stock_in',
'code': 'STOCKIN',
'reconcile': True,
'user_type_id': cls.env.ref('account.data_account_type_current_assets').id,
'company_id': company_data['company'].id,
}),
'default_account_stock_out': cls.env['account.account'].create({
'name': 'default_account_stock_out',
'code': 'STOCKOUT',
'reconcile': True,
'user_type_id': cls.env.ref('account.data_account_type_current_assets').id,
'company_id': company_data['company'].id,
}),
'default_account_stock_valuation': cls.env['account.account'].create({
'name': 'default_account_stock_valuation',
'code': 'STOCKVAL',
'reconcile': True,
'user_type_id': cls.env.ref('account.data_account_type_current_assets').id,
'company_id': company_data['company'].id,
}),
'default_warehouse': cls.env['stock.warehouse'].search(
[('company_id', '=', company_data['company'].id)],
limit=1,
),
})
return company_data
def check_reconciliation(self, invoice, picking, full_reconcile=True, operation='purchase'):
interim_account_id = self.company_data['default_account_stock_in'].id if operation == 'purchase' else self.company_data['default_account_stock_out'].id
invoice_line = invoice.line_ids.filtered(lambda line: line.account_id.id == interim_account_id)
stock_moves = picking.move_lines
valuation_line = stock_moves.mapped('account_move_ids.line_ids').filtered(lambda x: x.account_id.id == interim_account_id)
if invoice.is_purchase_document() and any(l.is_anglo_saxon_line for l in invoice_line):
self.assertEqual(len(invoice_line), 2, "Only two line2 should have been written by invoice in stock input account")
self.assertTrue(valuation_line.reconciled or invoice_line[0].reconciled or invoice_line[1].reconciled, "The valuation and invoice line should have been reconciled together.")
else:
self.assertEqual(len(invoice_line), 1, "Only one line should have been written by invoice in stock input account")
self.assertTrue(valuation_line.reconciled or invoice_line.reconciled, "The valuation and invoice line should have been reconciled together.")
if invoice.move_type not in ('out_refund', 'in_refund'):
self.assertEqual(len(valuation_line), 1, "Only one line should have been written for stock valuation in stock input account")
if full_reconcile:
self.assertTrue(valuation_line.full_reconcile_id, "The reconciliation should be total at that point.")
else:
self.assertFalse(valuation_line.full_reconcile_id, "The reconciliation should not be total at that point.")
def _process_pickings(self, pickings, date=False, quantity=False):
if not date:
date = fields.Date.today()
pickings.action_confirm()
pickings.action_assign()
for picking in pickings:
for ml in picking.move_line_ids:
ml.qty_done = quantity or ml.product_qty
pickings._action_done()
self._change_pickings_date(pickings, date)
def _change_pickings_date(self, pickings, date):
pickings.mapped('move_lines').write({'date': date})
pickings.mapped('move_lines.account_move_ids').write({'name': '/', 'state': 'draft'})
pickings.mapped('move_lines.account_move_ids').write({'date': date})
pickings.move_lines.account_move_ids.action_post()
| 51.10084
| 6,081
|
10,796
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
from odoo.addons.stock_account.tests.test_stockvaluationlayer import TestStockValuationCommon
class TestStockValuationLayerRevaluation(TestStockValuationCommon):
@classmethod
def setUpClass(cls):
super(TestStockValuationLayerRevaluation, cls).setUpClass()
cls.stock_input_account, cls.stock_output_account, cls.stock_valuation_account, cls.expense_account, cls.stock_journal = _create_accounting_data(cls.env)
cls.product1.write({
'property_account_expense_id': cls.expense_account.id,
})
cls.product1.categ_id.write({
'property_valuation': 'real_time',
'property_stock_account_input_categ_id': cls.stock_input_account.id,
'property_stock_account_output_categ_id': cls.stock_output_account.id,
'property_stock_valuation_account_id': cls.stock_valuation_account.id,
'property_stock_journal': cls.stock_journal.id,
})
cls.product1.categ_id.property_valuation = 'real_time'
def test_stock_valuation_layer_revaluation_avco(self):
self.product1.categ_id.property_cost_method = 'average'
context = {
'default_product_id': self.product1.id,
'default_company_id': self.env.company.id,
'default_added_value': 0.0
}
# Quantity of product1 is zero, raise
with self.assertRaises(UserError):
Form(self.env['stock.valuation.layer.revaluation'].with_context(context)).save()
self._make_in_move(self.product1, 10, unit_cost=2)
self._make_in_move(self.product1, 10, unit_cost=4)
self.assertEqual(self.product1.standard_price, 3)
self.assertEqual(self.product1.quantity_svl, 20)
old_layers = self.env['stock.valuation.layer'].search([('product_id', '=', self.product1.id)], order="create_date desc, id desc")
self.assertEqual(len(old_layers), 2)
self.assertEqual(old_layers[0].remaining_value, 40)
revaluation_wizard = Form(self.env['stock.valuation.layer.revaluation'].with_context(context))
revaluation_wizard.added_value = 20
revaluation_wizard.account_id = self.stock_valuation_account
revaluation_wizard.save().action_validate_revaluation()
# Check standard price change
self.assertEqual(self.product1.standard_price, 4)
self.assertEqual(self.product1.quantity_svl, 20)
# Check the creation of stock.valuation.layer
new_layer = self.env['stock.valuation.layer'].search([('product_id', '=', self.product1.id)], order="create_date desc, id desc", limit=1)
self.assertEqual(new_layer.value, 20)
# Check the remaing value of current layers
self.assertEqual(old_layers[0].remaining_value, 50)
self.assertEqual(sum(slv.remaining_value for slv in old_layers), 80)
# Check account move
self.assertTrue(bool(new_layer.account_move_id))
self.assertEqual(len(new_layer.account_move_id.line_ids), 2)
self.assertEqual(sum(new_layer.account_move_id.line_ids.mapped("debit")), 20)
self.assertEqual(sum(new_layer.account_move_id.line_ids.mapped("credit")), 20)
credit_lines = [l for l in new_layer.account_move_id.line_ids if l.credit > 0]
self.assertEqual(len(credit_lines), 1)
self.assertEqual(credit_lines[0].account_id.id, self.stock_valuation_account.id)
def test_stock_valuation_layer_revaluation_avco_rounding(self):
self.product1.categ_id.property_cost_method = 'average'
context = {
'default_product_id': self.product1.id,
'default_company_id': self.env.company.id,
'default_added_value': 0.0
}
# Quantity of product1 is zero, raise
with self.assertRaises(UserError):
Form(self.env['stock.valuation.layer.revaluation'].with_context(context)).save()
self._make_in_move(self.product1, 1, unit_cost=1)
self._make_in_move(self.product1, 1, unit_cost=1)
self._make_in_move(self.product1, 1, unit_cost=1)
self.assertEqual(self.product1.standard_price, 1)
self.assertEqual(self.product1.quantity_svl, 3)
old_layers = self.env['stock.valuation.layer'].search([('product_id', '=', self.product1.id)], order="create_date desc, id desc")
self.assertEqual(len(old_layers), 3)
self.assertEqual(old_layers[0].remaining_value, 1)
revaluation_wizard = Form(self.env['stock.valuation.layer.revaluation'].with_context(context))
revaluation_wizard.added_value = 1
revaluation_wizard.account_id = self.stock_valuation_account
revaluation_wizard.save().action_validate_revaluation()
# Check standard price change
self.assertEqual(self.product1.standard_price, 1.33)
self.assertEqual(self.product1.quantity_svl, 3)
# Check the creation of stock.valuation.layer
new_layer = self.env['stock.valuation.layer'].search([('product_id', '=', self.product1.id)], order="create_date desc, id desc", limit=1)
self.assertEqual(new_layer.value, 1)
# Check the remaing value of current layers
self.assertEqual(sum(slv.remaining_value for slv in old_layers), 4)
self.assertTrue(1.34 in old_layers.mapped("remaining_value"))
# Check account move
self.assertTrue(bool(new_layer.account_move_id))
self.assertEqual(len(new_layer.account_move_id.line_ids), 2)
self.assertEqual(sum(new_layer.account_move_id.line_ids.mapped("debit")), 1)
self.assertEqual(sum(new_layer.account_move_id.line_ids.mapped("credit")), 1)
credit_lines = [l for l in new_layer.account_move_id.line_ids if l.credit > 0]
self.assertEqual(len(credit_lines), 1)
self.assertEqual(credit_lines[0].account_id.id, self.stock_valuation_account.id)
def test_stock_valuation_layer_revaluation_avco_rounding_2_digits(self):
"""
Check that the rounding of the new price (cost) is equivalent to the rounding of the standard price (cost)
The check is done indirectly via the layers valuations.
If correct => rounding method is correct too
"""
self.product1.categ_id.property_cost_method = 'average'
self.env['decimal.precision'].search([
('name', '=', 'Product Price'),
]).digits = 2
self.product1.write({'standard_price': 0})
# First Move
self.product1.write({'standard_price': 0.022})
self._make_in_move(self.product1, 10000)
self.assertEqual(self.product1.standard_price, 0.02)
self.assertEqual(self.product1.quantity_svl, 10000)
layer = self.product1.stock_valuation_layer_ids
self.assertEqual(layer.value, 200)
# Second Move
self.product1.write({'standard_price': 0.053})
self.assertEqual(self.product1.standard_price, 0.05)
self.assertEqual(self.product1.quantity_svl, 10000)
layers = self.product1.stock_valuation_layer_ids
self.assertEqual(layers[0].value, 200)
self.assertEqual(layers[1].value, 300)
def test_stock_valuation_layer_revaluation_avco_rounding_5_digits(self):
"""
Check that the rounding of the new price (cost) is equivalent to the rounding of the standard price (cost)
The check is done indirectly via the layers valuations.
If correct => rounding method is correct too
"""
self.product1.categ_id.property_cost_method = 'average'
self.env['decimal.precision'].search([
('name', '=', 'Product Price'),
]).digits = 5
# First Move
self.product1.write({'standard_price': 0.00875})
self._make_in_move(self.product1, 10000)
self.assertEqual(self.product1.standard_price, 0.00875)
self.assertEqual(self.product1.quantity_svl, 10000)
layer = self.product1.stock_valuation_layer_ids
self.assertEqual(layer.value, 87.5)
# Second Move
self.product1.write({'standard_price': 0.00975})
self.assertEqual(self.product1.standard_price, 0.00975)
self.assertEqual(self.product1.quantity_svl, 10000)
layers = self.product1.stock_valuation_layer_ids
self.assertEqual(layers[0].value, 87.5)
self.assertEqual(layers[1].value, 10)
def test_stock_valuation_layer_revaluation_fifo(self):
self.product1.categ_id.property_cost_method = 'fifo'
context = {
'default_product_id': self.product1.id,
'default_company_id': self.env.company.id,
'default_added_value': 0.0
}
# Quantity of product1 is zero, raise
with self.assertRaises(UserError):
Form(self.env['stock.valuation.layer.revaluation'].with_context(context)).save()
self._make_in_move(self.product1, 10, unit_cost=2)
self._make_in_move(self.product1, 10, unit_cost=4)
self.assertEqual(self.product1.standard_price, 2)
self.assertEqual(self.product1.quantity_svl, 20)
old_layers = self.env['stock.valuation.layer'].search([('product_id', '=', self.product1.id)], order="create_date desc, id desc")
self.assertEqual(len(old_layers), 2)
self.assertEqual(old_layers[0].remaining_value, 40)
revaluation_wizard = Form(self.env['stock.valuation.layer.revaluation'].with_context(context))
revaluation_wizard.added_value = 20
revaluation_wizard.account_id = self.stock_valuation_account
revaluation_wizard.save().action_validate_revaluation()
self.assertEqual(self.product1.standard_price, 2)
# Check the creation of stock.valuation.layer
new_layer = self.env['stock.valuation.layer'].search([('product_id', '=', self.product1.id)], order="create_date desc, id desc", limit=1)
self.assertEqual(new_layer.value, 20)
# Check the remaing value of current layers
self.assertEqual(old_layers[0].remaining_value, 50)
self.assertEqual(sum(slv.remaining_value for slv in old_layers), 80)
# Check account move
self.assertTrue(bool(new_layer.account_move_id))
self.assertTrue(len(new_layer.account_move_id.line_ids), 2)
self.assertEqual(sum(new_layer.account_move_id.line_ids.mapped("debit")), 20)
self.assertEqual(sum(new_layer.account_move_id.line_ids.mapped("credit")), 20)
credit_lines = [l for l in new_layer.account_move_id.line_ids if l.credit > 0]
self.assertEqual(len(credit_lines), 1)
| 45.171548
| 10,796
|
173,485
|
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.exceptions import UserError
from odoo.fields import Datetime
from odoo.tests.common import Form, TransactionCase
def _create_accounting_data(env):
"""Create the accounts and journals used in stock valuation.
:param env: environment used to create the records
:return: an input account, an output account, a valuation account, an expense account, a stock journal
"""
stock_input_account = env['account.account'].create({
'name': 'Stock Input',
'code': 'StockIn',
'user_type_id': env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
stock_output_account = env['account.account'].create({
'name': 'Stock Output',
'code': 'StockOut',
'user_type_id': env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
stock_valuation_account = env['account.account'].create({
'name': 'Stock Valuation',
'code': 'Stock Valuation',
'user_type_id': env.ref('account.data_account_type_current_assets').id,
'reconcile': True,
})
expense_account = env['account.account'].create({
'name': 'Expense Account',
'code': 'Expense Account',
'user_type_id': env.ref('account.data_account_type_expenses').id,
'reconcile': True,
})
stock_journal = env['account.journal'].create({
'name': 'Stock Journal',
'code': 'STJTEST',
'type': 'general',
})
return stock_input_account, stock_output_account, stock_valuation_account, expense_account, stock_journal
class TestStockValuation(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestStockValuation, cls).setUpClass()
cls.env.ref('base.EUR').active = True
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.supplier_location = cls.env.ref('stock.stock_location_suppliers')
cls.partner = cls.env['res.partner'].create({'name': 'xxx'})
cls.owner1 = cls.env['res.partner'].create({'name': 'owner1'})
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.product1 = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'default_code': 'prda',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product2 = cls.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.inventory_user = cls.env['res.users'].create({
'name': 'Pauline Poivraisselle',
'login': 'pauline',
'email': 'p.p@example.com',
'notification_type': 'inbox',
'groups_id': [(6, 0, [cls.env.ref('stock.group_stock_user').id])]
})
cls.stock_input_account, cls.stock_output_account, cls.stock_valuation_account, cls.expense_account, cls.stock_journal = _create_accounting_data(cls.env)
cls.product1.categ_id.property_valuation = 'real_time'
cls.product2.categ_id.property_valuation = 'real_time'
cls.product1.write({
'property_account_expense_id': cls.expense_account.id,
})
cls.product1.categ_id.write({
'property_stock_account_input_categ_id': cls.stock_input_account.id,
'property_stock_account_output_categ_id': cls.stock_output_account.id,
'property_stock_valuation_account_id': cls.stock_valuation_account.id,
'property_stock_journal': cls.stock_journal.id,
})
def _get_stock_input_move_lines(self):
return self.env['account.move.line'].search([
('account_id', '=', self.stock_input_account.id),
], order='date, id')
def _get_stock_output_move_lines(self):
return self.env['account.move.line'].search([
('account_id', '=', self.stock_output_account.id),
], order='date, id')
def _get_stock_valuation_move_lines(self):
return self.env['account.move.line'].search([
('account_id', '=', self.stock_valuation_account.id),
], order='date, id')
def _make_in_move(self, product, quantity, unit_cost=None):
""" Helper to create and validate a receipt move.
"""
unit_cost = unit_cost or product.standard_price
in_move = self.env['stock.move'].create({
'name': 'in %s units @ %s per unit' % (str(quantity), str(unit_cost)),
'product_id': product.id,
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': self.env.ref('stock.stock_location_stock').id,
'product_uom': self.env.ref('uom.product_uom_unit').id,
'product_uom_qty': quantity,
'price_unit': unit_cost,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
in_move._action_confirm()
in_move._action_assign()
in_move.move_line_ids.qty_done = quantity
in_move._action_done()
return in_move.with_context(svl=True)
def _make_out_move(self, product, quantity):
""" Helper to create and validate a delivery move.
"""
out_move = self.env['stock.move'].create({
'name': 'out %s units' % str(quantity),
'product_id': product.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'product_uom': self.env.ref('uom.product_uom_unit').id,
'product_uom_qty': quantity,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
out_move._action_confirm()
out_move._action_assign()
out_move.move_line_ids.qty_done = quantity
out_move._action_done()
return out_move.with_context(svl=True)
def test_realtime(self):
""" Stock moves update stock value with product x cost price,
price change updates the stock value based on current stock level.
"""
# Enter 10 products while price is 5.0
self.product1.standard_price = 5.0
move1 = self.env['stock.move'].create({
'name': 'IN 10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
# Set price to 6.0
self.product1.standard_price = 6.0
stock_aml, price_change_aml = self._get_stock_valuation_move_lines()
self.assertEqual(stock_aml.debit, 50)
self.assertEqual(price_change_aml.debit, 10)
self.assertEqual(price_change_aml.ref, 'prda')
self.assertEqual(price_change_aml.product_id, self.product1)
def test_realtime_consumable(self):
""" An automatic consumable product should not create any account move entries"""
# Enter 10 products while price is 5.0
self.product1.standard_price = 5.0
self.product1.type = 'consu'
move1 = self.env['stock.move'].create({
'name': 'IN 10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
self.assertTrue(move1.stock_valuation_layer_ids)
self.assertFalse(move1.stock_valuation_layer_ids.account_move_id)
def test_fifo_perpetual_1(self):
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# receive 10 units @ 10.00 per unit
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': 'IN 10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
# stock_account values for move1
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
# account values for move1
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 1)
move1_input_aml = input_aml[-1]
self.assertEqual(move1_input_aml.debit, 0)
self.assertEqual(move1_input_aml.credit, 100)
valuation_aml = self._get_stock_valuation_move_lines()
move1_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 1)
self.assertEqual(move1_valuation_aml.debit, 100)
self.assertEqual(move1_valuation_aml.credit, 0)
self.assertEqual(move1_valuation_aml.product_id.id, self.product1.id)
self.assertEqual(move1_valuation_aml.quantity, 10)
self.assertEqual(move1_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
self.assertEqual(len(output_aml), 0)
# ---------------------------------------------------------------------
# receive 10 units @ 8.00 per unit
# ---------------------------------------------------------------------
move2 = self.env['stock.move'].create({
'name': 'IN 10 units @ 8.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 8.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
# stock_account values for move2
self.assertEqual(move2.stock_valuation_layer_ids.unit_cost, 8.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move2.stock_valuation_layer_ids.value, 80.0)
# account values for move2
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 2)
move2_input_aml = input_aml[-1]
self.assertEqual(move2_input_aml.debit, 0)
self.assertEqual(move2_input_aml.credit, 80)
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 2)
self.assertEqual(move2_valuation_aml.debit, 80)
self.assertEqual(move2_valuation_aml.credit, 0)
self.assertEqual(move2_valuation_aml.product_id.id, self.product1.id)
self.assertEqual(move2_valuation_aml.quantity, 10)
self.assertEqual(move2_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
self.assertEqual(len(output_aml), 0)
# ---------------------------------------------------------------------
# sale 3 units
# ---------------------------------------------------------------------
move3 = self.env['stock.move'].create({
'name': 'Sale 3 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 3.0
move3._action_done()
# stock_account values for move3
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out move
self.assertEqual(move3.stock_valuation_layer_ids.value, -30.0) # took 3 items from move 1 @ 10.00 per unit
# account values for move3
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 2)
valuation_aml = self._get_stock_valuation_move_lines()
move3_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 3)
self.assertEqual(move3_valuation_aml.debit, 0)
self.assertEqual(move3_valuation_aml.credit, 30)
self.assertEqual(move3_valuation_aml.product_id.id, self.product1.id)
# FIXME sle
#self.assertEqual(move3_valuation_aml.quantity, -3)
self.assertEqual(move3_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
move3_output_aml = output_aml[-1]
self.assertEqual(len(output_aml), 1)
self.assertEqual(move3_output_aml.debit, 30)
self.assertEqual(move3_output_aml.credit, 0)
# ---------------------------------------------------------------------
# Increase received quantity of move1 from 10 to 12, it should create
# a new stock layer at the top of the queue.
# ---------------------------------------------------------------------
move1.quantity_done = 12
# stock_account values for move3
self.assertEqual(move1.stock_valuation_layer_ids.sorted()[-1].unit_cost, 10.0)
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('remaining_qty')), 9.0)
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('value')), 120.0) # move 1 is now 10@10 + 2@10
# account values for move1
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 3)
move1_correction_input_aml = input_aml[-1]
self.assertEqual(move1_correction_input_aml.debit, 0)
self.assertEqual(move1_correction_input_aml.credit, 20)
valuation_aml = self._get_stock_valuation_move_lines()
move1_correction_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 4)
self.assertEqual(move1_correction_valuation_aml.debit, 20)
self.assertEqual(move1_correction_valuation_aml.credit, 0)
self.assertEqual(move1_correction_valuation_aml.product_id.id, self.product1.id)
self.assertEqual(move1_correction_valuation_aml.quantity, 2)
self.assertEqual(move1_correction_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
self.assertEqual(len(output_aml), 1)
# ---------------------------------------------------------------------
# Sale 9 units, the units available from the previous increase are not sent
# immediately as the new layer is at the top of the queue.
# ---------------------------------------------------------------------
move4 = self.env['stock.move'].create({
'name': 'Sale 9 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 9.0,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 9.0
move4._action_done()
# stock_account values for move4
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out move
self.assertEqual(move4.stock_valuation_layer_ids.value, -86.0) # took 9 items from move 1 @ 10.00 per unit
# account values for move4
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 3)
valuation_aml = self._get_stock_valuation_move_lines()
move4_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 5)
self.assertEqual(move4_valuation_aml.debit, 0)
self.assertEqual(move4_valuation_aml.credit, 86)
self.assertEqual(move4_valuation_aml.product_id.id, self.product1.id)
# FIXME sle
#self.assertEqual(move4_valuation_aml.quantity, -9)
self.assertEqual(move4_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
move4_output_aml = output_aml[-1]
self.assertEqual(len(output_aml), 2)
self.assertEqual(move4_output_aml.debit, 86)
self.assertEqual(move4_output_aml.credit, 0)
# ---------------------------------------------------------------------
# Sale 20 units, we fall in negative stock for 10 units. Theses are
# valued at the last FIFO cost and the total is negative.
# ---------------------------------------------------------------------
move5 = self.env['stock.move'].create({
'name': 'Sale 20 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 20.0,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 20.0
move5._action_done()
# stock_account values for move5
# (took 8 from the second receipt and 2 from the increase of the first receipt)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, -10.0)
self.assertEqual(move5.stock_valuation_layer_ids.value, -184.0)
# account values for move5
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 3)
valuation_aml = self._get_stock_valuation_move_lines()
move5_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 6)
self.assertEqual(move5_valuation_aml.debit, 0)
self.assertEqual(move5_valuation_aml.credit, 184)
self.assertEqual(move5_valuation_aml.product_id.id, self.product1.id)
#self.assertEqual(move5_valuation_aml.quantity, -20)
self.assertEqual(move5_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
move5_output_aml = output_aml[-1]
self.assertEqual(len(output_aml), 3)
self.assertEqual(move5_output_aml.debit, 184)
self.assertEqual(move5_output_aml.credit, 0)
# ---------------------------------------------------------------------
# Receive 10 units @ 12.00 to counterbalance the negative, the vacuum
# will be called directly: 10@10 should be revalued 10@12
# ---------------------------------------------------------------------
move6 = self.env['stock.move'].create({
'name': 'IN 10 units @ 12.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 12.0,
})
move6._action_confirm()
move6._action_assign()
move6.move_line_ids.qty_done = 10.0
move6._action_done()
# stock_account values for move6
self.assertEqual(move6.stock_valuation_layer_ids.unit_cost, 12.0)
self.assertEqual(move6.stock_valuation_layer_ids.remaining_qty, 0.0) # already consumed by the next vacuum
self.assertEqual(move6.stock_valuation_layer_ids.value, 120)
# vacuum aml, 10@10 should have been 10@12, get rid of 20
valuation_aml = self._get_stock_valuation_move_lines()
vacuum_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 8)
self.assertEqual(vacuum_valuation_aml.balance, -20)
self.assertEqual(vacuum_valuation_aml.product_id.id, self.product1.id)
self.assertEqual(vacuum_valuation_aml.quantity, 0)
self.assertEqual(vacuum_valuation_aml.product_uom_id.id, self.uom_unit.id)
output_aml = self._get_stock_output_move_lines()
vacuum_output_aml = output_aml[-1]
self.assertEqual(len(output_aml), 4)
self.assertEqual(vacuum_output_aml.balance, 20)
# ---------------------------------------------------------------------
# Edit move6, receive less: 2 in negative stock
# ---------------------------------------------------------------------
move6.quantity_done = 8
# stock_account values for move6
self.assertEqual(move6.stock_valuation_layer_ids.sorted()[-1].remaining_qty, -2)
self.assertEqual(move6.stock_valuation_layer_ids.sorted()[-1].value, -20)
# account values for move1
input_aml = self._get_stock_input_move_lines()
move6_correction_input_aml = input_aml[-1]
self.assertEqual(move6_correction_input_aml.debit, 20)
self.assertEqual(move6_correction_input_aml.credit, 0)
valuation_aml = self._get_stock_valuation_move_lines()
move6_correction_valuation_aml = valuation_aml[-1]
self.assertEqual(move6_correction_valuation_aml.debit, 0)
self.assertEqual(move6_correction_valuation_aml.credit, 20)
self.assertEqual(move6_correction_valuation_aml.product_id.id, self.product1.id)
# FIXME sle
#self.assertEqual(move6_correction_valuation_aml.quantity, -2)
self.assertEqual(move6_correction_valuation_aml.product_uom_id.id, self.uom_unit.id)
# -----------------------------------------------------------
# receive 4 to counterbalance now
# -----------------------------------------------------------
move7 = self.env['stock.move'].create({
'name': 'IN 4 units @ 15.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
'price_unit': 15.0,
})
move7._action_confirm()
move7._action_assign()
move7.move_line_ids.qty_done = 4.0
move7._action_done()
# account values after vacuum
input_aml = self._get_stock_input_move_lines()
self.assertEqual(len(input_aml), 7)
move6_correction2_input_aml = input_aml[-1]
self.assertEqual(move6_correction2_input_aml.debit, 10)
self.assertEqual(move6_correction2_input_aml.credit, 0)
valuation_aml = self._get_stock_valuation_move_lines()
move6_correction2_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 11)
self.assertEqual(move6_correction2_valuation_aml.debit, 0)
self.assertEqual(move6_correction2_valuation_aml.credit, 10)
self.assertEqual(move6_correction2_valuation_aml.product_id.id, self.product1.id)
self.assertEqual(move6_correction2_valuation_aml.quantity, 0)
self.assertEqual(move6_correction_valuation_aml.product_uom_id.id, self.uom_unit.id)
# ---------------------------------------------------------------------
# Ending
# ---------------------------------------------------------------------
self.assertEqual(self.product1.quantity_svl, 2)
self.assertEqual(self.product1.value_svl, 30)
# check on accounting entries
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 30)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 380)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 380)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 350)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 320)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
def test_fifo_perpetual_2(self):
""" Normal fifo flow (no negative handling) """
# http://accountingexplained.com/financial/inventories/fifo-method
self.product1.categ_id.property_cost_method = 'fifo'
# Beginning Inventory: 68 units @ 15.00 per unit
move1 = self.env['stock.move'].create({
'name': '68 units @ 15.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 68.0,
'price_unit': 15,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 68.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 1020.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 68.0)
# Purchase 140 units @ 15.50 per unit
move2 = self.env['stock.move'].create({
'name': '140 units @ 15.50 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 140.0,
'price_unit': 15.50,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 140.0
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, 2170.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 68.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 140.0)
# Sale 94 units @ 19.00 per unit
move3 = self.env['stock.move'].create({
'name': 'Sale 94 units @ 19.00 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 94.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 94.0
move3._action_done()
# note: it' ll have to get 68 units from the first batch and 26 from the second one
# so its value should be -((68*15) + (26*15.5)) = -1423
self.assertEqual(move3.stock_valuation_layer_ids.value, -1423.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 114)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
# Purchase 40 units @ 16.00 per unit
move4 = self.env['stock.move'].create({
'name': '140 units @ 15.50 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 40.0,
'price_unit': 16,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 40.0
move4._action_done()
self.assertEqual(move4.stock_valuation_layer_ids.value, 640.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 114)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 40.0)
# Purchase 78 units @ 16.50 per unit
move5 = self.env['stock.move'].create({
'name': 'Purchase 78 units @ 16.50 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 78.0,
'price_unit': 16.5,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 78.0
move5._action_done()
self.assertEqual(move5.stock_valuation_layer_ids.value, 1287.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 114)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 40.0)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, 78.0)
# Sale 116 units @ 19.50 per unit
move6 = self.env['stock.move'].create({
'name': 'Sale 116 units @ 19.50 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 116.0,
})
move6._action_confirm()
move6._action_assign()
move6.move_line_ids.qty_done = 116.0
move6._action_done()
# note: it' ll have to get 114 units from the move2 and 2 from move4
# so its value should be -((114*15.5) + (2*16)) = 1735
self.assertEqual(move6.stock_valuation_layer_ids.value, -1799.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 38.0)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, 78.0)
self.assertEqual(move6.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
# Sale 62 units @ 21 per unit
move7 = self.env['stock.move'].create({
'name': 'Sale 62 units @ 21 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 62.0,
})
move7._action_confirm()
move7._action_assign()
move7.move_line_ids.qty_done = 62.0
move7._action_done()
# note: it' ll have to get 38 units from the move4 and 24 from move5
# so its value should be -((38*16) + (24*16.5)) = 608 + 396
self.assertEqual(move7.stock_valuation_layer_ids.value, -1004.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, 54.0)
self.assertEqual(move6.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move7.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
# send 10 units in our transit location, the valorisation should not be impacted
transit_location = self.env['stock.location'].search([
('company_id', '=', self.env.company.id),
('usage', '=', 'transit'),
('active', '=', False)
], limit=1)
transit_location.active = True
move8 = self.env['stock.move'].create({
'name': 'Send 10 units in transit',
'location_id': self.stock_location.id,
'location_dest_id': transit_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move8._action_confirm()
move8._action_assign()
move8.move_line_ids.qty_done = 10.0
move8._action_done()
self.assertEqual(move8.stock_valuation_layer_ids.value, 0.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, 54.0)
self.assertEqual(move6.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move7.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move8.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in internal moves
# Sale 10 units @ 16.5 per unit
move9 = self.env['stock.move'].create({
'name': 'Sale 10 units @ 16.5 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move9._action_confirm()
move9._action_assign()
move9.move_line_ids.qty_done = 10.0
move9._action_done()
# note: it' ll have to get 10 units from move5 so its value should
# be -(10*16.50) = -165
self.assertEqual(move9.stock_valuation_layer_ids.value, -165.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, 44.0)
self.assertEqual(move6.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move7.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move8.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in internal moves
self.assertEqual(move9.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
def test_fifo_perpetual_3(self):
""" Normal fifo flow (no negative handling) """
self.product1.categ_id.property_cost_method = 'fifo'
# in 10 @ 100
move1 = self.env['stock.move'].create({
'name': 'in 10 @ 100',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 100,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 1000.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
# in 10 @ 80
move2 = self.env['stock.move'].create({
'name': 'in 10 @ 80',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 80,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, 800.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 10.0)
# out 15
move3 = self.env['stock.move'].create({
'name': 'out 15',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 15.0
move3._action_done()
# note: it' ll have to get 10 units from move1 and 5 from move2
# so its value should be -((10*100) + (5*80)) = -1423
self.assertEqual(move3.stock_valuation_layer_ids.value, -1400.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 5)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
# in 5 @ 60
move4 = self.env['stock.move'].create({
'name': 'in 5 @ 60',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
'price_unit': 60,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 5.0
move4._action_done()
self.assertEqual(move4.stock_valuation_layer_ids.value, 300.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 5)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 5.0)
# out 7
move5 = self.env['stock.move'].create({
'name': 'out 7',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 7.0,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 7.0
move5._action_done()
# note: it' ll have to get 5 units from the move2 and 2 from move4
# so its value should be -((5*80) + (2*60)) = 520
self.assertEqual(move5.stock_valuation_layer_ids.value, -520.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 3.0)
self.assertEqual(move5.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
def test_fifo_perpetual_4(self):
""" Fifo and return handling. """
self.product1.categ_id.property_cost_method = 'fifo'
# in 8 @ 10
move1 = self.env['stock.move'].create({
'name': 'in 8 @ 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 8.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 8.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 80.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 8.0)
# in 4 @ 16
move2 = self.env['stock.move'].create({
'name': 'in 4 @ 16',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
'price_unit': 16,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 4.0
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, 64)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 4.0)
# out 10
out_pick = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': self.env['res.partner'].search([], limit=1).id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move3 = self.env['stock.move'].create({
'name': 'out 10',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'picking_id': out_pick.id,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 10.0
move3._action_done()
# note: it' ll have to get 8 units from move1 and 2 from move2
# so its value should be -((8*10) + (2*16)) = -116
self.assertEqual(move3.stock_valuation_layer_ids.value, -112.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 2)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
# in 2 @ 6
move4 = self.env['stock.move'].create({
'name': 'in 2 @ 6',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'price_unit': 6,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 2.0
move4._action_done()
self.assertEqual(move4.stock_valuation_layer_ids.value, 12.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 2)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in out moves
self.assertEqual(move4.stock_valuation_layer_ids.remaining_qty, 2.0)
self.assertEqual(self.product1.standard_price, 16)
# return
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=out_pick.ids, active_id=out_pick.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 1.0 # Return only 2
stock_return_picking_action = stock_return_picking.create_returns()
return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_pick.move_lines[0].move_line_ids[0].qty_done = 1.0
return_pick.with_user(self.inventory_user)._action_done()
self.assertEqual(self.product1.standard_price, 16)
self.assertAlmostEqual(return_pick.move_lines.stock_valuation_layer_ids.unit_cost, 11.2)
def test_fifo_negative_1(self):
""" Send products that you do not have. Value the first outgoing move to the standard
price, receive in multiple times the delivered quantity and run _fifo_vacuum to compensate.
"""
self.product1.categ_id.property_cost_method = 'fifo'
# We expect the user to set manually set a standard price to its products if its first
# transfer is sending products that he doesn't have.
self.product1.product_tmpl_id.standard_price = 8.0
# ---------------------------------------------------------------------
# Send 50 units you don't have
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': '50 out',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 50.0,
'price_unit': 0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 50.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, -400.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, -50.0) # normally unused in out moves, but as it moved negative stock we mark it
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 8)
# account values for move1
valuation_aml = self._get_stock_valuation_move_lines()
move1_valuation_aml = valuation_aml[-1]
self.assertEqual(move1_valuation_aml.debit, 0)
self.assertEqual(move1_valuation_aml.credit, 400)
output_aml = self._get_stock_output_move_lines()
move1_output_aml = output_aml[-1]
self.assertEqual(move1_output_aml.debit, 400)
self.assertEqual(move1_output_aml.credit, 0)
# ---------------------------------------------------------------------
# Receive 40 units @ 15
# ---------------------------------------------------------------------
move2 = self.env['stock.move'].create({
'name': '40 in @15',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 40.0,
'price_unit': 15.0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 40.0,
})]
})
move2._action_confirm()
move2._action_done()
# stock values for move2
self.assertEqual(move2.stock_valuation_layer_ids.value, 600.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0)
self.assertEqual(move2.stock_valuation_layer_ids.unit_cost, 15.0)
# ---------------------------------------------------------------------
# The vacuum ran
# ---------------------------------------------------------------------
# account values after vacuum
valuation_aml = self._get_stock_valuation_move_lines()
vacuum1_valuation_aml = valuation_aml[-1]
self.assertEqual(vacuum1_valuation_aml.debit, 0)
# 280 was credited more in valuation (we compensated 40 items here, so initially 40 were
# valued at 8 -> 320 in credit but now we actually sent 40@15 = 600, so the difference is
# 280 more credited)
self.assertEqual(vacuum1_valuation_aml.credit, 280)
output_aml = self._get_stock_output_move_lines()
vacuum1_output_aml = output_aml[-1]
self.assertEqual(vacuum1_output_aml.debit, 280)
self.assertEqual(vacuum1_output_aml.credit, 0)
# ---------------------------------------------------------------------
# Receive 20 units @ 25
# ---------------------------------------------------------------------
move3 = self.env['stock.move'].create({
'name': '20 in @25',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 20.0,
'price_unit': 25.0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 20.0
})]
})
move3._action_confirm()
move3._action_done()
# ---------------------------------------------------------------------
# The vacuum ran
# ---------------------------------------------------------------------
# stock values for move1-3
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('value')), -850.0) # 40@15 + 10@25
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('remaining_qty')), 0.0)
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('value')), 600.0)
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('remaining_qty')), 0.0)
self.assertEqual(sum(move3.stock_valuation_layer_ids.mapped('value')), 500.0)
self.assertEqual(sum(move3.stock_valuation_layer_ids.mapped('remaining_qty')), 10.0)
# account values after vacuum
valuation_aml = self._get_stock_valuation_move_lines()
vacuum2_valuation_aml = valuation_aml[-1]
self.assertEqual(vacuum2_valuation_aml.debit, 0)
# there is still 10@8 to compensate with 10@25 -> 170 to credit more in the valuation account
self.assertEqual(vacuum2_valuation_aml.credit, 170)
output_aml = self._get_stock_output_move_lines()
vacuum2_output_aml = output_aml[-1]
self.assertEqual(vacuum2_output_aml.debit, 170)
self.assertEqual(vacuum2_output_aml.credit, 0)
# ---------------------------------------------------------------------
# Ending
# ---------------------------------------------------------------------
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.value_svl, 250)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 1100)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 1100)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 850)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 850)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
def test_fifo_negative_2(self):
""" Receives 10 units, send more, the extra quantity should be valued at the last fifo
price, running the vacuum should not do anything. Receive 2 units at the price the two
extra units were sent, check that no accounting entries are created.
"""
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# Receive 10@10
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': '10 in',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
# account values for move1
valuation_aml = self._get_stock_valuation_move_lines()
move1_valuation_aml = valuation_aml[-1]
self.assertEqual(move1_valuation_aml.debit, 100)
self.assertEqual(move1_valuation_aml.credit, 0)
input_aml = self._get_stock_input_move_lines()
move1_input_aml = input_aml[-1]
self.assertEqual(move1_input_aml.debit, 0)
self.assertEqual(move1_input_aml.credit, 100)
self.assertEqual(len(move1.account_move_ids), 1)
# ---------------------------------------------------------------------
# Send 12
# ---------------------------------------------------------------------
move2 = self.env['stock.move'].create({
'name': '12 out (2 negative)',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12.0,
'price_unit': 0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 12.0,
})]
})
move2._action_confirm()
move2._action_done()
# stock values for move2
self.assertEqual(move2.stock_valuation_layer_ids.value, -120.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, -2.0)
# account values for move2
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(move2_valuation_aml.debit, 0)
self.assertEqual(move2_valuation_aml.credit, 120)
output_aml = self._get_stock_output_move_lines()
move2_output_aml = output_aml[-1]
self.assertEqual(move2_output_aml.debit, 120)
self.assertEqual(move2_output_aml.credit, 0)
self.assertEqual(len(move2.account_move_ids), 1)
# ---------------------------------------------------------------------
# Run the vacuum
# ---------------------------------------------------------------------
self.product1._run_fifo_vacuum()
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
self.assertEqual(move2.stock_valuation_layer_ids.value, -120.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, -2.0)
self.assertEqual(len(move1.account_move_ids), 1)
self.assertEqual(len(move2.account_move_ids), 1)
self.assertEqual(self.product1.quantity_svl, -2)
self.assertEqual(self.product1.value_svl, -20)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 100)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 100)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 120)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 120)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
# Now receive exactly the extra units at exactly the price sent, no
# accounting entries should be created after the vacuum.
# ---------------------------------------------------------------------
# Receive 2@10
# ---------------------------------------------------------------------
move3 = self.env['stock.move'].create({
'name': '10 in',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 2.0,
})]
})
move3._action_confirm()
move3._action_done()
# ---------------------------------------------------------------------
# Ending
# ---------------------------------------------------------------------
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('value')), -120.0)
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('remaining_qty')), 0)
self.assertEqual(move3.stock_valuation_layer_ids.value, 20)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move3.stock_valuation_layer_ids.unit_cost, 10.0)
self.assertEqual(len(move1.account_move_ids), 1)
self.assertEqual(len(move2.account_move_ids), 1)
self.assertEqual(len(move3.account_move_ids), 1) # the created account move is due to the receipt
# nothing should have changed in the accounting regarding the output
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.value_svl, 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 120)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 120)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 120)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 120)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
def test_fifo_negative_3(self):
""" Receives 10 units, send 10 units, then send more: the extra quantity should be valued
at the last fifo price, running the vacuum should not do anything.
"""
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# Receive 10@10
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': '10 in',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
# account values for move1
valuation_aml = self._get_stock_valuation_move_lines()
move1_valuation_aml = valuation_aml[-1]
self.assertEqual(move1_valuation_aml.debit, 100)
self.assertEqual(move1_valuation_aml.credit, 0)
input_aml = self._get_stock_input_move_lines()
move1_input_aml = input_aml[-1]
self.assertEqual(move1_input_aml.debit, 0)
self.assertEqual(move1_input_aml.credit, 100)
self.assertEqual(len(move1.account_move_ids), 1)
# ---------------------------------------------------------------------
# Send 10
# ---------------------------------------------------------------------
move2 = self.env['stock.move'].create({
'name': '10 out',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move2._action_confirm()
move2._action_done()
# stock values for move2
self.assertEqual(move2.stock_valuation_layer_ids.value, -100.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0.0)
# account values for move2
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(move2_valuation_aml.debit, 0)
self.assertEqual(move2_valuation_aml.credit, 100)
output_aml = self._get_stock_output_move_lines()
move2_output_aml = output_aml[-1]
self.assertEqual(move2_output_aml.debit, 100)
self.assertEqual(move2_output_aml.credit, 0)
self.assertEqual(len(move2.account_move_ids), 1)
# ---------------------------------------------------------------------
# Send 21
# ---------------------------------------------------------------------
# FIXME sle last fifo price not updated on the product?
move3 = self.env['stock.move'].create({
'name': '10 in',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 21.0,
'price_unit': 0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 21.0,
})]
})
move3._action_confirm()
move3._action_done()
# stock values for move3
self.assertEqual(move3.stock_valuation_layer_ids.value, -210.0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, -21.0)
# account values for move3
valuation_aml = self._get_stock_valuation_move_lines()
move3_valuation_aml = valuation_aml[-1]
self.assertEqual(move3_valuation_aml.debit, 0)
self.assertEqual(move3_valuation_aml.credit, 210)
output_aml = self._get_stock_output_move_lines()
move3_output_aml = output_aml[-1]
self.assertEqual(move3_output_aml.debit, 210)
self.assertEqual(move3_output_aml.credit, 0)
self.assertEqual(len(move3.account_move_ids), 1)
# ---------------------------------------------------------------------
# Run the vacuum
# ---------------------------------------------------------------------
self.product1._run_fifo_vacuum()
self.assertEqual(len(move3.account_move_ids), 1)
# the vacuum shouldn't do anything in this case
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
self.assertEqual(move2.stock_valuation_layer_ids.value, -100.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move3.stock_valuation_layer_ids.value, -210.0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, -21.0)
self.assertEqual(len(move1.account_move_ids), 1)
self.assertEqual(len(move2.account_move_ids), 1)
self.assertEqual(len(move3.account_move_ids), 1)
# ---------------------------------------------------------------------
# Ending
# ---------------------------------------------------------------------
self.assertEqual(self.product1.quantity_svl, -21)
self.assertEqual(self.product1.value_svl, -210)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 100)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 100)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 310)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 310)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
def test_fifo_add_move_in_done_picking_1(self):
""" The flow is:
product2 std price = 20
IN01 10@10 product1
IN01 10@20 product2
IN01 correction 10@20 -> 11@20 (product2)
DO01 11 product2
DO02 1 product2
DO02 correction 1 -> 2 (negative stock)
IN03 2@30 product2
vacuum
"""
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# Receive 10@10
# ---------------------------------------------------------------------
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1 = self.env['stock.move'].create({
'picking_id': receipt.id,
'name': '10 in',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
# ---------------------------------------------------------------------
# Add a stock move, receive 10@20 of another product
# ---------------------------------------------------------------------
self.product2.categ_id.property_cost_method = 'fifo'
self.product2.standard_price = 20
move2 = self.env['stock.move'].create({
'picking_id': receipt.id,
'name': '10 in',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product2.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'move_line_ids': [(0, 0, {
'product_id': self.product2.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, 200.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move2.stock_valuation_layer_ids.unit_cost, 20.0)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product2.quantity_svl, 10)
self.assertEqual(self.product2.value_svl, 200)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 300)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 0)
# ---------------------------------------------------------------------
# Edit the previous stock move, receive 11
# ---------------------------------------------------------------------
move2.quantity_done = 11
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('value')), 220.0) # after correction, the move should be valued at 11@20
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('remaining_qty')), 11.0)
self.assertEqual(move2.stock_valuation_layer_ids.sorted()[-1].unit_cost, 20.0)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 320)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 0)
# ---------------------------------------------------------------------
# Send 11 product 2
# ---------------------------------------------------------------------
delivery = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move3 = self.env['stock.move'].create({
'picking_id': delivery.id,
'name': '11 out',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product2.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 11.0,
'move_line_ids': [(0, 0, {
'product_id': self.product2.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 11.0,
})]
})
move3._action_confirm()
move3._action_done()
self.assertEqual(move3.stock_valuation_layer_ids.value, -220.0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertEqual(move3.stock_valuation_layer_ids.unit_cost, 20.0)
self.assertEqual(self.product2.qty_available, 0)
self.assertEqual(self.product2.quantity_svl, 0)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 320)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 220)
# ---------------------------------------------------------------------
# Add one move of product 2, this'll make some negative stock.
# ---------------------------------------------------------------------
# FIXME: uncomment when negative stock is handled
#move4 = self.env['stock.move'].create({
# 'picking_id': delivery.id,
# 'name': '1 out',
# 'location_id': self.stock_location.id,
# 'location_dest_id': self.customer_location.id,
# 'product_id': self.product2.id,
# 'product_uom': self.uom_unit.id,
# 'product_uom_qty': 1.0,
# 'state': 'done', # simulate default_get override
# 'move_line_ids': [(0, 0, {
# 'product_id': self.product2.id,
# 'location_id': self.stock_location.id,
# 'location_dest_id': self.customer_location.id,
# 'product_uom_id': self.uom_unit.id,
# 'qty_done': 1.0,
# })]
#})
#self.assertEqual(move4.value, -20.0)
#self.assertEqual(move4.remaining_qty, -1.0)
#self.assertEqual(move4.price_unit, -20.0)
#self.assertEqual(self.product2.qty_available, -1)
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 320)
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 240)
## ---------------------------------------------------------------------
## edit the created move, add 1
## ---------------------------------------------------------------------
#move4.quantity_done = 2
#self.assertEqual(self.product2.qty_available, -2)
#self.assertEqual(move4.value, -40.0)
#self.assertEqual(move4.remaining_qty, -2.0)
#self.assertEqual(move4.price_unit, -20.0)
#self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
#self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 320) # 10*10 + 11*20
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 320)
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 260)
#self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 260)
#self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
#self.env['stock.move']._run_fifo_vacuum()
#self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
#self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 320) # 10*10 + 11*20
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 320)
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 260)
#self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 260)
#self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
## ---------------------------------------------------------------------
## receive 2 products 2 @ 30
## ---------------------------------------------------------------------
#move5 = self.env['stock.move'].create({
# 'picking_id': receipt.id,
# 'name': '10 in',
# 'location_id': self.supplier_location.id,
# 'location_dest_id': self.stock_location.id,
# 'product_id': self.product2.id,
# 'product_uom': self.uom_unit.id,
# 'product_uom_qty': 2.0,
# 'price_unit': 30,
# 'move_line_ids': [(0, 0, {
# 'product_id': self.product2.id,
# 'location_id': self.supplier_location.id,
# 'location_dest_id': self.stock_location.id,
# 'product_uom_id': self.uom_unit.id,
# 'qty_done': 2.0,
# })]
#})
#move5._action_confirm()
#move5._action_done()
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 380)
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 260)
## ---------------------------------------------------------------------
## run vacuum
## ---------------------------------------------------------------------
#self.env['stock.move']._run_fifo_vacuum()
#self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
#self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 380) # 10*10 + 11*20
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 380)
#self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 280) # 260/
#self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 280)
#self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
#self.assertEqual(self.product2.qty_available, 0)
#self.assertEqual(self.product2.stock_value, 0)
#self.assertEqual(move4.remaining_value, 0)
#self.assertEqual(move4.value, -60) # after correction, the move is valued -(2*30)
def test_fifo_add_moveline_in_done_move_1(self):
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# Receive 10@10
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': '10 in',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
self.assertEqual(len(move1.account_move_ids), 1)
# ---------------------------------------------------------------------
# Add a new move line to receive 10 more
# ---------------------------------------------------------------------
self.assertEqual(len(move1.move_line_ids), 1)
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 10,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('value')), 200.0)
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('remaining_qty')), 20.0)
self.assertEqual(move1.stock_valuation_layer_ids.sorted()[-1].unit_cost, 10.0)
self.assertEqual(len(move1.account_move_ids), 2)
self.assertEqual(self.product1.quantity_svl, 20)
self.assertEqual(self.product1.value_svl, 200)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 200)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 200)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 0)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
def test_fifo_edit_done_move1(self):
""" Increase OUT done move while quantities are available.
"""
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# Receive 10@10
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': 'receive 10@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
# account values for move1
valuation_aml = self._get_stock_valuation_move_lines()
move1_valuation_aml = valuation_aml[-1]
self.assertEqual(move1_valuation_aml.debit, 100)
self.assertEqual(move1_valuation_aml.credit, 0)
input_aml = self._get_stock_input_move_lines()
move1_input_aml = input_aml[-1]
self.assertEqual(move1_input_aml.debit, 0)
self.assertEqual(move1_input_aml.credit, 100)
self.assertEqual(len(move1.account_move_ids), 1)
self.assertAlmostEqual(self.product1.quantity_svl, 10.0)
self.assertEqual(self.product1.value_svl, 100)
# ---------------------------------------------------------------------
# Receive 10@12
# ---------------------------------------------------------------------
move2 = self.env['stock.move'].create({
'name': 'receive 10@12',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 12,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move2._action_confirm()
move2._action_done()
# stock values for move2
self.assertEqual(move2.stock_valuation_layer_ids.value, 120.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move2.stock_valuation_layer_ids.unit_cost, 12.0)
# account values for move2
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(move2_valuation_aml.debit, 120)
self.assertEqual(move2_valuation_aml.credit, 0)
input_aml = self._get_stock_input_move_lines()
move2_input_aml = input_aml[-1]
self.assertEqual(move2_input_aml.debit, 0)
self.assertEqual(move2_input_aml.credit, 120)
self.assertEqual(len(move2.account_move_ids), 1)
self.assertAlmostEqual(self.product1.qty_available, 20.0)
self.assertAlmostEqual(self.product1.quantity_svl, 20.0)
self.assertEqual(self.product1.value_svl, 220)
# ---------------------------------------------------------------------
# Send 8
# ---------------------------------------------------------------------
move3 = self.env['stock.move'].create({
'name': '12 out (2 negative)',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 8.0,
'price_unit': 0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 8.0,
})]
})
move3._action_confirm()
move3._action_done()
# stock values for move3
self.assertEqual(move3.stock_valuation_layer_ids.value, -80.0)
self.assertEqual(move3.stock_valuation_layer_ids.remaining_qty, 0.0)
# account values for move3
valuation_aml = self._get_stock_valuation_move_lines()
move3_valuation_aml = valuation_aml[-1]
self.assertEqual(move3_valuation_aml.debit, 0) # FIXME sle shiiiiiiieeeeet with_context out move doesn't work?
output_aml = self._get_stock_output_move_lines()
move3_output_aml = output_aml[-1]
self.assertEqual(move3_output_aml.debit, 80)
self.assertEqual(move3_output_aml.credit, 0)
self.assertEqual(len(move3.account_move_ids), 1)
self.assertAlmostEqual(self.product1.qty_available, 12.0)
self.assertAlmostEqual(self.product1.quantity_svl, 12.0)
self.assertEqual(self.product1.value_svl, 140)
# ---------------------------------------------------------------------
# Edit last move, send 14 instead
# it should send 2@10 and 4@12
# ---------------------------------------------------------------------
move3.quantity_done = 14
self.assertEqual(move3.product_qty, 14)
# old value: -80 -(8@10)
# new value: -148 => -(10@10 + 4@12)
self.assertEqual(sum(move3.stock_valuation_layer_ids.mapped('value')), -148)
# account values for move3
valuation_aml = self._get_stock_valuation_move_lines()
move3_valuation_aml = valuation_aml[-1]
self.assertEqual(move3_valuation_aml.debit, 0)
output_aml = self._get_stock_output_move_lines()
move3_output_aml = output_aml[-1]
self.assertEqual(move3_output_aml.debit, 68)
self.assertEqual(move3_output_aml.credit, 0)
self.assertEqual(len(move3.account_move_ids), 2)
self.assertEqual(self.product1.value_svl, 72)
# ---------------------------------------------------------------------
# Ending
# ---------------------------------------------------------------------
self.assertEqual(self.product1.qty_available, 6)
self.assertAlmostEqual(self.product1.quantity_svl, 6.0)
self.assertEqual(self.product1.value_svl, 72)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('debit')), 0)
self.assertEqual(sum(self._get_stock_input_move_lines().mapped('credit')), 220)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('debit')), 220)
self.assertEqual(sum(self._get_stock_valuation_move_lines().mapped('credit')), 148)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('debit')), 148)
self.assertEqual(sum(self._get_stock_output_move_lines().mapped('credit')), 0)
def test_fifo_edit_done_move2(self):
""" Decrease, then increase OUT done move while quantities are available.
"""
self.product1.categ_id.property_cost_method = 'fifo'
# ---------------------------------------------------------------------
# Receive 10@10
# ---------------------------------------------------------------------
move1 = self.env['stock.move'].create({
'name': 'receive 10@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move1._action_confirm()
move1._action_done()
# stock values for move1
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 10.0)
self.assertEqual(move1.stock_valuation_layer_ids.unit_cost, 10.0)
# ---------------------------------------------------------------------
# Send 10
# ---------------------------------------------------------------------
move2 = self.env['stock.move'].create({
'name': '12 out (2 negative)',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 0,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 10.0,
})]
})
move2._action_confirm()
move2._action_done()
# stock values for move2
self.assertEqual(move2.stock_valuation_layer_ids.value, -100.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0.0)
# ---------------------------------------------------------------------
# Actually, send 8 in the last move
# ---------------------------------------------------------------------
move2.quantity_done = 8
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('value')), -80.0) # the move actually sent 8@10
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 2)
self.product1.qty_available = 2
self.product1.value_svl = 20
self.product1.quantity_svl = 2
# ---------------------------------------------------------------------
# Actually, send 10 in the last move
# ---------------------------------------------------------------------
move2.quantity_done = 10
self.assertEqual(sum(move2.stock_valuation_layer_ids.mapped('value')), -100.0) # the move actually sent 10@10
self.assertEqual(sum(self.product1.stock_valuation_layer_ids.mapped('remaining_qty')), 0)
self.assertEqual(self.product1.quantity_svl, 0)
self.assertEqual(self.product1.value_svl, 0)
def test_fifo_standard_price_upate_1(self):
product = self.env['product.product'].create({
'name': 'product1',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
product.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self._make_in_move(product, 3, unit_cost=17)
self._make_in_move(product, 1, unit_cost=23)
self._make_out_move(product, 3)
self.assertEqual(product.standard_price, 23)
def test_fifo_standard_price_upate_2(self):
product = self.env['product.product'].create({
'name': 'product1',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
product.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self._make_in_move(product, 5, unit_cost=17)
self._make_in_move(product, 1, unit_cost=23)
self._make_out_move(product, 4)
self.assertEqual(product.standard_price, 17)
def test_fifo_standard_price_upate_3(self):
"""Standard price must be set on move in if no product and if first move."""
product = self.env['product.product'].create({
'name': 'product1',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
product.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self._make_in_move(product, 5, unit_cost=17)
self._make_in_move(product, 1, unit_cost=23)
self.assertEqual(product.standard_price, 17)
self._make_out_move(product, 4)
self.assertEqual(product.standard_price, 17)
self._make_out_move(product, 1)
self.assertEqual(product.standard_price, 23)
self._make_out_move(product, 1)
self.assertEqual(product.standard_price, 23)
self._make_in_move(product, 1, unit_cost=77)
self.assertEqual(product.standard_price, 77)
def test_average_perpetual_1(self):
# http://accountingexplained.com/financial/inventories/avco-method
self.product1.categ_id.property_cost_method = 'average'
# Beginning Inventory: 60 units @ 15.00 per unit
move1 = self.env['stock.move'].create({
'name': '60 units @ 15.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 60.0,
'price_unit': 15,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 60.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 900.0)
# Purchase 140 units @ 15.50 per unit
move2 = self.env['stock.move'].create({
'name': '140 units @ 15.50 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 140.0,
'price_unit': 15.50,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 140.0
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, 2170.0)
# Sale 190 units @ 15.35 per unit
move3 = self.env['stock.move'].create({
'name': 'Sale 190 units @ 19.00 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 190.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 190.0
move3._action_done()
self.assertEqual(move3.stock_valuation_layer_ids.value, -2916.5)
# Purchase 70 units @ $16.00 per unit
move4 = self.env['stock.move'].create({
'name': '70 units @ $16.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 70.0,
'price_unit': 16.00,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 70.0
move4._action_done()
self.assertEqual(move4.stock_valuation_layer_ids.value, 1120.0)
# Sale 30 units @ $19.50 per unit
move5 = self.env['stock.move'].create({
'name': '30 units @ $19.50 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 30.0,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 30.0
move5._action_done()
self.assertEqual(move5.stock_valuation_layer_ids.value, -477.56)
# Receives 10 units but assign them to an owner, the valuation should not be impacted.
move6 = self.env['stock.move'].create({
'name': '10 units to an owner',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 99,
})
move6._action_confirm()
move6._action_assign()
move6.move_line_ids.owner_id = self.owner1.id
move6.move_line_ids.qty_done = 10.0
move6._action_done()
self.assertEqual(move6.stock_valuation_layer_ids.value, 0)
# Sale 50 units @ $19.50 per unit (no stock anymore)
move7 = self.env['stock.move'].create({
'name': '50 units @ $19.50 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 50.0,
})
move7._action_confirm()
move7._action_assign()
move7.move_line_ids.qty_done = 50.0
move7._action_done()
self.assertEqual(move7.stock_valuation_layer_ids.value, -795.94)
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_average_perpetual_2(self):
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'Receive 10 units at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
self.assertEqual(self.product1.standard_price, 10)
move2 = self.env['stock.move'].create({
'name': 'Receive 10 units at 15',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 15,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
self.assertEqual(self.product1.standard_price, 12.5)
move3 = self.env['stock.move'].create({
'name': 'Deliver 15 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 15.0
move3._action_done()
self.assertEqual(self.product1.standard_price, 12.5)
move4 = self.env['stock.move'].create({
'name': 'Deliver 10 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 10.0
move4._action_done()
# note: 5 units were sent estimated at 12.5 (negative stock)
self.assertEqual(self.product1.standard_price, 12.5)
self.assertEqual(self.product1.quantity_svl, -5)
self.assertEqual(self.product1.value_svl, -62.5)
move2.move_line_ids.qty_done = 20
# incrementing the receipt triggered the vacuum, the negative stock is corrected
self.assertEqual(self.product1.stock_valuation_layer_ids[-1].value, -12.5)
self.assertEqual(self.product1.quantity_svl, 5)
self.assertEqual(self.product1.value_svl, 75)
self.assertEqual(self.product1.standard_price, 15)
def test_average_perpetual_3(self):
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'Receive 10 units at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
move2 = self.env['stock.move'].create({
'name': 'Receive 10 units at 15',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 15,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
move3 = self.env['stock.move'].create({
'name': 'Deliver 15 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 15.0
move3._action_done()
move4 = self.env['stock.move'].create({
'name': 'Deliver 10 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 10.0
move4._action_done()
move2.move_line_ids.qty_done = 0
self.assertEqual(self.product1.value_svl, -187.5)
def test_average_perpetual_4(self):
"""receive 1@10, receive 1@5 insteadof 3@5"""
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'Receive 1 unit at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1.0
move1._action_done()
move2 = self.env['stock.move'].create({
'name': 'Receive 3 units at 5',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
'price_unit': 5,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 1.0
move2._action_done()
self.assertAlmostEqual(self.product1.quantity_svl, 2.0)
self.assertAlmostEqual(self.product1.standard_price, 7.5)
def test_average_perpetual_5(self):
''' Set owner on incoming move => no valuation '''
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'Receive 1 unit at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1.0
move1.move_line_ids.owner_id = self.owner1.id
move1._action_done()
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_average_perpetual_6(self):
""" Batch validation of moves """
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'Receive 1 unit at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1.0
move2 = self.env['stock.move'].create({
'name': 'Receive 1 units at 5',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 5,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 1.0
# Receive both at the same time
(move1 | move2)._action_done()
self.assertAlmostEqual(self.product1.standard_price, 7.5)
self.assertEqual(self.product1.quantity_svl, 2)
self.assertEqual(self.product1.value_svl, 15)
def test_average_perpetual_7(self):
""" Test edit in the past. Receive 5@10, receive 10@20, edit the first move to receive
15 instead.
"""
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'IN 5@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5,
'price_unit': 10,
})
move1._action_confirm()
move1.quantity_done = 5
move1._action_done()
self.assertAlmostEqual(self.product1.standard_price, 10)
self.assertAlmostEqual(move1.stock_valuation_layer_ids.value, 50)
self.assertAlmostEqual(self.product1.quantity_svl, 5)
self.assertAlmostEqual(self.product1.value_svl, 50)
move2 = self.env['stock.move'].create({
'name': 'IN 10@20',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 20,
})
move2._action_confirm()
move2.quantity_done = 10
move2._action_done()
self.assertAlmostEqual(self.product1.standard_price, 16.67)
self.assertAlmostEqual(move2.stock_valuation_layer_ids.value, 200)
self.assertAlmostEqual(self.product1.quantity_svl, 15)
self.assertAlmostEqual(self.product1.value_svl, 250)
move1.move_line_ids.qty_done = 15
self.assertAlmostEqual(self.product1.standard_price, 14.0)
self.assertAlmostEqual(len(move1.stock_valuation_layer_ids), 2)
self.assertAlmostEqual(move1.stock_valuation_layer_ids.sorted()[-1].value, 100)
self.assertAlmostEqual(self.product1.quantity_svl, 25)
self.assertAlmostEqual(self.product1.value_svl, 350)
def test_average_perpetual_8(self):
""" Receive 1@10, then dropship 1@20, finally return the dropship. Dropship should not
impact the price.
"""
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'IN 1@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1,
'price_unit': 10,
})
move1._action_confirm()
move1.quantity_done = 1
move1._action_done()
self.assertAlmostEqual(self.product1.standard_price, 10)
move2 = self.env['stock.move'].create({
'name': 'IN 1@20',
'location_id': self.supplier_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1,
'price_unit': 20,
})
move2._action_confirm()
move2.quantity_done = 1
move2._action_done()
self.assertAlmostEqual(self.product1.standard_price, 10.0)
move3 = self.env['stock.move'].create({
'name': 'IN 1@20',
'location_id': self.customer_location.id,
'location_dest_id': self.supplier_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1,
'price_unit': 20,
})
move3._action_confirm()
move3.quantity_done = 1
move3._action_done()
self.assertAlmostEqual(self.product1.standard_price, 10.0)
def test_average_perpetual_9(self):
""" When a product has an available quantity of -5, edit an incoming shipment and increase
the received quantity by 5 units.
"""
self.product1.categ_id.property_cost_method = 'average'
# receive 10
move1 = self.env['stock.move'].create({
'name': 'IN 5@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 10,
})
move1._action_confirm()
move1.quantity_done = 10
move1._action_done()
# deliver 15
move2 = self.env['stock.move'].create({
'name': 'Deliver 10 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 15.0
move2._action_done()
# increase the receipt to 15
move1.move_line_ids.qty_done = 15
def test_average_stock_user(self):
""" deliver an average product as a stock user. """
self.product1.categ_id.property_cost_method = 'average'
# receive 10
move1 = self.env['stock.move'].create({
'name': 'IN 5@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 10,
})
move1._action_confirm()
move1.quantity_done = 10
move1._action_done()
# sell 15
move2 = self.env['stock.move'].create({
'name': 'Deliver 10 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 15.0
move2.with_user(self.inventory_user)._action_done()
def test_average_negative_1(self):
""" Test edit in the past. Receive 10, send 20, edit the second move to only send 10.
"""
self.product1.categ_id.property_cost_method = 'average'
move1 = self.env['stock.move'].create({
'name': 'Receive 10 units at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
move2 = self.env['stock.move'].create({
'name': 'send 20 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 20.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 20.0
move2._action_done()
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 2)
self.assertEqual(move2_valuation_aml.debit, 0)
self.assertEqual(move2_valuation_aml.credit, 200)
move2.quantity_done = 10.0
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 3)
self.assertEqual(move2_valuation_aml.debit, 100)
self.assertEqual(move2_valuation_aml.credit, 0)
move2.quantity_done = 11.0
valuation_aml = self._get_stock_valuation_move_lines()
move2_valuation_aml = valuation_aml[-1]
self.assertEqual(len(valuation_aml), 4)
self.assertEqual(move2_valuation_aml.debit, 0)
self.assertEqual(move2_valuation_aml.credit, 10)
def test_average_negative_2(self):
""" Send goods that you don't have in stock and never received any unit.
"""
self.product1.categ_id.property_cost_method = 'average'
# set a standard price
self.product1.standard_price = 99
# send 10 units that we do not have
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.stock_location), 0)
move1 = self.env['stock.move'].create({
'name': 'test_average_negative_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1.quantity_done = 10.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, -990.0) # as no move out were done for this product, fallback on the standard price
def test_average_negative_3(self):
""" Send goods that you don't have in stock but received and send some units before.
"""
self.product1.categ_id.property_cost_method= 'average'
# set a standard price
self.product1.standard_price = 99
# Receives 10 produts at 10
move1 = self.env['stock.move'].create({
'name': '68 units @ 15.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
# send 10 products
move2 = self.env['stock.move'].create({
'name': 'Sale 94 units @ 19.00 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, -100.0)
self.assertEqual(move2.stock_valuation_layer_ids.remaining_qty, 0.0) # unused in average move
# send 10 products again
move3 = self.env['stock.move'].create({
'name': 'Sale 94 units @ 19.00 per unit',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move3._action_confirm()
move3.quantity_done = 10.0
move3._action_done()
self.assertEqual(move3.stock_valuation_layer_ids.value, -100.0) # as no move out were done for this product, fallback on latest cost
def test_average_negative_4(self):
self.product1.categ_id.property_cost_method = 'average'
# set a standard price
self.product1.standard_price = 99
# Receives 10 produts at 10
move1 = self.env['stock.move'].create({
'name': '68 units @ 15.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
def test_average_negative_5(self):
self.product1.categ_id.property_cost_method = 'average'
# in 10 @ 10
move1 = self.env['stock.move'].create({
'name': '10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(self.product1.standard_price, 10)
# in 10 @ 20
move2 = self.env['stock.move'].create({
'name': '10 units @ 20.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 20,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, 200.0)
self.assertEqual(self.product1.standard_price, 15)
# send 5
move3 = self.env['stock.move'].create({
'name': 'Sale 5 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move3._action_confirm()
move3.quantity_done = 5.0
move3._action_done()
self.assertEqual(move3.stock_valuation_layer_ids.value, -75.0)
self.assertEqual(self.product1.standard_price, 15)
# send 30
move4 = self.env['stock.move'].create({
'name': 'Sale 5 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 30.0,
})
move4._action_confirm()
move4.quantity_done = 30.0
move4._action_done()
self.assertEqual(move4.stock_valuation_layer_ids.value, -450.0)
self.assertEqual(self.product1.standard_price, 15)
# in 20 @ 20
move5 = self.env['stock.move'].create({
'name': '20 units @ 20.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 20.0,
'price_unit': 20,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 20.0
move5._action_done()
self.assertEqual(move5.stock_valuation_layer_ids.value, 400.0)
# Move 4 is now fixed, it initially sent 30@15 but the 5 last units were negative and estimated
# at 15 (1125). The new receipt made these 5 units sent at 20 (1500), so a 450 value is added
# to move4.
self.assertEqual(move4.stock_valuation_layer_ids[0].value, -450)
# So we have 5@20 in stock.
self.assertEqual(self.product1.quantity_svl, 5)
self.assertEqual(self.product1.value_svl, 100)
self.assertEqual(self.product1.standard_price, 20)
# send 5 products to empty the inventory, the average price should not go to 0
move6 = self.env['stock.move'].create({
'name': 'Sale 5 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move6._action_confirm()
move6.quantity_done = 5.0
move6._action_done()
self.assertEqual(move6.stock_valuation_layer_ids.value, -100.0)
self.assertEqual(self.product1.standard_price, 20)
# in 10 @ 10, the new average price should be 10
move7 = self.env['stock.move'].create({
'name': '10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move7._action_confirm()
move7._action_assign()
move7.move_line_ids.qty_done = 10.0
move7._action_done()
self.assertEqual(move7.stock_valuation_layer_ids.value, 100.0)
self.assertEqual(self.product1.standard_price, 10)
def test_average_automated_with_cost_change(self):
""" Test of the handling of a cost change with a negative stock quantity with FIFO+AVCO costing method"""
self.product1.categ_id.property_cost_method = 'average'
self.product1.categ_id.property_valuation = 'real_time'
# Step 1: Sell (and confirm) 10 units we don't have @ 100
self.product1.standard_price = 100
move1 = self.env['stock.move'].create({
'name': 'Sale 10 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1.quantity_done = 10.0
move1._action_done()
self.assertAlmostEqual(self.product1.quantity_svl, -10.0)
self.assertEqual(move1.stock_valuation_layer_ids.value, -1000.0)
self.assertAlmostEqual(self.product1.value_svl, -1000.0)
# Step2: Change product cost from 100 to 10 -> Nothing should appear in inventory
# valuation as the quantity is negative
self.product1.standard_price = 10
self.assertEqual(self.product1.value_svl, -1000.0)
# Step 3: Make an inventory adjustment to set to total counted value at 0 -> Inventory
# valuation should be at 0 with a compensation layer at 900 (1000 - 100)
inventory_location = self.product1.property_stock_inventory
inventory_location.company_id = self.env.company.id
move2 = self.env['stock.move'].create({
'name': 'Adjustment of 10 units',
'location_id': inventory_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
# Check if the move adjustment has correctly been done
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertAlmostEqual(move2.stock_valuation_layer_ids.value, 100.0)
# Check if the compensation layer is as expected, with final inventory value being 0
self.assertAlmostEqual(self.product1.stock_valuation_layer_ids.sorted()[-1].value, 900.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_average_manual_1(self):
''' Set owner on incoming move => no valuation '''
self.product1.categ_id.property_cost_method = 'average'
self.product1.categ_id.property_valuation = 'manual_periodic'
move1 = self.env['stock.move'].create({
'name': 'Receive 1 unit at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1.0
move1.move_line_ids.owner_id = self.owner1.id
move1._action_done()
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_standard_perpetual_1(self):
''' Set owner on incoming move => no valuation '''
self.product1.categ_id.property_cost_method = 'standard'
move1 = self.env['stock.move'].create({
'name': 'Receive 1 unit at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1.0
move1.move_line_ids.owner_id = self.owner1.id
move1._action_done()
self.assertAlmostEqual(self.product1.qty_available, 1.0)
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_standard_manual_1(self):
''' Set owner on incoming move => no valuation '''
self.product1.categ_id.property_cost_method = 'standard'
self.product1.categ_id.property_valuation = 'manual_periodic'
move1 = self.env['stock.move'].create({
'name': 'Receive 1 unit at 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1.0
move1.move_line_ids.owner_id = self.owner1.id
move1._action_done()
self.assertAlmostEqual(self.product1.qty_available, 1.0)
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_standard_manual_2(self):
"""Validate a receipt as a regular stock user."""
self.product1.categ_id.property_cost_method = 'standard'
self.product1.categ_id.property_valuation = 'manual_periodic'
self.product1.standard_price = 10.0
move1 = self.env['stock.move'].with_user(self.inventory_user).create({
'name': 'IN 10 units',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
def test_standard_perpetual_2(self):
"""Validate a receipt as a regular stock user."""
self.product1.categ_id.property_cost_method = 'standard'
self.product1.categ_id.property_valuation = 'real_time'
self.product1.standard_price = 10.0
move1 = self.env['stock.move'].with_user(self.inventory_user).create({
'name': 'IN 10 units',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
def test_change_cost_method_1(self):
""" Change the cost method from FIFO to AVCO.
"""
# ---------------------------------------------------------------------
# Use FIFO, make some operations
# ---------------------------------------------------------------------
self.product1.categ_id.property_cost_method = 'fifo'
# receive 10@10
move1 = self.env['stock.move'].create({
'name': '10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
# receive 10@15
move2 = self.env['stock.move'].create({
'name': '10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 15,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
# sell 1
move3 = self.env['stock.move'].create({
'name': 'Sale 5 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 1.0
move3._action_done()
self.assertAlmostEqual(self.product1.quantity_svl, 19)
self.assertEqual(self.product1.value_svl, 240)
# ---------------------------------------------------------------------
# Change the production valuation to AVCO
# ---------------------------------------------------------------------
self.product1.categ_id.property_cost_method = 'average'
# valuation should stay to ~240
self.assertAlmostEqual(self.product1.quantity_svl, 19)
self.assertAlmostEqual(self.product1.value_svl, 285, delta=0.03)
# an accounting entry should be created
# FIXME sle check it
self.assertEqual(self.product1.standard_price, 15)
def test_change_cost_method_2(self):
""" Change the cost method from FIFO to standard.
"""
# ---------------------------------------------------------------------
# Use FIFO, make some operations
# ---------------------------------------------------------------------
self.product1.categ_id.property_cost_method = 'fifo'
# receive 10@10
move1 = self.env['stock.move'].create({
'name': '10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
# receive 10@15
move2 = self.env['stock.move'].create({
'name': '10 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'price_unit': 15,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10.0
move2._action_done()
# sell 1
move3 = self.env['stock.move'].create({
'name': 'Sale 5 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 1.0
move3._action_done()
self.assertAlmostEqual(self.product1.quantity_svl, 19)
self.assertEqual(self.product1.value_svl, 240)
# ---------------------------------------------------------------------
# Change the production valuation to AVCO
# ---------------------------------------------------------------------
self.product1.categ_id.property_cost_method = 'standard'
# valuation should stay to ~240
self.assertAlmostEqual(self.product1.value_svl, 285, delta=0.03)
self.assertAlmostEqual(self.product1.quantity_svl, 19)
# no accounting entry should be created
# FIXME sle check it
self.assertEqual(self.product1.standard_price, 15)
def test_fifo_sublocation_valuation_1(self):
""" Set the main stock as a view location. Receive 2 units of a
product, put 1 unit in an internal sublocation and the second
one in a scrap sublocation. Only a single unit, the one in the
internal sublocation, should be valued. Then, send these two
quants to a customer, only the one in the internal location
should be valued.
"""
self.product1.categ_id.property_cost_method = 'fifo'
view_location = self.env['stock.location'].create({'name': 'view', 'usage': 'view'})
subloc1 = self.env['stock.location'].create({
'name': 'internal',
'usage': 'internal',
'location_id': view_location.id,
})
# sane settings for a scrap location, company_id doesn't matter
subloc2 = self.env['stock.location'].create({
'name': 'scrap',
'usage': 'inventory',
'location_id': view_location.id,
'scrap_location': True,
})
move1 = self.env['stock.move'].create({
'name': '2 units @ 10.00 per unit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.write({'move_line_ids': [
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': self.supplier_location.id,
'location_dest_id': subloc1.id,
'product_uom_id': self.uom_unit.id
}),
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': self.supplier_location.id,
'location_dest_id': subloc2.id,
'product_uom_id': self.uom_unit.id
}),
]})
move1._action_done()
self.assertEqual(move1.stock_valuation_layer_ids.value, 10)
self.assertEqual(move1.stock_valuation_layer_ids.remaining_qty, 1)
self.assertAlmostEqual(self.product1.qty_available, 0.0)
self.assertAlmostEqual(self.product1.quantity_svl, 1.0)
self.assertEqual(self.product1.value_svl, 10)
self.assertTrue(len(move1.account_move_ids), 1)
move2 = self.env['stock.move'].create({
'name': '2 units out',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move2._action_confirm()
move2._action_assign()
move2.write({'move_line_ids': [
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': subloc1.id,
'location_dest_id': self.supplier_location.id,
'product_uom_id': self.uom_unit.id
}),
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': subloc2.id,
'location_dest_id': self.supplier_location.id,
'product_uom_id': self.uom_unit.id
}),
]})
move2._action_done()
self.assertEqual(move2.stock_valuation_layer_ids.value, -10)
def test_move_in_or_out(self):
""" Test a few combination of move and their move lines and
check their valuation. A valued move should be IN or OUT.
Creating a move that is IN and OUT should be forbidden.
"""
# an internal move should be considered as OUT if any of its move line
# is moved in a scrap location
scrap = self.env['stock.location'].create({
'name': 'scrap',
'usage': 'inventory',
'location_id': self.stock_location.id,
'scrap_location': True,
})
move1 = self.env['stock.move'].create({
'name': 'internal but out move',
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move1._action_confirm()
move1._action_assign()
move1.write({'move_line_ids': [
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id
}),
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': self.stock_location.id,
'location_dest_id': scrap.id,
'product_uom_id': self.uom_unit.id
}),
]})
self.assertEqual(move1._is_out(), True)
# a move should be considered as invalid if some of its move lines are
# entering the company and some are leaving
customer1 = self.env['stock.location'].create({
'name': 'customer',
'usage': 'customer',
'location_id': self.stock_location.id,
})
supplier1 = self.env['stock.location'].create({
'name': 'supplier',
'usage': 'supplier',
'location_id': self.stock_location.id,
})
move2 = self.env['stock.move'].create({
'name': 'internal but in and out move',
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move2._action_confirm()
move2._action_assign()
move2.write({'move_line_ids': [
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': customer1.id,
'location_dest_id': self.stock_location.id,
'product_uom_id': self.uom_unit.id
}),
(0, None, {
'product_id': self.product1.id,
'qty_done': 1,
'location_id': self.stock_location.id,
'location_dest_id': customer1.id,
'product_uom_id': self.uom_unit.id
}),
]})
self.assertEqual(move2._is_in(), True)
self.assertEqual(move2._is_out(), True)
with self.assertRaises(UserError):
move2._action_done()
def test_at_date_standard_1(self):
self.product1.categ_id.property_cost_method = 'standard'
now = Datetime.now()
date1 = now - timedelta(days=8)
date2 = now - timedelta(days=7)
date3 = now - timedelta(days=6)
date4 = now - timedelta(days=5)
date5 = now - timedelta(days=4)
date6 = now - timedelta(days=3)
date7 = now - timedelta(days=2)
date8 = now - timedelta(days=1)
# set the standard price to 10
self.product1.standard_price = 10.0
# receive 10
move1 = self.env['stock.move'].create({
'name': 'in 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10
move1._action_done()
move1.date = date2
move1.stock_valuation_layer_ids._write({'create_date': date2})
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.value_svl, 100)
# receive 20
move2 = self.env['stock.move'].create({
'name': 'in 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 20,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 20
move2._action_done()
move2.date = date3
move2.stock_valuation_layer_ids._write({'create_date': date3})
self.assertEqual(self.product1.quantity_svl, 30)
self.assertEqual(self.product1.value_svl, 300)
# send 15
move3 = self.env['stock.move'].create({
'name': 'out 10',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 15
move3._action_done()
move3.date = date4
move3.stock_valuation_layer_ids._write({'create_date': date4})
self.assertEqual(self.product1.quantity_svl, 15)
self.assertEqual(self.product1.value_svl, 150)
# set the standard price to 5
self.product1.standard_price = 5
self.product1.stock_valuation_layer_ids.sorted()[-1]._write({'create_date': date5})
self.assertEqual(self.product1.quantity_svl, 15)
self.assertEqual(self.product1.value_svl, 75)
# send 10
move4 = self.env['stock.move'].create({
'name': 'out 10',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 10
move4._action_done()
move4.date = date6
move4.stock_valuation_layer_ids._write({'create_date': date6})
self.assertEqual(self.product1.quantity_svl, 5)
self.assertEqual(self.product1.value_svl, 25.0)
# set the standard price to 7.5
self.product1.standard_price = 7.5
self.product1.stock_valuation_layer_ids.sorted()[-1]._write({'create_date': date7})
# receive 90
move5 = self.env['stock.move'].create({
'name': 'in 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 90,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 90
move5._action_done()
move5.date = date8
move5.stock_valuation_layer_ids._write({'create_date': date8})
self.assertEqual(self.product1.quantity_svl, 95)
self.assertEqual(self.product1.value_svl, 712.5)
# Quantity available at date
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).quantity_svl, 0)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).quantity_svl, 10)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date3)).quantity_svl, 30)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date4)).quantity_svl, 15)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date5)).quantity_svl, 15)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date6)).quantity_svl, 5)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date7)).quantity_svl, 5)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date8)).quantity_svl, 95)
# Valuation at date
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).value_svl, 0)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).value_svl, 100)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date3)).value_svl, 300)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date4)).value_svl, 150)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date5)).value_svl, 75)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date6)).value_svl, 25)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date8)).value_svl, 712.5)
# edit the done quantity of move1, decrease it
move1.quantity_done = 5
# the change is only visible right now
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).quantity_svl, 10)
self.assertEqual(self.product1.quantity_svl, 90)
# as when we decrease a quantity on a recreipt, we consider it as a out move with the price
# of today, the value will be decrease of 100 - (5*7.5)
self.assertEqual(sum(move1.stock_valuation_layer_ids.mapped('value')), 62.5)
# but the change is still only visible right now
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).value_svl, 100)
# edit move 4, send 15 instead of 10
move4.quantity_done = 15
# -(10*5) - (5*7.5)
self.assertEqual(sum(move4.stock_valuation_layer_ids.mapped('value')), -87.5)
# the change is only visible right now
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date6)).value_svl, 25)
self.assertEqual(self.product1.quantity_svl, 85)
self.assertEqual(self.product1.value_svl, 637.5)
def test_at_date_fifo_1(self):
""" Make some operations at different dates, check that the results of the valuation at
date wizard are consistent. Afterwards, edit the done quantity of some operations. The
valuation at date results should take these changes into account.
"""
self.product1.categ_id.property_cost_method = 'fifo'
now = Datetime.now()
date1 = now - timedelta(days=8)
date2 = now - timedelta(days=7)
date3 = now - timedelta(days=6)
date4 = now - timedelta(days=5)
date5 = now - timedelta(days=4)
date6 = now - timedelta(days=3)
# receive 10@10
move1 = self.env['stock.move'].create({
'name': 'in 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10
move1._action_done()
move1.date = date1
move1.stock_valuation_layer_ids._write({'create_date': date1})
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.value_svl, 100)
# receive 10@12
move2 = self.env['stock.move'].create({
'name': 'in 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 12,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10
move2._action_done()
move2.date = date2
move2.stock_valuation_layer_ids._write({'create_date': date2})
self.assertAlmostEqual(self.product1.quantity_svl, 20)
self.assertEqual(self.product1.value_svl, 220)
# send 15
move3 = self.env['stock.move'].create({
'name': 'out 10',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 15
move3._action_done()
move3.date = date3
move3.stock_valuation_layer_ids._write({'create_date': date3})
self.assertAlmostEqual(self.product1.quantity_svl, 5.0)
self.assertEqual(self.product1.value_svl, 60)
# send 20
move4 = self.env['stock.move'].create({
'name': 'out 10',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 20,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 20
move4._action_done()
move4.date = date4
move4.stock_valuation_layer_ids._write({'create_date': date4})
self.assertAlmostEqual(self.product1.quantity_svl, -15.0)
self.assertEqual(self.product1.value_svl, -180)
# receive 100@15
move5 = self.env['stock.move'].create({
'name': 'in 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100,
'price_unit': 15,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 100
move5._action_done()
move5.date = date5
move5.stock_valuation_layer_ids._write({'create_date': date5})
# the vacuum ran
move4.stock_valuation_layer_ids.sorted()[-1]._write({'create_date': date6})
self.assertEqual(self.product1.quantity_svl, 85)
self.assertEqual(self.product1.value_svl, 1275)
# Edit the quantity done of move1, increase it.
move1.quantity_done = 20
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).quantity_svl, 10)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).value_svl, 100)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).quantity_svl, 20)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).value_svl, 220)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date3)).quantity_svl, 5)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date3)).value_svl, 60)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date4)).quantity_svl, -15)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date4)).value_svl, -180)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date5)).quantity_svl, 85)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date5)).value_svl, 1320)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date6)).quantity_svl, 85)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date6)).value_svl, 1275)
self.assertEqual(self.product1.quantity_svl, 95)
self.assertEqual(self.product1.value_svl, 1375)
def test_at_date_fifo_2(self):
self.product1.categ_id.property_cost_method = 'fifo'
now = Datetime.now()
date1 = now - timedelta(days=8)
date2 = now - timedelta(days=7)
date3 = now - timedelta(days=6)
date4 = now - timedelta(days=5)
date5 = now - timedelta(days=4)
# receive 10@10
move1 = self.env['stock.move'].create({
'name': 'in 10@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 10,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10
move1._action_done()
move1.date = date1
move1.stock_valuation_layer_ids._write({'create_date': date1})
self.assertAlmostEqual(self.product1.quantity_svl, 10.0)
self.assertEqual(self.product1.value_svl, 100)
# receive 10@15
move2 = self.env['stock.move'].create({
'name': 'in 10@15',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 15,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 10
move2._action_done()
move2.date = date2
move2.stock_valuation_layer_ids._write({'create_date': date2})
self.assertAlmostEqual(self.product1.quantity_svl, 20.0)
self.assertEqual(self.product1.value_svl, 250)
# send 30
move3 = self.env['stock.move'].create({
'name': 'out 30',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 30,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 30
move3._action_done()
move3.date = date3
move3.stock_valuation_layer_ids._write({'create_date': date3})
self.assertAlmostEqual(self.product1.quantity_svl, -10.0)
self.assertEqual(self.product1.value_svl, -150)
# receive 10@20
move4 = self.env['stock.move'].create({
'name': 'in 10@20',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 20,
})
move4._action_confirm()
move4._action_assign()
move4.move_line_ids.qty_done = 10
move4._action_done()
move4.date = date4
move3.stock_valuation_layer_ids.sorted()[-1]._write({'create_date': date4})
move4.stock_valuation_layer_ids._write({'create_date': date4})
self.assertAlmostEqual(self.product1.quantity_svl, 0.0)
self.assertEqual(self.product1.value_svl, 0)
# receive 10@10
move5 = self.env['stock.move'].create({
'name': 'in 10@10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
'price_unit': 10,
})
move5._action_confirm()
move5._action_assign()
move5.move_line_ids.qty_done = 10
move5._action_done()
move5.date = date5
move5.stock_valuation_layer_ids._write({'create_date': date5})
self.assertAlmostEqual(self.product1.quantity_svl, 10.0)
self.assertEqual(self.product1.value_svl, 100)
# ---------------------------------------------------------------------
# ending: perpetual valuation
# ---------------------------------------------------------------------
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).quantity_svl, 10)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).value_svl, 100)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).quantity_svl, 20)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).value_svl, 250)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date3)).quantity_svl, -10)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date3)).value_svl, -150)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date4)).quantity_svl, 0)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date4)).value_svl, 0)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date5)).quantity_svl, 10)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date5)).value_svl, 100)
self.assertEqual(self.product1.quantity_svl, 10)
self.assertEqual(self.product1.value_svl, 100)
def test_inventory_fifo_1(self):
""" Make an inventory from a location with a company set, and ensure the product has a stock
value. When the product is sold, ensure there is no remaining quantity on the original move
and no stock value.
"""
self.product1.standard_price = 15
self.product1.categ_id.property_cost_method = 'fifo'
inventory_location = self.product1.property_stock_inventory
inventory_location.company_id = self.env.company.id
# Start Inventory: 12 units
move1 = self.env['stock.move'].create({
'name': 'Adjustment of 12 units',
'location_id': inventory_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 12.0
move1._action_done()
self.assertAlmostEqual(move1.stock_valuation_layer_ids.value, 180.0)
self.assertAlmostEqual(move1.stock_valuation_layer_ids.remaining_qty, 12.0)
self.assertAlmostEqual(self.product1.value_svl, 180.0)
# Sell the 12 units
move2 = self.env['stock.move'].create({
'name': 'Sell 12 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 12.0
move2._action_done()
self.assertAlmostEqual(move1.stock_valuation_layer_ids.remaining_qty, 0.0)
self.assertAlmostEqual(self.product1.value_svl, 0.0)
def test_at_date_average_1(self):
""" Set a company on the inventory loss, take items from there then put items there, check
the values and quantities at date.
"""
now = Datetime.now()
date1 = now - timedelta(days=8)
date2 = now - timedelta(days=7)
self.product1.standard_price = 10
self.product1.product_tmpl_id.cost_method = 'average'
inventory_location = self.product1.property_stock_inventory
inventory_location.company_id = self.env.company.id
move1 = self.env['stock.move'].create({
'name': 'Adjustment of 10 units',
'location_id': inventory_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10.0
move1._action_done()
move1.date = date1
move1.stock_valuation_layer_ids._write({'create_date': date1})
move2 = self.env['stock.move'].create({
'name': 'Sell 5 units',
'location_id': self.stock_location.id,
'location_dest_id': inventory_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 5.0
move2._action_done()
move2.date = date2
move2.stock_valuation_layer_ids._write({'create_date': date2})
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).quantity_svl, 10)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date1)).value_svl, 100)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).quantity_svl, 5)
self.assertEqual(self.product1.with_context(to_date=Datetime.to_string(date2)).value_svl, 50)
def test_forecast_report_value(self):
""" Create a SVL for two companies using different currency, and open
the forecast report. Checks the forecast report use the good currency to
display the product's valuation.
"""
# Settings
self.product1.categ_id.property_valuation = 'manual_periodic'
# Creates two new currencies.
currency_1 = self.env['res.currency'].create({
'name': 'UNF',
'symbol': 'U',
'rounding': 0.01,
'currency_unit_label': 'Unifranc',
'rate': 1,
'position': 'before',
})
currency_2 = self.env['res.currency'].create({
'name': 'DBL',
'symbol': 'DD',
'rounding': 0.01,
'currency_unit_label': 'Doublard',
'rate': 2,
})
# Create a new company using the "Unifranc" as currency.
company_form = Form(self.env['res.company'])
company_form.name = "BB Inc."
company_form.currency_id = currency_1
company_1 = company_form.save()
# Create a new company using the "Doublard" as currency.
company_form = Form(self.env['res.company'])
company_form.name = "BB Corp"
company_form.currency_id = currency_2
company_2 = company_form.save()
# Gets warehouses and locations.
warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', company_1.id)], limit=1)
warehouse_2 = self.env['stock.warehouse'].search([('company_id', '=', company_2.id)], limit=1)
stock_1 = warehouse_1.lot_stock_id
stock_2 = warehouse_2.lot_stock_id
self.env.user.company_ids += company_1
self.env.user.company_ids += company_2
# Updates the product's value.
self.product1.with_company(company_1).standard_price = 10
self.product1.with_company(company_2).standard_price = 12
# ---------------------------------------------------------------------
# Receive 5 units @ 10.00 per unit (company_1)
# ---------------------------------------------------------------------
move_1 = self.env['stock.move'].with_company(company_1).create({
'name': 'IN 5 units @ 10.00 U per unit',
'location_id': self.supplier_location.id,
'location_dest_id': stock_1.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move_1._action_confirm()
move_1.move_line_ids.qty_done = 5.0
move_1._action_done()
# ---------------------------------------------------------------------
# Receive 4 units @ 12.00 per unit (company_2)
# ---------------------------------------------------------------------
move_2 = self.env['stock.move'].with_company(company_2).create({
'name': 'IN 4 units @ 12.00 DD per unit',
'location_id': self.supplier_location.id,
'location_dest_id': stock_2.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
})
move_2._action_confirm()
move_2.move_line_ids.qty_done = 4.0
move_2._action_done()
# Opens the report for each company and compares the values.
report = self.env['report.stock.report_product_product_replenishment']
report_for_company_1 = report.with_context(warehouse=warehouse_1.id)
report_for_company_2 = report.with_context(warehouse=warehouse_2.id)
report_value_1 = report_for_company_1._get_report_values(docids=self.product1.ids)
report_value_2 = report_for_company_2._get_report_values(docids=self.product1.ids)
self.assertEqual(report_value_1['docs']['value'], "U 50.00")
self.assertEqual(report_value_2['docs']['value'], "48.00 DD")
def test_fifo_and_sml_owned_by_company(self):
"""
When receiving a FIFO product, if the picking is owned by the company,
there should be a SVL and an account move linked to the product SM
"""
self.product1.categ_id.property_cost_method = 'fifo'
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'owner_id': self.env.company.partner_id.id,
})
move = self.env['stock.move'].create({
'picking_id': receipt.id,
'name': 'IN 1 @ 10',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
receipt.action_confirm()
move.quantity_done = 1
receipt.button_validate()
self.assertEqual(move.stock_valuation_layer_ids.value, 10)
self.assertEqual(move.stock_valuation_layer_ids.account_move_id.amount_total, 10)
def test_create_svl_different_uom(self):
"""
Create a transfer and use in the move a different unit of measure than
the one set on the product form and ensure that when the qty done is changed
and the picking is already validated, an svl is created in the uom set in the product.
"""
uom_dozen = self.env.ref('uom.product_uom_dozen')
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'owner_id': self.env.company.partner_id.id,
})
move = self.env['stock.move'].create({
'picking_id': receipt.id,
'name': 'test',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product1.id,
'product_uom': uom_dozen.id,
'product_uom_qty': 1.0,
'price_unit': 10,
})
receipt.action_confirm()
move.quantity_done = 1
receipt.button_validate()
self.assertEqual(self.product1.uom_name, 'Units')
self.assertEqual(self.product1.quantity_svl, 12)
move.quantity_done = 2
self.assertEqual(self.product1.quantity_svl, 24)
def test_average_manual_price_change(self):
"""
When doing a Manual Price Change, an SVL is created to update the value_svl.
This test check that the value of this SVL is correct and does result in new_std_price * quantity.
To do so, we create 2 In moves, which result in a standard price rounded at $5.29, the non-rounded value ≃ 5.2857.
Then we update the standard price to $7
"""
self.product1.categ_id.property_cost_method = 'average'
self._make_in_move(self.product1, 5, unit_cost=5)
self._make_in_move(self.product1, 2, unit_cost=6)
self.product1.write({'standard_price': 7})
self.assertEqual(self.product1.value_svl, 49)
| 43.555862
| 173,483
|
7,363
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
from odoo.tests.common import tagged, Form
from odoo import fields
@tagged("post_install", "-at_install")
class TestAccountMove(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
(
cls.stock_input_account,
cls.stock_output_account,
cls.stock_valuation_account,
cls.expense_account,
cls.stock_journal,
) = _create_accounting_data(cls.env)
# `all_categ` should not be altered, so we can test the `post_init` hook of `stock_account`
cls.all_categ = cls.env.ref('product.product_category_all')
cls.auto_categ = cls.env['product.category'].create({
'name': 'child_category',
'parent_id': cls.all_categ.id,
"property_stock_account_input_categ_id": cls.stock_input_account.id,
"property_stock_account_output_categ_id": cls.stock_output_account.id,
"property_stock_valuation_account_id": cls.stock_valuation_account.id,
"property_stock_journal": cls.stock_journal.id,
"property_valuation": "real_time",
"property_cost_method": "standard",
})
cls.product_A = cls.env["product.product"].create(
{
"name": "Product A",
"type": "product",
"default_code": "prda",
"categ_id": cls.auto_categ.id,
"taxes_id": [(5, 0, 0)],
"supplier_taxes_id": [(5, 0, 0)],
"lst_price": 100.0,
"standard_price": 10.0,
"property_account_income_id": cls.company_data["default_account_revenue"].id,
"property_account_expense_id": cls.company_data["default_account_expense"].id,
}
)
def test_standard_perpetual_01_mc_01(self):
rate = self.currency_data["rates"].sorted()[0].rate
move_form = Form(self.env["account.move"].with_context(default_move_type="out_invoice"))
move_form.partner_id = self.partner_a
move_form.currency_id = self.currency_data["currency"]
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product_A
line_form.tax_ids.clear()
invoice = move_form.save()
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_total)
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_residual)
self.assertEqual(len(invoice.mapped("line_ids")), 2)
self.assertEqual(len(invoice.mapped("line_ids.currency_id")), 1)
invoice._post()
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_total)
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_residual)
self.assertEqual(len(invoice.mapped("line_ids")), 4)
self.assertEqual(len(invoice.mapped("line_ids").filtered("is_anglo_saxon_line")), 2)
self.assertEqual(len(invoice.mapped("line_ids.currency_id")), 2)
def test_fifo_perpetual_01_mc_01(self):
self.product_A.categ_id.property_cost_method = "fifo"
rate = self.currency_data["rates"].sorted()[0].rate
move_form = Form(self.env["account.move"].with_context(default_move_type="out_invoice"))
move_form.partner_id = self.partner_a
move_form.currency_id = self.currency_data["currency"]
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product_A
line_form.tax_ids.clear()
invoice = move_form.save()
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_total)
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_residual)
self.assertEqual(len(invoice.mapped("line_ids")), 2)
self.assertEqual(len(invoice.mapped("line_ids.currency_id")), 1)
invoice._post()
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_total)
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_residual)
self.assertEqual(len(invoice.mapped("line_ids")), 4)
self.assertEqual(len(invoice.mapped("line_ids").filtered("is_anglo_saxon_line")), 2)
self.assertEqual(len(invoice.mapped("line_ids.currency_id")), 2)
def test_average_perpetual_01_mc_01(self):
self.product_A.categ_id.property_cost_method = "average"
rate = self.currency_data["rates"].sorted()[0].rate
move_form = Form(self.env["account.move"].with_context(default_move_type="out_invoice"))
move_form.partner_id = self.partner_a
move_form.currency_id = self.currency_data["currency"]
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product_A
line_form.tax_ids.clear()
invoice = move_form.save()
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_total)
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_residual)
self.assertEqual(len(invoice.mapped("line_ids")), 2)
self.assertEqual(len(invoice.mapped("line_ids.currency_id")), 1)
invoice._post()
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_total)
self.assertAlmostEqual(self.product_A.lst_price * rate, invoice.amount_residual)
self.assertEqual(len(invoice.mapped("line_ids")), 4)
self.assertEqual(len(invoice.mapped("line_ids").filtered("is_anglo_saxon_line")), 2)
self.assertEqual(len(invoice.mapped("line_ids.currency_id")), 2)
def test_basic_bill(self):
"""
When billing a storable product with a basic category (manual
valuation), the account used should be the expenses one. This test
checks the flow with two companies:
- One that existed before the installation of `stock_account` (to test
the post-install hook)
- One created after the module installation
"""
first_company = self.env['res.company'].browse(1)
self.env.user.company_ids |= first_company
basic_product = self.env['product.product'].create({
'name': 'SuperProduct',
'type': 'product',
'categ_id': self.all_categ.id,
})
for company in (self.env.company | first_company):
bill_form = Form(self.env['account.move'].with_company(company.id).with_context(default_move_type='in_invoice'))
bill_form.partner_id = self.partner_a
bill_form.invoice_date = fields.Date.today()
with bill_form.invoice_line_ids.new() as line:
line.product_id = basic_product
line.price_unit = 100
bill = bill_form.save()
bill.action_post()
product_accounts = basic_product.product_tmpl_id.with_company(company.id).get_product_accounts()
self.assertEqual(bill.invoice_line_ids.account_id, product_accounts['expense'])
| 47.811688
| 7,363
|
784
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.tools.misc import format_datetime
class StockQuantityHistory(models.TransientModel):
_inherit = 'stock.quantity.history'
def open_at_date(self):
active_model = self.env.context.get('active_model')
if active_model == 'stock.valuation.layer':
action = self.env["ir.actions.actions"]._for_xml_id("stock_account.stock_valuation_layer_action")
action['domain'] = [('create_date', '<=', self.inventory_datetime), ('product_id.type', '=', 'product')]
action['display_name'] = format_datetime(self.env, self.inventory_datetime)
return action
return super(StockQuantityHistory, self).open_at_date()
| 43.555556
| 784
|
1,297
|
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 StockReturnPicking(models.TransientModel):
_inherit = "stock.return.picking"
@api.model
def default_get(self, default_fields):
res = super(StockReturnPicking, self).default_get(default_fields)
for i, k, vals in res.get('product_return_moves', []):
vals.update({'to_refund': True})
return res
def _create_returns(self):
new_picking_id, pick_type_id = super(StockReturnPicking, self)._create_returns()
new_picking = self.env['stock.picking'].browse([new_picking_id])
for move in new_picking.move_lines:
return_picking_line = self.product_return_moves.filtered(lambda r: r.move_id == move.origin_returned_move_id)[:1]
if return_picking_line and return_picking_line.to_refund:
move.to_refund = True
return new_picking_id, pick_type_id
class StockReturnPickingLine(models.TransientModel):
_inherit = "stock.return.picking.line"
to_refund = fields.Boolean(string="Update quantities on SO/PO", default=True,
help='Trigger a decrease of the delivered/received quantity in the associated Sale Order/Purchase Order')
| 41.83871
| 1,297
|
465
|
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 StockRequestCount(models.TransientModel):
_inherit = 'stock.request.count'
accounting_date = fields.Date('Accounting Date')
def _get_values_to_write(self):
res = super()._get_values_to_write()
if self.accounting_date:
res['accounting_date'] = self.accounting_date
return res
| 29.0625
| 465
|
8,026
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import float_is_zero
class StockValuationLayerRevaluation(models.TransientModel):
_name = 'stock.valuation.layer.revaluation'
_description = "Wizard model to reavaluate a stock inventory for a product"
_check_company_auto = True
@api.model
def default_get(self, default_fields):
res = super().default_get(default_fields)
if res.get('product_id'):
product = self.env['product.product'].browse(res['product_id'])
if product.categ_id.property_cost_method == 'standard':
raise UserError(_("You cannot revalue a product with a standard cost method."))
if product.quantity_svl <= 0:
raise UserError(_("You cannot revalue a product with an empty or negative stock."))
if 'account_journal_id' not in res and 'account_journal_id' in default_fields and product.categ_id.property_valuation == 'real_time':
accounts = product.product_tmpl_id.get_product_accounts()
res['account_journal_id'] = accounts['stock_journal'].id
return res
company_id = fields.Many2one('res.company', "Company", readonly=True, required=True)
currency_id = fields.Many2one('res.currency', "Currency", related='company_id.currency_id', required=True)
product_id = fields.Many2one('product.product', "Related product", required=True, check_company=True)
property_valuation = fields.Selection(related='product_id.categ_id.property_valuation')
product_uom_name = fields.Char("Unit of Measure", related='product_id.uom_id.name')
current_value_svl = fields.Float("Current Value", related="product_id.value_svl")
current_quantity_svl = fields.Float("Current Quantity", related="product_id.quantity_svl")
added_value = fields.Monetary("Added value", required=True)
new_value = fields.Monetary("New value", compute='_compute_new_value')
new_value_by_qty = fields.Monetary("New value by quantity", compute='_compute_new_value')
reason = fields.Char("Reason", help="Reason of the revaluation")
account_journal_id = fields.Many2one('account.journal', "Journal", check_company=True)
account_id = fields.Many2one('account.account', "Counterpart Account", domain=[('deprecated', '=', False)], check_company=True)
date = fields.Date("Accounting Date")
@api.depends('current_value_svl', 'current_quantity_svl', 'added_value')
def _compute_new_value(self):
for reval in self:
reval.new_value = reval.current_value_svl + reval.added_value
if not float_is_zero(reval.current_quantity_svl, precision_rounding=self.product_id.uom_id.rounding):
reval.new_value_by_qty = reval.new_value / reval.current_quantity_svl
else:
reval.new_value_by_qty = 0.0
def action_validate_revaluation(self):
""" Revaluate the stock for `self.product_id` in `self.company_id`.
- Change the stardard price with the new valuation by product unit.
- Create a manual stock valuation layer with the `added_value` of `self`.
- Distribute the `added_value` on the remaining_value of layers still in stock (with a remaining quantity)
- If the Inventory Valuation of the product category is automated, create
related account move.
"""
self.ensure_one()
if self.currency_id.is_zero(self.added_value):
raise UserError(_("The added value doesn't have any impact on the stock valuation"))
product_id = self.product_id.with_company(self.company_id)
remaining_svls = self.env['stock.valuation.layer'].search([
('product_id', '=', product_id.id),
('remaining_qty', '>', 0),
('company_id', '=', self.company_id.id),
])
# Create a manual stock valuation layer
if self.reason:
description = _("Manual Stock Valuation: %s.", self.reason)
else:
description = _("Manual Stock Valuation: No Reason Given.")
if product_id.categ_id.property_cost_method == 'average':
description += _(
" Product cost updated from %(previous)s to %(new_cost)s.",
previous=product_id.standard_price,
new_cost=product_id.standard_price + self.added_value / self.current_quantity_svl
)
revaluation_svl_vals = {
'company_id': self.company_id.id,
'product_id': product_id.id,
'description': description,
'value': self.added_value,
'quantity': 0,
}
remaining_qty = sum(remaining_svls.mapped('remaining_qty'))
remaining_value = self.added_value
remaining_value_unit_cost = self.currency_id.round(remaining_value / remaining_qty)
for svl in remaining_svls:
if float_is_zero(svl.remaining_qty - remaining_qty, precision_rounding=self.product_id.uom_id.rounding):
svl.remaining_value += remaining_value
else:
taken_remaining_value = remaining_value_unit_cost * svl.remaining_qty
svl.remaining_value += taken_remaining_value
remaining_value -= taken_remaining_value
remaining_qty -= svl.remaining_qty
revaluation_svl = self.env['stock.valuation.layer'].create(revaluation_svl_vals)
# Update the stardard price in case of AVCO
if product_id.categ_id.property_cost_method == 'average':
product_id.with_context(disable_auto_svl=True).standard_price += self.added_value / self.current_quantity_svl
# If the Inventory Valuation of the product category is automated, create related account move.
if self.property_valuation != 'real_time':
return True
accounts = product_id.product_tmpl_id.get_product_accounts()
if self.added_value < 0:
debit_account_id = self.account_id.id
credit_account_id = accounts.get('stock_valuation') and accounts['stock_valuation'].id
else:
debit_account_id = accounts.get('stock_valuation') and accounts['stock_valuation'].id
credit_account_id = self.account_id.id
move_vals = {
'journal_id': self.account_journal_id.id or accounts['stock_journal'].id,
'company_id': self.company_id.id,
'ref': _("Revaluation of %s", product_id.display_name),
'stock_valuation_layer_ids': [(6, None, [revaluation_svl.id])],
'date': self.date or fields.Date.today(),
'move_type': 'entry',
'line_ids': [(0, 0, {
'name': _('%(user)s changed stock valuation from %(previous)s to %(new_value)s - %(product)s',
user=self.env.user.name,
previous=self.current_value_svl,
new_value=self.current_value_svl + self.added_value,
product=product_id.display_name,
),
'account_id': debit_account_id,
'debit': abs(self.added_value),
'credit': 0,
'product_id': product_id.id,
}), (0, 0, {
'name': _('%(user)s changed stock valuation from %(previous)s to %(new_value)s - %(product)s',
user=self.env.user.name,
previous=self.current_value_svl,
new_value=self.current_value_svl + self.added_value,
product=product_id.display_name,
),
'account_id': credit_account_id,
'debit': 0,
'credit': abs(self.added_value),
'product_id': product_id.id,
})],
}
account_move = self.env['account.move'].create(move_vals)
account_move._post()
return True
| 50.1625
| 8,026
|
6,505
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, tools
from odoo.tools import float_compare, float_is_zero
class StockValuationLayer(models.Model):
"""Stock Valuation Layer"""
_name = 'stock.valuation.layer'
_description = 'Stock Valuation Layer'
_order = 'create_date, id'
_rec_name = 'product_id'
company_id = fields.Many2one('res.company', 'Company', readonly=True, required=True)
product_id = fields.Many2one('product.product', 'Product', readonly=True, required=True, check_company=True, auto_join=True)
categ_id = fields.Many2one('product.category', related='product_id.categ_id')
product_tmpl_id = fields.Many2one('product.template', related='product_id.product_tmpl_id')
quantity = fields.Float('Quantity', help='Quantity', readonly=True, digits='Product Unit of Measure')
uom_id = fields.Many2one(related='product_id.uom_id', readonly=True, required=True)
currency_id = fields.Many2one('res.currency', 'Currency', related='company_id.currency_id', readonly=True, required=True)
unit_cost = fields.Monetary('Unit Value', readonly=True)
value = fields.Monetary('Total Value', readonly=True)
remaining_qty = fields.Float(readonly=True, digits='Product Unit of Measure')
remaining_value = fields.Monetary('Remaining Value', readonly=True)
description = fields.Char('Description', readonly=True)
stock_valuation_layer_id = fields.Many2one('stock.valuation.layer', 'Linked To', readonly=True, check_company=True, index=True)
stock_valuation_layer_ids = fields.One2many('stock.valuation.layer', 'stock_valuation_layer_id')
stock_move_id = fields.Many2one('stock.move', 'Stock Move', readonly=True, check_company=True, index=True)
account_move_id = fields.Many2one('account.move', 'Journal Entry', readonly=True, check_company=True, index=True)
def init(self):
tools.create_index(
self._cr, 'stock_valuation_layer_index',
self._table, ['product_id', 'remaining_qty', 'stock_move_id', 'company_id', 'create_date']
)
def _validate_accounting_entries(self):
am_vals = []
for svl in self:
if not svl.with_company(svl.company_id).product_id.valuation == 'real_time':
continue
if svl.currency_id.is_zero(svl.value):
continue
am_vals += svl.stock_move_id.with_company(svl.company_id)._account_entry_move(svl.quantity, svl.description, svl.id, svl.value)
if am_vals:
account_moves = self.env['account.move'].sudo().create(am_vals)
account_moves._post()
for svl in self:
# Eventually reconcile together the invoice and valuation accounting entries on the stock interim accounts
if svl.company_id.anglo_saxon_accounting:
svl.stock_move_id._get_related_invoices()._stock_account_anglo_saxon_reconcile_valuation(product=svl.product_id)
def _validate_analytic_accounting_entries(self):
for svl in self:
svl.stock_move_id._account_analytic_entry_move()
def _consume_specific_qty(self, qty_valued, qty_to_value):
"""
Iterate on the SVL to first skip the qty already valued. Then, keep
iterating to consume `qty_to_value` and stop
The method returns the valued quantity and its valuation
"""
if not self:
return 0, 0
rounding = self.product_id.uom_id.rounding
qty_to_take_on_candidates = qty_to_value
tmp_value = 0 # to accumulate the value taken on the candidates
for candidate in self:
if float_is_zero(candidate.quantity, precision_rounding=rounding):
continue
candidate_quantity = abs(candidate.quantity)
returned_qty = sum([sm.product_uom._compute_quantity(sm.quantity_done, self.uom_id)
for sm in candidate.stock_move_id.returned_move_ids if sm.state == 'done'])
candidate_quantity -= returned_qty
if float_is_zero(candidate_quantity, precision_rounding=rounding):
continue
if not float_is_zero(qty_valued, precision_rounding=rounding):
qty_ignored = min(qty_valued, candidate_quantity)
qty_valued -= qty_ignored
candidate_quantity -= qty_ignored
if float_is_zero(candidate_quantity, precision_rounding=rounding):
continue
qty_taken_on_candidate = min(qty_to_take_on_candidates, candidate_quantity)
qty_to_take_on_candidates -= qty_taken_on_candidate
tmp_value += qty_taken_on_candidate * ((candidate.value + sum(candidate.stock_valuation_layer_ids.mapped('value'))) / candidate.quantity)
if float_is_zero(qty_to_take_on_candidates, precision_rounding=rounding):
break
return qty_to_value - qty_to_take_on_candidates, tmp_value
def _consume_all(self, qty_valued, valued, qty_to_value):
"""
The method consumes all svl to get the total qty/value. Then it deducts
the already consumed qty/value. Finally, it tries to consume the `qty_to_value`
The method returns the valued quantity and its valuation
"""
if not self:
return 0, 0
rounding = self.product_id.uom_id.rounding
qty_total = -qty_valued
value_total = -valued
new_valued_qty = 0
new_valuation = 0
for svl in self:
if float_is_zero(svl.quantity, precision_rounding=rounding):
continue
relevant_qty = abs(svl.quantity)
returned_qty = sum([sm.product_uom._compute_quantity(sm.quantity_done, self.uom_id)
for sm in svl.stock_move_id.returned_move_ids if sm.state == 'done'])
relevant_qty -= returned_qty
if float_is_zero(relevant_qty, precision_rounding=rounding):
continue
qty_total += relevant_qty
value_total += relevant_qty * ((svl.value + sum(svl.stock_valuation_layer_ids.mapped('value'))) / svl.quantity)
if float_compare(qty_total, 0, precision_rounding=rounding) > 0:
unit_cost = value_total / qty_total
new_valued_qty = min(qty_total, qty_to_value)
new_valuation = unit_cost * new_valued_qty
return new_valued_qty, new_valuation
| 50.820313
| 6,505
|
1,706
|
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 StockLocation(models.Model):
_inherit = "stock.location"
valuation_in_account_id = fields.Many2one(
'account.account', 'Stock Valuation Account (Incoming)',
domain=[('internal_type', '=', 'other'), ('deprecated', '=', False)],
help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
"this account will be used to hold the value of products being moved from an internal location "
"into this location, instead of the generic Stock Output Account set on the product. "
"This has no effect for internal locations.")
valuation_out_account_id = fields.Many2one(
'account.account', 'Stock Valuation Account (Outgoing)',
domain=[('internal_type', '=', 'other'), ('deprecated', '=', False)],
help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
"this account will be used to hold the value of products being moved out of this location "
"and into an internal location, instead of the generic Stock Output Account set on the product. "
"This has no effect for internal locations.")
def _should_be_valued(self):
""" This method returns a boolean reflecting whether the products stored in `self` should
be considered when valuating the stock of a company.
"""
self.ensure_one()
if self.usage == 'internal' or (self.usage == 'transit' and self.company_id):
return True
return False
| 51.69697
| 1,706
|
11,999
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
from odoo.tools import float_is_zero
class AccountMove(models.Model):
_inherit = 'account.move'
stock_move_id = fields.Many2one('stock.move', string='Stock Move', index=True)
stock_valuation_layer_ids = fields.One2many('stock.valuation.layer', 'account_move_id', string='Stock Valuation Layer')
# -------------------------------------------------------------------------
# OVERRIDE METHODS
# -------------------------------------------------------------------------
def _get_lines_onchange_currency(self):
# OVERRIDE
return self.line_ids.filtered(lambda l: not l.is_anglo_saxon_line)
def _reverse_move_vals(self, default_values, cancel=True):
# OVERRIDE
# Don't keep anglo-saxon lines if not cancelling an existing invoice.
move_vals = super(AccountMove, self)._reverse_move_vals(default_values, cancel=cancel)
if not cancel:
move_vals['line_ids'] = [vals for vals in move_vals['line_ids'] if not vals[2]['is_anglo_saxon_line']]
return move_vals
def copy_data(self, default=None):
# OVERRIDE
# Don't keep anglo-saxon lines when copying a journal entry.
res = super().copy_data(default=default)
if not self._context.get('move_reverse_cancel'):
for copy_vals in res:
if 'line_ids' in copy_vals:
copy_vals['line_ids'] = [line_vals for line_vals in copy_vals['line_ids']
if line_vals[0] != 0 or not line_vals[2].get('is_anglo_saxon_line')]
return res
def _post(self, soft=True):
# OVERRIDE
# Don't change anything on moves used to cancel another ones.
if self._context.get('move_reverse_cancel'):
return super()._post(soft)
# Create additional COGS lines for customer invoices.
self.env['account.move.line'].create(self._stock_account_prepare_anglo_saxon_out_lines_vals())
# Post entries.
posted = super()._post(soft)
# Reconcile COGS lines in case of anglo-saxon accounting with perpetual valuation.
posted._stock_account_anglo_saxon_reconcile_valuation()
return posted
def button_draft(self):
res = super(AccountMove, self).button_draft()
# Unlink the COGS lines generated during the 'post' method.
self.mapped('line_ids').filtered(lambda line: line.is_anglo_saxon_line).unlink()
return res
def button_cancel(self):
# OVERRIDE
res = super(AccountMove, self).button_cancel()
# Unlink the COGS lines generated during the 'post' method.
# In most cases it shouldn't be necessary since they should be unlinked with 'button_draft'.
# However, since it can be called in RPC, better be safe.
self.mapped('line_ids').filtered(lambda line: line.is_anglo_saxon_line).unlink()
return res
# -------------------------------------------------------------------------
# COGS METHODS
# -------------------------------------------------------------------------
def _stock_account_prepare_anglo_saxon_out_lines_vals(self):
''' Prepare values used to create the journal items (account.move.line) corresponding to the Cost of Good Sold
lines (COGS) for customer invoices.
Example:
Buy a product having a cost of 9 being a storable product and having a perpetual valuation in FIFO.
Sell this product at a price of 10. The customer invoice's journal entries looks like:
Account | Debit | Credit
---------------------------------------------------------------
200000 Product Sales | | 10.0
---------------------------------------------------------------
101200 Account Receivable | 10.0 |
---------------------------------------------------------------
This method computes values used to make two additional journal items:
---------------------------------------------------------------
220000 Expenses | 9.0 |
---------------------------------------------------------------
101130 Stock Interim Account (Delivered) | | 9.0
---------------------------------------------------------------
Note: COGS are only generated for customer invoices except refund made to cancel an invoice.
:return: A list of Python dictionary to be passed to env['account.move.line'].create.
'''
lines_vals_list = []
price_unit_prec = self.env['decimal.precision'].precision_get('Product Price')
for move in self:
# Make the loop multi-company safe when accessing models like product.product
move = move.with_company(move.company_id)
if not move.is_sale_document(include_receipts=True) or not move.company_id.anglo_saxon_accounting:
continue
for line in move.invoice_line_ids:
# Filter out lines being not eligible for COGS.
if not line._eligible_for_cogs():
continue
# Retrieve accounts needed to generate the COGS.
accounts = line.product_id.product_tmpl_id.get_product_accounts(fiscal_pos=move.fiscal_position_id)
debit_interim_account = accounts['stock_output']
credit_expense_account = accounts['expense'] or move.journal_id.default_account_id
if not debit_interim_account or not credit_expense_account:
continue
# Compute accounting fields.
sign = -1 if move.move_type == 'out_refund' else 1
price_unit = line._stock_account_get_anglo_saxon_price_unit()
balance = sign * line.quantity * price_unit
if move.currency_id.is_zero(balance) or float_is_zero(price_unit, precision_digits=price_unit_prec):
continue
# Add interim account line.
lines_vals_list.append({
'name': line.name[:64],
'move_id': move.id,
'partner_id': move.commercial_partner_id.id,
'product_id': line.product_id.id,
'product_uom_id': line.product_uom_id.id,
'quantity': line.quantity,
'price_unit': price_unit,
'debit': balance < 0.0 and -balance or 0.0,
'credit': balance > 0.0 and balance or 0.0,
'account_id': debit_interim_account.id,
'exclude_from_invoice_tab': True,
'is_anglo_saxon_line': True,
})
# Add expense account line.
lines_vals_list.append({
'name': line.name[:64],
'move_id': move.id,
'partner_id': move.commercial_partner_id.id,
'product_id': line.product_id.id,
'product_uom_id': line.product_uom_id.id,
'quantity': line.quantity,
'price_unit': -price_unit,
'debit': balance > 0.0 and balance or 0.0,
'credit': balance < 0.0 and -balance or 0.0,
'account_id': credit_expense_account.id,
'analytic_account_id': line.analytic_account_id.id,
'analytic_tag_ids': [(6, 0, line.analytic_tag_ids.ids)],
'exclude_from_invoice_tab': True,
'is_anglo_saxon_line': True,
})
return lines_vals_list
def _stock_account_get_last_step_stock_moves(self):
""" To be overridden for customer invoices and vendor bills in order to
return the stock moves related to the invoices in self.
"""
return self.env['stock.move']
def _stock_account_anglo_saxon_reconcile_valuation(self, product=False):
""" Reconciles the entries made in the interim accounts in anglosaxon accounting,
reconciling stock valuation move lines with the invoice's.
"""
for move in self:
if not move.is_invoice():
continue
if not move.company_id.anglo_saxon_accounting:
continue
stock_moves = move._stock_account_get_last_step_stock_moves()
if not stock_moves:
continue
products = product or move.mapped('invoice_line_ids.product_id')
for prod in products:
if prod.valuation != 'real_time':
continue
# We first get the invoices move lines (taking the invoice and the previous ones into account)...
product_accounts = prod.product_tmpl_id._get_product_accounts()
if move.is_sale_document():
product_interim_account = product_accounts['stock_output']
else:
product_interim_account = product_accounts['stock_input']
if product_interim_account.reconcile:
# Search for anglo-saxon lines linked to the product in the journal entry.
product_account_moves = move.line_ids.filtered(
lambda line: line.product_id == prod and line.account_id == product_interim_account and not line.reconciled)
# Search for anglo-saxon lines linked to the product in the stock moves.
product_stock_moves = stock_moves.filtered(lambda stock_move: stock_move.product_id == prod)
product_account_moves += product_stock_moves.mapped('account_move_ids.line_ids')\
.filtered(lambda line: line.account_id == product_interim_account and not line.reconciled)
# Reconcile.
product_account_moves.reconcile()
def _get_invoiced_lot_values(self):
return []
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
is_anglo_saxon_line = fields.Boolean(help="Technical field used to retrieve the anglo-saxon lines.")
def _get_computed_account(self):
# OVERRIDE to use the stock input account by default on vendor bills when dealing
# with anglo-saxon accounting.
self.ensure_one()
self = self.with_company(self.move_id.journal_id.company_id)
if self._can_use_stock_accounts() \
and self.move_id.company_id.anglo_saxon_accounting \
and self.move_id.is_purchase_document():
fiscal_position = self.move_id.fiscal_position_id
accounts = self.product_id.product_tmpl_id.get_product_accounts(fiscal_pos=fiscal_position)
if accounts['stock_input']:
return accounts['stock_input']
return super(AccountMoveLine, self)._get_computed_account()
def _eligible_for_cogs(self):
self.ensure_one()
return self.product_id.type == 'product' and self.product_id.valuation == 'real_time'
def _can_use_stock_accounts(self):
return self.product_id.type == 'product' and self.product_id.categ_id.property_valuation == 'real_time'
def _stock_account_get_anglo_saxon_price_unit(self):
self.ensure_one()
if not self.product_id:
return self.price_unit
original_line = self.move_id.reversed_entry_id.line_ids.filtered(lambda l: l.is_anglo_saxon_line
and l.product_id == self.product_id and l.product_uom_id == self.product_uom_id and l.price_unit >= 0)
original_line = original_line and original_line[0]
return original_line.price_unit if original_line \
else self.product_id.with_company(self.company_id)._stock_account_get_anglo_saxon_price_unit(uom=self.product_uom_id)
| 46.688716
| 11,999
|
3,770
|
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.tools import float_compare, float_is_zero
class StockMoveLine(models.Model):
_inherit = 'stock.move.line'
# -------------------------------------------------------------------------
# CRUD
# -------------------------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
analytic_move_to_recompute = set()
move_lines = super(StockMoveLine, self).create(vals_list)
for move_line in move_lines:
move = move_line.move_id
analytic_move_to_recompute.add(move.id)
if move_line.state != 'done':
continue
rounding = move.product_id.uom_id.rounding
diff = move.product_uom._compute_quantity(move_line.qty_done, move.product_id.uom_id)
if float_is_zero(diff, precision_rounding=rounding):
continue
self._create_correction_svl(move, diff)
if analytic_move_to_recompute:
self.env['stock.move'].browse(
analytic_move_to_recompute)._account_analytic_entry_move()
return move_lines
def write(self, vals):
analytic_move_to_recompute = set()
if 'qty_done' in vals or 'move_id' in vals:
for move_line in self:
move_id = vals.get('move_id') if vals.get('move_id') else move_line.move_id.id
analytic_move_to_recompute.add(move_id)
if 'qty_done' in vals:
for move_line in self:
if move_line.state != 'done':
continue
move = move_line.move_id
if float_compare(vals['qty_done'], move_line.qty_done, precision_rounding=move.product_uom.rounding) == 0:
continue
rounding = move.product_id.uom_id.rounding
diff = move.product_uom._compute_quantity(vals['qty_done'] - move_line.qty_done, move.product_id.uom_id, rounding_method='HALF-UP')
if float_is_zero(diff, precision_rounding=rounding):
continue
self._create_correction_svl(move, diff)
res = super(StockMoveLine, self).write(vals)
if analytic_move_to_recompute:
self.env['stock.move'].browse(analytic_move_to_recompute)._account_analytic_entry_move()
return res
# -------------------------------------------------------------------------
# SVL creation helpers
# -------------------------------------------------------------------------
@api.model
def _create_correction_svl(self, move, diff):
stock_valuation_layers = self.env['stock.valuation.layer']
if move._is_in() and diff > 0 or move._is_out() and diff < 0:
move.product_price_update_before_done(forced_qty=diff)
stock_valuation_layers |= move._create_in_svl(forced_quantity=abs(diff))
if move.product_id.cost_method in ('average', 'fifo'):
move.product_id._run_fifo_vacuum(move.company_id)
elif move._is_in() and diff < 0 or move._is_out() and diff > 0:
stock_valuation_layers |= move._create_out_svl(forced_quantity=abs(diff))
elif move._is_dropshipped() and diff > 0 or move._is_dropshipped_returned() and diff < 0:
stock_valuation_layers |= move._create_dropshipped_svl(forced_quantity=abs(diff))
elif move._is_dropshipped() and diff < 0 or move._is_dropshipped_returned() and diff > 0:
stock_valuation_layers |= move._create_dropshipped_returned_svl(forced_quantity=abs(diff))
stock_valuation_layers._validate_accounting_entries()
| 50.266667
| 3,770
|
3,935
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.float_utils import float_is_zero
from odoo.tools.misc import groupby
class StockQuant(models.Model):
_inherit = 'stock.quant'
value = fields.Monetary('Value', compute='_compute_value', groups='stock.group_stock_manager')
currency_id = fields.Many2one('res.currency', compute='_compute_value', groups='stock.group_stock_manager')
accounting_date = fields.Date(
'Accounting Date',
help="Date at which the accounting entries will be created"
" in case of automated inventory valuation."
" If empty, the inventory date will be used.")
@api.depends('company_id', 'location_id', 'owner_id', 'product_id', 'quantity')
def _compute_value(self):
""" For standard and AVCO valuation, compute the current accounting
valuation of the quants by multiplying the quantity by
the standard price. Instead for FIFO, use the quantity times the
average cost (valuation layers are not manage by location so the
average cost is the same for all location and the valuation field is
a estimation more than a real value).
"""
for quant in self:
quant.currency_id = quant.company_id.currency_id
# If the user didn't enter a location yet while enconding a quant.
if not quant.location_id:
quant.value = 0
return
if not quant.location_id._should_be_valued() or\
(quant.owner_id and quant.owner_id != quant.company_id.partner_id):
quant.value = 0
continue
if quant.product_id.cost_method == 'fifo':
quantity = quant.product_id.with_company(quant.company_id).quantity_svl
if float_is_zero(quantity, precision_rounding=quant.product_id.uom_id.rounding):
quant.value = 0.0
continue
average_cost = quant.product_id.with_company(quant.company_id).value_svl / quantity
quant.value = quant.quantity * average_cost
else:
quant.value = quant.quantity * quant.product_id.with_company(quant.company_id).standard_price
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
""" This override is done in order for the grouped list view to display the total value of
the quants inside a location. This doesn't work out of the box because `value` is a computed
field.
"""
if 'value' not in fields:
return super(StockQuant, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
res = super(StockQuant, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
for group in res:
if group.get('__domain'):
quants = self.search(group['__domain'])
group['value'] = sum(quant.value for quant in quants)
return res
def _apply_inventory(self):
for accounting_date, inventory_ids in groupby(self, key=lambda q: q.accounting_date):
inventories = self.env['stock.quant'].concat(*inventory_ids)
if accounting_date:
super(StockQuant, inventories.with_context(force_period_date=accounting_date))._apply_inventory()
inventories.accounting_date = False
else:
super(StockQuant, inventories)._apply_inventory()
@api.model
def _get_inventory_fields_write(self):
""" Returns a list of fields user can edit when editing a quant in `inventory_mode`."""
res = super()._get_inventory_fields_write()
res += ['accounting_date']
return res
| 49.810127
| 3,935
|
30,909
|
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 float_compare, float_is_zero, OrderedSet
import logging
_logger = logging.getLogger(__name__)
class StockMove(models.Model):
_inherit = "stock.move"
to_refund = fields.Boolean(string="Update quantities on SO/PO", copy=False,
help='Trigger a decrease of the delivered/received quantity in the associated Sale Order/Purchase Order')
account_move_ids = fields.One2many('account.move', 'stock_move_id')
stock_valuation_layer_ids = fields.One2many('stock.valuation.layer', 'stock_move_id')
analytic_account_line_id = fields.Many2one(
'account.analytic.line', copy=False)
def _filter_anglo_saxon_moves(self, product):
return self.filtered(lambda m: m.product_id.id == product.id)
def action_get_account_moves(self):
self.ensure_one()
action_data = self.env['ir.actions.act_window']._for_xml_id('account.action_move_journal_line')
action_data['domain'] = [('id', 'in', self.account_move_ids.ids)]
return action_data
def _action_cancel(self):
self.analytic_account_line_id.unlink()
return super()._action_cancel()
def _should_force_price_unit(self):
self.ensure_one()
return False
def _get_price_unit(self):
""" Returns the unit price to value this stock move """
self.ensure_one()
price_unit = self.price_unit
precision = self.env['decimal.precision'].precision_get('Product Price')
# If the move is a return, use the original move's price unit.
if self.origin_returned_move_id and self.origin_returned_move_id.sudo().stock_valuation_layer_ids:
layers = self.origin_returned_move_id.sudo().stock_valuation_layer_ids
# dropshipping create additional positive svl to make sure there is no impact on the stock valuation
# We need to remove them from the computation of the price unit.
if self.origin_returned_move_id._is_dropshipped() or self.origin_returned_move_id._is_dropshipped_returned():
layers = layers.filtered(lambda l: float_compare(l.value, 0, precision_rounding=l.product_id.uom_id.rounding) <= 0)
layers |= layers.stock_valuation_layer_ids
quantity = sum(layers.mapped("quantity"))
return layers.currency_id.round(sum(layers.mapped("value")) / quantity) if not float_is_zero(quantity, precision_rounding=layers.uom_id.rounding) else 0
return price_unit if not float_is_zero(price_unit, precision) or self._should_force_price_unit() else self.product_id.standard_price
@api.model
def _get_valued_types(self):
"""Returns a list of `valued_type` as strings. During `action_done`, we'll call
`_is_[valued_type]'. If the result of this method is truthy, we'll consider the move to be
valued.
:returns: a list of `valued_type`
:rtype: list
"""
return ['in', 'out', 'dropshipped', 'dropshipped_returned']
def _get_in_move_lines(self):
""" Returns the `stock.move.line` records of `self` considered as incoming. It is done thanks
to the `_should_be_valued` method of their source and destionation location as well as their
owner.
:returns: a subset of `self` containing the incoming records
:rtype: recordset
"""
self.ensure_one()
res = OrderedSet()
for move_line in self.move_line_ids:
if move_line.owner_id and move_line.owner_id != move_line.company_id.partner_id:
continue
if not move_line.location_id._should_be_valued() and move_line.location_dest_id._should_be_valued():
res.add(move_line.id)
return self.env['stock.move.line'].browse(res)
def _is_in(self):
"""Check if the move should be considered as entering the company so that the cost method
will be able to apply the correct logic.
:returns: True if the move is entering the company else False
:rtype: bool
"""
self.ensure_one()
if self._get_in_move_lines() and not self._is_dropshipped_returned():
return True
return False
def _get_out_move_lines(self):
""" Returns the `stock.move.line` records of `self` considered as outgoing. It is done thanks
to the `_should_be_valued` method of their source and destionation location as well as their
owner.
:returns: a subset of `self` containing the outgoing records
:rtype: recordset
"""
res = self.env['stock.move.line']
for move_line in self.move_line_ids:
if move_line.owner_id and move_line.owner_id != move_line.company_id.partner_id:
continue
if move_line.location_id._should_be_valued() and not move_line.location_dest_id._should_be_valued():
res |= move_line
return res
def _is_out(self):
"""Check if the move should be considered as leaving the company so that the cost method
will be able to apply the correct logic.
:returns: True if the move is leaving the company else False
:rtype: bool
"""
self.ensure_one()
if self._get_out_move_lines() and not self._is_dropshipped():
return True
return False
def _is_dropshipped(self):
"""Check if the move should be considered as a dropshipping move so that the cost method
will be able to apply the correct logic.
:returns: True if the move is a dropshipping one else False
:rtype: bool
"""
self.ensure_one()
return self.location_id.usage == 'supplier' and self.location_dest_id.usage == 'customer'
def _is_dropshipped_returned(self):
"""Check if the move should be considered as a returned dropshipping move so that the cost
method will be able to apply the correct logic.
:returns: True if the move is a returned dropshipping one else False
:rtype: bool
"""
self.ensure_one()
return self.location_id.usage == 'customer' and self.location_dest_id.usage == 'supplier'
def _prepare_common_svl_vals(self):
"""When a `stock.valuation.layer` is created from a `stock.move`, we can prepare a dict of
common vals.
:returns: the common values when creating a `stock.valuation.layer` from a `stock.move`
:rtype: dict
"""
self.ensure_one()
return {
'stock_move_id': self.id,
'company_id': self.company_id.id,
'product_id': self.product_id.id,
'description': self.reference and '%s - %s' % (self.reference, self.product_id.name) or self.product_id.name,
}
def _create_in_svl(self, forced_quantity=None):
"""Create a `stock.valuation.layer` from `self`.
:param forced_quantity: under some circunstances, the quantity to value is different than
the initial demand of the move (Default value = None)
"""
svl_vals_list = []
for move in self:
move = move.with_company(move.company_id)
valued_move_lines = move._get_in_move_lines()
valued_quantity = 0
for valued_move_line in valued_move_lines:
valued_quantity += valued_move_line.product_uom_id._compute_quantity(valued_move_line.qty_done, move.product_id.uom_id)
unit_cost = abs(move._get_price_unit()) # May be negative (i.e. decrease an out move).
if move.product_id.cost_method == 'standard':
unit_cost = move.product_id.standard_price
svl_vals = move.product_id._prepare_in_svl_vals(forced_quantity or valued_quantity, unit_cost)
svl_vals.update(move._prepare_common_svl_vals())
if forced_quantity:
svl_vals['description'] = 'Correction of %s (modification of past move)' % move.picking_id.name or move.name
svl_vals_list.append(svl_vals)
return self.env['stock.valuation.layer'].sudo().create(svl_vals_list)
def _create_out_svl(self, forced_quantity=None):
"""Create a `stock.valuation.layer` from `self`.
:param forced_quantity: under some circunstances, the quantity to value is different than
the initial demand of the move (Default value = None)
"""
svl_vals_list = []
for move in self:
move = move.with_company(move.company_id)
valued_move_lines = move._get_out_move_lines()
valued_quantity = 0
for valued_move_line in valued_move_lines:
valued_quantity += valued_move_line.product_uom_id._compute_quantity(valued_move_line.qty_done, move.product_id.uom_id)
if float_is_zero(forced_quantity or valued_quantity, precision_rounding=move.product_id.uom_id.rounding):
continue
svl_vals = move.product_id._prepare_out_svl_vals(forced_quantity or valued_quantity, move.company_id)
svl_vals.update(move._prepare_common_svl_vals())
if forced_quantity:
svl_vals['description'] = 'Correction of %s (modification of past move)' % move.picking_id.name or move.name
svl_vals['description'] += svl_vals.pop('rounding_adjustment', '')
svl_vals_list.append(svl_vals)
return self.env['stock.valuation.layer'].sudo().create(svl_vals_list)
def _create_dropshipped_svl(self, forced_quantity=None):
"""Create a `stock.valuation.layer` from `self`.
:param forced_quantity: under some circunstances, the quantity to value is different than
the initial demand of the move (Default value = None)
"""
svl_vals_list = []
for move in self:
move = move.with_company(move.company_id)
valued_move_lines = move.move_line_ids
valued_quantity = 0
for valued_move_line in valued_move_lines:
valued_quantity += valued_move_line.product_uom_id._compute_quantity(valued_move_line.qty_done, move.product_id.uom_id)
quantity = forced_quantity or valued_quantity
unit_cost = move._get_price_unit()
if move.product_id.cost_method == 'standard':
unit_cost = move.product_id.standard_price
common_vals = dict(move._prepare_common_svl_vals(), remaining_qty=0)
# create the in if it does not come from a valued location (eg subcontract -> customer)
if not move.location_id._should_be_valued():
in_vals = {
'unit_cost': unit_cost,
'value': unit_cost * quantity,
'quantity': quantity,
}
in_vals.update(common_vals)
svl_vals_list.append(in_vals)
# create the out if it does not go to a valued location (eg customer -> subcontract)
if not move.location_dest_id._should_be_valued():
out_vals = {
'unit_cost': unit_cost,
'value': unit_cost * quantity * -1,
'quantity': quantity * -1,
}
out_vals.update(common_vals)
svl_vals_list.append(out_vals)
return self.env['stock.valuation.layer'].sudo().create(svl_vals_list)
def _create_dropshipped_returned_svl(self, forced_quantity=None):
"""Create a `stock.valuation.layer` from `self`.
:param forced_quantity: under some circunstances, the quantity to value is different than
the initial demand of the move (Default value = None)
"""
return self._create_dropshipped_svl(forced_quantity=forced_quantity)
def _action_done(self, cancel_backorder=False):
# Init a dict that will group the moves by valuation type, according to `move._is_valued_type`.
valued_moves = {valued_type: self.env['stock.move'] for valued_type in self._get_valued_types()}
for move in self:
if float_is_zero(move.quantity_done, precision_rounding=move.product_uom.rounding):
continue
for valued_type in self._get_valued_types():
if getattr(move, '_is_%s' % valued_type)():
valued_moves[valued_type] |= move
# AVCO application
valued_moves['in'].product_price_update_before_done()
res = super(StockMove, self)._action_done(cancel_backorder=cancel_backorder)
# '_action_done' might have deleted some exploded stock moves
valued_moves = {value_type: moves.exists() for value_type, moves in valued_moves.items()}
# '_action_done' might have created an extra move to be valued
for move in res - self:
for valued_type in self._get_valued_types():
if getattr(move, '_is_%s' % valued_type)():
valued_moves[valued_type] |= move
stock_valuation_layers = self.env['stock.valuation.layer'].sudo()
# Create the valuation layers in batch by calling `moves._create_valued_type_svl`.
for valued_type in self._get_valued_types():
todo_valued_moves = valued_moves[valued_type]
if todo_valued_moves:
todo_valued_moves._sanity_check_for_valuation()
stock_valuation_layers |= getattr(todo_valued_moves, '_create_%s_svl' % valued_type)()
stock_valuation_layers._validate_accounting_entries()
stock_valuation_layers._validate_analytic_accounting_entries()
stock_valuation_layers._check_company()
# For every in move, run the vacuum for the linked product.
products_to_vacuum = valued_moves['in'].mapped('product_id')
company = valued_moves['in'].mapped('company_id') and valued_moves['in'].mapped('company_id')[0] or self.env.company
for product_to_vacuum in products_to_vacuum:
product_to_vacuum._run_fifo_vacuum(company)
return res
def _sanity_check_for_valuation(self):
for move in self:
# Apply restrictions on the stock move to be able to make
# consistent accounting entries.
if move._is_in() and move._is_out():
raise UserError(_("The move lines are not in a consistent state: some are entering and other are leaving the company."))
company_src = move.mapped('move_line_ids.location_id.company_id')
company_dst = move.mapped('move_line_ids.location_dest_id.company_id')
try:
if company_src:
company_src.ensure_one()
if company_dst:
company_dst.ensure_one()
except ValueError:
raise UserError(_("The move lines are not in a consistent states: they do not share the same origin or destination company."))
if company_src and company_dst and company_src.id != company_dst.id:
raise UserError(_("The move lines are not in a consistent states: they are doing an intercompany in a single step while they should go through the intercompany transit location."))
def product_price_update_before_done(self, forced_qty=None):
tmpl_dict = defaultdict(lambda: 0.0)
# adapt standard price on incomming moves if the product cost_method is 'average'
std_price_update = {}
for move in self.filtered(lambda move: move._is_in() and move.with_company(move.company_id).product_id.cost_method == 'average'):
product_tot_qty_available = move.product_id.sudo().with_company(move.company_id).quantity_svl + tmpl_dict[move.product_id.id]
rounding = move.product_id.uom_id.rounding
valued_move_lines = move._get_in_move_lines()
qty_done = 0
for valued_move_line in valued_move_lines:
qty_done += valued_move_line.product_uom_id._compute_quantity(valued_move_line.qty_done, move.product_id.uom_id)
qty = forced_qty or qty_done
if float_is_zero(product_tot_qty_available, precision_rounding=rounding):
new_std_price = move._get_price_unit()
elif float_is_zero(product_tot_qty_available + move.product_qty, precision_rounding=rounding) or \
float_is_zero(product_tot_qty_available + qty, precision_rounding=rounding):
new_std_price = move._get_price_unit()
else:
# Get the standard price
amount_unit = std_price_update.get((move.company_id.id, move.product_id.id)) or move.product_id.with_company(move.company_id).standard_price
new_std_price = ((amount_unit * product_tot_qty_available) + (move._get_price_unit() * qty)) / (product_tot_qty_available + qty)
tmpl_dict[move.product_id.id] += qty_done
# Write the standard price, as SUPERUSER_ID because a warehouse manager may not have the right to write on products
move.product_id.with_company(move.company_id.id).with_context(disable_auto_svl=True).sudo().write({'standard_price': new_std_price})
std_price_update[move.company_id.id, move.product_id.id] = new_std_price
# adapt standard price on incomming moves if the product cost_method is 'fifo'
for move in self.filtered(lambda move:
move.with_company(move.company_id).product_id.cost_method == 'fifo'
and float_is_zero(move.product_id.sudo().quantity_svl, precision_rounding=move.product_id.uom_id.rounding)):
move.product_id.with_company(move.company_id.id).sudo().write({'standard_price': move._get_price_unit()})
def _get_accounting_data_for_valuation(self):
""" Return the accounts and journal to use to post Journal Entries for
the real-time valuation of the quant. """
self.ensure_one()
self = self.with_company(self.company_id)
accounts_data = self.product_id.product_tmpl_id.get_product_accounts()
acc_src = self._get_src_account(accounts_data)
acc_dest = self._get_dest_account(accounts_data)
acc_valuation = accounts_data.get('stock_valuation', False)
if acc_valuation:
acc_valuation = acc_valuation.id
if not accounts_data.get('stock_journal', False):
raise UserError(_('You don\'t have any stock journal defined on your product category, check if you have installed a chart of accounts.'))
if not acc_src:
raise UserError(_('Cannot find a stock input account for the product %s. You must define one on the product category, or on the location, before processing this operation.') % (self.product_id.display_name))
if not acc_dest:
raise UserError(_('Cannot find a stock output account for the product %s. You must define one on the product category, or on the location, before processing this operation.') % (self.product_id.display_name))
if not acc_valuation:
raise UserError(_('You don\'t have any stock valuation account defined on your product category. You must define one before processing this operation.'))
journal_id = accounts_data['stock_journal'].id
return journal_id, acc_src, acc_dest, acc_valuation
def _get_src_account(self, accounts_data):
return self.location_id.valuation_out_account_id.id or accounts_data['stock_input'].id
def _get_dest_account(self, accounts_data):
return self.location_dest_id.valuation_in_account_id.id or accounts_data['stock_output'].id
def _prepare_account_move_line(self, qty, cost, credit_account_id, debit_account_id, description):
"""
Generate the account.move.line values to post to track the stock valuation difference due to the
processing of the given quant.
"""
self.ensure_one()
# the standard_price of the product may be in another decimal precision, or not compatible with the coinage of
# the company currency... so we need to use round() before creating the accounting entries.
debit_value = self.company_id.currency_id.round(cost)
credit_value = debit_value
valuation_partner_id = self._get_partner_id_for_valuation_lines()
res = [(0, 0, line_vals) for line_vals in self._generate_valuation_lines_data(valuation_partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id, description).values()]
return res
def _prepare_analytic_line(self):
self.ensure_one()
if not self._get_analytic_account():
return False
if self.state in ['cancel', 'draft']:
return False
if self.state != 'done':
unit_amount = self.product_uom._compute_quantity(
self.quantity_done, self.product_id.uom_id)
# Falsy in FIFO but since it's an estimation we don't require exact correct cost. Otherwise
# we would have to recompute all the analytic estimation at each out.
amount = - unit_amount * self.product_id.standard_price
elif self.product_id.valuation == 'real_time':
accounts_data = self.product_id.product_tmpl_id.get_product_accounts()
account_valuation = accounts_data.get('stock_valuation', False)
analytic_line_vals = self.stock_valuation_layer_ids.account_move_id.line_ids.filtered(
lambda l: l.account_id == account_valuation)._prepare_analytic_line()
amount = - sum(vals['amount'] for vals in analytic_line_vals)
unit_amount = - sum(vals['unit_amount'] for vals in analytic_line_vals)
elif sum(self.stock_valuation_layer_ids.mapped('quantity')):
amount = sum(self.stock_valuation_layer_ids.mapped('value'))
unit_amount = - sum(self.stock_valuation_layer_ids.mapped('quantity'))
if self.analytic_account_line_id:
self.analytic_account_line_id.unit_amount = unit_amount
self.analytic_account_line_id.amount = amount
return False
elif amount:
return self._generate_analytic_lines_data(
unit_amount, amount)
def _generate_analytic_lines_data(self, unit_amount, amount):
self.ensure_one()
account_id = self._get_analytic_account()
return {
'name': self.name,
'amount': amount,
'account_id': account_id.id,
'unit_amount': unit_amount,
'product_id': self.product_id.id,
'product_uom_id': self.product_id.uom_id.id,
'company_id': self.company_id.id,
'ref': self._description,
'category': 'other',
}
def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id, description):
# This method returns a dictionary to provide an easy extension hook to modify the valuation lines (see purchase for an example)
self.ensure_one()
debit_line_vals = {
'name': description,
'product_id': self.product_id.id,
'quantity': qty,
'product_uom_id': self.product_id.uom_id.id,
'ref': description,
'partner_id': partner_id,
'debit': debit_value if debit_value > 0 else 0,
'credit': -debit_value if debit_value < 0 else 0,
'account_id': debit_account_id,
}
credit_line_vals = {
'name': description,
'product_id': self.product_id.id,
'quantity': qty,
'product_uom_id': self.product_id.uom_id.id,
'ref': description,
'partner_id': partner_id,
'credit': credit_value if credit_value > 0 else 0,
'debit': -credit_value if credit_value < 0 else 0,
'account_id': credit_account_id,
}
rslt = {'credit_line_vals': credit_line_vals, 'debit_line_vals': debit_line_vals}
if credit_value != debit_value:
# for supplier returns of product in average costing method, in anglo saxon mode
diff_amount = debit_value - credit_value
price_diff_account = self.product_id.property_account_creditor_price_difference
if not price_diff_account:
price_diff_account = self.product_id.categ_id.property_account_creditor_price_difference_categ
if not price_diff_account:
raise UserError(_('Configuration error. Please configure the price difference account on the product or its category to process this operation.'))
rslt['price_diff_line_vals'] = {
'name': self.name,
'product_id': self.product_id.id,
'quantity': qty,
'product_uom_id': self.product_id.uom_id.id,
'ref': description,
'partner_id': partner_id,
'credit': diff_amount > 0 and diff_amount or 0,
'debit': diff_amount < 0 and -diff_amount or 0,
'account_id': price_diff_account.id,
}
return rslt
def _get_partner_id_for_valuation_lines(self):
return (self.picking_id.partner_id and self.env['res.partner']._find_accounting_partner(self.picking_id.partner_id).id) or False
def _prepare_move_split_vals(self, uom_qty):
vals = super(StockMove, self)._prepare_move_split_vals(uom_qty)
vals['to_refund'] = self.to_refund
return vals
def _prepare_account_move_vals(self, credit_account_id, debit_account_id, journal_id, qty, description, svl_id, cost):
self.ensure_one()
move_lines = self._prepare_account_move_line(qty, cost, credit_account_id, debit_account_id, description)
date = self._context.get('force_period_date', fields.Date.context_today(self))
return {
'journal_id': journal_id,
'line_ids': move_lines,
'date': date,
'ref': description,
'stock_move_id': self.id,
'stock_valuation_layer_ids': [(6, None, [svl_id])],
'move_type': 'entry',
}
def _account_analytic_entry_move(self):
analytic_lines_vals = []
moves_to_link = []
for move in self:
analytic_line_vals = move._prepare_analytic_line()
if not analytic_line_vals:
continue
moves_to_link.append(move.id)
analytic_lines_vals.append(analytic_line_vals)
analytic_lines = self.env['account.analytic.line'].sudo().create(analytic_lines_vals)
for move_id, analytic_line in zip(moves_to_link, analytic_lines):
self.env['stock.move'].browse(
move_id).analytic_account_line_id = analytic_line
def _account_entry_move(self, qty, description, svl_id, cost):
""" Accounting Valuation Entries """
self.ensure_one()
am_vals = []
if self.product_id.type != 'product':
# no stock valuation for consumable products
return am_vals
if self.restrict_partner_id and self.restrict_partner_id != self.company_id.partner_id:
# if the move isn't owned by the company, we don't make any valuation
return am_vals
company_from = self._is_out() and self.mapped('move_line_ids.location_id.company_id') or False
company_to = self._is_in() and self.mapped('move_line_ids.location_dest_id.company_id') or False
journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation()
# Create Journal Entry for products arriving in the company; in case of routes making the link between several
# warehouse of the same company, the transit location belongs to this company, so we don't need to create accounting entries
if self._is_in():
if self._is_returned(valued_type='in'):
am_vals.append(self.with_company(company_to)._prepare_account_move_vals(acc_dest, acc_valuation, journal_id, qty, description, svl_id, cost))
else:
am_vals.append(self.with_company(company_to)._prepare_account_move_vals(acc_src, acc_valuation, journal_id, qty, description, svl_id, cost))
# Create Journal Entry for products leaving the company
if self._is_out():
cost = -1 * cost
if self._is_returned(valued_type='out'):
am_vals.append(self.with_company(company_from)._prepare_account_move_vals(acc_valuation, acc_src, journal_id, qty, description, svl_id, cost))
else:
am_vals.append(self.with_company(company_from)._prepare_account_move_vals(acc_valuation, acc_dest, journal_id, qty, description, svl_id, cost))
if self.company_id.anglo_saxon_accounting:
# Creates an account entry from stock_input to stock_output on a dropship move. https://github.com/odoo/odoo/issues/12687
if self._is_dropshipped():
if cost > 0:
am_vals.append(self.with_company(self.company_id)._prepare_account_move_vals(acc_src, acc_valuation, journal_id, qty, description, svl_id, cost))
else:
cost = -1 * cost
am_vals.append(self.with_company(self.company_id)._prepare_account_move_vals(acc_valuation, acc_dest, journal_id, qty, description, svl_id, cost))
elif self._is_dropshipped_returned():
if cost > 0:
am_vals.append(self.with_company(self.company_id)._prepare_account_move_vals(acc_valuation, acc_src, journal_id, qty, description, svl_id, cost))
else:
cost = -1 * cost
am_vals.append(self.with_company(self.company_id)._prepare_account_move_vals(acc_dest, acc_valuation, journal_id, qty, description, svl_id, cost))
return am_vals
def _get_analytic_account(self):
return False
def _get_related_invoices(self): # To be overridden in purchase and sale_stock
""" This method is overrided in both purchase and sale_stock modules to adapt
to the way they mix stock moves with invoices.
"""
return self.env['account.move']
def _is_returned(self, valued_type):
self.ensure_one()
if valued_type == 'in':
return self.location_id and self.location_id.usage == 'customer' # goods returned from customer
if valued_type == 'out':
return self.location_dest_id and self.location_dest_id.usage == 'supplier' # goods returned to supplier
| 51.515
| 30,909
|
863
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from odoo import models, fields
class StockPicking(models.Model):
_inherit = 'stock.picking'
country_code = fields.Char(related="company_id.account_fiscal_country_id.code")
def action_view_stock_valuation_layers(self):
self.ensure_one()
scraps = self.env['stock.scrap'].search([('picking_id', '=', self.id)])
domain = [('id', 'in', (self.move_lines + scraps.move_id).stock_valuation_layer_ids.ids)]
action = self.env["ir.actions.actions"]._for_xml_id("stock_account.stock_valuation_layer_action")
context = literal_eval(action['context'])
context.update(self.env.context)
context['no_at_date'] = True
return dict(action, domain=domain, context=context)
| 39.227273
| 863
|
1,817
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
import logging
_logger = logging.getLogger(__name__)
class AccountChartTemplate(models.Model):
_inherit = "account.chart.template"
@api.model
def generate_journals(self, acc_template_ref, company, journals_dict=None):
journal_to_add = [{'name': _('Inventory Valuation'), 'type': 'general', 'code': 'STJ', 'favorite': False, 'sequence': 8}]
return super(AccountChartTemplate, self).generate_journals(acc_template_ref=acc_template_ref, company=company, journals_dict=journal_to_add)
def generate_properties(self, acc_template_ref, company, property_list=None):
res = super(AccountChartTemplate, self).generate_properties(acc_template_ref=acc_template_ref, company=company)
PropertyObj = self.env['ir.property'] # Property Stock Journal
value = self.env['account.journal'].search([('company_id', '=', company.id), ('code', '=', 'STJ'), ('type', '=', 'general')], limit=1)
if value:
PropertyObj._set_default("property_stock_journal", "product.category", value, company)
todo_list = [ # Property Stock Accounts
'property_stock_account_input_categ_id',
'property_stock_account_output_categ_id',
'property_stock_valuation_account_id',
]
categ_values = {category.id: False for category in self.env['product.category'].search([])}
for field in todo_list:
account = self[field]
value = acc_template_ref[account].id if account else False
PropertyObj._set_default(field, "product.category", value, company)
PropertyObj._set_multi(field, "product.category", categ_values, True)
return res
| 49.108108
| 1,817
|
47,097
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_is_zero, float_repr, float_round, float_compare
from odoo.exceptions import ValidationError
from collections import defaultdict
class ProductTemplate(models.Model):
_name = 'product.template'
_inherit = 'product.template'
cost_method = fields.Selection(related="categ_id.property_cost_method", readonly=True)
valuation = fields.Selection(related="categ_id.property_valuation", readonly=True)
def write(self, vals):
impacted_templates = {}
move_vals_list = []
Product = self.env['product.product']
SVL = self.env['stock.valuation.layer']
if 'categ_id' in vals:
# When a change of category implies a change of cost method, we empty out and replenish
# the stock.
new_product_category = self.env['product.category'].browse(vals.get('categ_id'))
for product_template in self:
product_template = product_template.with_company(product_template.company_id)
valuation_impacted = False
if product_template.cost_method != new_product_category.property_cost_method:
valuation_impacted = True
if product_template.valuation != new_product_category.property_valuation:
valuation_impacted = True
if valuation_impacted is False:
continue
# Empty out the stock with the current cost method.
description = _("Due to a change of product category (from %s to %s), the costing method\
has changed for product template %s: from %s to %s.") %\
(product_template.categ_id.display_name, new_product_category.display_name,
product_template.display_name, product_template.cost_method, new_product_category.property_cost_method)
out_svl_vals_list, products_orig_quantity_svl, products = Product\
._svl_empty_stock(description, product_template=product_template)
out_stock_valuation_layers = SVL.create(out_svl_vals_list)
if product_template.valuation == 'real_time':
move_vals_list += Product._svl_empty_stock_am(out_stock_valuation_layers)
impacted_templates[product_template] = (products, description, products_orig_quantity_svl)
res = super(ProductTemplate, self).write(vals)
for product_template, (products, description, products_orig_quantity_svl) in impacted_templates.items():
# Replenish the stock with the new cost method.
in_svl_vals_list = products._svl_replenish_stock(description, products_orig_quantity_svl)
in_stock_valuation_layers = SVL.create(in_svl_vals_list)
if product_template.valuation == 'real_time':
move_vals_list += Product._svl_replenish_stock_am(in_stock_valuation_layers)
# Check access right
if move_vals_list and not self.env['stock.valuation.layer'].check_access_rights('read', raise_exception=False):
raise UserError(_("The action leads to the creation of a journal entry, for which you don't have the access rights."))
# Create the account moves.
if move_vals_list:
account_moves = self.env['account.move'].sudo().create(move_vals_list)
account_moves._post()
return res
# -------------------------------------------------------------------------
# Misc.
# -------------------------------------------------------------------------
def _get_product_accounts(self):
""" Add the stock accounts related to product to the result of super()
@return: dictionary which contains information regarding stock accounts and super (income+expense accounts)
"""
accounts = super(ProductTemplate, self)._get_product_accounts()
res = self._get_asset_accounts()
accounts.update({
'stock_input': res['stock_input'] or self.categ_id.property_stock_account_input_categ_id,
'stock_output': res['stock_output'] or self.categ_id.property_stock_account_output_categ_id,
'stock_valuation': self.categ_id.property_stock_valuation_account_id or False,
})
return accounts
def get_product_accounts(self, fiscal_pos=None):
""" Add the stock journal related to product to the result of super()
@return: dictionary which contains all needed information regarding stock accounts and journal and super (income+expense accounts)
"""
accounts = super(ProductTemplate, self).get_product_accounts(fiscal_pos=fiscal_pos)
accounts.update({'stock_journal': self.categ_id.property_stock_journal or False})
return accounts
class ProductProduct(models.Model):
_inherit = 'product.product'
value_svl = fields.Float(compute='_compute_value_svl', compute_sudo=True)
quantity_svl = fields.Float(compute='_compute_value_svl', compute_sudo=True)
stock_valuation_layer_ids = fields.One2many('stock.valuation.layer', 'product_id')
valuation = fields.Selection(related="categ_id.property_valuation", readonly=True)
cost_method = fields.Selection(related="categ_id.property_cost_method", readonly=True)
def write(self, vals):
if 'standard_price' in vals and not self.env.context.get('disable_auto_svl'):
self.filtered(lambda p: p.cost_method != 'fifo')._change_standard_price(vals['standard_price'])
return super(ProductProduct, self).write(vals)
@api.depends('stock_valuation_layer_ids')
@api.depends_context('to_date', 'company')
def _compute_value_svl(self):
"""Compute `value_svl` and `quantity_svl`."""
company_id = self.env.company.id
domain = [
('product_id', 'in', self.ids),
('company_id', '=', company_id),
]
if self.env.context.get('to_date'):
to_date = fields.Datetime.to_datetime(self.env.context['to_date'])
domain.append(('create_date', '<=', to_date))
groups = self.env['stock.valuation.layer'].read_group(domain, ['value:sum', 'quantity:sum'], ['product_id'], orderby='id')
products = self.browse()
for group in groups:
product = self.browse(group['product_id'][0])
product.value_svl = self.env.company.currency_id.round(group['value'])
product.quantity_svl = group['quantity']
products |= product
remaining = (self - products)
remaining.value_svl = 0
remaining.quantity_svl = 0
# -------------------------------------------------------------------------
# Actions
# -------------------------------------------------------------------------
def action_revaluation(self):
self.ensure_one()
ctx = dict(self._context, default_product_id=self.id, default_company_id=self.env.company.id)
return {
'name': _("Product Revaluation"),
'view_mode': 'form',
'res_model': 'stock.valuation.layer.revaluation',
'view_id': self.env.ref('stock_account.stock_valuation_layer_revaluation_form_view').id,
'type': 'ir.actions.act_window',
'context': ctx,
'target': 'new'
}
# -------------------------------------------------------------------------
# SVL creation helpers
# -------------------------------------------------------------------------
def _prepare_in_svl_vals(self, quantity, unit_cost):
"""Prepare the values for a stock valuation layer created by a receipt.
:param quantity: the quantity to value, expressed in `self.uom_id`
:param unit_cost: the unit cost to value `quantity`
:return: values to use in a call to create
:rtype: dict
"""
self.ensure_one()
company_id = self.env.context.get('force_company', self.env.company.id)
company = self.env['res.company'].browse(company_id)
vals = {
'product_id': self.id,
'value': company.currency_id.round(unit_cost * quantity),
'unit_cost': unit_cost,
'quantity': quantity,
}
if self.cost_method in ('average', 'fifo'):
vals['remaining_qty'] = quantity
vals['remaining_value'] = vals['value']
return vals
def _prepare_out_svl_vals(self, quantity, company):
"""Prepare the values for a stock valuation layer created by a delivery.
:param quantity: the quantity to value, expressed in `self.uom_id`
:return: values to use in a call to create
:rtype: dict
"""
self.ensure_one()
company_id = self.env.context.get('force_company', self.env.company.id)
company = self.env['res.company'].browse(company_id)
currency = company.currency_id
# Quantity is negative for out valuation layers.
quantity = -1 * quantity
vals = {
'product_id': self.id,
'value': currency.round(quantity * self.standard_price),
'unit_cost': self.standard_price,
'quantity': quantity,
}
if self.product_tmpl_id.cost_method in ('average', 'fifo'):
fifo_vals = self._run_fifo(abs(quantity), company)
vals['remaining_qty'] = fifo_vals.get('remaining_qty')
# In case of AVCO, fix rounding issue of standard price when needed.
if self.product_tmpl_id.cost_method == 'average' and not float_is_zero(self.quantity_svl, precision_rounding=self.uom_id.rounding):
rounding_error = currency.round(
(self.standard_price * self.quantity_svl - self.value_svl) * abs(quantity / self.quantity_svl)
)
if rounding_error:
# If it is bigger than the (smallest number of the currency * quantity) / 2,
# then it isn't a rounding error but a stock valuation error, we shouldn't fix it under the hood ...
if abs(rounding_error) <= max((abs(quantity) * currency.rounding) / 2, currency.rounding):
vals['value'] += rounding_error
vals['rounding_adjustment'] = '\nRounding Adjustment: %s%s %s' % (
'+' if rounding_error > 0 else '',
float_repr(rounding_error, precision_digits=currency.decimal_places),
currency.symbol
)
if self.product_tmpl_id.cost_method == 'fifo':
vals.update(fifo_vals)
return vals
def _change_standard_price(self, new_price):
"""Helper to create the stock valuation layers and the account moves
after an update of standard price.
:param new_price: new standard price
"""
# Handle stock valuation layers.
if self.filtered(lambda p: p.valuation == 'real_time') and not self.env['stock.valuation.layer'].check_access_rights('read', raise_exception=False):
raise UserError(_("You cannot update the cost of a product in automated valuation as it leads to the creation of a journal entry, for which you don't have the access rights."))
svl_vals_list = []
company_id = self.env.company
price_unit_prec = self.env['decimal.precision'].precision_get('Product Price')
rounded_new_price = float_round(new_price, precision_digits=price_unit_prec)
for product in self:
if product.cost_method not in ('standard', 'average'):
continue
quantity_svl = product.sudo().quantity_svl
if float_compare(quantity_svl, 0.0, precision_rounding=product.uom_id.rounding) <= 0:
continue
value_svl = product.sudo().value_svl
value = company_id.currency_id.round((rounded_new_price * quantity_svl) - value_svl)
if company_id.currency_id.is_zero(value):
continue
svl_vals = {
'company_id': company_id.id,
'product_id': product.id,
'description': _('Product value manually modified (from %s to %s)') % (product.standard_price, rounded_new_price),
'value': value,
'quantity': 0,
}
svl_vals_list.append(svl_vals)
stock_valuation_layers = self.env['stock.valuation.layer'].sudo().create(svl_vals_list)
# Handle account moves.
product_accounts = {product.id: product.product_tmpl_id.get_product_accounts() for product in self}
am_vals_list = []
for stock_valuation_layer in stock_valuation_layers:
product = stock_valuation_layer.product_id
value = stock_valuation_layer.value
if product.type != 'product' or product.valuation != 'real_time':
continue
# Sanity check.
if not product_accounts[product.id].get('expense'):
raise UserError(_('You must set a counterpart account on your product category.'))
if not product_accounts[product.id].get('stock_valuation'):
raise UserError(_('You don\'t have any stock valuation account defined on your product category. You must define one before processing this operation.'))
if value < 0:
debit_account_id = product_accounts[product.id]['expense'].id
credit_account_id = product_accounts[product.id]['stock_valuation'].id
else:
debit_account_id = product_accounts[product.id]['stock_valuation'].id
credit_account_id = product_accounts[product.id]['expense'].id
move_vals = {
'journal_id': product_accounts[product.id]['stock_journal'].id,
'company_id': company_id.id,
'ref': product.default_code,
'stock_valuation_layer_ids': [(6, None, [stock_valuation_layer.id])],
'move_type': 'entry',
'line_ids': [(0, 0, {
'name': _(
'%(user)s changed cost from %(previous)s to %(new_price)s - %(product)s',
user=self.env.user.name,
previous=product.standard_price,
new_price=new_price,
product=product.display_name
),
'account_id': debit_account_id,
'debit': abs(value),
'credit': 0,
'product_id': product.id,
}), (0, 0, {
'name': _(
'%(user)s changed cost from %(previous)s to %(new_price)s - %(product)s',
user=self.env.user.name,
previous=product.standard_price,
new_price=new_price,
product=product.display_name
),
'account_id': credit_account_id,
'debit': 0,
'credit': abs(value),
'product_id': product.id,
})],
}
am_vals_list.append(move_vals)
account_moves = self.env['account.move'].sudo().create(am_vals_list)
if account_moves:
account_moves._post()
def _run_fifo(self, quantity, company):
self.ensure_one()
# Find back incoming stock valuation layers (called candidates here) to value `quantity`.
qty_to_take_on_candidates = quantity
candidates = self.env['stock.valuation.layer'].sudo().search([
('product_id', '=', self.id),
('remaining_qty', '>', 0),
('company_id', '=', company.id),
])
new_standard_price = 0
tmp_value = 0 # to accumulate the value taken on the candidates
for candidate in candidates:
qty_taken_on_candidate = min(qty_to_take_on_candidates, candidate.remaining_qty)
candidate_unit_cost = candidate.remaining_value / candidate.remaining_qty
new_standard_price = candidate_unit_cost
value_taken_on_candidate = qty_taken_on_candidate * candidate_unit_cost
value_taken_on_candidate = candidate.currency_id.round(value_taken_on_candidate)
new_remaining_value = candidate.remaining_value - value_taken_on_candidate
candidate_vals = {
'remaining_qty': candidate.remaining_qty - qty_taken_on_candidate,
'remaining_value': new_remaining_value,
}
candidate.write(candidate_vals)
qty_to_take_on_candidates -= qty_taken_on_candidate
tmp_value += value_taken_on_candidate
if float_is_zero(qty_to_take_on_candidates, precision_rounding=self.uom_id.rounding):
if float_is_zero(candidate.remaining_qty, precision_rounding=self.uom_id.rounding):
next_candidates = candidates.filtered(lambda svl: svl.remaining_qty > 0)
new_standard_price = next_candidates and next_candidates[0].unit_cost or new_standard_price
break
# Update the standard price with the price of the last used candidate, if any.
if new_standard_price and self.cost_method == 'fifo':
self.sudo().with_company(company.id).with_context(disable_auto_svl=True).standard_price = new_standard_price
# If there's still quantity to value but we're out of candidates, we fall in the
# negative stock use case. We chose to value the out move at the price of the
# last out and a correction entry will be made once `_fifo_vacuum` is called.
vals = {}
if float_is_zero(qty_to_take_on_candidates, precision_rounding=self.uom_id.rounding):
vals = {
'value': -tmp_value,
'unit_cost': tmp_value / quantity,
}
else:
assert qty_to_take_on_candidates > 0
last_fifo_price = new_standard_price or self.standard_price
negative_stock_value = last_fifo_price * -qty_to_take_on_candidates
tmp_value += abs(negative_stock_value)
vals = {
'remaining_qty': -qty_to_take_on_candidates,
'value': -tmp_value,
'unit_cost': last_fifo_price,
}
return vals
def _run_fifo_vacuum(self, company=None):
"""Compensate layer valued at an estimated price with the price of future receipts
if any. If the estimated price is equals to the real price, no layer is created but
the original layer is marked as compensated.
:param company: recordset of `res.company` to limit the execution of the vacuum
"""
self.ensure_one()
if company is None:
company = self.env.company
svls_to_vacuum = self.env['stock.valuation.layer'].sudo().search([
('product_id', '=', self.id),
('remaining_qty', '<', 0),
('stock_move_id', '!=', False),
('company_id', '=', company.id),
], order='create_date, id')
if not svls_to_vacuum:
return
as_svls = []
domain = [
('company_id', '=', company.id),
('product_id', '=', self.id),
('remaining_qty', '>', 0),
('create_date', '>=', svls_to_vacuum[0].create_date),
]
all_candidates = self.env['stock.valuation.layer'].sudo().search(domain)
for svl_to_vacuum in svls_to_vacuum:
# We don't use search to avoid executing _flush_search and to decrease interaction with DB
candidates = all_candidates.filtered(
lambda r: r.create_date > svl_to_vacuum.create_date
or r.create_date == svl_to_vacuum.create_date
and r.id > svl_to_vacuum.id
)
if not candidates:
break
qty_to_take_on_candidates = abs(svl_to_vacuum.remaining_qty)
qty_taken_on_candidates = 0
tmp_value = 0
for candidate in candidates:
qty_taken_on_candidate = min(candidate.remaining_qty, qty_to_take_on_candidates)
qty_taken_on_candidates += qty_taken_on_candidate
candidate_unit_cost = candidate.remaining_value / candidate.remaining_qty
value_taken_on_candidate = qty_taken_on_candidate * candidate_unit_cost
value_taken_on_candidate = candidate.currency_id.round(value_taken_on_candidate)
new_remaining_value = candidate.remaining_value - value_taken_on_candidate
candidate_vals = {
'remaining_qty': candidate.remaining_qty - qty_taken_on_candidate,
'remaining_value': new_remaining_value
}
candidate.write(candidate_vals)
if not (candidate.remaining_qty > 0):
all_candidates -= candidate
qty_to_take_on_candidates -= qty_taken_on_candidate
tmp_value += value_taken_on_candidate
if float_is_zero(qty_to_take_on_candidates, precision_rounding=self.uom_id.rounding):
break
# Get the estimated value we will correct.
remaining_value_before_vacuum = svl_to_vacuum.unit_cost * qty_taken_on_candidates
new_remaining_qty = svl_to_vacuum.remaining_qty + qty_taken_on_candidates
corrected_value = remaining_value_before_vacuum - tmp_value
svl_to_vacuum.write({
'remaining_qty': new_remaining_qty,
})
# Don't create a layer or an accounting entry if the corrected value is zero.
if svl_to_vacuum.currency_id.is_zero(corrected_value):
continue
corrected_value = svl_to_vacuum.currency_id.round(corrected_value)
move = svl_to_vacuum.stock_move_id
vals = {
'product_id': self.id,
'value': corrected_value,
'unit_cost': 0,
'quantity': 0,
'remaining_qty': 0,
'stock_move_id': move.id,
'company_id': move.company_id.id,
'description': 'Revaluation of %s (negative inventory)' % (move.picking_id.name or move.name),
'stock_valuation_layer_id': svl_to_vacuum.id,
}
vacuum_svl = self.env['stock.valuation.layer'].sudo().create(vals)
if self.valuation != 'real_time':
continue
as_svls.append((vacuum_svl, svl_to_vacuum))
# If some negative stock were fixed, we need to recompute the standard price.
product = self.with_company(company.id)
if product.cost_method == 'average' and not float_is_zero(product.quantity_svl, precision_rounding=self.uom_id.rounding):
product.sudo().with_context(disable_auto_svl=True).write({'standard_price': product.value_svl / product.quantity_svl})
self.env['stock.valuation.layer'].browse(x[0].id for x in as_svls)._validate_accounting_entries()
for vacuum_svl, svl_to_vacuum in as_svls:
self._create_fifo_vacuum_anglo_saxon_expense_entry(vacuum_svl, svl_to_vacuum)
def _create_fifo_vacuum_anglo_saxon_expense_entry(self, vacuum_svl, svl_to_vacuum):
""" When product is delivered and invoiced while you don't have units in stock anymore, there are chances of that
product getting undervalued/overvalued. So, we should nevertheless take into account the fact that the product has
already been delivered and invoiced to the customer by posting the value difference in the expense account also.
Consider the below case where product is getting undervalued:
You bought 8 units @ 10$ -> You have a stock valuation of 8 units, unit cost 10.
Then you deliver 10 units of the product.
You assumed the missing 2 should go out at a value of 10$ but you are not sure yet as it hasn't been bought in Odoo yet.
Afterwards, you buy missing 2 units of the same product at 12$ instead of expected 10$.
In case the product has been undervalued when delivered without stock, the vacuum entry is the following one (this entry already takes place):
Account | Debit | Credit
===================================================
Stock Valuation | 0.00 | 4.00
Stock Interim (Delivered) | 4.00 | 0.00
So, on delivering product with different price, We should create additional journal items like:
Account | Debit | Credit
===================================================
Stock Interim (Delivered) | 0.00 | 4.00
Expenses Revaluation | 4.00 | 0.00
"""
if not vacuum_svl.company_id.anglo_saxon_accounting or not svl_to_vacuum.stock_move_id._is_out():
return False
AccountMove = self.env['account.move'].sudo()
account_move_lines = svl_to_vacuum.account_move_id.line_ids
# Find related customer invoice where product is delivered while you don't have units in stock anymore
reconciled_line_ids = list(set(account_move_lines._reconciled_lines()) - set(account_move_lines.ids))
account_move = AccountMove.search([('line_ids','in', reconciled_line_ids)], limit=1)
# If delivered quantity is not invoiced then no need to create this entry
if not account_move:
return False
accounts = svl_to_vacuum.product_id.product_tmpl_id.get_product_accounts(fiscal_pos=account_move.fiscal_position_id)
if not accounts.get('stock_output') or not accounts.get('expense'):
return False
description = "Expenses %s" % (vacuum_svl.description)
move_lines = vacuum_svl.stock_move_id._prepare_account_move_line(
vacuum_svl.quantity, vacuum_svl.value * -1,
accounts['stock_output'].id, accounts['expense'].id,
description)
new_account_move = AccountMove.sudo().create({
'journal_id': accounts['stock_journal'].id,
'line_ids': move_lines,
'date': self._context.get('force_period_date', fields.Date.context_today(self)),
'ref': description,
'stock_move_id': vacuum_svl.stock_move_id.id,
'move_type': 'entry',
})
new_account_move._post()
to_reconcile_account_move_lines = vacuum_svl.account_move_id.line_ids.filtered(lambda l: not l.reconciled and l.account_id == accounts['stock_output'] and l.account_id.reconcile)
to_reconcile_account_move_lines += new_account_move.line_ids.filtered(lambda l: not l.reconciled and l.account_id == accounts['stock_output'] and l.account_id.reconcile)
return to_reconcile_account_move_lines.reconcile()
@api.model
def _svl_empty_stock(self, description, product_category=None, product_template=None):
impacted_product_ids = []
impacted_products = self.env['product.product']
products_orig_quantity_svl = {}
# get the impacted products
domain = [('type', '=', 'product')]
if product_category is not None:
domain += [('categ_id', '=', product_category.id)]
elif product_template is not None:
domain += [('product_tmpl_id', '=', product_template.id)]
else:
raise ValueError()
products = self.env['product.product'].search_read(domain, ['quantity_svl'])
for product in products:
impacted_product_ids.append(product['id'])
products_orig_quantity_svl[product['id']] = product['quantity_svl']
impacted_products |= self.env['product.product'].browse(impacted_product_ids)
# empty out the stock for the impacted products
empty_stock_svl_list = []
for product in impacted_products:
# FIXME sle: why not use products_orig_quantity_svl here?
if float_is_zero(product.quantity_svl, precision_rounding=product.uom_id.rounding):
# FIXME: create an empty layer to track the change?
continue
if float_compare(product.quantity_svl, 0, precision_rounding=product.uom_id.rounding) > 0:
svsl_vals = product._prepare_out_svl_vals(product.quantity_svl, self.env.company)
else:
svsl_vals = product._prepare_in_svl_vals(abs(product.quantity_svl), product.value_svl / product.quantity_svl)
svsl_vals['description'] = description + svsl_vals.pop('rounding_adjustment', '')
svsl_vals['company_id'] = self.env.company.id
empty_stock_svl_list.append(svsl_vals)
return empty_stock_svl_list, products_orig_quantity_svl, impacted_products
def _svl_replenish_stock(self, description, products_orig_quantity_svl):
refill_stock_svl_list = []
for product in self:
quantity_svl = products_orig_quantity_svl[product.id]
if quantity_svl:
if float_compare(quantity_svl, 0, precision_rounding=product.uom_id.rounding) > 0:
svl_vals = product._prepare_in_svl_vals(quantity_svl, product.standard_price)
else:
svl_vals = product._prepare_out_svl_vals(abs(quantity_svl), self.env.company)
svl_vals['description'] = description
svl_vals['company_id'] = self.env.company.id
refill_stock_svl_list.append(svl_vals)
return refill_stock_svl_list
@api.model
def _svl_empty_stock_am(self, stock_valuation_layers):
move_vals_list = []
product_accounts = {product.id: product.product_tmpl_id.get_product_accounts() for product in stock_valuation_layers.mapped('product_id')}
for out_stock_valuation_layer in stock_valuation_layers:
product = out_stock_valuation_layer.product_id
stock_input_account = product_accounts[product.id].get('stock_input')
if not stock_input_account:
raise UserError(_('You don\'t have any stock input account defined on your product category. You must define one before processing this operation.'))
if not product_accounts[product.id].get('stock_valuation'):
raise UserError(_('You don\'t have any stock valuation account defined on your product category. You must define one before processing this operation.'))
debit_account_id = stock_input_account.id
credit_account_id = product_accounts[product.id]['stock_valuation'].id
value = out_stock_valuation_layer.value
move_vals = {
'journal_id': product_accounts[product.id]['stock_journal'].id,
'company_id': self.env.company.id,
'ref': product.default_code,
'stock_valuation_layer_ids': [(6, None, [out_stock_valuation_layer.id])],
'line_ids': [(0, 0, {
'name': out_stock_valuation_layer.description,
'account_id': debit_account_id,
'debit': abs(value),
'credit': 0,
'product_id': product.id,
}), (0, 0, {
'name': out_stock_valuation_layer.description,
'account_id': credit_account_id,
'debit': 0,
'credit': abs(value),
'product_id': product.id,
})],
'move_type': 'entry',
}
move_vals_list.append(move_vals)
return move_vals_list
def _svl_replenish_stock_am(self, stock_valuation_layers):
move_vals_list = []
product_accounts = {product.id: product.product_tmpl_id.get_product_accounts() for product in stock_valuation_layers.mapped('product_id')}
for out_stock_valuation_layer in stock_valuation_layers:
product = out_stock_valuation_layer.product_id
if not product_accounts[product.id].get('stock_input'):
raise UserError(_('You don\'t have any input valuation account defined on your product category. You must define one before processing this operation.'))
if not product_accounts[product.id].get('stock_valuation'):
raise UserError(_('You don\'t have any stock valuation account defined on your product category. You must define one before processing this operation.'))
debit_account_id = product_accounts[product.id]['stock_valuation'].id
credit_account_id = product_accounts[product.id]['stock_input'].id
value = out_stock_valuation_layer.value
move_vals = {
'journal_id': product_accounts[product.id]['stock_journal'].id,
'company_id': self.env.company.id,
'ref': product.default_code,
'stock_valuation_layer_ids': [(6, None, [out_stock_valuation_layer.id])],
'line_ids': [(0, 0, {
'name': out_stock_valuation_layer.description,
'account_id': debit_account_id,
'debit': abs(value),
'credit': 0,
'product_id': product.id,
}), (0, 0, {
'name': out_stock_valuation_layer.description,
'account_id': credit_account_id,
'debit': 0,
'credit': abs(value),
'product_id': product.id,
})],
'move_type': 'entry',
}
move_vals_list.append(move_vals)
return move_vals_list
# -------------------------------------------------------------------------
# Anglo saxon helpers
# -------------------------------------------------------------------------
def _stock_account_get_anglo_saxon_price_unit(self, uom=False):
price = self.standard_price
if not self or not uom or self.uom_id.id == uom.id:
return price or 0.0
return self.uom_id._compute_price(price, uom)
def _compute_average_price(self, qty_invoiced, qty_to_invoice, stock_moves):
"""Go over the valuation layers of `stock_moves` to value `qty_to_invoice` while taking
care of ignoring `qty_invoiced`. If `qty_to_invoice` is greater than what's possible to
value with the valuation layers, use the product's standard price.
:param qty_invoiced: quantity already invoiced
:param qty_to_invoice: quantity to invoice
:param stock_moves: recordset of `stock.move`
:returns: the anglo saxon price unit
:rtype: float
"""
self.ensure_one()
if not qty_to_invoice:
return 0
# if True, consider the incoming moves
is_returned = self.env.context.get('is_returned', False)
candidates = stock_moves\
.sudo()\
.filtered(lambda m: is_returned == bool(m.origin_returned_move_id and sum(m.stock_valuation_layer_ids.mapped('quantity')) >= 0))\
.mapped('stock_valuation_layer_ids')\
.sorted()
value_invoiced = self.env.context.get('value_invoiced', 0)
if 'value_invoiced' in self.env.context:
qty_valued, valuation = candidates._consume_all(qty_invoiced, value_invoiced, qty_to_invoice)
else:
qty_valued, valuation = candidates._consume_specific_qty(qty_invoiced, qty_to_invoice)
# If there's still quantity to invoice but we're out of candidates, we chose the standard
# price to estimate the anglo saxon price unit.
missing = qty_to_invoice - qty_valued
for sml in stock_moves.move_line_ids:
if not sml.owner_id or sml.owner_id == sml.company_id.partner_id:
continue
missing -= sml.product_uom_id._compute_quantity(sml.qty_done, self.uom_id, rounding_method='HALF-UP')
if float_compare(missing, 0, precision_rounding=self.uom_id.rounding) > 0:
valuation += self.standard_price * missing
return valuation / qty_to_invoice
class ProductCategory(models.Model):
_inherit = 'product.category'
property_valuation = fields.Selection([
('manual_periodic', 'Manual'),
('real_time', 'Automated')], string='Inventory Valuation',
company_dependent=True, copy=True, required=True,
help="""Manual: The accounting entries to value the inventory are not posted automatically.
Automated: An accounting entry is automatically created to value the inventory when a product enters or leaves the company.
""")
property_cost_method = fields.Selection([
('standard', 'Standard Price'),
('fifo', 'First In First Out (FIFO)'),
('average', 'Average Cost (AVCO)')], string="Costing Method",
company_dependent=True, copy=True, required=True,
help="""Standard Price: The products are valued at their standard cost defined on the product.
Average Cost (AVCO): The products are valued at weighted average cost.
First In First Out (FIFO): The products are valued supposing those that enter the company first will also leave it first.
""")
property_stock_journal = fields.Many2one(
'account.journal', 'Stock Journal', company_dependent=True,
domain="[('company_id', '=', allowed_company_ids[0])]", check_company=True,
help="When doing automated inventory valuation, this is the Accounting Journal in which entries will be automatically posted when stock moves are processed.")
property_stock_account_input_categ_id = fields.Many2one(
'account.account', 'Stock Input Account', company_dependent=True,
domain="[('company_id', '=', allowed_company_ids[0]), ('deprecated', '=', False)]", check_company=True,
help="""Counterpart journal items for all incoming stock moves will be posted in this account, unless there is a specific valuation account
set on the source location. This is the default value for all products in this category. It can also directly be set on each product.""")
property_stock_account_output_categ_id = fields.Many2one(
'account.account', 'Stock Output Account', company_dependent=True,
domain="[('company_id', '=', allowed_company_ids[0]), ('deprecated', '=', False)]", check_company=True,
help="""When doing automated inventory valuation, counterpart journal items for all outgoing stock moves will be posted in this account,
unless there is a specific valuation account set on the destination location. This is the default value for all products in this category.
It can also directly be set on each product.""")
property_stock_valuation_account_id = fields.Many2one(
'account.account', 'Stock Valuation Account', company_dependent=True,
domain="[('company_id', '=', allowed_company_ids[0]), ('deprecated', '=', False)]", check_company=True,
help="""When automated inventory valuation is enabled on a product, this account will hold the current value of the products.""",)
@api.constrains('property_stock_valuation_account_id', 'property_stock_account_output_categ_id', 'property_stock_account_input_categ_id')
def _check_valuation_accouts(self):
# Prevent to set the valuation account as the input or output account.
for category in self:
valuation_account = category.property_stock_valuation_account_id
input_and_output_accounts = category.property_stock_account_input_categ_id | category.property_stock_account_output_categ_id
if valuation_account and valuation_account in input_and_output_accounts:
raise ValidationError(_('The Stock Input and/or Output accounts cannot be the same as the Stock Valuation account.'))
@api.onchange('property_cost_method')
def onchange_property_cost(self):
if not self._origin:
# don't display the warning when creating a product category
return
return {
'warning': {
'title': _("Warning"),
'message': _("Changing your cost method is an important change that will impact your inventory valuation. Are you sure you want to make that change?"),
}
}
def write(self, vals):
impacted_categories = {}
move_vals_list = []
Product = self.env['product.product']
SVL = self.env['stock.valuation.layer']
if 'property_cost_method' in vals or 'property_valuation' in vals:
# When the cost method or the valuation are changed on a product category, we empty
# out and replenish the stock for each impacted products.
new_cost_method = vals.get('property_cost_method')
new_valuation = vals.get('property_valuation')
for product_category in self:
property_stock_fields = ['property_stock_account_input_categ_id', 'property_stock_account_output_categ_id', 'property_stock_valuation_account_id']
if 'property_valuation' in vals and vals['property_valuation'] == 'manual_periodic' and product_category.property_valuation != 'manual_periodic':
for stock_property in property_stock_fields:
vals[stock_property] = False
elif 'property_valuation' in vals and vals['property_valuation'] == 'real_time' and product_category.property_valuation != 'real_time':
company_id = self.env.company
for stock_property in property_stock_fields:
vals[stock_property] = vals.get(stock_property, False) or company_id[stock_property]
elif product_category.property_valuation == 'manual_periodic':
for stock_property in property_stock_fields:
if stock_property in vals:
vals.pop(stock_property)
else:
for stock_property in property_stock_fields:
if stock_property in vals and vals[stock_property] is False:
vals.pop(stock_property)
valuation_impacted = False
if new_cost_method and new_cost_method != product_category.property_cost_method:
valuation_impacted = True
if new_valuation and new_valuation != product_category.property_valuation:
valuation_impacted = True
if valuation_impacted is False:
continue
# Empty out the stock with the current cost method.
if new_cost_method:
description = _("Costing method change for product category %s: from %s to %s.") \
% (product_category.display_name, product_category.property_cost_method, new_cost_method)
else:
description = _("Valuation method change for product category %s: from %s to %s.") \
% (product_category.display_name, product_category.property_valuation, new_valuation)
out_svl_vals_list, products_orig_quantity_svl, products = Product\
._svl_empty_stock(description, product_category=product_category)
out_stock_valuation_layers = SVL.sudo().create(out_svl_vals_list)
if product_category.property_valuation == 'real_time':
move_vals_list += Product._svl_empty_stock_am(out_stock_valuation_layers)
impacted_categories[product_category] = (products, description, products_orig_quantity_svl)
res = super(ProductCategory, self).write(vals)
for product_category, (products, description, products_orig_quantity_svl) in impacted_categories.items():
# Replenish the stock with the new cost method.
in_svl_vals_list = products._svl_replenish_stock(description, products_orig_quantity_svl)
in_stock_valuation_layers = SVL.sudo().create(in_svl_vals_list)
if product_category.property_valuation == 'real_time':
move_vals_list += Product._svl_replenish_stock_am(in_stock_valuation_layers)
# Check access right
if move_vals_list and not self.env['stock.valuation.layer'].check_access_rights('read', raise_exception=False):
raise UserError(_("The action leads to the creation of a journal entry, for which you don't have the access rights."))
# Create the account moves.
if move_vals_list:
account_moves = self.env['account.move'].sudo().create(move_vals_list)
account_moves._post()
return res
@api.model
def create(self, vals):
if 'property_valuation' not in vals or vals['property_valuation'] == 'manual_periodic':
vals['property_stock_account_input_categ_id'] = False
vals['property_stock_account_output_categ_id'] = False
vals['property_stock_valuation_account_id'] = False
if 'property_valuation' in vals and vals['property_valuation'] == 'real_time':
company_id = self.env.company
vals['property_stock_account_input_categ_id'] = vals.get('property_stock_account_input_categ_id', False) or company_id.property_stock_account_input_categ_id
vals['property_stock_account_output_categ_id'] = vals.get('property_stock_account_output_categ_id', False) or company_id.property_stock_account_output_categ_id
vals['property_stock_valuation_account_id'] = vals.get('property_stock_valuation_account_id', False) or company_id.property_stock_valuation_account_id
return super().create(vals)
@api.onchange('property_valuation')
def onchange_property_valuation(self):
# Remove or set the account stock properties if necessary
if self.property_valuation == 'manual_periodic':
self.property_stock_account_input_categ_id = False
self.property_stock_account_output_categ_id = False
self.property_stock_valuation_account_id = False
if self.property_valuation == 'real_time':
company_id = self.env.company
self.property_stock_account_input_categ_id = company_id.property_stock_account_input_categ_id
self.property_stock_account_output_categ_id = company_id.property_stock_account_output_categ_id
self.property_stock_valuation_account_id = company_id.property_stock_valuation_account_id
| 54.700348
| 47,097
|
582
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
module_stock_landed_costs = fields.Boolean("Landed Costs",
help="Affect landed costs on reception operations and split them among products to update their cost price.")
group_lot_on_invoice = fields.Boolean("Display Lots & Serial Numbers on Invoices",
implied_group='stock_account.group_lot_on_invoice')
| 44.769231
| 582
|
2,129
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.tools.float_utils import float_is_zero, float_repr
class ReplenishmentReport(models.AbstractModel):
_inherit = 'report.stock.report_product_product_replenishment'
def _compute_draft_quantity_count(self, product_template_ids, product_variant_ids, wh_location_ids):
""" Overrides to computes the valuations of the stock. """
res = super()._compute_draft_quantity_count(product_template_ids, product_variant_ids, wh_location_ids)
if not self.user_has_groups('stock.group_stock_manager'):
return res
domain = self._product_domain(product_template_ids, product_variant_ids)
company = self.env['stock.location'].browse(wh_location_ids[0]).company_id
svl = self.env['stock.valuation.layer'].search(domain + [('company_id', '=', company.id)])
domain_quants = [
('company_id', '=', company.id),
('location_id', 'in', wh_location_ids)
]
if product_template_ids:
domain_quants += [('product_id.product_tmpl_id', 'in', product_template_ids)]
else:
domain_quants += [('product_id', 'in', product_variant_ids)]
quants = self.env['stock.quant'].search(domain_quants)
currency = svl.currency_id or self.env.company.currency_id
total_quantity = sum(svl.mapped('quantity'))
# Because we can have negative quantities, `total_quantity` may be equal to zero even if the warehouse's `quantity` is positive.
if svl and not float_is_zero(total_quantity, precision_rounding=svl.product_id.uom_id.rounding):
value = sum(svl.mapped('value')) * (sum(quants.mapped('quantity')) / total_quantity)
else:
value = 0
value = float_repr(value, precision_digits=currency.decimal_places)
if currency.position == 'after':
value = '%s %s' % (value, currency.symbol)
else:
value = '%s %s' % (currency.symbol, value)
res['value'] = value
return res
| 51.926829
| 2,129
|
785
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Online Task Submission',
'category': 'Website/Website',
'summary': 'Add a task suggestion form to your website',
'version': '1.0',
'description': """
Generate tasks in Project app from a form published on your website. This module requires the use of the *Form Builder* module (available in Odoo Enterprise) in order to build the form.
""",
'depends': ['website', 'project'],
'data': [
'data/website_form_project_data.xml',
],
'installable': True,
'auto_install': True,
'assets': {
'website.assets_editor': [
'website_form_project/static/src/**/*',
],
},
'license': 'LGPL-3',
}
| 32.708333
| 785
|
613
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website.controllers import form
class WebsiteForm(form.WebsiteForm):
def insert_record(self, request, model, values, custom, meta=None):
if model.model == 'project.task':
visitor_sudo = request.env['website.visitor']._get_visitor_from_request()
visitor_partner = visitor_sudo.partner_id
if visitor_partner:
values['partner_id'] = visitor_partner.id
return super().insert_record(request, model, values, custom, meta=meta)
| 40.866667
| 613
|
684
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Fleet History',
'version': '1.0',
'category': 'Human Resources',
'summary': 'Get history of driven cars by employees',
'description': "",
'depends': ['hr', 'fleet'],
'data': [
'security/ir.model.access.csv',
'security/hr_fleet_security.xml',
'views/employee_views.xml',
'views/fleet_vehicle_views.xml',
'views/fleet_vehicle_cost_views.xml',
'wizard/hr_departure_wizard_views.xml',
],
'demo': [
'data/hr_fleet_demo.xml',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 29.73913
| 684
|
1,433
|
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 HrDepartureWizard(models.TransientModel):
_inherit = 'hr.departure.wizard'
release_campany_car = fields.Boolean("Release Company Car", default=True,
help="Release the company car.")
def action_register_departure(self):
super(HrDepartureWizard, self).action_register_departure()
if self.release_campany_car:
self._free_campany_car()
def _free_campany_car(self):
"""Find all fleet.vehichle.assignation.log records that link to the employee, if there is no
end date or end date > departure date, update the date. Also check fleet.vehicle to see if
there is any record with its dirver_id to be the employee, set them to False."""
drivers = self.employee_id.user_id.partner_id | self.employee_id.sudo().address_home_id
assignations = self.env['fleet.vehicle.assignation.log'].search([('driver_id', 'in', drivers.ids)])
for assignation in assignations:
if self.departure_date and (not assignation.date_end or assignation.date_end > self.departure_date):
assignation.write({'date_end': self.departure_date})
cars = self.env['fleet.vehicle'].search([('driver_id', 'in', drivers.ids)])
cars.write({'driver_id': False, 'driver_employee_id': False})
| 51.178571
| 1,433
|
958
|
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 FleetVehicleLogServices(models.Model):
_inherit = 'fleet.vehicle.log.services'
purchaser_employee_id = fields.Many2one(
'hr.employee', string="Driver (Employee)",
compute='_compute_purchaser_employee_id', readonly=False, store=True,
)
@api.depends('vehicle_id', 'purchaser_employee_id')
def _compute_purchaser_id(self):
internals = self.filtered(lambda r: r.purchaser_employee_id)
super(FleetVehicleLogServices, (self - internals))._compute_purchaser_id()
for service in internals:
service.purchaser_id = service.purchaser_employee_id.address_home_id
@api.depends('vehicle_id')
def _compute_purchaser_employee_id(self):
for service in self:
service.purchaser_employee_id = service.vehicle_id.driver_employee_id
| 39.916667
| 958
|
1,248
|
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 FleetVehicleAssignationLog(models.Model):
_inherit = 'fleet.vehicle.assignation.log'
driver_employee_id = fields.Many2one(related="vehicle_id.driver_employee_id", string='Driver (Employee)')
attachment_number = fields.Integer('Number of Attachments', compute='_compute_attachment_number')
def _compute_attachment_number(self):
attachment_data = self.env['ir.attachment'].read_group([
('res_model', '=', 'fleet.vehicle.assignation.log'),
('res_id', 'in', self.ids)], ['res_id'], ['res_id'])
attachment = dict((data['res_id'], data['res_id_count']) for data in attachment_data)
for doc in self:
doc.attachment_number = attachment.get(doc.id, 0)
def action_get_attachment_view(self):
self.ensure_one()
res = self.env['ir.actions.act_window']._for_xml_id('base.action_attachment')
res['domain'] = [('res_model', '=', 'fleet.vehicle.assignation.log'), ('res_id', 'in', self.ids)]
res['context'] = {'default_res_model': 'fleet.vehicle.assignation.log', 'default_res_id': self.id}
return res
| 48
| 1,248
|
5,153
|
py
|
PYTHON
|
15.0
|
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class FleetVehicle(models.Model):
_inherit = 'fleet.vehicle'
mobility_card = fields.Char(compute='_compute_mobility_card', store=True)
driver_employee_id = fields.Many2one(
'hr.employee', 'Driver (Employee)',
compute='_compute_driver_employee_id', store=True,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
tracking=True,
)
driver_employee_name = fields.Char(related="driver_employee_id.name")
future_driver_employee_id = fields.Many2one(
'hr.employee', 'Future Driver (Employee)',
compute='_compute_future_driver_employee_id', store=True,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
tracking=True,
)
@api.depends('driver_id')
def _compute_driver_employee_id(self):
for vehicle in self:
if vehicle.driver_id:
vehicle.driver_employee_id = self.env['hr.employee'].search([
('address_home_id', '=', vehicle.driver_id.id),
], limit=1)
else:
vehicle.driver_employee_id = False
@api.depends('future_driver_id')
def _compute_future_driver_employee_id(self):
for vehicle in self:
if vehicle.future_driver_id:
vehicle.future_driver_employee_id = self.env['hr.employee'].search([
('address_home_id', '=', vehicle.future_driver_id.id),
], limit=1)
else:
vehicle.future_driver_employee_id = False
@api.depends('driver_id')
def _compute_mobility_card(self):
for vehicle in self:
employee = self.env['hr.employee']
if vehicle.driver_id:
employee = employee.search([('address_home_id', '=', vehicle.driver_id.id)], limit=1)
if not employee:
employee = employee.search([('user_id.partner_id', '=', vehicle.driver_id.id)], limit=1)
vehicle.mobility_card = employee.mobility_card
def _update_create_write_vals(self, vals):
if 'driver_employee_id' in vals:
partner = False
if vals['driver_employee_id']:
employee = self.env['hr.employee'].sudo().browse(vals['driver_employee_id'])
partner = employee.address_home_id.id
vals['driver_id'] = partner
elif 'driver_id' in vals:
# Reverse the process if we can find a single employee
employee = False
if vals['driver_id']:
# Limit to 2, we only care about the first one if he is the only one
employee_ids = self.env['hr.employee'].sudo().search([
('address_home_id', '=', vals['driver_id'])
], limit=2)
if len(employee_ids) == 1:
employee = employee_ids[0].id
vals['driver_employee_id'] = employee
# Same for future driver
if 'future_driver_employee_id' in vals:
partner = False
if vals['future_driver_employee_id']:
employee = self.env['hr.employee'].sudo().browse(vals['future_driver_employee_id'])
partner = employee.address_home_id.id
vals['future_driver_id'] = partner
elif 'future_driver_id' in vals:
# Reverse the process if we can find a single employee
employee = False
if vals['future_driver_id']:
# Limit to 2, we only care about the first one if he is the only one
employee_ids = self.env['hr.employee'].sudo().search([
('address_home_id', '=', vals['future_driver_id'])
], limit=2)
if len(employee_ids) == 1:
employee = employee_ids[0].id
vals['future_driver_employee_id'] = employee
@api.model
def create(self, vals):
self._update_create_write_vals(vals)
return super().create(vals)
def write(self, vals):
self._update_create_write_vals(vals)
if 'driver_employee_id' in vals:
for vehicle in self:
if vehicle.driver_employee_id and vehicle.driver_employee_id.id != vals['driver_employee_id']:
partners_to_unsubscribe = vehicle.driver_id.ids
employee = vehicle.driver_employee_id
if employee and employee.user_id.partner_id:
partners_to_unsubscribe.append(employee.user_id.partner_id.id)
vehicle.message_unsubscribe(partner_ids=partners_to_unsubscribe)
return super().write(vals)
def action_open_employee(self):
self.ensure_one()
return {
'name': _('Related Employee'),
'type': 'ir.actions.act_window',
'res_model': 'hr.employee',
'view_mode': 'form',
'res_id': self.driver_employee_id.id,
}
| 43.669492
| 5,153
|
3,015
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class Employee(models.Model):
_inherit = 'hr.employee'
employee_cars_count = fields.Integer(compute="_compute_employee_cars_count", string="Cars", groups="fleet.fleet_group_manager")
car_ids = fields.One2many(
'fleet.vehicle', 'driver_employee_id', string='Vehicles (private)',
groups="fleet.fleet_group_manager,hr.group_hr_user",
)
mobility_card = fields.Char(groups="fleet.fleet_group_user")
def action_open_employee_cars(self):
self.ensure_one()
cars = self.env['fleet.vehicle.assignation.log'].search([
('driver_id', 'in', (self.user_id.partner_id | self.sudo().address_home_id).ids)]).mapped('vehicle_id')
return {
"type": "ir.actions.act_window",
"res_model": "fleet.vehicle",
"views": [[False, "kanban"], [False, "form"], [False, "tree"]],
"domain": [("id", "in", cars.ids)],
"context": dict(self._context, create=False),
"name": "History Employee Cars",
}
def _compute_employee_cars_count(self):
for employee in self:
employee.employee_cars_count = len(employee.car_ids)
def action_get_claim_report(self):
self.ensure_one()
return {
'name': 'Claim Report',
'type': 'ir.actions.act_url',
'url': '/fleet/print_claim_report/%(employee_id)s' % {'employee_id': self.id},
}
@api.constrains('address_home_id')
def _check_address_home_id(self):
no_address = self.filtered(lambda r: not r.address_home_id)
car_ids = self.env['fleet.vehicle'].sudo().search([
('driver_employee_id', 'in', no_address.ids),
])
# Prevent from removing employee address when linked to a car
if car_ids:
raise ValidationError(_('Cannot remove address from employees with linked cars.'))
def write(self, vals):
res = super().write(vals)
#Update car partner when it is changed on the employee
if 'address_home_id' in vals:
car_ids = self.env['fleet.vehicle'].sudo().search([
('driver_employee_id', 'in', self.ids),
('driver_id', 'in', self.mapped('address_home_id').ids),
])
if car_ids:
car_ids.write({'driver_id': vals['address_home_id']})
if 'mobility_card' in vals:
#NOTE: keeping it as a search on driver_id but we might be able to use driver_employee_id in the future
vehicles = self.env['fleet.vehicle'].search([('driver_id', 'in', (self.user_id.partner_id | self.sudo().address_home_id).ids)])
vehicles._compute_mobility_card()
return res
class EmployeePublic(models.Model):
_inherit = 'hr.employee.public'
mobility_card = fields.Char(readonly=True)
| 40.743243
| 3,015
|
595
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class User(models.Model):
_inherit = ['res.users']
employee_cars_count = fields.Integer(related='employee_id.employee_cars_count')
@property
def SELF_READABLE_FIELDS(self):
return super().SELF_READABLE_FIELDS + ['employee_cars_count']
def action_get_claim_report(self):
return self.employee_id.action_get_claim_report()
def action_open_employee_cars(self):
return self.employee_id.action_open_employee_cars()
| 29.75
| 595
|
359
|
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 FleetVehicleLogContract(models.Model):
_inherit = 'fleet.vehicle.log.contract'
purchaser_employee_id = fields.Many2one(
related='vehicle_id.driver_employee_id',
string='Driver (Employee)',
)
| 29.916667
| 359
|
365
|
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 FleetVehicleOdometer(models.Model):
_inherit = 'fleet.vehicle.odometer'
driver_employee_id = fields.Many2one(
related='vehicle_id.driver_employee_id', string='Driver (Employee)',
readonly=True,
)
| 28.076923
| 365
|
3,089
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import io
from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from odoo import _
from odoo.http import request, route, Controller
class HrFleet(Controller):
@route(["/fleet/print_claim_report/<int:employee_id>"], type='http', auth='user')
def get_claim_report_user(self, employee_id, **post):
if not request.env.user.has_group('fleet.fleet_group_manager'):
return request.not_found()
employee = request.env['hr.employee'].search([('id', '=', employee_id)], limit=1)
partner_ids = (employee.user_id.partner_id | employee.sudo().address_home_id).ids
if not employee or not partner_ids:
return request.not_found()
car_assignation_logs = request.env['fleet.vehicle.assignation.log'].search([('driver_id', 'in', partner_ids)])
doc_list = request.env['ir.attachment'].search([
('res_model', '=', 'fleet.vehicle.assignation.log'),
('res_id', 'in', car_assignation_logs.ids)], order='create_date')
writer = PdfFileWriter()
font = "Helvetica"
normal_font_size = 14
for document in doc_list:
car_line_doc = request.env['fleet.vehicle.assignation.log'].browse(document.res_id)
try:
reader = PdfFileReader(io.BytesIO(base64.b64decode(document.datas)), strict=False, overwriteWarnings=False)
except Exception:
continue
width = float(reader.getPage(0).mediaBox.getUpperRight_x())
height = float(reader.getPage(0).mediaBox.getUpperRight_y())
header = io.BytesIO()
can = canvas.Canvas(header)
can.setFont(font, normal_font_size)
can.setFillColorRGB(1, 0, 0)
car_name = car_line_doc.vehicle_id.display_name
date_start = car_line_doc.date_start
date_end = car_line_doc.date_end or '...'
text_to_print = _(
"%(car_name)s (driven from: %(date_start)s to %(date_end)s)",
car_name=car_name,
date_start=date_start,
date_end=date_end
)
can.drawCentredString(width / 2, height - normal_font_size, text_to_print)
can.save()
header_pdf = PdfFileReader(header, overwriteWarnings=False)
for page_number in range(0, reader.getNumPages()):
page = reader.getPage(page_number)
page.mergePage(header_pdf.getPage(0))
writer.addPage(page)
if not writer.getNumPages():
request.not_found(_('There is no pdf attached to generate a claim report.'))
_buffer = io.BytesIO()
writer.write(_buffer)
merged_pdf = _buffer.getvalue()
_buffer.close()
pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(merged_pdf))]
return request.make_response(merged_pdf, headers=pdfhttpheaders)
| 38.6125
| 3,089
|
696
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Stock - SMS",
'summary': 'Send text messages when final stock move',
'description': "Send text messages when final stock move",
'category': 'Hidden',
'version': '1.0',
'depends': ['stock', 'sms'],
'data': [
'data/sms_data.xml',
'views/res_config_settings_views.xml',
'wizard/confirm_stock_sms_views.xml',
'security/ir.model.access.csv',
'security/sms_security.xml',
],
'application': False,
'auto_install': True,
'post_init_hook': '_assign_default_sms_template_picking_id',
'license': 'LGPL-3',
}
| 31.636364
| 696
|
1,245
|
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 ConfirmStockSms(models.TransientModel):
_name = 'confirm.stock.sms'
_description = 'Confirm Stock SMS'
pick_ids = fields.Many2many('stock.picking', 'stock_picking_sms_rel')
def send_sms(self):
self.ensure_one()
for company in self.pick_ids.company_id:
if not company.has_received_warning_stock_sms:
company.sudo().write({'has_received_warning_stock_sms': True})
pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids'))
return pickings_to_validate.button_validate()
def dont_send_sms(self):
self.ensure_one()
for company in self.pick_ids.company_id:
if not company.has_received_warning_stock_sms:
company.sudo().write({
'has_received_warning_stock_sms': True,
'stock_move_sms_validation': False,
})
pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids'))
return pickings_to_validate.button_validate()
| 40.16129
| 1,245
|
815
|
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"
def _default_confirmation_sms_picking_template(self):
try:
return self.env.ref('stock_sms.sms_template_data_stock_delivery').id
except ValueError:
return False
stock_move_sms_validation = fields.Boolean("SMS Confirmation", default=True)
stock_sms_confirmation_template_id = fields.Many2one(
'sms.template', string="SMS Template",
domain="[('model', '=', 'stock.picking')]",
default=_default_confirmation_sms_picking_template,
help="SMS sent to the customer once the order is done.")
has_received_warning_stock_sms = fields.Boolean()
| 37.045455
| 815
|
2,847
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
import threading
class Picking(models.Model):
_inherit = 'stock.picking'
def _pre_action_done_hook(self):
res = super()._pre_action_done_hook()
if res is True and not self.env.context.get('skip_sms'):
pickings_to_warn_sms = self._check_warn_sms()
if pickings_to_warn_sms:
return pickings_to_warn_sms._action_generate_warn_sms_wizard()
return res
def _check_warn_sms(self):
warn_sms_pickings = self.browse()
for picking in self:
is_delivery = picking.company_id.stock_move_sms_validation \
and picking.picking_type_id.code == 'outgoing' \
and (picking.partner_id.mobile or picking.partner_id.phone)
if is_delivery and not getattr(threading.current_thread(), 'testing', False) \
and not self.env.registry.in_test_mode() \
and not picking.company_id.has_received_warning_stock_sms \
and picking.company_id.stock_move_sms_validation:
warn_sms_pickings |= picking
return warn_sms_pickings
def _action_generate_warn_sms_wizard(self):
view = self.env.ref('stock_sms.view_confirm_stock_sms')
wiz = self.env['confirm.stock.sms'].create({'pick_ids': [(4, p.id) for p in self]})
return {
'name': _('SMS'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'confirm.stock.sms',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'res_id': wiz.id,
'context': self.env.context,
}
def _sms_get_number_fields(self):
""" This method returns the fields to use to find the number to use to
send an SMS on a record. """
return ['mobile', 'phone']
def _send_confirmation_email(self):
super(Picking, self)._send_confirmation_email()
if not self.env.context.get('skip_sms') and not getattr(threading.current_thread(), 'testing', False) and not self.env.registry.in_test_mode():
pickings = self.filtered(lambda p: p.company_id.stock_move_sms_validation and p.picking_type_id.code == 'outgoing' and (p.partner_id.mobile or p.partner_id.phone))
for picking in pickings:
# Sudo as the user has not always the right to read this sms template.
template = picking.company_id.sudo().stock_sms_confirmation_template_id
picking._message_sms_with_template(
template=template,
partner_ids=picking.partner_id.ids,
put_in_queue=False
)
| 44.484375
| 2,847
|
528
|
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'
stock_move_sms_validation = fields.Boolean(
related='company_id.stock_move_sms_validation',
string='SMS Validation with stock move', readonly=False)
stock_sms_confirmation_template_id = fields.Many2one(
related='company_id.stock_sms_confirmation_template_id', readonly=False)
| 37.714286
| 528
|
738
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Website Modules Test',
'version': '1.0',
'category': 'Hidden',
'sequence': 9876,
'description': """This module contains tests related to website modules.
It allows to test website business code when another website module is
installed.""",
'depends': [
'theme_default',
'website',
'website_blog',
'website_event_sale',
'website_slides',
],
'data': [
],
'installable': True,
'application': False,
'assets': {
'web.assets_tests': [
'test_website_modules/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 25.448276
| 738
|
457
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
from odoo.addons.website.tests.test_configurator import TestConfiguratorCommon
@odoo.tests.common.tagged('post_install', '-at_install')
class TestConfigurator(TestConfiguratorCommon):
def test_01_configurator_flow(self):
self.start_tour('/web#action=website.action_website_configuration', 'configurator_flow', login="admin")
| 41.545455
| 457
|
1,903
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2008-2008 凯源吕鑫 lvxin@gmail.com <basic chart data>
# 维智众源 oldrev@gmail.com <states data>
# Copyright (C) 2012-2012 南京盈通 ccdos@intoerp.com <small business chart>
# Copyright (C) 2008-now 开阖软件 jeff@osbzr.com < PM and LTS >
# Copyright (C) 2018-now jeffery9@gmail.com
{
'name': 'China - Accounting',
'version': '1.8',
'category': 'Accounting/Localizations/Account Charts',
'author': 'www.openerp-china.org',
'maintainer': 'jeff@osbzr.com',
'website': 'http://openerp-china.org',
'description': """
Includes the following data for the Chinese localization
========================================================
Account Type/科目类型
State Data/省份数据
科目类型\会计科目表模板\增值税\辅助核算类别\管理会计凭证簿\财务会计凭证簿
添加中文省份数据
增加小企业会计科目表
修改小企业会计科目表
修改小企业会计税率
We added the option to print a voucher which will also
print the amount in words (special Chinese characters for numbers)
correctly when the cn2an library is installed. (e.g. with pip3 install cn2an)
""",
'depends': ['base', 'account', 'l10n_multilang'],
'data': [
'data/account_tax_group_data.xml',
'data/l10n_cn_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_cn_chart_post_data.xml',
'data/account_tax_template_data.xml',
'data/account_chart_template_data.xml',
'views/account_move_view.xml',
'views/account_report.xml',
'views/report_voucher.xml',
],
'demo': [
'demo/demo_company.xml',
],
'post_init_hook': 'load_translations',
'license': 'LGPL-3',
}
| 30.589286
| 1,713
|
1,610
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.osv import expression
try:
from cn2an import an2cn
except ImportError:
an2cn = None
class AccountMove(models.Model):
_inherit = 'account.move'
fapiao = fields.Char(string='Fapiao Number', size=8, copy=False, tracking=True)
@api.constrains('fapiao')
def _check_fapiao(self):
for record in self:
if record.fapiao and (len(record.fapiao) != 8 or not record.fapiao.isdecimal()):
raise ValidationError(_("Fapiao number is an 8-digit number. Please enter a correct one."))
@api.model
def check_cn2an(self):
return an2cn
@api.model
def _convert_to_amount_in_word(self, number):
"""Convert number to ``amount in words`` for Chinese financial usage."""
if not self.check_cn2an():
return None
return an2cn(number, 'rmb')
def _count_attachments(self):
domains = [[('res_model', '=', 'account.move'), ('res_id', '=', self.id)]]
statement_ids = self.line_ids.mapped('statement_id')
payment_ids = self.line_ids.mapped('payment_id')
if statement_ids:
domains.append([('res_model', '=', 'account.bank.statement'), ('res_id', 'in', statement_ids.ids)])
if payment_ids:
domains.append([('res_model', '=', 'account.payment'), ('res_id', 'in', payment_ids.ids)])
return self.env['ir.attachment'].search_count(expression.OR(domains))
| 37.44186
| 1,610
|
1,339
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Google Drive™ integration',
'version': '0.2',
'category': 'Productivity',
'installable': True,
'auto_install': False,
'data': [
'security/ir.model.access.csv',
'data/google_drive_data.xml',
'views/google_drive_views.xml',
'views/res_config_settings_views.xml',
],
'demo': [
'data/google_drive_demo.xml'
],
'depends': ['base_setup', 'google_account'],
'description': """
Integrate google document to Odoo record.
============================================
This module allows you to integrate google documents to any of your Odoo record quickly and easily using OAuth 2.0 for Installed Applications,
You can configure your google Authorization Code from Settings > Configuration > General Settings by clicking on "Generate Google Authorization Code"
""",
'assets': {
'web.assets_backend': [
'google_drive/static/src/css/google_drive.css',
'google_drive/static/src/js/gdrive.js',
],
'web.qunit_suite_tests': [
'google_drive/static/tests/**/*',
],
'web.assets_qweb': [
'google_drive/static/src/xml/*.xml',
],
},
'license': 'LGPL-3',
}
| 33.425
| 1,337
|
2,221
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code')
google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help="The URL to generate the authorization code from Google")
is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated')
@api.depends('google_drive_authorization_code')
def _compute_drive_uri(self):
google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope())
for config in self:
config.google_drive_uri = google_drive_uri
def get_values(self):
res = super(ResConfigSettings, self).get_values()
refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False)
res.update(is_google_drive_token_generated=bool(refresh_token))
return res
def confirm_setup_token(self):
params = self.env['ir.config_parameter'].sudo()
authorization_code_before = params.get_param('google_drive_authorization_code')
authorization_code = self.google_drive_authorization_code
if authorization_code != authorization_code_before:
refresh_token = (
self.env['google.service'].generate_refresh_token('drive', authorization_code)
if authorization_code else False
)
params.set_param('google_drive_refresh_token', refresh_token)
def action_setup_token(self):
self.ensure_one()
if self.env['google.drive.config']._module_deprecated():
return
template = self.env.ref('google_drive.google_drive_auth_code_wizard')
return {
'name': _('Set up refresh token'),
'type': 'ir.actions.act_window',
'res_model': 'res.config.settings',
'views': [(template.id, 'form')],
'target': 'new',
}
| 45.326531
| 2,221
|
12,520
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import logging
import json
import re
import requests
import werkzeug.urls
from odoo import api, fields, models
from odoo.exceptions import RedirectWarning, UserError, ValidationError
from odoo.tools.translate import _
from odoo.addons.google_account.models.google_service import GOOGLE_TOKEN_ENDPOINT, TIMEOUT
from datetime import date
_logger = logging.getLogger(__name__)
# Google is depreciating their OOB Auth Flow on 3rd October 2022, the Google Drive
# integration thus become irrelevant after that date.
# https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html#disallowed-oob
GOOGLE_AUTH_DEPRECATION_DATE = date(2022, 10, 3)
class GoogleDrive(models.Model):
_name = 'google.drive.config'
_description = "Google Drive templates config"
def _module_deprecated(self):
return GOOGLE_AUTH_DEPRECATION_DATE < fields.Date.today()
def get_google_drive_url(self, res_id, template_id):
if self._module_deprecated():
return
self.ensure_one()
self = self.sudo()
model = self.model_id
filter_name = self.filter_id.name if self.filter_id else False
record = self.env[model.model].browse(res_id).read()[0]
record.update({
'model': model.name,
'filter': filter_name
})
name_gdocs = self.name_template
try:
name_gdocs = name_gdocs % record
except:
raise UserError(_("At least one key cannot be found in your Google Drive name pattern."))
attachments = self.env["ir.attachment"].search([('res_model', '=', model.model), ('name', '=', name_gdocs), ('res_id', '=', res_id)])
url = False
if attachments:
url = attachments[0].url
else:
url = self.copy_doc(res_id, template_id, name_gdocs, model.model).get('url')
return url
@api.model
def get_access_token(self, scope=None):
if self._module_deprecated():
return
Config = self.env['ir.config_parameter'].sudo()
google_drive_refresh_token = Config.get_param('google_drive_refresh_token')
user_is_admin = self.env.is_admin()
if not google_drive_refresh_token:
if user_is_admin:
action_id = self.env['ir.model.data']._xmlid_lookup('base_setup.action_general_configuration')[2]
msg = _("There is no refresh code set for Google Drive. You can set it up from the configuration panel.")
raise RedirectWarning(msg, action_id, _('Go to the configuration panel'))
else:
raise UserError(_("Google Drive is not yet configured. Please contact your administrator."))
google_drive_client_id = Config.get_param('google_drive_client_id')
google_drive_client_secret = Config.get_param('google_drive_client_secret')
#For Getting New Access Token With help of old Refresh Token
data = {
'client_id': google_drive_client_id,
'refresh_token': google_drive_refresh_token,
'client_secret': google_drive_client_secret,
'grant_type': "refresh_token",
'scope': scope or 'https://www.googleapis.com/auth/drive'
}
headers = {"Content-type": "application/x-www-form-urlencoded"}
try:
req = requests.post(GOOGLE_TOKEN_ENDPOINT, data=data, headers=headers, timeout=TIMEOUT)
req.raise_for_status()
except requests.HTTPError:
if user_is_admin:
action_id = self.env['ir.model.data']._xmlid_lookup('base_setup.action_general_configuration')[2]
msg = _("Something went wrong during the token generation. Please request again an authorization code .")
raise RedirectWarning(msg, action_id, _('Go to the configuration panel'))
else:
raise UserError(_("Google Drive is not yet configured. Please contact your administrator."))
return req.json().get('access_token')
@api.model
def copy_doc(self, res_id, template_id, name_gdocs, res_model):
if self._module_deprecated():
return
google_web_base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
access_token = self.get_access_token()
# Copy template in to drive with help of new access token
request_url = "https://www.googleapis.com/drive/v2/files/%s?fields=parents/id&access_token=%s" % (template_id, access_token)
headers = {"Content-type": "application/x-www-form-urlencoded"}
try:
req = requests.get(request_url, headers=headers, timeout=TIMEOUT)
req.raise_for_status()
parents_dict = req.json()
except requests.HTTPError:
raise UserError(_("The Google Template cannot be found. Maybe it has been deleted."))
record_url = "Click on link to open Record in Odoo\n %s/?db=%s#id=%s&model=%s" % (google_web_base_url, self._cr.dbname, res_id, res_model)
data = {
"title": name_gdocs,
"description": record_url,
"parents": parents_dict['parents']
}
request_url = "https://www.googleapis.com/drive/v2/files/%s/copy?access_token=%s" % (template_id, access_token)
headers = {
'Content-type': 'application/json',
'Accept': 'text/plain'
}
# resp, content = Http().request(request_url, "POST", data_json, headers)
req = requests.post(request_url, data=json.dumps(data), headers=headers, timeout=TIMEOUT)
req.raise_for_status()
content = req.json()
res = {}
if content.get('alternateLink'):
res['id'] = self.env["ir.attachment"].create({
'res_model': res_model,
'name': name_gdocs,
'res_id': res_id,
'type': 'url',
'url': content['alternateLink']
}).id
# Commit in order to attach the document to the current object instance, even if the permissions has not been written.
self._cr.commit()
res['url'] = content['alternateLink']
key = self._get_key_from_url(res['url'])
request_url = "https://www.googleapis.com/drive/v2/files/%s/permissions?emailMessage=This+is+a+drive+file+created+by+Odoo&sendNotificationEmails=false&access_token=%s" % (key, access_token)
data = {'role': 'writer', 'type': 'anyone', 'value': '', 'withLink': True}
try:
req = requests.post(request_url, data=json.dumps(data), headers=headers, timeout=TIMEOUT)
req.raise_for_status()
except requests.HTTPError:
raise self.env['res.config.settings'].get_config_warning(_("The permission 'reader' for 'anyone with the link' has not been written on the document"))
if self.env.user.email:
data = {'role': 'writer', 'type': 'user', 'value': self.env.user.email}
try:
requests.post(request_url, data=json.dumps(data), headers=headers, timeout=TIMEOUT)
except requests.HTTPError:
pass
return res
@api.model
def get_google_drive_config(self, res_model, res_id):
'''
Function called by the js, when no google doc are yet associated with a record, with the aim to create one. It
will first seek for a google.docs.config associated with the model `res_model` to find out what's the template
of google doc to copy (this is usefull if you want to start with a non-empty document, a type or a name
different than the default values). If no config is associated with the `res_model`, then a blank text document
with a default name is created.
:param res_model: the object for which the google doc is created
:param ids: the list of ids of the objects for which the google doc is created. This list is supposed to have
a length of 1 element only (batch processing is not supported in the code, though nothing really prevent it)
:return: the config id and config name
'''
# TO DO in master: fix my signature and my model
if isinstance(res_model, str):
res_model = self.env['ir.model']._get_id(res_model)
if not res_id:
raise UserError(_("Creating google drive may only be done by one at a time."))
# check if a model is configured with a template
configs = self.search([('model_id', '=', res_model)])
config_values = []
for config in configs.sudo():
if config.filter_id:
if config.filter_id.user_id and config.filter_id.user_id.id != self.env.user.id:
#Private
continue
try:
domain = [('id', 'in', [res_id])] + ast.literal_eval(config.filter_id.domain)
except:
raise UserError(_("The document filter must not include any 'dynamic' part, so it should not be based on the current time or current user, for example."))
additionnal_context = ast.literal_eval(config.filter_id.context)
google_doc_configs = self.env[config.filter_id.model_id].with_context(**additionnal_context).search(domain)
if google_doc_configs:
config_values.append({'id': config.id, 'name': config.name})
else:
config_values.append({'id': config.id, 'name': config.name})
return config_values
name = fields.Char('Template Name', required=True)
model_id = fields.Many2one('ir.model', 'Model', required=True, ondelete='cascade')
model = fields.Char('Related Model', related='model_id.model', readonly=True)
filter_id = fields.Many2one('ir.filters', 'Filter', domain="[('model_id', '=', model)]")
google_drive_template_url = fields.Char('Template URL', required=True)
google_drive_resource_id = fields.Char('Resource Id', compute='_compute_ressource_id')
google_drive_client_id = fields.Char('Google Client', compute='_compute_client_id')
name_template = fields.Char('Google Drive Name Pattern', default='Document %(name)s', help='Choose how the new google drive will be named, on google side. Eg. gdoc_%(field_name)s', required=True)
active = fields.Boolean('Active', default=True)
def _get_key_from_url(self, url):
word = re.search("(key=|/d/)([A-Za-z0-9-_]+)", url)
if word:
return word.group(2)
return None
def _compute_ressource_id(self):
for record in self:
if record.google_drive_template_url:
word = self._get_key_from_url(record.google_drive_template_url)
if word:
record.google_drive_resource_id = word
else:
raise UserError(_("Please enter a valid Google Document URL."))
else:
record.google_drive_resource_id = False
def _compute_client_id(self):
google_drive_client_id = self.env['ir.config_parameter'].sudo().get_param('google_drive_client_id')
for record in self:
record.google_drive_client_id = google_drive_client_id
@api.onchange('model_id')
def _onchange_model_id(self):
if self.model_id:
self.model = self.model_id.model
else:
self.filter_id = False
self.model = False
@api.constrains('model_id', 'filter_id')
def _check_model_id(self):
for drive in self:
if drive.filter_id and drive.model_id.model != drive.filter_id.model_id:
raise ValidationError(_(
"Incoherent Google Drive %(drive)s: the model of the selected filter %(filter)r is not matching the model of current template (%(filter_model)r, %(drive_model)r)",
drive=drive.name, filter=drive.filter_id.name, filter_model=drive.filter_id.model_id.model, drive_model=drive.model_id.model,
))
if self.model_id.model and self.filter_id:
# force an execution of the filter to verify compatibility
self.get_google_drive_config(self.model_id.model, 1)
def get_google_scope(self):
return 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file'
| 49.486166
| 12,520
|
827
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Italy - E-invoicing',
'icon': '/l10n_it/static/description/icon.png',
'version': '0.3',
'depends': [
'l10n_it',
'fetchmail',
'account_edi'
],
'author': 'Odoo',
'description': """
E-invoice implementation
""",
'category': 'Accounting/Localizations/EDI',
'website': 'http://www.odoo.com/',
'data': [
'security/ir.model.access.csv',
'data/account_edi_data.xml',
'data/invoice_it_template.xml',
'data/invoice_it_simplified_template.xml',
'views/l10n_it_view.xml',
],
'demo': [
'data/account_invoice_demo.xml',
],
'post_init_hook': '_l10n_it_edi_post_init',
'license': 'LGPL-3',
}
| 26.677419
| 827
|
1,970
|
py
|
PYTHON
|
15.0
|
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import warnings
_logger = logging.getLogger(__name__)
try:
from OpenSSL import crypto as ssl_crypto
import OpenSSL._util as ssl_util
except ImportError:
ssl_crypto = None
_logger.warning("Cannot import library 'OpenSSL' for PKCS#7 envelope extraction.")
def remove_signature(content):
""" Remove the PKCS#7 envelope from given content, making a '.xml.p7m' file content readable as it was '.xml'.
As OpenSSL may not be installed, in that case a warning is issued and None is returned. """
# Prevent using the library if it had import errors
if not ssl_crypto:
_logger.warning("Error reading the content, check if the OpenSSL library is installed for for PKCS#7 envelope extraction.")
return None
# Load some tools from the library
null = ssl_util.ffi.NULL
verify = ssl_util.lib.PKCS7_verify
# By default ignore the validity of the certificates, just validate the structure
flags = ssl_util.lib.PKCS7_NOVERIFY | ssl_util.lib.PKCS7_NOSIGS
# Read the signed data fron the content
out_buffer = ssl_crypto._new_mem_buf()
# This method is deprecated, but there are actually no alternatives
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
try:
loaded_data = ssl_crypto.load_pkcs7_data(ssl_crypto.FILETYPE_ASN1, content)
except ssl_crypto.Error:
_logger.warning("Error reading the content, PKCS#7 signature missing or invalid. Content will be tentatively used as it is.")
return content
# Verify the signature
if verify(loaded_data._pkcs7, null, null, null, out_buffer, flags) != 1:
ssl_crypto._raise_current_error()
# Get the content as a byte-string
decoded_content = ssl_crypto._bio_to_string(out_buffer)
return decoded_content
| 38.627451
| 1,970
|
1,928
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase, tagged
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestResPartner(TransactionCase):
def test_validate_fiscal_code(self):
valid_codes = [
"AORTHV05P30V295L",
"SPDTHB43S93F42VH",
"MDRTUV99H14X2MNU",
"XPTDRX73R64YPLUD",
"LOLXDR40T3MZRTSV",
"GJTIUG55DLQZRTSS",
"CDEOTG5PBLQZRTSE",
"PERTLELPALQZRTSN",
"IT12345678887",
"IT12345670546",
"IT95286931217",
"IT95867361206",
"IT94567689990",
"12345670546",
"95286931217",
"95867361206",
"94567689990",
]
invalid_codes = [
"AORTHV05P34V295U",
"SPDTHB43O93F42VH",
"MDRTUVV9H14X2MNU",
"XPTDRX73RS4YPLUD",
"LOLXDRQ0T3QZRTSJ",
"GJTIUGR5DLQZRTSS",
"CDEOTG5PBLQZRTSS",
"PERTLEZPALQZRTSN",
"IT12345678901",
"IT12345678885",
"IT45689349992",
"IT78239131204",
"IT45692151219",
"12345678901",
"12345678885",
"45689349992",
"78239131204",
"45692151219",
]
partners = self.env['res.partner']
for i, code in enumerate(invalid_codes):
with self.assertRaises(UserError):
partners += self.env['res.partner'].create({'name': f'partner_{i}', 'l10n_it_codice_fiscale': code})
for i, code in enumerate(valid_codes):
partners += self.env['res.partner'].create({'name': f'partner_{i}', 'l10n_it_codice_fiscale': code})
self.assertEqual(len(partners), len(valid_codes))
| 31.606557
| 1,928
|
7,512
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import logging
from collections import namedtuple
from unittest.mock import patch
from freezegun import freeze_time
from odoo import tools
from odoo.tests import tagged
from odoo.addons.account_edi.tests.common import AccountEdiTestCommon
from odoo.addons.l10n_it_edi.tools.remove_signature import remove_signature
_logger = logging.getLogger(__name__)
@tagged('post_install_l10n', 'post_install', '-at_install')
class PecMailServerTests(AccountEdiTestCommon):
""" Main test class for the l10n_it_edi vendor bills XML import from a PEC mail account"""
fake_test_content = """<?xml version="1.0" encoding="UTF-8"?>
<p:FatturaElettronica versione="FPR12" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 http://www.fatturapa.gov.it/export/fatturazione/sdi/fatturapa/v1.2/Schema_del_file_xml_FatturaPA_versione_1.2.xsd">
<FatturaElettronicaHeader>
<CessionarioCommittente>
<DatiAnagrafici>
<CodiceFiscale>01234560157</CodiceFiscale>
</DatiAnagrafici>
</CessionarioCommittente>
</FatturaElettronicaHeader>
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
<TipoDocumento>TD02</TipoDocumento>
</DatiGeneraliDocumento>
</DatiGenerali>
</FatturaElettronicaBody>
</p:FatturaElettronica>"""
@classmethod
def setUpClass(cls):
""" Setup the test class with a PEC mail server and a fake fatturaPA content """
super().setUpClass(chart_template_ref='l10n_it.l10n_it_chart_template_generic',
edi_format_ref='l10n_it_edi.edi_fatturaPA')
# Use the company_data_2 to test that the e-invoice is imported for the right company
cls.company = cls.company_data_2['company']
# Initialize the company's codice fiscale
cls.company.l10n_it_codice_fiscale = '01234560157'
# Build test data.
# invoice_filename1 is used for vendor bill receipts tests
# invoice_filename2 is used for vendor bill tests
cls.invoice_filename1 = 'IT01234567890_FPR01.xml'
cls.invoice_filename2 = 'IT01234567890_FPR02.xml'
cls.signed_invoice_filename = 'IT01234567890_FPR01.xml.p7m'
cls.invoice_content = cls._get_test_file_content(cls.invoice_filename1)
cls.signed_invoice_content = cls._get_test_file_content(cls.signed_invoice_filename)
cls.invoice = cls.env['account.move'].create({
'move_type': 'in_invoice',
'ref': '01234567890'
})
cls.attachment = cls.env['ir.attachment'].create({
'name': cls.invoice_filename1,
'raw': cls.invoice_content,
'res_id': cls.invoice.id,
'res_model': 'account.move',
})
cls.edi_document = cls.env['account.edi.document'].create({
'edi_format_id': cls.edi_format.id,
'move_id': cls.invoice.id,
'attachment_id': cls.attachment.id,
'state': 'sent'
})
# Initialize the fetchmail server that has to be tested
cls.server = cls.env['fetchmail.server'].sudo().create({
'name': 'test_server',
'server_type': 'imap',
'l10n_it_is_pec': True})
cls.test_invoice_xmls = {k: cls._get_test_file_content(v) for k, v in [
('normal_1', 'IT01234567890_FPR01.xml'),
('signed', 'IT01234567890_FPR01.xml.p7m'),
]}
@classmethod
def _get_test_file_content(cls, filename):
""" Get the content of a test file inside this module """
path = 'l10n_it_edi/tests/expected_xmls/' + filename
with tools.file_open(path, mode='rb') as test_file:
return test_file.read()
def _create_invoice(self, content, filename):
""" Create an invoice from given attachment content """
with patch.object(self.server._cr, 'commit', return_value=None):
if filename.endswith(".p7m"):
content = remove_signature(content)
return self.server._create_invoice_from_mail(content, filename, 'fake@address.be')
# -----------------------------
#
# Vendor bills
#
# -----------------------------
def test_receive_vendor_bill(self):
""" Test a sample e-invoice file from https://www.fatturapa.gov.it/export/documenti/fatturapa/v1.2/IT01234567890_FPR01.xml """
invoices = self._create_invoice(self.invoice_content, self.invoice_filename2)
self.assertTrue(bool(invoices))
def test_receive_signed_vendor_bill(self):
""" Test a signed (P7M) sample e-invoice file from https://www.fatturapa.gov.it/export/documenti/fatturapa/v1.2/IT01234567890_FPR01.xml """
with freeze_time('2020-04-06'):
invoices = self._create_invoice(self.signed_invoice_content, self.signed_invoice_filename)
self.assertRecordValues(invoices, [{
'company_id': self.company.id,
'name': 'BILL/2014/12/0001',
'invoice_date': datetime.date(2014, 12, 18),
'ref': '01234567890',
}])
def test_receive_same_vendor_bill_twice(self):
""" Test that the second time we are receiving a PEC mail with the same attachment, the second is discarded """
content = self.fake_test_content.encode()
for result in [True, False]:
invoice = self._create_invoice(content, self.invoice_filename2)
self.assertEqual(result, bool(invoice))
# -----------------------------
#
# Receipts
#
# -----------------------------
def _test_receipt(self, receipt_type, source_state, destination_state):
""" Test a receipt from the ones in the module's test files """
# Simulate the 'sent' state of the move, even if we didn't actually send an email in this test
self.invoice.l10n_it_send_state = source_state
# Create a fake receipt from the test file
receipt_filename = 'IT01234567890_FPR01_%s_001.xml' % receipt_type
receipt_content = self._get_test_file_content(receipt_filename).decode()
create_mail_attachment = namedtuple('Attachment', ('fname', 'content', 'info'))
receipt_mail_attachment = create_mail_attachment(receipt_filename, receipt_content, {})
# Simulate the arrival of the receipt
with patch.object(self.server._cr, 'commit', return_value=None):
self.server._message_receipt_invoice(receipt_type, receipt_mail_attachment)
# Check the Destination state of the edi_document
self.assertTrue(destination_state, self.edi_document.state)
def test_ricevuta_consegna(self):
""" Test a receipt adapted from https://www.fatturapa.gov.it/export/documenti/messaggi/v1.0/IT01234567890_11111_RC_001.xml """
self._test_receipt('RC', 'sent', 'delivered')
def test_decorrenza_termini(self):
""" Test a receipt adapted from https://www.fatturapa.gov.it/export/documenti/messaggi/v1.0/IT01234567890_11111_DT_001.xml """
self._test_receipt('DT', 'delivered', 'delivered_expired')
| 45.253012
| 7,512
|
676
|
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 L10nItDdt(models.Model):
_name = 'l10n_it.ddt'
_description = 'Transport Document'
invoice_id = fields.One2many('account.move', 'l10n_it_ddt_id', string='Invoice Reference')
name = fields.Char(string="Numero DDT", size=20, help="Transport document number", required=True)
date = fields.Date(string="Data DDT", help="Transport document date", required=True)
def name_get(self):
res = []
for ddt in self:
res.append((ddt.id, ("%s (%s)") % (ddt.name, ddt.date)))
return res
| 37.555556
| 676
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.