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
3,245
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestMailOptionalFollowernotifications(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner_obj = cls.env["res.partner"] cls.partner_01 = cls.env.ref("base.res_partner_2") demo_user = cls.env.ref("base.user_demo") cls.partner_follower = demo_user.partner_id cls.partner_no_follower = demo_user.copy().partner_id cls.partner_01.message_subscribe(partner_ids=[cls.partner_follower.id]) ctx = cls.env.context.copy() ctx.update( { "default_model": "res.partner", "default_res_id": cls.partner_01.id, "default_composition_mode": "comment", "test_optional_follow_notification": True, } ) cls.mail_compose_context = ctx cls.MailCompose = cls.env["mail.compose.message"] def _send_mail(self, recipients, notify_followers): old_messages = self.env["mail.message"].search([]) values = self.MailCompose.with_context( **self.mail_compose_context )._onchange_template_id(False, "comment", "res.partner", self.partner_01.id)[ "value" ] values["partner_ids"] = [(6, 0, recipients.ids)] values["notify_followers"] = notify_followers composer = self.MailCompose.with_context(**self.mail_compose_context).create( values ) composer.action_send_mail() return self.env["mail.message"].search([]) - old_messages def test_1(self): """ Data: One partner follower of partner_01 Test case: Send message to the follower and a non follower partner Expected result: Both are notified """ message = self._send_mail( self.partner_follower + self.partner_no_follower, notify_followers=True ) self.assertEqual( message.notification_ids.mapped("res_partner_id"), self.partner_no_follower + self.partner_follower, ) def test_2(self): """ Data: One partner follower of partner_01 Test case: Send message to the non follower partner Expected result: Both are notified """ message = self._send_mail(self.partner_no_follower, notify_followers=True) self.assertEqual( message.notification_ids.mapped("res_partner_id"), self.partner_no_follower + self.partner_follower, ) def test_3(self): """ Data: One partner follower of partner_01 Test case: Send message to the non follower partner and disable the notification to followers Expected result: Only the non follower partner is notified """ message = self._send_mail(self.partner_no_follower, notify_followers=False) self.assertEqual( message.notification_ids.mapped("res_partner_id"), self.partner_no_follower )
36.460674
3,245
564
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class MailComposeMessage(models.TransientModel): _inherit = "mail.compose.message" notify_followers = fields.Boolean(default=True) def _action_send_mail(self, auto_commit=False): for wizard in self: wizard = wizard.with_context(notify_followers=wizard.notify_followers) super(MailComposeMessage, wizard)._action_send_mail(auto_commit=auto_commit) return True
35.25
564
1,179
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models from odoo.tools import config class MailThread(models.AbstractModel): _inherit = "mail.thread" def _notify_compute_recipients(self, message, msg_vals): """Compute recipients to notify based on subtype and followers. This method returns data structured as expected for ``_notify_recipients``.""" test_condition = config["test_enable"] and not self.env.context.get( "test_optional_follow_notification" ) recipient_data = super()._notify_compute_recipients(message, msg_vals) if test_condition: return recipient_data if "notify_followers" in self.env.context and not self.env.context.get( "notify_followers", False ): # filter out all the followers pids = ( msg_vals.get("partner_ids", []) if msg_vals else message.sudo().partner_ids.ids ) recipient_data = [d for d in recipient_data if d["id"] in pids] return recipient_data
39.3
1,179
885
py
PYTHON
15.0
# Copyright 2018 David Juaneda - <[email protected]> # Copyright 2021 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail Activity Board", "summary": "Add Activity Boards", "version": "15.0.2.0.0", "development_status": "Beta", "category": "Social Network", "website": "https://github.com/OCA/social", "author": "SDi, David Juaneda, Sodexis, ACSONE SA/NV, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["calendar", "board"], "data": ["views/mail_activity_view.xml"], "assets": { "web.assets_backend": [ "mail_activity_board/static/src/components/chatter_topbar/chatter_topbar.esm.js", ], "web.assets_qweb": [ "mail_activity_board/static/src/components/chatter_topbar/chatter_topbar.xml", ], }, }
36.875
885
7,662
py
PYTHON
15.0
# Copyright 2018 David Juaneda - <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestMailActivityBoardMethods(TransactionCase): def setUp(self): super(TestMailActivityBoardMethods, self).setUp() # Set up activities # Create a user as 'Crm Salesman' and added few groups mail_activity_group = self.create_mail_activity_group() self.employee = self.env["res.users"].create( { "company_id": self.env.ref("base.main_company").id, "name": "Employee", "login": "csu", "email": "[email protected]", "groups_id": [ ( 6, 0, [ self.env.ref("base.group_user").id, ], ) ], } ) # Create a user who doesn't have access to anything except activities self.employee2 = self.env["res.users"].create( { "company_id": self.env.ref("base.main_company").id, "name": "Employee2", "login": "alien", "email": "[email protected]", "groups_id": [(6, 0, [mail_activity_group.id])], } ) # lead_model_id = self.env['ir.model']._get('crm.lead').id partner_model = self.env["ir.model"]._get("res.partner") ActivityType = self.env["mail.activity.type"] self.activity1 = ActivityType.create( { "name": "Initial Contact", "delay_count": 5, "delay_unit": "days", "summary": "ACT 1 : Presentation, barbecue, ... ", "res_model": partner_model.model, } ) self.activity2 = ActivityType.create( { "name": "Call for Demo", "delay_count": 6, "delay_unit": "days", "summary": "ACT 2 : I want to show you my ERP !", "res_model": partner_model.model, } ) self.activity3 = ActivityType.create( { "name": "Celebrate the sale", "delay_count": 3, "delay_unit": "days", "summary": "ACT 3 : " "Beers for everyone because I am a good salesman !", "res_model": partner_model.model, } ) # I create an opportunity, as employee self.partner_client = self.env.ref("base.res_partner_1") # assure there isn't any mail activity yet self.env["mail.activity"].sudo().search([]).unlink() self.act1 = ( self.env["mail.activity"] .sudo() .create( { "activity_type_id": self.activity3.id, "note": "Partner activity 1.", "res_id": self.partner_client.id, "res_model_id": partner_model.id, "user_id": self.employee.id, } ) ) self.act2 = ( self.env["mail.activity"] .sudo() .create( { "activity_type_id": self.activity2.id, "note": "Partner activity 2.", "res_id": self.partner_client.id, "res_model_id": partner_model.id, "user_id": self.employee.id, } ) ) self.act3 = ( self.env["mail.activity"] .sudo() .create( { "activity_type_id": self.activity3.id, "note": "Partner activity 3.", "res_id": self.partner_client.id, "res_model_id": partner_model.id, "user_id": self.employee.id, } ) ) def create_mail_activity_group(self): manager_mail_activity_test_group = self.env["res.groups"].create( {"name": "group_manager_mail_activity_test"} ) mail_activity_model_id = ( self.env["ir.model"] .sudo() .search([("model", "=", "mail.activity")], limit=1) ) access = self.env["ir.model.access"].create( { "name": "full_access_mail_activity", "model_id": mail_activity_model_id.id, "perm_read": True, "perm_write": True, "perm_create": True, "perm_unlink": True, } ) access.group_id = manager_mail_activity_test_group return manager_mail_activity_test_group def get_view(self, activity): action = activity.open_origin() result = self.env[action.get("res_model")].load_views(action.get("views")) return result.get("fields_views").get(action.get("view_mode")) def test_open_origin_res_partner(self): """This test case checks - If the method redirects to the form view of the correct one of an object of the 'res.partner' class to which the activity belongs. """ # Id of the form view for the class 'crm.lead', type 'lead' form_view_partner_id = self.env.ref("base.view_partner_form").id # Id of the form view return open_origin() view = self.get_view(self.act1) # Check the next view is correct self.assertEqual(form_view_partner_id, view.get("view_id")) # Id of the form view return open_origin() view = self.get_view(self.act2) # Check the next view is correct self.assertEqual(form_view_partner_id, view.get("view_id")) # Id of the form view return open_origin() view = self.get_view(self.act3) # Check the next view is correct self.assertEqual(form_view_partner_id, view.get("view_id")) def test_redirect_to_activities(self): """This test case checks - if the method returns the correct action, - if the correct activities are shown. """ action_id = self.env.ref("mail_activity_board.open_boards_activities").id action = self.partner_client.redirect_to_activities( **{"id": self.partner_client.id} ) self.assertEqual(action.get("id"), action_id) kwargs = {"groupby": ["activity_type_id"]} kwargs["domain"] = action.get("domain") result = self.env[action.get("res_model")].load_views(action.get("views")) fields = result.get("fields_views").get("kanban").get("fields") kwargs["fields"] = list(fields.keys()) result = self.env["mail.activity"].read_group(**kwargs) acts = [] for group in result: records = self.env["mail.activity"].search_read( domain=group.get("__domain"), fields=kwargs["fields"] ) acts += [record_id.get("id") for record_id in records] for act in acts: self.assertIn(act, self.partner_client.activity_ids.ids) def test_related_model_instance(self): """This test case checks the direct access from the activity to the linked model instance """ self.assertEqual(self.act3.related_model_instance, self.partner_client) self.act3.write({"res_id": False, "res_model": False}) self.assertFalse(self.act3.related_model_instance)
36.141509
7,662
2,884
py
PYTHON
15.0
# Copyright 2018 David Juaneda - <[email protected]> # Copyright 2018 ForgeFlow S.L. <https://www.forgeflow.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailActivity(models.Model): _inherit = "mail.activity" res_model_id_name = fields.Char( related="res_model_id.name", string="Origin", readonly=True ) duration = fields.Float(related="calendar_event_id.duration", readonly=True) calendar_event_id_start = fields.Datetime( related="calendar_event_id.start", readonly=True ) calendar_event_id_partner_ids = fields.Many2many( related="calendar_event_id.partner_ids", readonly=True ) related_model_instance = fields.Reference( selection="_selection_related_model_instance", compute="_compute_related_model_instance", string="Document", ) @api.depends("res_id", "res_model") def _compute_related_model_instance(self): for record in self: ref = False if record.res_id: ref = "{},{}".format(record.res_model, record.res_id) record.related_model_instance = ref @api.model def _selection_related_model_instance(self): models = self.env["ir.model"].sudo().search([("is_mail_activity", "=", True)]) return [(model.model, model.name) for model in models] def open_origin(self): self.ensure_one() vid = self.env[self.res_model].browse(self.res_id).get_formview_id() response = { "type": "ir.actions.act_window", "res_model": self.res_model, "view_mode": "form", "res_id": self.res_id, "target": "current", "flags": {"form": {"action_buttons": False}}, "views": [(vid, "form")], } return response @api.model def action_activities_board(self): action = self.env.ref("mail_activity_board.open_boards_activities").read()[0] return action @api.model def _find_allowed_model_wise(self, doc_model, doc_dict): doc_ids = list(doc_dict) allowed_doc_ids = ( self.env[doc_model] .with_context(active_test=False) .search([("id", "in", doc_ids)]) .ids ) return { message_id for allowed_doc_id in allowed_doc_ids for message_id in doc_dict[allowed_doc_id] } @api.model def _find_allowed_doc_ids(self, model_ids): ir_model_access_model = self.env["ir.model.access"] allowed_ids = set() for doc_model, doc_dict in model_ids.items(): if not ir_model_access_model.check(doc_model, "read", False): continue allowed_ids |= self._find_allowed_model_wise(doc_model, doc_dict) return allowed_ids
35.604938
2,884
1,195
py
PYTHON
15.0
# Copyright 2018 David Juaneda - <[email protected]> # Copyright 2021 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class MailActivityMixin(models.AbstractModel): _inherit = "mail.activity.mixin" def redirect_to_activities(self, **kwargs): """Redirects to the list of activities of the object shown. Redirects to the activity board and configures the domain so that only those activities that are related to the object shown are displayed. Add to the title of the view the name the class of the object from which the activities will be displayed. :param kwargs: contains the id of the object and the model it's about. :return: action. """ _id = kwargs.get("id") model = kwargs.get("model") action = self.env["mail.activity"].action_activities_board() views = [] for v in action["views"]: if v[1] == "tree": v = (v[0], "list") views.append(v) action["views"] = views action["domain"] = [("res_id", "=", _id), (("res_model", "=", model))] return action
35.147059
1,195
565
py
PYTHON
15.0
# Copyright 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "QWeb for email templates", "version": "15.0.1.0.0", "author": "Therp BV, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Marketing", "summary": "Use the QWeb templating mechanism for emails", "website": "https://github.com/OCA/social", "depends": ["mail"], "demo": ["demo/ir_ui_view.xml", "demo/mail_template.xml"], "data": ["views/mail_template.xml"], "installable": True, }
37.666667
565
994
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, api def migrate(cr, version): if not version: return env = api.Environment(cr, SUPERUSER_ID, {}) body_type = env["ir.model.fields"].search( [("name", "=", "body_type"), ("model", "=", "mail.template")] ) # Note: no need to migrate the existing values of the `body_type` of the # model `mail_template` because Odoo already does it # See https://github.com/odoo/odoo/blob/15.0/odoo/addons/base/models/ir_model.py#L1351 if body_type: # qweb -> qweb_view qweb = env["ir.model.fields.selection"].search( [("value", "=", "qweb"), ("field_id", "=", body_type.id)] ) qweb.write({"value": "qweb_view"}) # jinja2 -> qweb jinja = env["ir.model.fields.selection"].search( [("value", "=", "jinja2"), ("field_id", "=", body_type.id)] ) jinja.write({"value": "qweb"})
34.275862
994
1,125
py
PYTHON
15.0
# Copyright 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestMailTemplateQweb(TransactionCase): def test_email_template_qweb(self): template = self.env.ref("email_template_qweb.email_template_demo1") mail_values = template.generate_email([self.env.user.id], ["body_html"]) self.assertTrue( # this comes from the called template if everything worked "<footer>" in mail_values[self.env.user.id]["body_html"], "Did not receive rendered template in response. Got: \n%s\n" % (mail_values[self.env.user.id]["body_html"]), ) # the same method is also called in a non multi mode mail_values = template.generate_email(self.env.user.id, ["body_html"]) self.assertTrue( # this comes from the called template if everything worked "<footer>" in mail_values["body_html"], "Did not receive rendered template in response. Got: \n%s\n" % (mail_values["body_html"]), )
48.913043
1,125
2,097
py
PYTHON
15.0
# Copyright 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models, tools class MailTemplate(models.Model): _inherit = "mail.template" body_type = fields.Selection( [("qweb", "QWeb"), ("qweb_view", "QWeb View")], "Body templating engine", default="qweb", required=True, ) body_view_id = fields.Many2one("ir.ui.view", domain=[("type", "=", "qweb")]) body_view_arch = fields.Text(related="body_view_id.arch") def generate_email(self, res_ids, fields): multi_mode = True if isinstance(res_ids, int): res_ids = [res_ids] multi_mode = False result = super(MailTemplate, self).generate_email(res_ids, fields=fields) for lang, (_template, _template_res_ids) in self._classify_per_lang( res_ids ).items(): self_with_lang = self.with_context(lang=lang) for res_id in res_ids: if self.body_type == "qweb_view" and ( not fields or "body_html" in fields ): for record in self_with_lang.env[self.model].browse(res_id): body_html = self_with_lang.body_view_id._render( {"object": record, "email_template": self_with_lang} ) # Some wizards, like when sending a sales order, need this # fix to display accents correctly body_html = tools.ustr(body_html) result[res_id][ "body_html" ] = self_with_lang._render_template_postprocess( {res_id: body_html} )[ res_id ] result[res_id]["body"] = tools.html_sanitize( result[res_id]["body_html"] ) return result if multi_mode else result[res_ids[0]]
42.795918
2,097
688
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Mass mailing event", "summary": "Link mass mailing with event for excluding recipients", "version": "15.0.1.0.0", "category": "Marketing", "website": "https://github.com/OCA/social", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["mass_mailing", "event"], "data": [ "security/ir.model.access.csv", "data/event_state_data.xml", "views/mailing_mailing_views.xml", ], }
32.761905
688
5,748
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - David Vidal # Copyright 2020 Tecnativa - Alexandre D. Díaz # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestMassMailingEventRegistrationExclude(TransactionCase): at_install = False post_install = True @classmethod def setUpClass(cls): super().setUpClass() cls.event = cls.env["event.event"].create( { "name": "Test event", "date_begin": "2020-06-24 08:00:00", "date_end": "2020-06-30 18:00:00", } ) cls.registration = cls.env["event.registration"].create( {"event_id": cls.event.id, "email": "[email protected]"} ) cls.states_all = cls.env["event.registration.state"].search([]) cls.state_confirmed = cls.env["event.registration.state"].search( [("code", "=", "open")] ) cls.contact_list = cls.env["mailing.list"].create({"name": "Test list"}) cls.contact_a = cls.env["mailing.contact"].create( { "list_ids": [(4, cls.contact_list.id, False)], "name": "Test contact A", "email": "[email protected]", } ) cls.contact_b = cls.env["mailing.contact"].create( { "list_ids": [(4, cls.contact_list.id, False)], "name": "Test contact B", "email": "[email protected]", } ) cls.partner_a = cls.env["res.partner"].create( {"name": "Test partner A", "email": "[email protected]"} ) cls.partner_b = cls.env["res.partner"].create( {"name": "Test partner B", "email": "[email protected]"} ) def test_mailing_contact(self): domain = [("list_ids", "in", [self.contact_list.id]), ("opt_out", "=", False)] mass_mailing = ( self.env["mailing.mailing"] .create( { "name": "Test subject", "email_from": "[email protected]", "mailing_model_id": self.env.ref( "mass_mailing.model_mailing_contact" ).id, "mailing_domain": str(domain), "contact_list_ids": [(6, 0, [self.contact_list.id])], "body_html": "<p>Test email body</p>", "reply_to_mode": "new", "subject": "Test email subject", } ) .with_context(default_list_ids=[self.contact_list.id]) ) mail_contact = self.env["mailing.contact"].with_context( default_list_ids=[self.contact_list.id], exclude_mass_mailing=mass_mailing.id, ) self.assertEqual( [self.contact_a.id, self.contact_b.id], mass_mailing._get_recipients() ) self.assertEqual(2, mail_contact.search_count(domain)) mass_mailing.write( { "event_id": self.event.id, "exclude_event_state_ids": [(6, 0, self.states_all.ids)], } ) self.assertEqual([self.contact_b.id], mass_mailing._get_recipients()) self.assertEqual(1, mail_contact.search_count(domain)) self.registration.state = "draft" mass_mailing.write( {"exclude_event_state_ids": [(6, 0, self.state_confirmed.ids)]} ) self.assertEqual( [self.contact_a.id, self.contact_b.id], mass_mailing._get_recipients() ) self.assertEqual(2, mail_contact.search_count(domain)) def test_mailing_partner(self): domain = [("id", "in", [self.partner_a.id, self.partner_b.id])] domain_reg = [("event_id", "=", self.event.id)] mass_mailing = ( self.env["mailing.mailing"] .create( { "name": "Test subject", "email_from": "[email protected]", "mailing_model_id": self.env.ref("base.model_res_partner").id, "mailing_domain": str(domain), "body_html": "<p>Test email body</p>", "reply_to_mode": "new", "subject": "Test email subject", } ) .with_context(default_list_ids=[self.contact_list.id]) ) mail_partner = self.env["res.partner"].with_context( exclude_mass_mailing=mass_mailing.id ) mail_registration = self.env["event.registration"].with_context( exclude_mass_mailing=mass_mailing.id ) self.assertEqual( [self.partner_a.id, self.partner_b.id], mass_mailing._get_recipients() ) self.assertEqual(2, mail_partner.search_count(domain)) mass_mailing.write( { "event_id": self.event.id, "exclude_event_state_ids": [(6, 0, self.states_all.ids)], } ) self.assertEqual([self.partner_b.id], mass_mailing._get_recipients()) self.assertEqual(1, mail_partner.search_count(domain)) self.assertEqual(0, mail_registration.search_count(domain_reg)) self.registration.state = "draft" mass_mailing.write( {"exclude_event_state_ids": [(6, 0, self.state_confirmed.ids)]} ) self.assertEqual( [self.partner_a.id, self.partner_b.id], mass_mailing._get_recipients() ) self.assertEqual(2, mail_partner.search_count(domain)) self.assertEqual(1, mail_registration.search_count(domain_reg))
40.471831
5,747
660
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2020 Tecnativa - Alexandre D. Díaz # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models from .mailing import event_filtered_ids class MassMailingContact(models.Model): _inherit = "mailing.contact" @api.model def search_count(self, domain): res = super().search_count(domain) mass_mailing_id = self.env.context.get("exclude_mass_mailing", False) if mass_mailing_id: res_ids = event_filtered_ids(self, mass_mailing_id, domain, field="email") res = len(res_ids) if res_ids else 0 return res
32.95
659
1,844
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import copy from odoo import fields, models def event_filtered_ids(model, mailing_mailing_id, domain, field="email"): field = field or "email" domain = domain or [] exclude_emails = [] mailing_mailing = model.env["mailing.mailing"].browse(mailing_mailing_id) if mailing_mailing.event_id: exclude = mailing_mailing.exclude_event_state_ids.mapped("code") reg_domain = False registrations = model.env["event.registration"] if exclude: reg_domain = [ ("event_id", "=", mailing_mailing.event_id.id), ("state", "in", exclude), ] if reg_domain: registrations = registrations.search(reg_domain) if registrations: exclude_emails = registrations.mapped("email") apply_domain = copy.deepcopy(domain) if exclude_emails: apply_domain.append((field, "not in", exclude_emails)) rows = model.search(apply_domain) return rows.ids class MassMailing(models.Model): _inherit = "mailing.mailing" def _default_exclude_event_state_ids(self): return self.env["event.registration.state"].search([]) event_id = fields.Many2one(string="Event related", comodel_name="event.event") exclude_event_state_ids = fields.Many2many( comodel_name="event.registration.state", string="Exclude", default=_default_exclude_event_state_ids, ) def _get_recipients(self): res_ids = super()._get_recipients() if res_ids: domain = [("id", "in", res_ids)] res_ids = event_filtered_ids( self.env[self.mailing_model_real], self.id, domain, field="email" ) return res_ids
34.148148
1,844
613
py
PYTHON
15.0
# Copyright 2016 Tenativa - Antonio Espinosa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models from .mailing import event_filtered_ids class EventRegistration(models.Model): _inherit = "event.registration" @api.model def search_count(self, domain): res = super().search_count(domain) mass_mailing_id = self.env.context.get("exclude_mass_mailing", False) if mass_mailing_id: res_ids = event_filtered_ids(self, mass_mailing_id, domain, field="email") res = len(res_ids) if res_ids else 0 return res
32.263158
613
351
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class EventRegistrationState(models.Model): _name = "event.registration.state" _description = "Event Registration State" name = fields.Char(required=True) code = fields.Char(required=True)
29.25
351
600
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models from .mailing import event_filtered_ids class ResPartner(models.Model): _inherit = "res.partner" @api.model def search_count(self, domain): res = super().search_count(domain) mass_mailing_id = self.env.context.get("exclude_mass_mailing", False) if mass_mailing_id: res_ids = event_filtered_ids(self, mass_mailing_id, domain, field="email") res = len(res_ids) if res_ids else 0 return res
31.578947
600
599
py
PYTHON
15.0
# Copyright 2017-2020 Tecnativa - Pedro M. Baeza # Copyright 2018 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Resend mass mailings", "version": "15.0.1.0.0", "category": "Marketing", "website": "https://github.com/OCA/social", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["mass_mailing"], "data": ["views/mailing_mailing_views.xml"], "maintainers": ["pedrobaeza"], "development_status": "Mature", }
33.277778
599
2,372
py
PYTHON
15.0
# Copyright 2017-2020 Tecnativa - Pedro M. Baeza # Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import exceptions from odoo.tests import common class TestMassMailingResend(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.list = cls.env["mailing.list"].create({"name": "Test list"}) cls.contact1 = cls.env["mailing.contact"].create( { "name": "Contact 1", "email": "[email protected]", "list_ids": [[6, 0, [cls.list.id]]], } ) cls.contact2 = cls.env["mailing.contact"].create( { "name": "Contact 2", "email": "[email protected]", "list_ids": [[6, 0, [cls.list.id]]], } ) cls.mass_mailing = cls.env["mailing.mailing"].create( { "name": "Test mass mailing", "email_from": "[email protected]", "mailing_model_id": cls.env.ref("mass_mailing.model_mailing_list").id, "contact_list_ids": [(6, 0, cls.list.ids)], "subject": "Mailing test", } ) cls.mm_cron = cls.env.ref("mass_mailing.ir_cron_mass_mailing_queue").sudo() def test_resend_error(self): with self.assertRaises(exceptions.UserError): self.mass_mailing.button_draft() def _mailing_action_done(self): self.mass_mailing.action_launch() self.mm_cron.method_direct_trigger() def test_resend_process(self): # Send mailing self._mailing_action_done() self.assertEqual(self.mass_mailing.state, "done") self.assertEqual(self.mass_mailing.sent, 2) # Simulate that an email has not been sent self.mass_mailing.mailing_trace_ids.filtered( lambda x: x.email == self.contact2.email ).unlink() self.assertEqual(self.mass_mailing.sent, 1) # Back to draft self.mass_mailing.button_draft() self.assertEqual(self.mass_mailing.state, "draft") # Send mailing again (already sent not sent again) self._mailing_action_done() self.assertEqual(self.mass_mailing.state, "done") self.assertEqual(self.mass_mailing.sent, 2)
37.619048
2,370
630
py
PYTHON
15.0
# Copyright 2017-2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, exceptions, models class MailingMailing(models.Model): _inherit = "mailing.mailing" def button_draft(self): """Return to draft state for resending the mass mailing.""" if any(self.mapped(lambda x: x.state != "done")): raise exceptions.UserError( _( "You can't resend a mass mailing that is being sent or in " "draft state." ) ) self.write({"state": "draft"})
31.5
630
532
py
PYTHON
15.0
# Copyright 2015 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Mail Attach Existing Attachment", "summary": "Adding attachment on the object by sending this one", "author": "ACSONE SA/NV, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "category": "Social Network", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["mail"], "data": ["wizard/mail_compose_message_view.xml"], "installable": True, }
35.466667
532
1,309
py
PYTHON
15.0
# Copyright 2015 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import common class TestAttachExistingAttachment(common.TransactionCase): def setUp(self): super(TestAttachExistingAttachment, self).setUp() self.partner_obj = self.env["res.partner"] self.partner_01 = self.env["res.partner"].create( { "name": "Partner 1", "email": "[email protected]", "is_company": True, "parent_id": False, } ) def test_send_email_attachment(self): attach1 = self.env["ir.attachment"].create( { "name": "Attach1", "datas": "bWlncmF0aW9uIHRlc3Q=", "res_model": "res.partner", "res_id": self.partner_01.id, } ) vals = { "model": "res.partner", "partner_ids": [(6, 0, [self.partner_01.id])], "res_id": self.partner_01.id, "object_attachment_ids": [(6, 0, [attach1.id])], } mail = self.env["mail.compose.message"].create(vals) values = mail.get_mail_values([self.partner_01.id]) self.assertTrue(attach1.id in values[self.partner_01.id]["attachment_ids"])
35.378378
1,309
1,234
py
PYTHON
15.0
# Copyright 2015 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class MailComposeMessage(models.TransientModel): _inherit = "mail.compose.message" @api.model def default_get(self, fields_list): res = super().default_get(fields_list) if ( res.get("res_id") and res.get("model") and res.get("composition_mode", "") != "mass_mail" and not res.get("can_attach_attachment") ): res["can_attach_attachment"] = True # pragma: no cover return res can_attach_attachment = fields.Boolean() object_attachment_ids = fields.Many2many( comodel_name="ir.attachment", relation="mail_compose_message_ir_attachments_object_rel", column1="wizard_id", column2="attachment_id", string="Object Attachments", ) def get_mail_values(self, res_ids): res = super().get_mail_values(res_ids) if self.object_attachment_ids.ids and self.model and len(res_ids) == 1: res[res_ids[0]].setdefault("attachment_ids", []).extend( self.object_attachment_ids.ids ) return res
33.351351
1,234
714
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Pedro M. Baeza # Copyright 2020 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Allow to unsubscribe discretely from an event", "category": "Marketing", "version": "15.0.1.0.0", "depends": ["event", "mass_mailing_custom_unsubscribe"], "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "data": ["views/event_registration_views.xml"], "assets": { "web.assets_tests": [ "/mass_mailing_custom_unsubscribe_event/static/src/js/tour.esm.js" ] }, "license": "AGPL-3", "installable": True, "auto_install": True, }
35.65
713
5,380
py
PYTHON
15.0
# Copyright 2020 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from unittest import mock from werkzeug import urls from odoo.tests.common import HttpCase, tagged @tagged("post_install", "-at_install") class UICase(HttpCase): def extract_url(self, mail, *args, **kwargs): url = mail.mailing_id._get_unsubscribe_url(self.email, mail.res_id) self.assertTrue(urls.url_parse(url).decode_query().get("token")) self.assertTrue(url.startswith(self.domain)) self.url = url.replace(self.domain, "", 1) return True def setUp(self): super().setUp() self.email = "[email protected]" self.mail_postprocess_patch = mock.patch( "odoo.addons.mass_mailing.models.mail_mail.MailMail." "_postprocess_sent_message", autospec=True, side_effect=self.extract_url, ) self.domain = self.env["ir.config_parameter"].get_param("web.base.url") self.partner = self.env["res.partner"].create( {"name": "Demo Partner <%s>" % self.email, "email": self.email} ) self.event_1 = self.env["event.event"].create( { "name": "test_event_2", "event_type_id": 1, "date_end": "2012-01-01 19:05:15", "date_begin": "2012-01-01 18:05:15", } ) self.event_2 = self.env["event.event"].create( { "name": "test_event_2", "event_type_id": 1, "date_end": "2012-01-01 19:05:15", "date_begin": "2012-01-01 18:05:15", } ) self.event_registration_1 = self.env["event.registration"].create( { "name": "test_registration_1", "event_id": self.event_1.id, "email": self.email, "partner_id": self.partner.id, } ) self.event_registration_2 = self.env["event.registration"].create( { "name": "test_registration_2", "event_id": self.event_2.id, "email": self.email, "partner_id": self.partner.id, } ) self.mailing_1 = self.env["mailing.mailing"].create( { "name": "test_mailing_1", "mailing_model_id": self.env.ref("event.model_event_registration").id, "mailing_domain": "[['id','=',%s]]" % self.event_registration_1.id, "reply_to_mode": "update", "subject": "Test 1", } ) self.mailing_1.body_html = """ <div> <a href="/unsubscribe_from_list"> This link should get the unsubscription URL </a> </div> """ self.mailing_2 = self.env["mailing.mailing"].create( { "name": "test_mailing_2", "mailing_model_id": self.env.ref("event.model_event_registration").id, "mailing_domain": "[['id','=',%s]]" % self.event_registration_2.id, "reply_to_mode": "update", "subject": "Test 2", } ) self.mailing_2.body_html = """ <div> <a href="/unsubscribe_from_list"> This link should get the unsubscription URL </a> </div> """ def tearDown(self): del ( self.email, self.event_1, self.event_2, self.event_registration_1, self.event_registration_2, self.mailing_1, self.mailing_2, self.partner, self.url, ) super(UICase, self).tearDown() def test_unsubscription_event_1(self): """Test a mass mailing contact that wants to unsubscribe.""" # Extract the unsubscription link from the message body with self.mail_postprocess_patch: self.mailing_1.action_send_mail() tour = "mass_mailing_custom_unsubscribe_event_tour" self.start_tour(url_path=self.url, tour_name=tour, login="demo") # Check results from running tour # User should be opted out from event 1 mailing list self.assertTrue(self.event_registration_1.opt_out) # User should not be opted out from event 2 mailing list self.assertFalse(self.event_registration_2.opt_out) reason_xid = "mass_mailing_custom_unsubscribe.reason_not_interested" unsubscriptions = self.env["mail.unsubscription"].search( [ ("action", "=", "unsubscription"), ("mass_mailing_id", "=", self.mailing_1.id), ("email", "=", self.email), ( "unsubscriber_id", "=", "event.registration,%d" % self.event_registration_1.id, ), ("details", "=", False), ("reason_id", "=", self.env.ref(reason_xid).id), ] ) # Unsubscription record must exist self.assertEqual(1, len(unsubscriptions)) self.mailing_2.action_send_mail() # Mail to user must have been sent self.assertEqual(1, self.mailing_2.sent)
37.615385
5,379
468
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class EventRegistration(models.Model): _inherit = "event.registration" opt_out = fields.Boolean( string="Opt-Out", help="If opt-out is checked, this registree has refused to receive " "emails for mass mailing and marketing campaign.", ) # No need of email field, as it already exists
31.2
468
529
py
PYTHON
15.0
# Copyright 2018 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail Activity Partner", "summary": "Add Partner to Activities", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Social Network", "website": "https://github.com/OCA/social", "author": "ForgeFlow, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "data": ["views/mail_activity_views.xml"], "depends": ["mail_activity_board"], }
35.266667
529
3,711
py
PYTHON
15.0
# Copyright 2018 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestMailActivityPartner(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # disable tracking test suite wise cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.user_model = cls.env["res.users"].with_context(no_reset_password=True) cls.user_admin = cls.env.ref("base.user_root") cls.employee = cls.env["res.users"].create( { "company_id": cls.env.ref("base.main_company").id, "name": "Employee", "login": "csu", "email": "[email protected]", "groups_id": [ ( 6, 0, [ cls.env.ref("base.group_user").id, cls.env.ref("base.group_partner_manager").id, ], ) ], } ) cls.partner_model = cls.env["ir.model"]._get("res.partner") activity_type_model = cls.env["mail.activity.type"] cls.activity1 = activity_type_model.create( { "name": "Initial Contact", "delay_count": 5, "delay_unit": "days", "summary": "ACT 1 : Presentation, barbecue, ... ", "res_model": cls.partner_model.model, } ) cls.activity2 = activity_type_model.create( { "name": "Call for Demo", "delay_count": 6, "summary": "ACT 2 : I want to show you my ERP !", "res_model": cls.partner_model.model, } ) cls.partner_01 = cls.env.ref("base.res_partner_1") cls.homer = cls.env["res.partner"].create( { "name": "Homer Simpson", "city": "Springfield", "street": "742 Evergreen Terrace", "street2": "Donut Lane", } ) # test synchro of street3 on create cls.partner_10 = cls.env["res.partner"].create( {"name": "Bart Simpson", "parent_id": cls.homer.id, "type": "contact"} ) def test_partner_for_activity(self): self.act1 = ( self.env["mail.activity"] .sudo() .create( { "activity_type_id": self.activity1.id, "note": "Partner activity 1.", "res_id": self.partner_01.id, "res_model_id": self.partner_model.id, "user_id": self.user_admin.id, } ) ) self.act2 = ( self.env["mail.activity"] .with_user(self.employee) .create( { "activity_type_id": self.activity2.id, "note": "Partner activity 10.", "res_id": self.partner_10.id, "res_model_id": self.partner_model.id, "user_id": self.employee.id, } ) ) # Check partner_id of created activities self.assertEqual(self.act1.partner_id, self.partner_01) self.assertEqual(self.act2.partner_id, self.partner_10) # Check commercial_partner_id for created activities self.assertEqual(self.act1.commercial_partner_id, self.partner_01) self.assertEqual(self.act2.commercial_partner_id, self.homer)
34.361111
3,711
1,256
py
PYTHON
15.0
# Copyright 2018 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailActivity(models.Model): _inherit = "mail.activity" partner_id = fields.Many2one( comodel_name="res.partner", index=True, compute="_compute_res_partner_id", store=True, ) commercial_partner_id = fields.Many2one( related="partner_id.commercial_partner_id", string="Commercial Entity", store=True, related_sudo=True, readonly=True, ) @api.depends("res_model", "res_id") def _compute_res_partner_id(self): for activity in self: res_model = activity.res_model res_id = activity.res_id activity.partner_id = False if res_model: if res_model == "res.partner": activity.partner_id = res_id else: res_model_id = self.env[res_model].browse(res_id) if "partner_id" in res_model_id._fields and res_model_id.partner_id: activity.partner_id = res_model_id.partner_id else: activity.partner_id = False
33.052632
1,256
386
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) import logging _logger = logging.getLogger(__name__) def deprecate(): _logger.warning( """ `microsoft_outlook_single_tenant` is deprecated. Configure microsoft_outlook.endpoint ir.config_parameter """ ) def post_load_hook(): deprecate()
20.315789
386
484
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) { "name": "Microsoft Outlook Single Tenant (DEPRECATED)", "version": "15.0.2.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Hidden", "website": "https://github.com/OCA/social", "depends": [ "microsoft_outlook", ], "data": ["views/res_config_settings_views.xml"], "installable": True, }
32.266667
484
2,229
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo.tests.common import TransactionCase class TestFetchMailServerMicrosoftOutlook(TransactionCase): def _create_mail_server(self): return self.env["fetchmail.server"].create( { "name": "Test server", "use_microsoft_outlook_service": True, "user": "[email protected]", "password": "", "server_type": "imap", "is_ssl": True, } ) def test_default_app_endpoint(self): self.env["res.config.settings"].create( { "microsoft_outlook_client_identifier": "test_client_id", "microsoft_outlook_client_secret": "test_secret", } ).set_values() mail_server = self._create_mail_server() common_endpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/" self.assertIn(common_endpoint, mail_server.microsoft_outlook_uri) def test_single_tenant_app_endpoint(self): self.env["ir.config_parameter"].sudo().set_param( "microsoft_outlook.endpoint", "https://login.microsoftonline.com/test_directory_tenant_id/oauth2/v2.0/", ) self.env["res.config.settings"].create( { "microsoft_outlook_client_identifier": "test_client_id", "microsoft_outlook_directory_tenant_id": "test_directory_tenant_id", "microsoft_outlook_client_secret": "test_secret", } ).set_values() mail_server = self._create_mail_server() mail_server = self.env["fetchmail.server"].create( { "name": "Test server", "use_microsoft_outlook_service": True, "user": "[email protected]", "password": "", "server_type": "imap", "is_ssl": True, } ) single_tenant_endpoint = ( "https://login.microsoftonline.com/test_directory_tenant_id/oauth2/v2.0/" ) self.assertIn(single_tenant_endpoint, mail_server.microsoft_outlook_uri)
37.15
2,229
564
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import models class MicrosoftOutlookMixin(models.AbstractModel): _inherit = "microsoft.outlook.mixin" @property def _OUTLOOK_ENDPOINT(self): outlook_endpoint = "https://login.microsoftonline.com/{path}/oauth2/v2.0/" path = ( self.env["ir.config_parameter"] .sudo() .get_param("microsoft_outlook_directory_tenant_id", "common") ) return outlook_endpoint.format(path=path)
31.333333
564
476
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" microsoft_outlook_directory_tenant_id = fields.Char( string="Directory (tenant) ID", help="Place here Tenant ID (or Application ID), if single-tenant application", config_parameter="microsoft_outlook_directory_tenant_id", )
34
476
601
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail optional autofollow", "summary": """ Choose if you want to automatically add new recipients as followers on mail.compose.message""", "author": "ACSONE SA/NV," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "category": "Social Network", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["mail"], "data": ["wizard/mail_compose_message_view.xml"], "installable": True, }
37.5625
601
2,073
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import common class TestAttachExistingAttachment(common.TransactionCase): def setUp(self): super(TestAttachExistingAttachment, self).setUp() self.partner_obj = self.env["res.partner"] self.partner_01 = self.env.ref("base.res_partner_10") self.partner_02 = self.env.ref("base.res_partner_address_17") def test_send_email_attachment(self): ctx = self.env.context.copy() ctx.update( { "default_model": "res.partner", "default_res_id": self.partner_01.id, "default_composition_mode": "comment", } ) mail_compose = self.env["mail.compose.message"] values = mail_compose.with_context(**ctx)._onchange_template_id( False, "comment", "res.partner", self.partner_01.id )["value"] values["partner_ids"] = [(4, self.partner_02.id)] compose_id = mail_compose.with_context(**ctx).create(values) compose_id.autofollow_recipients = False compose_id.with_context(**ctx).action_send_mail() res = self.env["mail.followers"].search( [ ("res_model", "=", "res.partner"), ("res_id", "=", self.partner_01.id), ("partner_id", "=", self.partner_02.id), ] ) # I check if the recipient isn't a follower self.assertEqual(len(res.ids), 0) compose_id = mail_compose.with_context(**ctx).create(values) compose_id.autofollow_recipients = True compose_id.with_context(**ctx).action_send_mail() res = self.env["mail.followers"].search( [ ("res_model", "=", "res.partner"), ("res_id", "=", self.partner_01.id), ("partner_id", "=", self.partner_02.id), ] ) # I check if the recipient is a follower self.assertEqual(len(res.ids), 1)
40.647059
2,073
1,028
py
PYTHON
15.0
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailComposeMessage(models.TransientModel): _inherit = "mail.compose.message" @api.model def default_get(self, fields_list): res = super(MailComposeMessage, self).default_get(fields_list) res.setdefault( "autofollow_recipients", self.env.context.get("mail_post_autofollow", False) ) return res autofollow_recipients = fields.Boolean( string="Make recipients followers", help="""if checked, the additional recipients will be added as\ followers on the related object""", ) def _action_send_mail(self, auto_commit=False): for wizard in self: super( MailComposeMessage, wizard.with_context(mail_post_autofollow=wizard.autofollow_recipients), )._action_send_mail(auto_commit=auto_commit) return True
34.266667
1,028
650
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Mail Layout Force", "summary": "Force a mail layout on selected email templates", "version": "15.0.1.0.1", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainers": ["ivantodorovich"], "website": "https://github.com/OCA/social", "license": "AGPL-3", "category": "Marketing", "depends": ["mail"], "demo": ["demo/mail_layout.xml"], "data": ["data/mail_layout.xml", "views/mail_template.xml"], }
38.176471
649
2,895
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import TransactionCase class TestMailLayoutForce(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.layout_noop = cls.env.ref("mail_layout_force.mail_layout_noop") cls.layout_test = cls.env["ir.ui.view"].create( { "name": "Test Layout", "type": "qweb", "mode": "primary", "arch": "<t t-name='test'><h1></h1><t t-out='message.body'/></t>", } ) cls.template = cls.env["mail.template"].create( { "name": "Test Template", "body_html": "<p>Test</p>", "subject": "Test", "model_id": cls.env.ref("base.model_res_partner").id, "auto_delete": False, } ) cls.partner = cls.env.ref("base.res_partner_10") cls.partner.message_ids.unlink() cls.partner.message_subscribe([cls.partner.id]) def test_noop_layout(self): self.template.force_email_layout_id = self.layout_noop self.partner.message_post_with_template( self.template.id, # This is ignored because the template has a force_email_layout_id email_layout_xmlid="mail.mail_notification_light", ) message = self.partner.message_ids[-1] self.assertEqual(message.mail_ids.body_html.strip(), "<p>Test</p>") def test_custom_layout(self): self.template.force_email_layout_id = self.layout_test self.partner.message_post_with_template( self.template.id, # This is ignored because the template has a force_email_layout_id email_layout_xmlid="mail.mail_notification_light", ) message = self.partner.message_ids[-1] self.assertEqual(message.mail_ids.body_html.strip(), "<h1></h1><p>Test</p>") def test_custom_layout_composer(self): self.template.force_email_layout_id = self.layout_test composer = ( self.env["mail.compose.message"] .with_context( # This is ignored because the template has a force_email_layout_id custom_layout="mail.mail_notification_light" ) .create( { "res_id": self.partner.id, "model": self.partner._name, "template_id": self.template.id, } ) ) composer._onchange_template_id_wrapper() composer._action_send_mail() message = self.partner.message_ids[-1] self.assertEqual(message.mail_ids.body_html.strip(), "<h1></h1><p>Test</p>")
39.643836
2,894
1,499
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class MailTemplate(models.Model): _inherit = "mail.template" force_email_layout_id = fields.Many2one( comodel_name="ir.ui.view", string="Force Layout", domain=[("type", "=", "qweb"), ("mode", "=", "primary")], context={"default_type": "qweb"}, help="Force a mail layout for this template.", ) def _ensure_force_email_layout_xml_id(self): missing = self.force_email_layout_id.filtered(lambda rec: not rec.xml_id) if missing: vals = [ { "module": "__export__", "name": "force_email_layout_%s" % rec.id, "model": rec._name, "res_id": rec.id, } for rec in missing ] self.env["ir.model.data"].sudo().create(vals) self.force_email_layout_id.invalidate_cache(["xml_id"]) @api.model_create_multi def create(self, vals_list): records = super().create(vals_list) records._ensure_force_email_layout_xml_id() return records def write(self, vals): res = super().write(vals) if "force_email_layout_id" in vals: self._ensure_force_email_layout_xml_id() return res
34.045455
1,498
787
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class MailThread(models.AbstractModel): _inherit = "mail.thread" def message_post_with_template( self, template_id, email_layout_xmlid=None, **kwargs ): # OVERRIDE to force the email_layout_xmlid defined on the mail.template template = self.env["mail.template"].sudo().browse(template_id) if template.force_email_layout_id: email_layout_xmlid = template.force_email_layout_id.xml_id return super().message_post_with_template( template_id, email_layout_xmlid=email_layout_xmlid, **kwargs )
39.3
786
807
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class MailComposer(models.TransientModel): _inherit = "mail.compose.message" def _action_send_mail(self, auto_commit=False): # OVERRIDE to force the email_layout_xmlid defined on the mail.template res = [] for rec in self: if rec.template_id.force_email_layout_id: rec = rec.with_context( custom_layout=self.template_id.force_email_layout_id.xml_id ) res.append( super(MailComposer, rec)._action_send_mail(auto_commit=auto_commit) ) return all(res)
36.636364
806
735
py
PYTHON
15.0
# Copyright 2021 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Mail Message Reply", "summary": """ Make a reply using a message""", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "Creu Blanca,Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "depends": ["mail"], "data": [], "assets": { "web.assets_qweb": [ "/mail_quoted_reply/static/src/xml/mail_message_reply.xml", ], "web.assets_backend": [ "/mail_quoted_reply/static/src/models/mail_message_reply.esm.js", "/mail_quoted_reply/static/src/components/mail_message_reply.esm.js", ], }, }
31.956522
735
1,743
py
PYTHON
15.0
# Copyright 2021 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import re from odoo.tests import TransactionCase class TestMessageReply(TransactionCase): def test_reply(self): partner = self.env["res.partner"].create({"name": "demo partner"}) self.assertFalse( partner.message_ids.filtered(lambda r: r.message_type != "notification") ) # pylint: disable=C8107 message = partner.message_post( body="demo message", message_type="email", partner_ids=self.env.ref("base.partner_demo").ids, ) partner.refresh() self.assertIn( message, partner.message_ids.filtered(lambda r: r.message_type != "notification"), ) self.assertFalse( partner.message_ids.filtered( lambda r: r.message_type != "notification" and r != message ) ) action = message.reply_message() wizard = ( self.env[action["res_model"]].with_context(**action["context"]).create({}) ) self.assertTrue(wizard.partner_ids) self.assertEqual(message.partner_ids, wizard.partner_ids) # the onchange in the composer isn't triggered in tests, so we check for the # correct quote in the context email_quote = re.search("<p>.*?</p>", wizard._context["quote_body"]).group() self.assertEqual("<p>demo message</p>", email_quote) wizard.action_send_mail() new_message = partner.message_ids.filtered( lambda r: r.message_type != "notification" and r != message ) self.assertTrue(new_message) self.assertEqual(1, len(new_message))
37.891304
1,743
457
py
PYTHON
15.0
from markupsafe import Markup from odoo import api, models class MailComposeMessage(models.TransientModel): _inherit = "mail.compose.message" @api.onchange("template_id") def _onchange_template_id_wrapper(self): super()._onchange_template_id_wrapper() context = self._context if "is_quoted_reply" in context.keys() and context["is_quoted_reply"]: self.body += Markup(context["quote_body"]) return
30.466667
457
1,478
py
PYTHON
15.0
# Copyright 2021 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class MailMessage(models.Model): _inherit = "mail.message" def _prep_quoted_reply_body(self): return """ <div> <br/> <br/> </div> <br/> <blockquote style="padding-right:0px; padding-left:5px; border-left-color: #000; margin-left:5px; margin-right:0px;border-left-width: 2px; border-left-style:solid"> From: {email_from}<br/> Date: {date}<br/> Subject: {subject}<br/> {body} </blockquote> """.format( email_from=self.email_from, date=self.date, subject=self.subject, body=self.body, ) def reply_message(self): action = self.env["ir.actions.actions"]._for_xml_id( "mail.action_email_compose_message_wizard" ) action["context"] = { "default_model": self.model, "default_res_id": self.res_id, "default_composition_mode": "comment", "quote_body": self._prep_quoted_reply_body(), "default_is_log": False, "is_log": False, "is_quoted_reply": True, "default_notify": True, "force_email": True, "default_partner_ids": self.partner_ids.ids, } return action
30.791667
1,478
537
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Mail parent recipient", "summary": "Send email to parent partner if partner's email is empty", "category": "Mail", "license": "AGPL-3", "version": "15.0.1.0.0", "website": "https://github.com/OCA/social", "author": "Camptocamp, Odoo Community Association (OCA)", "application": False, "installable": True, "depends": [ "mail", ], "data": ["views/res_config_views.xml"], }
31.588235
537
3,036
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.addons.mail.tests.common import MailCommon class TestMailTemplate(MailCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.env["ir.config_parameter"].set_param("mail.use_parent_address", True) cls.res_partner = cls.env["res.partner"] cls.company_test = cls.res_partner.create( { "name": "company_name_test", "email": "company.mail.test@company", } ) cls.partner_no_mail = cls.res_partner.create( { "name": "partner_1", "parent_id": cls.company_test.id, } ) cls.partner_with_mail = cls.res_partner.create( { "name": "partner_2", "email": "partner.2.mail.test@company", "parent_id": cls.company_test.id, } ) cls.record = cls.env.ref("base.partner_demo") cls.email_template = ( cls.env["mail.template"] .with_context(test_parent_mail_recipient=True) .create( { "model_id": cls.env["ir.model"] .search([("model", "=", "mail.channel")], limit=1) .id, "name": "Pigs Template", "subject": "${object.name}", "body_html": "${object.description}", "partner_to": "", } ) ) def _get_email_recipient_for(self, partner_to_send_ids): self.email_template.partner_to = ",".join( [str(partner_id) for partner_id in partner_to_send_ids] ) values = self.email_template.generate_email(self.record.id, ["partner_to"]) return values["partner_ids"] def test_mail_send_to_partner_no_mail(self): """Check recipient without email, comapny email is used.""" recipients = self._get_email_recipient_for(self.partner_no_mail.ids) self.assertEqual(recipients, self.company_test.ids) def test_mail_send_to_partner_with_mail(self): """Check recipient has email, nothing is changed.""" recipients = self._get_email_recipient_for(self.partner_with_mail.ids) self.assertEqual(recipients, self.partner_with_mail.ids) def test_mail_send_to_company_test(self): """Check company email is used.""" recipients = self._get_email_recipient_for(self.company_test.ids) self.assertEqual(recipients, self.company_test.ids) def test_mail_send_to_company_and_partner_no_mail(self): """Check a partner is not add twice in recipient list.""" recipients = self._get_email_recipient_for( [self.partner_no_mail.id, self.company_test.id] ) self.assertEqual(recipients, self.company_test.ids)
38.43038
3,036
1,494
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class MailTemplate(models.Model): _inherit = "mail.template" def generate_recipients(self, results, res_ids): """Use partner's parent email as recipient. Walk up the hierarchy of recipient partners via `parent_id` and pick the 1st one having an email. """ results = super().generate_recipients(results, res_ids) use_parent_address = ( self.env["ir.config_parameter"].sudo().get_param("mail.use_parent_address") ) disabled = self.env.context.get("no_parent_mail_recipient") if use_parent_address and not disabled: for res_id, values in results.items(): partner_ids = values.get("partner_ids", []) partners_with_emails = [] partners = self.env["res.partner"].sudo().browse(partner_ids) for partner in partners: if partner.email: partners_with_emails.append(partner.id) elif partner.commercial_partner_id.email: if partner.commercial_partner_id.id not in partners.ids: partners_with_emails.append( partner.commercial_partner_id.id ) results[res_id]["partner_ids"] = partners_with_emails return results
42.685714
1,494
484
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" use_parent_mail_address = fields.Boolean( config_parameter="mail.use_parent_address", help=""" When checked, for partner without eamil the system will try to use the email address of the partner's parent. """, )
30.25
484
1,067
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow S.L. # Copyright 2021 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail Activity Team", "summary": "Add Teams to Activities", "version": "15.0.2.1.0", "development_status": "Alpha", "category": "Social Network", "website": "https://github.com/OCA/social", "author": "ForgeFlow, Sodexis, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["mail_activity_board"], "data": [ "security/ir.model.access.csv", "security/mail_activity_team_security.xml", "views/ir_actions_server_views.xml", "views/mail_activity_type.xml", "views/mail_activity_team_views.xml", "views/mail_activity_views.xml", "views/res_users_views.xml", ], "assets": { "web.assets_backend": [ "mail_activity_team/static/src/js/systray.esm.js", ], "web.assets_qweb": [ "mail_activity_team/static/src/xml/systray.xml", ], }, }
33.34375
1,067
13,163
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from odoo.tests.common import Form, TransactionCase class TestMailActivityTeam(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # Start from a clean slate cls.env["mail.activity.team"].search([]).unlink() # Create Users cls.employee = cls.env["res.users"].create( { "company_id": cls.env.ref("base.main_company").id, "name": "Employee", "login": "csu", "email": "[email protected]", "groups_id": [ ( 6, 0, [ cls.env.ref("base.group_user").id, cls.env.ref("base.group_partner_manager").id, ], ) ], } ) cls.employee2 = cls.env["res.users"].create( { "company_id": cls.env.ref("base.main_company").id, "name": "Employee 2", "login": "csu2", "email": "[email protected]", "groups_id": [(6, 0, [cls.env.ref("base.group_user").id])], } ) cls.employee3 = cls.env["res.users"].create( { "company_id": cls.env.ref("base.main_company").id, "name": "Employee 3", "login": "csu3", "email": "[email protected]", "groups_id": [(6, 0, [cls.env.ref("base.group_user").id])], } ) # Create Activity Types cls.activity1 = cls.env["mail.activity.type"].create( { "name": "Initial Contact", "delay_count": 5, "delay_unit": "days", "summary": "ACT 1 : Presentation, barbecue, ... ", "res_model": "res.partner", } ) cls.activity2 = cls.env["mail.activity.type"].create( { "name": "Call for Demo", "delay_count": 6, "delay_unit": "days", "summary": "ACT 2 : I want to show you my ERP !", "res_model": "res.partner", } ) # Create Teams and Activities cls.partner_client = cls.env.ref("base.res_partner_1") cls.partner_ir_model = cls.env["ir.model"]._get("res.partner") cls.act1 = ( cls.env["mail.activity"] .with_user(cls.employee) .create( { "activity_type_id": cls.activity1.id, "note": "Partner activity 1.", "res_id": cls.partner_client.id, "res_model_id": cls.partner_ir_model.id, "user_id": cls.employee.id, } ) ) cls.team1 = cls.env["mail.activity.team"].create( { "name": "Team 1", "res_model_ids": [(6, 0, [cls.partner_ir_model.id])], "member_ids": [(6, 0, [cls.employee.id])], } ) cls.team2 = cls.env["mail.activity.team"].create( { "name": "Team 2", "res_model_ids": [(6, 0, [cls.partner_ir_model.id])], "member_ids": [(6, 0, [cls.employee.id, cls.employee2.id])], } ) cls.act2 = ( cls.env["mail.activity"] .with_user(cls.employee) .create( { "activity_type_id": cls.activity2.id, "note": "Partner activity 2.", "res_id": cls.partner_client.id, "res_model_id": cls.partner_ir_model.id, "user_id": cls.employee.id, } ) ) def test_activity_members(self): self.team1.member_ids |= self.employee2 self.partner_client.refresh() self.assertIn(self.employee2, self.partner_client.activity_team_user_ids) self.assertIn(self.employee, self.partner_client.activity_team_user_ids) self.assertEqual( self.partner_client, self.env["res.partner"].search( [("activity_team_user_ids", "=", self.employee.id)] ), ) def test_team_and_user_onchange(self): with self.assertRaises(ValidationError): self.team1.member_ids = [(3, self.employee.id)] self.act2.team_id = self.team1 self.act2.user_id = self.employee def test_missing_activities(self): self.assertFalse(self.act1.team_id, "Error: Activity 1 should not have a team.") self.assertEqual(self.team1.count_missing_activities, 1) self.team1.assign_team_to_unassigned_activities() self.team1._compute_missing_activities() self.assertEqual(self.team1.count_missing_activities, 0) self.assertEqual(self.act1.team_id, self.team1) def test_leader_onchange(self): self.team2.user_id = self.employee3 self.team2._onchange_user_id() self.assertTrue(self.employee3 in self.team2.member_ids) def test_activity_onchanges_keep_user(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) with Form(self.act2) as form: form.team_id = self.env["mail.activity.team"] self.assertEqual(form.user_id, self.employee) def test_activity_onchanges_user_no_member_team(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) with Form(self.act2) as form: form.user_id = self.employee2 self.assertEqual(form.team_id, self.team2) def test_activity_onchanges_user_no_team(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) with Form(self.act2) as form: form.team_id = self.env["mail.activity.team"] form.user_id = self.employee2 self.assertEqual(form.team_id, self.team2) def test_activity_onchanges_team_no_member(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) self.team2.user_id = False self.team2.member_ids = False with Form(self.act2) as form: form.team_id = self.team2 self.assertFalse(form.user_id) def test_activity_onchanges_team_different_member(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) self.team2.user_id = self.employee2 self.team2.member_ids = self.employee2 with Form(self.act2) as form: form.team_id = self.team2 self.assertEqual(form.user_id, self.employee2) def test_activity_onchanges_team_different_member_no_leader(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) self.team2.user_id = False self.team2.member_ids = self.employee2 with Form(self.act2) as form: form.team_id = self.team2 self.assertEqual(form.user_id, self.employee2) def test_activity_onchanges_activity_type_set_team(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) self.activity1.default_team_id = self.team2 self.assertEqual(self.act2.activity_type_id, self.activity2) with Form(self.act2) as form: form.activity_type_id = self.activity1 self.assertEqual(form.team_id, self.team2) def test_activity_onchanges_activity_type_no_team(self): self.assertEqual( self.act2.team_id, self.team1, "Error: Activity 2 should have Team 1." ) self.assertEqual(self.act2.activity_type_id, self.activity2) with Form(self.act2) as form: form.activity_type_id = self.activity1 self.assertEqual(form.team_id, self.team1) def test_activity_constrain(self): with self.assertRaises(ValidationError): self.act2.write({"user_id": self.employee2.id, "team_id": self.team1.id}) def test_schedule_activity(self): """Correctly assign teams to auto scheduled activities. Those won't trigger onchanges and could raise constraints and team missmatches""" partner_record = self.employee.partner_id.with_user(self.employee.id) activity = partner_record.activity_schedule( user_id=self.employee2.id, activity_type_id=self.env.ref("mail.mail_activity_data_call").id, ) self.assertEqual(activity.team_id, self.team2) def test_schedule_activity_default_team(self): """Correctly assign teams to auto scheduled activities. Those won't trigger onchanges and could raise constraints and team missmatches""" partner_record = self.employee.partner_id.with_user(self.employee.id) self.env.ref("mail.mail_activity_data_call").default_team_id = self.team2 activity = partner_record.activity_schedule( act_type_xmlid="mail.mail_activity_data_call", user_id=self.employee2.id, ) self.assertEqual(activity.team_id, self.team2) self.assertEqual(activity.user_id, self.employee2) def test_schedule_activity_default_team_no_user(self): """Correctly assign teams to auto scheduled activities. Those won't trigger onchanges and could raise constraints and team missmatches""" partner_record = self.employee.partner_id.with_user(self.employee.id) self.activity2.default_team_id = self.team2 self.team2.member_ids = self.employee2 activity = partner_record.activity_schedule( activity_type_id=self.activity2.id, ) self.assertEqual(activity.team_id, self.team2) self.assertEqual(activity.user_id, self.employee2) def test_activity_count(self): res = ( self.env["res.users"] .with_user(self.employee.id) .with_context(**{"team_activities": True}) .systray_get_activities() ) self.assertEqual(res[0]["total_count"], 0) self.assertEqual(res[0]["today_count"], 1) partner_record = self.employee.partner_id.with_user(self.employee.id) self.activity2.default_team_id = self.team2 activity = partner_record.activity_schedule( activity_type_id=self.activity2.id, user_id=self.employee2.id ) activity.flush() res = ( self.env["res.users"] .with_user(self.employee.id) .with_context(**{"team_activities": True}) .systray_get_activities() ) self.assertEqual(res[0]["total_count"], 1) self.assertEqual(res[0]["today_count"], 2) res = self.env["res.users"].with_user(self.employee.id).systray_get_activities() self.assertEqual(res[0]["total_count"], 2) def test_activity_schedule_next(self): self.activity1.write( { "default_team_id": self.team1.id, "triggered_next_type_id": self.activity2.id, } ) self.activity2.default_team_id = self.team2 self.team2.member_ids = self.employee2 partner_record = self.employee.partner_id.with_user(self.employee.id) activity = partner_record.activity_schedule(activity_type_id=self.activity1.id) activity.flush() _messages, next_activities = activity._action_done() self.assertTrue(next_activities) self.assertEqual(next_activities.team_id, self.team2) self.assertEqual(next_activities.user_id, self.employee2) def test_schedule_activity_from_server_action(self): partner = self.env["res.partner"].create({"name": "Test Partner"}) action = self.env["ir.actions.server"].create( { "name": "Test Server Action", "model_id": self.partner_ir_model.id, "state": "next_activity", "activity_type_id": self.activity1.id, "activity_user_type": "specific", "activity_user_id": self.employee.id, "activity_team_id": self.team1.id, } ) action.with_context(active_model=partner._name, active_ids=partner.ids).run() self.assertEqual(partner.activity_ids[-1].team_id, self.team1) action.activity_team_id = self.team2 action.with_context(active_model=partner._name, active_ids=partner.ids).run() self.assertEqual(partner.activity_ids[-1].team_id, self.team2)
41.393082
13,163
276
py
PYTHON
15.0
# Copyright 2022 CreuBlanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MailActivityType(models.Model): _inherit = "mail.activity.type" default_team_id = fields.Many2one(comodel_name="mail.activity.team")
25.090909
276
2,638
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow S.L. # Copyright 2021 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailActivityTeam(models.Model): _name = "mail.activity.team" _description = "Mail Activity Team" @api.depends("res_model_ids", "member_ids") def _compute_missing_activities(self): activity_model = self.env["mail.activity"] for team in self: domain = [("team_id", "=", False)] if team.member_ids: domain.append(("user_id", "in", team.member_ids.ids)) if team.res_model_ids: domain.append(("res_model_id", "in", team.res_model_ids.ids)) team.count_missing_activities = activity_model.search(domain, count=True) name = fields.Char(required=True, translate=True) active = fields.Boolean(default=True) res_model_ids = fields.Many2many( comodel_name="ir.model", string="Used models", domain=lambda self: [ ( "model", "in", [ k for k in self.env.registry if issubclass( type(self.env[k]), type(self.env["mail.activity.mixin"]) ) and self.env[k]._auto ], ) ], ) member_ids = fields.Many2many( comodel_name="res.users", relation="mail_activity_team_users_rel", string="Team Members", ) user_id = fields.Many2one(comodel_name="res.users", string="Team Leader") count_missing_activities = fields.Integer( string="Missing Activities", compute="_compute_missing_activities", default=0 ) @api.onchange("user_id") def _onchange_user_id(self): if self.user_id and self.user_id not in self.member_ids: members_ids = self.member_ids.ids members_ids.append(self.user_id.id) self.member_ids = [(4, member) for member in members_ids] def assign_team_to_unassigned_activities(self): activity_model = self.env["mail.activity"] for team in self: domain = [("team_id", "=", False)] if team.member_ids: domain.append(("user_id", "in", team.member_ids.ids)) if team.res_model_ids: domain.append(("res_model_id", "in", team.res_model_ids.ids)) missing_activities = activity_model.search(domain) for missing_activity in missing_activities: missing_activity.write({"team_id": team.id})
38.231884
2,638
3,549
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID, _, api, fields, models from odoo.exceptions import ValidationError class MailActivity(models.Model): _inherit = "mail.activity" def _get_default_team_id(self, user_id=None): if not user_id: user_id = self.env.uid res_model = self.env.context.get("default_res_model") model = self.sudo().env["ir.model"].search([("model", "=", res_model)], limit=1) domain = [("member_ids", "in", [user_id])] if res_model: domain.extend( ["|", ("res_model_ids", "=", False), ("res_model_ids", "in", model.ids)] ) return self.env["mail.activity.team"].search(domain, limit=1) user_id = fields.Many2one(string="User", required=False) team_user_id = fields.Many2one( string="Team user", related="user_id", readonly=False ) team_id = fields.Many2one( comodel_name="mail.activity.team", default=lambda s: s._get_default_team_id() ) @api.onchange("user_id") def _onchange_user_id(self): if not self.user_id or ( self.team_id and self.user_id in self.team_id.member_ids ): return self.team_id = self.with_context( default_res_model=self.sudo().res_model_id.model )._get_default_team_id(user_id=self.user_id.id) @api.onchange("team_id") def _onchange_team_id(self): if self.team_id and self.user_id not in self.team_id.member_ids: if self.team_id.user_id: self.user_id = self.team_id.user_id elif len(self.team_id.member_ids) == 1: self.user_id = self.team_id.member_ids else: self.user_id = self.env["res.users"] @api.constrains("team_id", "user_id") def _check_team_and_user(self): for activity in self: # SUPERUSER is used to put mail.activity on some objects # like sale.order coming from stock.picking # (for example with exception type activity, with no backorder). # SUPERUSER is inactive and then even if you add it # to member_ids it's not taken account # To not be blocked we must add it to constraint condition. # We must consider also users that could be archived but come from # an automatic scheduled activity if ( activity.user_id.id != SUPERUSER_ID and activity.team_id and activity.user_id and activity.user_id not in activity.team_id.with_context(active_test=False).member_ids ): raise ValidationError( _( "The assigned user %(user_name)s is " "not member of the team %(team_name)s.", user_name=activity.user_id.name, team_name=activity.team_id.name, ) ) @api.onchange("activity_type_id") def _onchange_activity_type_id(self): res = super(MailActivity, self)._onchange_activity_type_id() if self.activity_type_id.default_team_id: self.team_id = self.activity_type_id.default_team_id members = self.activity_type_id.default_team_id.member_ids if self.user_id not in members and members: self.user_id = members[:1] return res
40.793103
3,549
2,938
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models, modules class ResUsers(models.Model): _inherit = "res.users" activity_team_ids = fields.Many2many( comodel_name="mail.activity.team", relation="mail_activity_team_users_rel", string="Activity Teams", ) @api.model def systray_get_activities(self): if not self.env.context.get("team_activities"): return super().systray_get_activities() query = """SELECT m.id, count(*), act.res_model as model, CASE WHEN %(today)s::date - act.date_deadline::date = 0 Then 'today' WHEN %(today)s::date - act.date_deadline::date > 0 Then 'overdue' WHEN %(today)s::date - act.date_deadline::date < 0 Then 'planned' END AS states, act.user_id as user_id FROM mail_activity AS act JOIN ir_model AS m ON act.res_model_id = m.id WHERE team_id in ( SELECT mail_activity_team_id FROM mail_activity_team_users_rel WHERE res_users_id = %(user_id)s ) GROUP BY m.id, states, act.res_model, act.user_id;""" user = self.env.uid self.env.cr.execute( query, { "today": fields.Date.context_today(self), "user_id": user, }, ) activity_data = self.env.cr.dictfetchall() model_ids = [a["id"] for a in activity_data] model_names = { n[0]: n[1] for n in self.env["ir.model"].sudo().browse(model_ids).name_get() } user_activities = {} for activity in activity_data: if not user_activities.get(activity["model"]): user_activities[activity["model"]] = { "name": model_names[activity["id"]], "model": activity["model"], "type": "activity", "icon": modules.module.get_module_icon( self.env[activity["model"]]._original_module ), "total_count": 0, "today_count": 0, "overdue_count": 0, "planned_count": 0, } user_activities[activity["model"]][ "%s_count" % activity["states"] ] += activity["count"] if ( activity["states"] in ("today", "overdue") and activity["user_id"] != user ): user_activities[activity["model"]]["total_count"] += activity["count"] return list(user_activities.values())
40.805556
2,938
3,376
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailActivityMixin(models.AbstractModel): _inherit = "mail.activity.mixin" activity_team_user_ids = fields.Many2many( comodel_name="res.users", string="test field", compute="_compute_activity_team_user_ids", search="_search_activity_team_user_ids", ) @api.depends("activity_ids") def _compute_activity_team_user_ids(self): for rec in self: rec.activity_team_user_ids = rec.activity_ids.mapped("team_id.member_ids") def _search_my_activity_date_deadline(self, operator, operand): if not self._context.get("team_activities", False): return super(MailActivityMixin, self)._search_my_activity_date_deadline( operator, operand ) activity_ids = self.env["mail.activity"]._search( [ "|", ("user_id", "=", self.env.user.id), "&", ("date_deadline", operator, operand), ("res_model", "=", self._name), ] ) return [("activity_ids", "in", activity_ids)] @api.model def _search_activity_team_user_ids(self, operator, operand): return [("activity_ids.team_id.member_ids", operator, operand)] def activity_schedule( self, act_type_xmlid="", date_deadline=None, summary="", note="", **act_values ): """With automatic activities, the user onchange won't act so we must ensure the right group is set and no exceptions are raised due to user-team missmatch. We can hook onto `act_values` dict as it's passed to the create activity method. """ if self.env.context.get("force_activity_team"): act_values["team_id"] = self.env.context["force_activity_team"].id if "team_id" not in act_values: if act_type_xmlid: activity_type = self.sudo().env.ref(act_type_xmlid) else: activity_type = ( self.env["mail.activity.type"] .sudo() .browse(act_values["activity_type_id"]) ) if activity_type.default_team_id: act_values.update({"team_id": activity_type.default_team_id.id}) if ( not act_values.get("user_id") and activity_type.default_team_id.member_ids ): act_values.update( {"user_id": activity_type.default_team_id.member_ids[:1].id} ) else: user_id = act_values.get("user_id") if user_id: team = ( self.env["mail.activity"] .with_context( default_res_model=self._name, ) ._get_default_team_id(user_id=user_id) ) act_values.update({"team_id": team.id}) return super().activity_schedule( act_type_xmlid=act_type_xmlid, date_deadline=date_deadline, summary=summary, note=note, **act_values )
39.255814
3,376
762
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class IrActionsServer(models.Model): _inherit = "ir.actions.server" activity_team_id = fields.Many2one( "mail.activity.team", string="Activity Team", ) def _run_action_next_activity(self, eval_context=None): # OVERRIDE to force the activity team on scheduled actions if self.activity_user_type == "specific" and self.activity_team_id: self = self.with_context(force_activity_team=self.activity_team_id) return super()._run_action_next_activity(eval_context=eval_context)
38.05
761
3,113
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow <http://www.forgeflow.com> # Copyright 2018 Odoo, S.A. # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import Command, fields from odoo.addons.mail.models.mail_activity import MailActivity def pre_init_hook(cr): """The objective of this hook is to default to false all values of field 'done' of mail.activity """ cr.execute( """SELECT column_name FROM information_schema.columns WHERE table_name='mail_activity' AND column_name='done'""" ) if not cr.fetchone(): cr.execute( """ ALTER TABLE mail_activity ADD COLUMN done boolean; """ ) cr.execute( """ UPDATE mail_activity SET done = False """ ) def post_load_hook(): def _new_action_done(self, feedback=False, attachment_ids=None): """Overwritten method""" if "done" not in self._fields: return self._action_done_original( feedback=feedback, attachment_ids=attachment_ids ) # marking as 'done' messages = self.env["mail.message"] next_activities_values = [] for activity in self: # extract value to generate next activities if activity.chaining_type == "trigger": vals = activity.with_context( activity_previous_deadline=activity.date_deadline )._prepare_next_activity_values() next_activities_values.append(vals) # post message on activity, before deleting it record = self.env[activity.res_model].browse(activity.res_id) activity.done = True activity.active = False activity.date_done = fields.Date.today() record.message_post_with_view( "mail.message_activity_done", values={ "activity": activity, "feedback": feedback, "display_assignee": activity.user_id != self.env.user, }, subtype_id=self.env["ir.model.data"]._xmlid_to_res_id( "mail.mt_activities" ), mail_activity_type_id=activity.activity_type_id.id, attachment_ids=[ Command.link(attachment_id) for attachment_id in attachment_ids ] if attachment_ids else [], ) messages |= record.message_ids[0] next_activities = self.env["mail.activity"].create(next_activities_values) return messages, next_activities if not hasattr(MailActivity, "_action_done_original"): MailActivity._action_done_original = MailActivity._action_done MailActivity._action_done = _new_action_done def uninstall_hook(cr, registry): """The objective of this hook is to remove all activities that are done upon module uninstall """ cr.execute( """ DELETE FROM mail_activity WHERE done=True """ )
33.117021
3,113
539
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow <http://www.forgeflow.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Mail Activity Done", "version": "15.0.1.0.1", "author": "ForgeFlow, Odoo Community Association (OCA)", "license": "LGPL-3", "category": "Discuss", "website": "https://github.com/OCA/social", "depends": ["mail"], "data": ["views/mail_activity_views.xml"], "pre_init_hook": "pre_init_hook", "post_load": "post_load_hook", "uninstall_hook": "uninstall_hook", }
35.933333
539
1,449
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import date from odoo.tests.common import TransactionCase class TestMailActivityDoneMethods(TransactionCase): def setUp(self): super(TestMailActivityDoneMethods, self).setUp() self.employee = self.env["res.users"].create( { "company_id": self.env.ref("base.main_company").id, "name": "Test User", "login": "testuser", "groups_id": [(6, 0, [self.env.ref("base.group_user").id])], } ) activity_type = self.env["mail.activity.type"].search( [("name", "=", "Meeting")], limit=1 ) self.act1 = self.env["mail.activity"].create( { "activity_type_id": activity_type.id, "res_id": self.env.ref("base.res_partner_1").id, "res_model_id": self.env["ir.model"]._get("res.partner").id, "user_id": self.employee.id, "date_deadline": date.today(), } ) def test_mail_activity_done(self): self.act1.done = True self.assertEqual(self.act1.state, "done") def test_systray_get_activities(self): act_count = self.employee.with_user(self.employee).systray_get_activities() self.assertEqual( len(act_count), 1, "Number of activities should be equal to one" )
35.341463
1,449
2,452
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow <http://www.forgeflow.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class MailActivity(models.Model): _inherit = "mail.activity" active = fields.Boolean(default=True) done = fields.Boolean(default=False) state = fields.Selection( selection_add=[("done", "Done")], compute="_compute_state", search="_search_state", ) date_done = fields.Date("Completed Date", index=True, readonly=True) @api.depends("date_deadline", "done") def _compute_state(self): res = super()._compute_state() for record in self.filtered(lambda activity: activity.done): record.state = "done" return res def _search_state(self, operator, operand): if not operand: # checking for is (not) set if operator == "=": # is not set - never happens actually so we create impossible domain return [("id", "=", False)] else: # is set - always - return empty domain return [] else: # checking for value if operand == "done": if operator == "=": return ["&", ("done", operator, True), ("active", "=", False)] else: return ["&", ("done", operator, False), ("active", "=", True)] else: if operator == "=": return [ "&", ( "date_deadline", {"today": "=", "overdue": "<", "planned": ">"}[operand], fields.Date.today(), ), ("done", "=", False), ] else: return [ "|", ( "date_deadline", {"today": "!=", "overdue": ">=", "planned": "<="}[operand], fields.Date.today(), ), ("done", "=", True), ] class MailActivityMixin(models.AbstractModel): _inherit = "mail.activity.mixin" activity_ids = fields.One2many( domain=lambda self: [("res_model", "=", self._name), ("active", "=", True)] )
35.028571
2,452
2,519
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow <http://www.forgeflow.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models, modules class ResUsers(models.Model): _inherit = "res.users" @api.model def systray_get_activities(self): # Here we totally override the method. Not very nice, but # we should perhaps ask Odoo to add a hook here. query = """SELECT m.id, count(*), act.res_model as model, CASE WHEN %(today)s::date - act.date_deadline::date = 0 Then 'today' WHEN %(today)s::date - act.date_deadline::date > 0 Then 'overdue' WHEN %(today)s::date - act.date_deadline::date < 0 Then 'planned' END AS states FROM mail_activity AS act JOIN ir_model AS m ON act.res_model_id = m.id WHERE user_id = %(user_id)s AND act.done = False GROUP BY m.id, states, act.res_model; """ self.env.cr.execute( query, {"today": fields.Date.context_today(self), "user_id": self.env.uid} ) activity_data = self.env.cr.dictfetchall() model_ids = [a["id"] for a in activity_data] model_names = { n[0]: n[1] for n in self.env["ir.model"].sudo().browse(model_ids).name_get() } user_activities = {} for activity in activity_data: if not user_activities.get(activity["model"]): user_activities[activity["model"]] = { "name": model_names[activity["id"]], "model": activity["model"], "icon": modules.module.get_module_icon( self.env[activity["model"]]._original_module ), "total_count": 0, "today_count": 0, "overdue_count": 0, "planned_count": 0, "type": "activity", } user_activities[activity["model"]][ "%s_count" % activity["states"] ] += activity["count"] if activity["states"] in ("today", "overdue"): user_activities[activity["model"]]["total_count"] += activity["count"] return list(user_activities.values())
43.431034
2,519
1,514
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <[email protected]> # Copyright 2018 David Vidal <[email protected]> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Customizable unsubscription process on mass mailing emails", "summary": "Know and track (un)subscription reasons, GDPR compliant", "category": "Marketing", "version": "15.0.1.0.0", "depends": ["mass_mailing"], "data": [ "security/ir.model.access.csv", "data/mail_unsubscription_reason.xml", "templates/general_reason_form.xml", "templates/mass_mailing_contact_reason.xml", "views/mail_unsubscription_reason_view.xml", "views/mail_mass_mailing_list_view.xml", "views/mail_unsubscription_view.xml", ], "assets": { "web.assets_backend": [ ( "replace", "mass_mailing/static/src/js/unsubscribe.js", "mass_mailing_custom_unsubscribe/static/src/js/unsubscribe.js", ), ], "web.assets_tests": [ "mass_mailing_custom_unsubscribe/static/src/js/contact.tour.esm.js", "mass_mailing_custom_unsubscribe/static/src/js/partner.tour.esm.js", ], }, "demo": ["demo/assets.xml"], "images": ["images/form.png"], "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "license": "AGPL-3", "installable": True, }
38.820513
1,514
285
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions class DetailsRequiredError(exceptions.ValidationError): pass class ReasonRequiredError(exceptions.ValidationError): pass
23.75
285
6,165
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from unittest import mock from werkzeug import urls from odoo.tests.common import HttpCase class UICase(HttpCase): def extract_url(self, mail, *args, **kwargs): url = mail.mailing_id._get_unsubscribe_url(self.email, mail.res_id) self.assertTrue(urls.url_parse(url).decode_query().get("token")) self.assertTrue(url.startswith(self.domain)) self.url = url.replace(self.domain, "", 1) return True def setUp(self): super().setUp() self.email = "[email protected]" self.mail_postprocess_patch = mock.patch( "odoo.addons.mass_mailing.models.mail_mail.MailMail." "_postprocess_sent_message", autospec=True, side_effect=self.extract_url, ) self.domain = self.env["ir.config_parameter"].get_param("web.base.url") List = self.lists = self.env["mailing.list"] for n in range(4): self.lists += List.create({"name": "test list %d" % n}) self.contact = self.env["mailing.contact"].create( { "name": "test contact", "email": self.email, "list_ids": [(6, False, self.lists.ids)], } ) self.mailing = self.env["mailing.mailing"].create( { "name": "test mailing %d" % n, "mailing_model_id": self.env.ref("mass_mailing.model_mailing_list").id, "contact_list_ids": [(6, 0, [self.lists[0].id, self.lists[3].id])], "reply_to_mode": "update", "subject": "Test", } ) # HACK https://github.com/odoo/odoo/pull/14429 self.mailing.body_html = """ <div> <a href="/unsubscribe_from_list"> This link should get the unsubscription URL </a> </div> """ def tearDown(self): del self.email, self.lists, self.contact, self.mailing, self.url super().tearDown() def test_contact_unsubscription(self): """Test a mass mailing contact that wants to unsubscribe.""" # This list we are unsubscribing from, should appear always in UI self.lists[0].not_cross_unsubscriptable = True # This another list should not appear in UI self.lists[2].not_cross_unsubscriptable = True # This another list should not appear in UI, even if it is one of # the lists of the mailing self.lists[3].is_public = False # Extract the unsubscription link from the message body with self.mail_postprocess_patch: self.mailing.action_send_mail() self.start_tour( self.url, "mass_mailing_custom_unsubscribe_tour_contact", login="admin" ) # Check results from running tour self.assertFalse(self.lists[0].subscription_ids.opt_out) self.assertTrue(self.lists[1].subscription_ids.opt_out) self.assertFalse(self.lists[2].subscription_ids.opt_out) cnt = self.contact common_domain = [ ("mass_mailing_id", "=", self.mailing.id), ("email", "=", self.email), ("unsubscriber_id", "=", "%s,%d" % (cnt._name, cnt.id)), ] # first unsubscription reason = "mass_mailing_custom_unsubscribe.reason_other" unsubscription_1 = self.env["mail.unsubscription"].search( common_domain + [ ("action", "=", "unsubscription"), ("details", "=", "I want to unsubscribe because I want. " "Period."), ("reason_id", "=", self.env.ref(reason).id), ] ) # second unsubscription reason = "mass_mailing_custom_unsubscribe.reason_not_interested" unsubscription_2 = self.env["mail.unsubscription"].search( common_domain + [ ("action", "=", "unsubscription"), ("reason_id", "=", self.env.ref(reason).id), ] ) # re-subscription from self.lists[3] unsubscription_3 = self.env["mail.unsubscription"].search( common_domain + [("action", "=", "subscription")] ) # unsubscriptions above are all unsubscriptions saved during the # tour and they are all the existing unsubscriptions self.assertEqual( unsubscription_1 | unsubscription_2 | unsubscription_3, self.env["mail.unsubscription"].search([]), ) self.assertEqual(3, len(self.env["mail.unsubscription"].search([]))) def test_partner_unsubscription(self): """Test a partner that wants to unsubscribe.""" # Change mailing to be sent to partner partner_id = self.env["res.partner"].name_create( "Demo Partner <%s>" % self.email )[0] self.mailing.mailing_model_id = self.env.ref("base.model_res_partner") self.mailing.mailing_domain = repr( [("is_blacklisted", "=", False), ("id", "=", partner_id)] ) # Extract the unsubscription link from the message body with self.mail_postprocess_patch: self.mailing.action_send_mail() self.start_tour( self.url, "mass_mailing_custom_unsubscribe_tour_partner", login="demo" ) # Check results from running tour partner = self.env["res.partner"].browse(partner_id) self.assertTrue(partner.is_blacklisted) reason_xid = "mass_mailing_custom_unsubscribe.reason_not_interested" unsubscriptions = self.env["mail.unsubscription"].search( [ ("action", "=", "blacklist_add"), ("mass_mailing_id", "=", self.mailing.id), ("email", "=", self.email), ("unsubscriber_id", "=", "res.partner,%d" % partner_id), ("details", "=", False), ("reason_id", "=", self.env.ref(reason_xid).id), ] ) self.assertEqual(1, len(unsubscriptions))
40.559211
6,165
1,464
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import SavepointCase from .. import exceptions class UnsubscriptionCase(SavepointCase): def test_details_required(self): """Cannot create unsubscription without details when required.""" with self.assertRaises(exceptions.DetailsRequiredError): self.env["mail.unsubscription"].create( { "email": "[email protected]", "mass_mailing_id": self.env.ref("mass_mailing.mass_mail_1").id, "unsubscriber_id": "res.partner,%d" % self.env.ref("base.res_partner_2").id, "reason_id": self.env.ref( "mass_mailing_custom_unsubscribe.reason_other" ).id, } ) def test_reason_required(self): """Cannot create unsubscription without reason when required.""" with self.assertRaises(exceptions.ReasonRequiredError): self.env["mail.unsubscription"].create( { "email": "[email protected]", "mass_mailing_id": self.env.ref("mass_mailing.mass_mail_1").id, "unsubscriber_id": "res.partner,%d" % self.env.ref("base.res_partner_2").id, } )
41.828571
1,464
525
py
PYTHON
15.0
# Copyright 2016 Pedro M. Baeza <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MailMassMailing(models.Model): _inherit = "mailing.list" not_cross_unsubscriptable = fields.Boolean( string="Not cross unsubscriptable", help="If you mark this field, this list won't be shown when " "unsubscribing from other mailing list, in the section: " "'Is there any other mailing list you want to leave?'", )
35
525
1,495
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class MailBlackList(models.Model): _inherit = "mail.blacklist" def _add(self, email): mailing_id = self.env.context.get("mailing_id") res_id = self.env.context.get("unsubscription_res_id") if mailing_id and res_id: mailing = self.env["mailing.mailing"].browse(mailing_id) model_name = mailing.mailing_model_real self.env["mail.unsubscription"].create( { "email": email, "mass_mailing_id": mailing_id, "unsubscriber_id": "%s,%d" % (model_name, res_id), "action": "blacklist_add", } ) return super()._add(email) def _remove(self, email): mailing_id = self.env.context.get("mailing_id") res_id = self.env.context.get("unsubscription_res_id") if mailing_id and res_id: mailing = self.env["mailing.mailing"].browse(mailing_id) model_name = mailing.mailing_model_real self.env["mail.unsubscription"].create( { "email": email, "mass_mailing_id": mailing_id, "unsubscriber_id": "%s,%d" % (model_name, res_id), "action": "blacklist_rm", } ) return super()._remove(email)
37.375
1,495
3,811
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from .. import exceptions class MailUnsubscription(models.Model): _name = "mail.unsubscription" _description = "Mail unsubscription" _inherit = "mail.thread" _mail_post_access = "read" _rec_name = "date" _order = "date DESC" date = fields.Datetime(default=lambda self: self._default_date(), required=True) email = fields.Char(required=True) action = fields.Selection( selection=[ ("subscription", "Subscription"), ("unsubscription", "Unsubscription"), ("blacklist_add", "Blacklisting"), ("blacklist_rm", "De-blacklisting"), ], required=True, default="unsubscription", help="What did the (un)subscriber choose to do.", ) mass_mailing_id = fields.Many2one( "mailing.mailing", "Mass mailing", required=True, help="Mass mailing from which he was unsubscribed.", ) unsubscriber_id = fields.Reference( lambda self: self._selection_unsubscriber_id(), "(Un)subscriber", help="Who was subscribed or unsubscribed.", ) mailing_list_ids = fields.Many2many( comodel_name="mailing.list", string="Mailing lists", help="(Un)subscribed mass mailing lists, if any.", ) reason_id = fields.Many2one( "mail.unsubscription.reason", "Reason", ondelete="restrict", help="Why the unsubscription was made.", ) details = fields.Text(help="More details on why the unsubscription was made.") details_required = fields.Boolean(related="reason_id.details_required") metadata = fields.Text( readonly=True, help="HTTP request metadata used when creating this record." ) @api.model def _default_date(self): return fields.Datetime.now() @api.model def _selection_unsubscriber_id(self): """Models that can be linked to a ``mailing.mailing``.""" models = self.env["ir.model"].search( [("is_mailing_enabled", "=", True), ("model", "!=", "mailing.list")] ) return [(model.model, model.name) for model in models] @api.constrains("action", "reason_id") def _check_reason_needed(self): """Ensure reason is given for unsubscriptions.""" for one in self: unsubscription_states = {"unsubscription", "blacklist_add"} if one.action in unsubscription_states and not one.reason_id: raise exceptions.ReasonRequiredError( _("Please indicate why are you unsubscribing.") ) @api.constrains("details", "reason_id") def _check_details_needed(self): """Ensure details are given if required.""" for one in self: if not one.details and one.details_required: raise exceptions.DetailsRequiredError( _("Please provide details on why you are unsubscribing.") ) @api.model def create(self, vals): # No reasons for subscriptions if vals.get("action") in {"subscription", "blacklist_rm"}: vals = dict(vals, reason_id=False, details=False) return super().create(vals) class MailUnsubscriptionReason(models.Model): _name = "mail.unsubscription.reason" _description = "Mail unsubscription reason" _order = "sequence, name" name = fields.Char(index=True, translate=True, required=True) details_required = fields.Boolean( help="Check to ask for more details when this reason is selected." ) sequence = fields.Integer(index=True, help="Position of the reason in the list.")
35.95283
3,811
3,321
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <[email protected]> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from itertools import groupby from odoo import models, tools from odoo.tools.safe_eval import safe_eval class MailMassMailing(models.Model): _inherit = "mailing.mailing" def update_opt_out(self, email, list_ids, value): """Save unsubscription reason when opting out from mailing.""" self.ensure_one() action = "unsubscription" if value else "subscription" subscription_model = self.env["mailing.contact.subscription"] opt_out_records = subscription_model.search( [ ("contact_id.email", "=ilike", email), ("list_id", "in", list_ids), ("opt_out", "!=", value), ] ) model_name = "mailing.contact" for contact, subscriptions in groupby(opt_out_records, lambda r: r.contact_id): mailing_list_ids = [r.list_id.id for r in subscriptions] # reason_id and details are expected from the context self.env["mail.unsubscription"].create( { "email": email, "mass_mailing_id": self.id, "unsubscriber_id": "%s,%d" % (model_name, contact.id), "mailing_list_ids": [(6, False, mailing_list_ids)], "action": action, } ) return super().update_opt_out(email, list_ids, value) def update_opt_out_other(self, email, res_ids, value): """Method for changing unsubscription for models with opt_out field.""" model = self.env[self.mailing_model_real].with_context(active_test=False) action = "unsubscription" if value else "subscription" if "opt_out" in model._fields: email_fname = "email_from" if "email" in model._fields: email_fname = "email" records = model.search( [("id", "in", res_ids), (email_fname, "ilike", email)] ) records.write({"opt_out": value}) for res_id in res_ids: self.env["mail.unsubscription"].create( { "email": email, "mass_mailing_id": self.id, "unsubscriber_id": "%s,%d" % (self.mailing_model_real, res_id), "action": action, } ) def _get_opt_out_list(self): """Handle models with opt_out field for excluding them.""" self.ensure_one() model = self.env[self.mailing_model_real].with_context(active_test=False) if self.mailing_model_real != "mailing.contact" and "opt_out" in model._fields: email_fname = "email_from" if "email" in model._fields: email_fname = "email" domain = safe_eval(self.mailing_domain) domain = [("opt_out", "=", True)] + domain recs = self.env[self.mailing_model_real].search(domain) normalized_email = (tools.email_split(c[email_fname]) for c in recs) return {e[0].lower() for e in normalized_email if e} return super()._get_opt_out_list()
43.697368
3,321
6,038
py
PYTHON
15.0
# Copyright 2015 Antiun Ingeniería S.L. (http://www.antiun.com) # Copyright 2016 Jairo Llopis <[email protected]> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo.http import request, route from odoo.addons.mass_mailing.controllers.main import MassMailController _logger = logging.getLogger(__name__) class CustomUnsubscribe(MassMailController): def reason_form(self, mailing_id, email, res_id, reasons, token): """Get the unsubscription reason form. :param mailing.mailing mailing: Mailing where the unsubscription is being processed. :param str email: Email to be unsubscribed. :param int res_id: ID of the unsubscriber. :param str token: Security token for unsubscriptions. """ return request.render( "mass_mailing_custom_unsubscribe.reason_form", { "email": email, "mailing_id": mailing_id, "reasons": reasons, "res_id": res_id, "token": token, }, ) @route() def mailing(self, mailing_id, email=None, res_id=None, token="", **post): """Ask/save unsubscription reason.""" _logger.debug( "Called `mailing()` with: %r", (mailing_id, email, res_id, token, post) ) reasons = request.env["mail.unsubscription.reason"].search([]) if not res_id: res_id = "0" res_id = res_id and int(res_id) try: # Check if we already have a reason for unsubscription reason_id = int(post["reason_id"]) except (KeyError, ValueError): # No reasons? Ask for them return self.reason_form(mailing_id, email, res_id, reasons, token) else: # Unsubscribe, saving reason and details by context details = post.get("details", False) self._add_extra_context(mailing_id, res_id, reason_id, details) mailing_obj = request.env["mailing.mailing"] mass_mailing = mailing_obj.sudo().browse(mailing_id) model = mass_mailing.mailing_model_real if "opt_out" in request.env[model]._fields and model != "mailing.contact": mass_mailing.update_opt_out_other(email, [res_id], True) result = request.render( "mass_mailing.page_unsubscribed", { "email": email, "mailing_id": mailing_id, "res_id": res_id, "show_blacklist_button": request.env["ir.config_parameter"] .sudo() .get_param("mass_mailing.show_blacklist_buttons"), }, ) result.qcontext.update({"reasons": reasons}) else: # You could get a DetailsRequiredError here, but only if HTML5 # validation fails, which should not happen in modern browsers result = super().mailing(mailing_id, email, res_id, token=token, **post) if model == "mailing.contact": # update list_ids taking into account # not_cross_unsubscriptable field result.qcontext.update( { "reasons": reasons, "list_ids": result.qcontext["list_ids"].filtered( lambda m_list: not m_list.not_cross_unsubscriptable or m_list in mass_mailing.contact_list_ids ), } ) return result @route() def unsubscribe( self, mailing_id, opt_in_ids, opt_out_ids, email, res_id, token, reason_id=None, details=None, ): """Store unsubscription reasons when unsubscribing from RPC.""" # Update request context self._add_extra_context(mailing_id, res_id, reason_id, details) _logger.debug( "Called `unsubscribe()` with: %r", ( mailing_id, opt_in_ids, opt_out_ids, email, res_id, token, reason_id, details, ), ) return super().unsubscribe( mailing_id, opt_in_ids, opt_out_ids, email, res_id, token ) @route() def blacklist_add( self, mailing_id, res_id, email, token, reason_id=None, details=None ): self._add_extra_context(mailing_id, res_id, reason_id, details) return super().blacklist_add(mailing_id, res_id, email, token) @route() def blacklist_remove( self, mailing_id, res_id, email, token, reason_id=None, details=None ): self._add_extra_context(mailing_id, res_id, reason_id, details) return super().blacklist_remove(mailing_id, res_id, email, token) def _add_extra_context(self, mailing_id, res_id, reason_id, details): environ = request.httprequest.headers.environ # Add mailing_id and res_id to request.context to be used in the # redefinition of _add and _remove methods of the mail.blacklist class extra_context = { "default_metadata": "\n".join( "{}: {}".format(val, environ.get(val)) for val in ("REMOTE_ADDR", "HTTP_USER_AGENT", "HTTP_ACCEPT_LANGUAGE") ), "mailing_id": mailing_id, "unsubscription_res_id": int(res_id), } if reason_id: extra_context["default_reason_id"] = int(reason_id) if details: extra_context["default_details"] = details request.context = dict(request.context, **extra_context)
37.968553
6,037
537
py
PYTHON
15.0
# Copyright (C) 2014 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail - Send Email Copy", "summary": "Send to you a copy of each mail sent by Odoo", "version": "15.0.1.0.0", "category": "Social Network", "author": "GRAP," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "license": "AGPL-3", "depends": ["mail"], "installable": True, }
38.357143
537
738
py
PYTHON
15.0
# Copyright (C) 2014 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from email.utils import COMMASPACE from odoo import api, models class IrMailServer(models.Model): _inherit = "ir.mail_server" @api.model def send_email(self, message, *args, **kwargs): do_not_send_copy = self.env.context.get("do_not_send_copy", False) if not do_not_send_copy: if message["Bcc"]: message["Bcc"] = message["Bcc"].join(COMMASPACE, message["From"]) else: message["Bcc"] = message["From"] return super().send_email(message, *args, **kwargs)
35.142857
738
557
py
PYTHON
15.0
# Copyright 2016-2022 LasLabs Inc. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Mail Outbound Static", "summary": "Allows you to configure the from header for a mail server.", "version": "15.0.1.0.1", "category": "Discuss", "website": "https://github.com/OCA/social", "author": "brain-tec AG, LasLabs, Adhoc SA, Odoo Community Association (OCA)", "license": "LGPL-3", "application": False, "installable": True, "depends": ["base"], "data": ["views/ir_mail_server_view.xml"], }
34.8125
557
14,477
py
PYTHON
15.0
# Copyright 2017 LasLabs Inc. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import logging import os from email import message_from_string import odoo.tools as tools from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase from odoo.addons.base.tests.common import MockSmtplibCase _logger = logging.getLogger(__name__) class TestIrMailServer(TransactionCase, MockSmtplibCase): @classmethod def setUpClass(cls): super().setUpClass() cls.email_from = "[email protected]" cls.email_from_another = "[email protected]" cls.IrMailServer = cls.env["ir.mail_server"] cls.parameter_model = cls.env["ir.config_parameter"] cls._delete_mail_servers() cls.IrMailServer.create( { "name": "localhost", "smtp_host": "localhost", "smtp_from": cls.email_from, } ) message_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), "test.msg" ) with open(message_file, "r") as fh: cls.message = message_from_string(fh.read()) @classmethod def _delete_mail_servers(cls): """Delete all available mail servers""" all_mail_servers = cls.IrMailServer.search([]) if all_mail_servers: all_mail_servers.unlink() def _init_mail_server_domain_whilelist_based(self): self._delete_mail_servers() self.assertFalse(self.IrMailServer.search([])) self.mail_server_domainone = self.IrMailServer.create( { "name": "sandbox domainone", "smtp_host": "localhost", "smtp_from": "[email protected]", "domain_whitelist": "domainone.com", } ) self.mail_server_domaintwo = self.IrMailServer.create( { "name": "sandbox domaintwo", "smtp_host": "localhost", "smtp_from": "[email protected]", "domain_whitelist": "domaintwo.com", } ) self.mail_server_domainthree = self.IrMailServer.create( { "name": "sandbox domainthree", "smtp_host": "localhost", "smtp_from": "[email protected]", "domain_whitelist": "domainthree.com,domainmulti.com", } ) def _skip_test(self, reason): _logger.warning(reason) self.skipTest(reason) def _send_mail( self, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_ssl_certificate=None, smtp_ssl_private_key=None, smtp_debug=False, smtp_session=None, ): smtp = smtp_session if not smtp: smtp = self.IrMailServer.connect( smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption, smtp_from=message["From"], ssl_certificate=smtp_ssl_certificate, ssl_private_key=smtp_ssl_private_key, smtp_debug=smtp_debug, mail_server_id=mail_server_id, ) send_from, send_to, message_string = self.IrMailServer._prepare_email_message( message, smtp ) self.IrMailServer.send_email(message) return message_string def test_send_email_injects_from_no_canonical(self): """It should inject the FROM header correctly when no canonical name.""" self.message.replace_header("From", "[email protected]") # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], self.email_from) def test_send_email_injects_from_with_canonical(self): """It should inject the FROM header correctly with a canonical name. Note that there is an extra `<` in the canonical name to test for proper handling in the split. """ user = "Test < User" self.message.replace_header("From", "%s <[email protected]>" % user) bounce_parameter = self.parameter_model.search( [("key", "=", "mail.bounce.alias")] ) if bounce_parameter: # Remove mail.bounce.alias to test Return-Path bounce_parameter.unlink() # Also check passing mail_server_id mail_server_id = ( self.IrMailServer.sudo().search([], order="sequence", limit=1)[0].id ) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message, mail_server_id=mail_server_id) self.assertEqual(message["From"], '"{}" <{}>'.format(user, self.email_from)) self.assertEqual( message["Return-Path"], '"{}" <{}>'.format(user, self.email_from) ) def test_01_from_outgoing_server_domainone(self): self._init_mail_server_domain_whilelist_based() domain = "domainone.com" email_from = "Mitchell Admin <admin@%s>" % domain expected_mail_server = self.mail_server_domainone self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], email_from) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertEqual( used_mail_server, expected_mail_server, "It using %s but we expect to use %s" % (used_mail_server.name, expected_mail_server.name), ) def test_02_from_outgoing_server_domaintwo(self): self._init_mail_server_domain_whilelist_based() domain = "domaintwo.com" email_from = "Mitchell Admin <admin@%s>" % domain expected_mail_server = self.mail_server_domaintwo self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], email_from) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertEqual( used_mail_server, expected_mail_server, "It using %s but we expect to use %s" % (used_mail_server.name, expected_mail_server.name), ) def test_03_from_outgoing_server_another(self): self._init_mail_server_domain_whilelist_based() domain = "example.com" email_from = "Mitchell Admin <admin@%s>" % domain expected_mail_server = self.mail_server_domainone self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual( message["From"], "Mitchell Admin <%s>" % expected_mail_server.smtp_from ) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertEqual( used_mail_server, expected_mail_server, "It using %s but we expect to use %s" % (used_mail_server.name, expected_mail_server.name), ) def test_04_from_outgoing_server_none_use_config(self): self._init_mail_server_domain_whilelist_based() domain = "example.com" email_from = "Mitchell Admin <admin@%s>" % domain self._delete_mail_servers() self.assertFalse(self.IrMailServer.search([])) # Find config values config_smtp_from = tools.config.get("smtp_from") config_smtp_domain_whitelist = tools.config.get("smtp_domain_whitelist") if not config_smtp_from or not config_smtp_domain_whitelist: self._skip_test( "Cannot test transactions because there is not either smtp_from" " or smtp_domain_whitelist." ) self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], "Mitchell Admin <%s>" % config_smtp_from) used_mail_server = self.IrMailServer._get_mail_sever("example.com") used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertFalse( used_mail_server, "using this mail server %s" % (used_mail_server.name) ) def test_05_from_outgoing_server_none_same_domain(self): self._init_mail_server_domain_whilelist_based() # Find config values config_smtp_from = tools.config.get("smtp_from") config_smtp_domain_whitelist = domain = tools.config.get( "smtp_domain_whitelist" ) if not config_smtp_from or not config_smtp_domain_whitelist: self._skip_test( "Cannot test transactions because there is not either smtp_from" " or smtp_domain_whitelist." ) email_from = "Mitchell Admin <admin@%s>" % domain self._delete_mail_servers() self.assertFalse(self.IrMailServer.search([])) self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], email_from) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertFalse(used_mail_server) def test_06_from_outgoing_server_no_name_from(self): self._init_mail_server_domain_whilelist_based() domain = "example.com" email_from = "test@%s" % domain expected_mail_server = self.mail_server_domainone self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], expected_mail_server.smtp_from) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertEqual( used_mail_server, expected_mail_server, "It using %s but we expect to use %s" % (used_mail_server.name, expected_mail_server.name), ) def test_07_from_outgoing_server_multidomain_1(self): self._init_mail_server_domain_whilelist_based() domain = "domainthree.com" email_from = "Mitchell Admin <admin@%s>" % domain expected_mail_server = self.mail_server_domainthree self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], email_from) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertEqual( used_mail_server, expected_mail_server, "It using %s but we expect to use %s" % (used_mail_server.name, expected_mail_server.name), ) def test_08_from_outgoing_server_multidomain_3(self): self._init_mail_server_domain_whilelist_based() domain = "domainmulti.com" email_from = "test@%s" % domain expected_mail_server = self.mail_server_domainthree self.message.replace_header("From", email_from) # A mail server is configured for the email with self.mock_smtplib_connection(): message = self._send_mail(self.message) self.assertEqual(message["From"], email_from) used_mail_server = self.IrMailServer._get_mail_sever(domain) used_mail_server = self.IrMailServer.browse(used_mail_server) self.assertEqual( used_mail_server, expected_mail_server, "It using %s but we expect to use %s" % (used_mail_server.name, expected_mail_server.name), ) def test_09_not_valid_domain_whitelist(self): self._init_mail_server_domain_whilelist_based() mail_server = self.mail_server_domainone mail_server.domain_whitelist = "example.com" error_msg = ( "%s is not a valid domain. Please define a list of valid" " domains separated by comma" ) with self.assertRaisesRegex(ValidationError, error_msg % "asdasd"): mail_server.domain_whitelist = "asdasd" with self.assertRaisesRegex(ValidationError, error_msg % "asdasd"): mail_server.domain_whitelist = "example.com, asdasd" with self.assertRaisesRegex(ValidationError, error_msg % "invalid"): mail_server.domain_whitelist = "example.com; invalid" with self.assertRaisesRegex(ValidationError, error_msg % ";"): mail_server.domain_whitelist = ";" with self.assertRaisesRegex(ValidationError, error_msg % "."): mail_server.domain_whitelist = "hola.com,." def test_10_not_valid_smtp_from(self): self._init_mail_server_domain_whilelist_based() mail_server = self.mail_server_domainone error_msg = "Not a valid Email From" with self.assertRaisesRegex(ValidationError, error_msg): mail_server.smtp_from = "asdasd" with self.assertRaisesRegex(ValidationError, error_msg): mail_server.smtp_from = "example.com" with self.assertRaisesRegex(ValidationError, error_msg): mail_server.smtp_from = "." mail_server.smtp_from = "[email protected]"
39.233062
14,477
6,017
py
PYTHON
15.0
# Copyright 2017 LasLabs Inc. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import re from email.utils import formataddr, parseaddr from odoo import _, api, fields, models, tools from odoo.exceptions import ValidationError class IrMailServer(models.Model): _inherit = "ir.mail_server" smtp_from = fields.Char( string="Email From", help="Set this in order to email from a specific address." " If the original message's 'From' does not match with the domain" " whitelist then it is replaced with this value. If does match with the" " domain whitelist then the original message's 'From' will not change", ) domain_whitelist = fields.Char( help="Allowed Domains list separated by commas. If there is not given" " SMTP server it will let us to search the proper mail server to be" " used to sent the messages where the message 'From' email domain" " match with the domain whitelist." ) @api.constrains("domain_whitelist") def check_valid_domain_whitelist(self): if self.domain_whitelist: domains = list(self.domain_whitelist.split(",")) for domain in domains: if not self._is_valid_domain(domain): raise ValidationError( _( "%s is not a valid domain. Please define a list of" " valid domains separated by comma" ) % (domain) ) @api.constrains("smtp_from") def check_valid_smtp_from(self): if self.smtp_from: match = re.match( r"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\." r"[a-z]{2,4})$", self.smtp_from, ) if match is None: raise ValidationError(_("Not a valid Email From")) def _is_valid_domain(self, domain_name): domain_regex = ( r"(([\da-zA-Z])([_\w-]{,62})\.){,127}(([\da-zA-Z])" r"[_\w-]{,61})?([\da-zA-Z]\.((xn\-\-[a-zA-Z\d]+)|([a-zA-Z\d]{2,})))" ) domain_regex = "{}$".format(domain_regex) valid_domain_name_regex = re.compile(domain_regex, re.IGNORECASE) domain_name = domain_name.lower().strip() return True if re.match(valid_domain_name_regex, domain_name) else False @api.model def _get_domain_whitelist(self, domain_whitelist_string): res = domain_whitelist_string.split(",") if domain_whitelist_string else [] res = [item.strip() for item in res] return res def _prepare_email_message(self, message, smtp_session): smtp_from, smtp_to_list, message = super()._prepare_email_message( message, smtp_session ) name_from = self._context.get("name_from") email_from = self._context.get("email_from") email_domain = self._context.get("email_domain") mail_server = self.browse(self._context.get("mail_server_id")) domain_whitelist = mail_server.domain_whitelist or tools.config.get( "smtp_domain_whitelist" ) domain_whitelist = self._get_domain_whitelist(domain_whitelist) # Replace the From only if needed if mail_server.smtp_from and ( not domain_whitelist or email_domain not in domain_whitelist ): email_from = formataddr((name_from, mail_server.smtp_from)) message.replace_header("From", email_from) smtp_from = email_from if not self._get_default_bounce_address(): # then, bounce handling is disabled and we want # Return-Path = From if "Return-Path" in message: message.replace_header("Return-Path", email_from) else: message.add_header("Return-Path", email_from) return smtp_from, smtp_to_list, message @api.model def send_email( self, message, mail_server_id=None, smtp_server=None, *args, **kwargs ): # Get email_from and name_from if message["From"].count("<") > 1: split_from = message["From"].rsplit(" <", 1) name_from = split_from[0] email_from = split_from[-1].replace(">", "") else: name_from, email_from = parseaddr(message["From"]) email_domain = email_from.split("@")[1] # Replicate logic from core to get mail server # Get proper mail server to use if not smtp_server and not mail_server_id: mail_server_id = self._get_mail_sever(email_domain) self = self.with_context( name_from=name_from, email_from=email_from, email_domain=email_domain, mail_server_id=mail_server_id, ) return super(IrMailServer, self).send_email( message, mail_server_id, smtp_server, *args, **kwargs ) @tools.ormcache("email_domain") def _get_mail_sever(self, email_domain): """return the mail server id that match with the domain_whitelist If not match then return the default mail server id available one""" mail_server_id = None for item in self.sudo().search( [("domain_whitelist", "!=", False)], order="sequence" ): domain_whitelist = self._get_domain_whitelist(item.domain_whitelist) if email_domain in domain_whitelist: mail_server_id = item.id break if not mail_server_id: mail_server_id = self.sudo().search([], order="sequence", limit=1).id return mail_server_id @api.model def create(self, values): self.clear_caches() return super().create(values) def write(self, values): self.clear_caches() return super().write(values) def unlink(self): self.clear_caches() return super().unlink()
39.847682
6,017
675
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Document Page Reference", "summary": """ Include references on document pages""", "version": "15.0.1.1.0", "license": "AGPL-3", "author": "Creu Blanca,Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "depends": ["document_page", "web_editor"], "data": [ "views/document_page.xml", "views/report_document_page.xml", ], "assets": { "web.assets_backend": [ "document_page_reference/static/src/js/**/*", ], }, "maintainers": ["etobella"], }
29.347826
675
2,217
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestDocumentReference(TransactionCase): def setUp(self): super().setUp() self.page_obj = self.env["document.page"] self.history_obj = self.env["document.page.history"] self.page1 = self.page_obj.create( {"name": "Test Page 1", "content": "${r2}", "reference": "R1"} ) self.page2 = self.page_obj.create( {"name": "Test Page 1", "content": "${r1}", "reference": "r2"} ) def test_constrains_01(self): with self.assertRaises(ValidationError): self.page2.write({"reference": self.page1.reference}) def test_constrains_02(self): with self.assertRaises(ValidationError): self.page2.write({"reference": self.page2.reference + "-02"}) def test_no_contrains(self): self.page1.write({"reference": False}) self.page2.write({"reference": False}) self.assertEqual(self.page1.reference, self.page2.reference) def test_check_raw(self): self.assertEqual(self.page2.display_name, self.page1.get_raw_content()) def test_check_reference(self): self.assertRegex(self.page1.content_parsed, ".*%s.*" % self.page2.display_name) def test_no_reference(self): self.page2.reference = "r3" self.assertRegex(self.page1.content_parsed, ".*r2.*") def test_auto_reference(self): """Test if reference is proposed when saving a page without one.""" self.assertEqual(self.page1.reference, "R1") new_page = self.page_obj.create( {"name": "Test Page with no rEfErenCe", "content": "some content"} ) self.assertEqual(new_page.reference, "test_page_with_no_reference") new_page_duplicated_name = self.page_obj.create( { "name": "test page with no reference", "content": "this should have an empty reference " "because reference must be unique", } ) self.assertFalse(new_page_duplicated_name.reference)
38.894737
2,217
4,910
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import _, api, fields, models, tools from odoo.exceptions import ValidationError from odoo.tools.misc import html_escape from odoo.addons.http_routing.models.ir_http import slugify _logger = logging.getLogger(__name__) try: import re from jinja2 import Undefined from jinja2.lexer import name_re as old_name_re from jinja2.sandbox import SandboxedEnvironment name_re = re.compile("^%s$" % old_name_re.pattern) class Context(SandboxedEnvironment.context_class): def resolve(self, key): res = super().resolve(key) if not isinstance(res, Undefined): return res return self.parent["ref"](key) class Environment(SandboxedEnvironment): context_class = Context mako_template_env = Environment( block_start_string="<%", block_end_string="%>", variable_start_string="${", variable_end_string="}", comment_start_string="<%doc>", comment_end_string="</%doc>", line_statement_prefix="%", line_comment_prefix="##", trim_blocks=True, # do not output newline after blocks autoescape=False, ) except Exception: _logger.error("Jinja2 is not available") class DocumentPage(models.Model): _inherit = "document.page" reference = fields.Char( help="Used to find the document, it can contain letters, numbers and _" ) content_parsed = fields.Html(compute="_compute_content_parsed") def get_formview_action(self, access_uid=None): res = super().get_formview_action(access_uid) view_id = self.env.ref("document_page.view_wiki_form").id res["views"] = [(view_id, "form")] return res @api.depends("history_head") def _compute_content_parsed(self): for record in self: content = record.get_content() if content == "<p>" and self.content != "<p>": _logger.error( "Template from page with id = %s cannot be processed correctly" % self.id ) content = self.content record.content_parsed = content @api.constrains("reference") def _check_reference(self): for record in self: if not record.reference: continue record._validate_reference(record=record) @api.model def _validate_reference(self, record=None, reference=None): if not reference: reference = self.reference if not name_re.match(reference): raise ValidationError(_("Reference is not valid")) uniq_domain = [("reference", "=", reference)] if record: uniq_domain += [("id", "!=", record.id)] if self.search(uniq_domain): raise ValidationError(_("Reference must be unique")) def _get_document(self, code): # Hook created in order to add check on other models document = self.search([("reference", "=", code)]) if document: return document else: return self.env[self._name] def get_reference(self, code): element = self._get_document(code) if self.env.context.get("raw_reference", False): return html_escape(element.display_name) text = """<a href="#" class="oe_direct_line" data-oe-model="%s" data-oe-id="%s" name="%s">%s</a> """ if not element: text = "<i>%s</i>" % text res = text % ( element._name, element and element.id or "", code, html_escape(element.display_name or code), ) return res def _get_template_variables(self): return {"ref": self.get_reference} def get_content(self): try: content = self.content mako_env = mako_template_env template = mako_env.from_string(tools.ustr(content)) return template.render(self._get_template_variables()) except Exception: _logger.error( "Template from page with id = %s cannot be processed" % self.id ) return self.content def get_raw_content(self): return self.with_context(raw_reference=True).get_content() @api.model def create(self, vals): if not vals.get("reference"): # Propose a default reference reference = slugify(vals.get("name")).replace("-", "_") try: self._validate_reference(reference=reference) vals["reference"] = reference except ValidationError: # pylint: disable=W7938 # Do not fill reference. pass return super(DocumentPage, self).create(vals)
32.733333
4,910
796
py
PYTHON
15.0
# Copyright 2018 Ivan Todorovich (<[email protected]>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging _logger = logging.getLogger(__name__) def post_init_hook(cr, registry): # pragma: no cover # Set all pre-existing pages history to approved _logger.info("Setting history to approved.") cr.execute( """ UPDATE document_page_history SET state='approved', approved_uid=create_uid, approved_date=create_date WHERE state IS NULL OR state = 'draft' """ ) def uninstall_hook(cr, registry): # pragma: no cover # Remove unapproved pages _logger.info("Deleting unapproved Change Requests.") cr.execute("DELETE FROM document_page_history WHERE state != 'approved'")
31.84
796
862
py
PYTHON
15.0
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Document Page Approval", "version": "15.0.1.1.0", "author": "Savoir-faire Linux, Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "license": "AGPL-3", "category": "Knowledge Management", "depends": ["document_page", "mail"], "data": [ "data/email_template.xml", "views/document_page_approval.xml", "security/document_page_security.xml", "security/ir.model.access.csv", ], "images": [ "images/category.png", "images/page_history_list.png", "images/page_history.png", ], "post_init_hook": "post_init_hook", "uninstall_hook": "uninstall_hook", "installable": True, }
33.153846
862
4,901
py
PYTHON
15.0
from odoo.tests import common class TestDocumentPageApproval(common.TransactionCase): def setUp(self): super().setUp() self.page_obj = self.env["document.page"] self.history_obj = self.env["document.page.history"] # demo self.category1 = self.env.ref("document_page.demo_category1") self.page1 = self.env.ref("document_page.demo_page1") self.approver_gid = self.env.ref( "document_page_approval.group_document_approver_user" ) self.env.ref("base.user_root").write({"groups_id": [(4, self.approver_gid.id)]}) # demo_approval self.category2 = self.page_obj.create( { "name": "This category requires approval", "type": "category", "approval_required": True, "approver_gid": self.approver_gid.id, } ) self.page2 = self.page_obj.create( { "name": "This page requires approval", "parent_id": self.category2.id, "content": "This content will require approval", } ) def test_approval_required(self): page = self.page2 self.assertTrue(page.is_approval_required) self.assertTrue(page.has_changes_pending_approval) self.assertEqual(len(page.history_ids), 0) def test_change_request_approve(self): page = self.page2 chreq = self.history_obj.search( [("page_id", "=", page.id), ("state", "!=", "approved")] )[0] # It should automatically be in 'to approve' state self.assertEqual(chreq.state, "to approve") # Needed to compute calculated fields page.refresh() self.assertNotEqual(chreq.content, page.content) # who_am_i self.assertTrue(chreq.am_i_owner) self.assertTrue(chreq.am_i_approver) # approve chreq.action_approve() self.assertEqual(chreq.state, "approved") self.assertEqual(chreq.content, page.content) # new changes should create change requests page.write({"content": "New content"}) # Needed to compute calculated fields page.refresh() self.assertNotEqual(page.content, "New content") chreq = self.history_obj.search( [("page_id", "=", page.id), ("state", "!=", "approved")] )[0] chreq.action_approve() self.assertEqual(page.content, "New content") def test_change_request_auto_approve(self): page = self.page1 self.assertFalse(page.is_approval_required) page.write({"content": "New content"}) self.assertEqual(page.content, "New content") def test_change_request_from_scratch(self): page = self.page2 # aprove everything self.history_obj.search( [("page_id", "=", page.id), ("state", "!=", "approved")] ).action_approve() # new change request from scrath chreq = self.history_obj.create( { "page_id": page.id, "summary": "Changed something", "content": "New content", } ) self.assertEqual(chreq.state, "draft") self.assertNotEqual(page.content, chreq.content) self.assertNotEqual(page.approved_date, chreq.approved_date) self.assertNotEqual(page.approved_uid, chreq.approved_uid) chreq.action_to_approve() self.assertEqual(chreq.state, "to approve") self.assertNotEqual(page.content, chreq.content) self.assertNotEqual(page.approved_date, chreq.approved_date) self.assertNotEqual(page.approved_uid, chreq.approved_uid) chreq.action_cancel() self.assertEqual(chreq.state, "cancelled") self.assertNotEqual(page.content, chreq.content) self.assertNotEqual(page.approved_date, chreq.approved_date) self.assertNotEqual(page.approved_uid, chreq.approved_uid) chreq.action_draft() self.assertEqual(chreq.state, "draft") self.assertNotEqual(page.content, chreq.content) self.assertNotEqual(page.approved_date, chreq.approved_date) self.assertNotEqual(page.approved_uid, chreq.approved_uid) chreq.action_approve() self.assertEqual(chreq.state, "approved") self.assertEqual(page.content, chreq.content) self.assertEqual(page.approved_date, chreq.approved_date) self.assertEqual(page.approved_uid, chreq.approved_uid) def test_get_approvers_guids(self): """Get approver guids.""" page = self.page2 self.assertTrue(len(page.approver_group_ids) > 0) def test_get_page_url(self): """Test if page url exist.""" pages = self.env["document.page.history"].search([]) page = pages[0] self.assertIsNotNone(page.page_url)
36.849624
4,901
5,080
py
PYTHON
15.0
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from ast import literal_eval from odoo import api, fields, models class DocumentPage(models.Model): """Useful to know the state of a document.""" _inherit = "document.page" history_ids = fields.One2many(domain=[("state", "=", "approved")]) approved_date = fields.Datetime( "Approved Date", related="history_head.approved_date", store=True, index=True, readonly=True, ) approved_uid = fields.Many2one( "res.users", "Approved by", related="history_head.approved_uid", store=True, index=True, readonly=True, ) approval_required = fields.Boolean( "Require approval", help="Require approval for changes on this page or its child pages.", ) approver_gid = fields.Many2one( "res.groups", "Approver group", help="Users must also belong to the Approvers group", ) is_approval_required = fields.Boolean( "Approval required", help="If true, changes of this page require approval", compute="_compute_is_approval_required", recursive=True, ) am_i_approver = fields.Boolean(compute="_compute_am_i_approver") approver_group_ids = fields.Many2many( "res.groups", string="Approver groups", help="Groups that can approve changes to this document", compute="_compute_approver_group_ids", recursive=True, ) # pylint: disable=W8113 has_changes_pending_approval = fields.Boolean( compute="_compute_has_changes_pending_approval", string="Has changes pending approval", ) user_has_drafts = fields.Boolean( compute="_compute_user_has_drafts", string="User has drafts?" ) def _valid_field_parameter(self, field, name): return name == "order" or super()._valid_field_parameter(field, name) @api.depends("approval_required", "parent_id.is_approval_required") def _compute_is_approval_required(self): """Check if the document required approval based on his parents.""" for page in self: res = page.approval_required if page.parent_id: res = res or page.parent_id.is_approval_required page.is_approval_required = res @api.depends("approver_gid", "parent_id.approver_group_ids") def _compute_approver_group_ids(self): """Compute the approver groups based on his parents.""" for page in self: res = page.approver_gid if page.parent_id: res = res | page.parent_id.approver_group_ids page.approver_group_ids = res @api.depends("is_approval_required", "approver_group_ids") def _compute_am_i_approver(self): """Check if the current user can approve changes to this page.""" for rec in self: rec.am_i_approver = rec.can_user_approve_this_page(self.env.user) def can_user_approve_this_page(self, user): """Check if a user can approve this page.""" self.ensure_one() # if it's not required, anyone can approve if not self.is_approval_required: return True # if user belongs to 'Knowledge / Manager', he can approve anything if user.has_group("document_page.group_document_manager"): return True # to approve, user must have approver rights if not user.has_group("document_page_approval.group_document_approver_user"): return False # if there aren't any approver_groups_defined, user can approve if not self.approver_group_ids: return True # to approve, user must belong to any of the approver groups return len(user.groups_id & self.approver_group_ids) > 0 def _compute_has_changes_pending_approval(self): history = self.env["document.page.history"] for rec in self: changes = history.search_count( [("page_id", "=", rec.id), ("state", "=", "to approve")] ) rec.has_changes_pending_approval = changes > 0 def _compute_user_has_drafts(self): history = self.env["document.page.history"] for rec in self: changes = history.search_count( [("page_id", "=", rec.id), ("state", "=", "draft")] ) rec.user_has_drafts = changes > 0 def _create_history(self, vals): res = super()._create_history(vals) res.action_to_approve() return res def action_changes_pending_approval(self): self.ensure_one() action = self.env.ref("document_page_approval.action_change_requests") action = action.sudo().read()[0] context = literal_eval(action["context"]) context["search_default_page_id"] = self.id context["default_page_id"] = self.id action["context"] = context return action
34.794521
5,080
6,391
py
PYTHON
15.0
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models from odoo.exceptions import UserError from odoo.tools.translate import _ class DocumentPageHistory(models.Model): """Useful to manage edition's workflow on a document.""" _name = "document.page.history" _inherit = ["document.page.history", "mail.thread"] _order = "approved_date DESC, id DESC" state = fields.Selection( [ ("draft", "Draft"), ("to approve", "Pending Approval"), ("approved", "Approved"), ("cancelled", "Cancelled"), ], "Status", default="draft", readonly=True, ) approved_date = fields.Datetime() approved_uid = fields.Many2one("res.users", "Approved by") is_approval_required = fields.Boolean( related="page_id.is_approval_required", string="Approval required" ) am_i_owner = fields.Boolean(compute="_compute_am_i_owner") am_i_approver = fields.Boolean(related="page_id.am_i_approver", related_sudo=False) page_url = fields.Text(compute="_compute_page_url", string="URL") def action_draft(self): """Set a change request as draft""" for rec in self: if not rec.state == "cancelled": raise UserError(_("You need to cancel it before reopening.")) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _( "You are not authorized to do this.\r\n" "Only owners or approvers can reopen Change Requests." ) ) rec.write({"state": "draft"}) def action_to_approve(self): """Set a change request as to approve""" template = self.env.ref( "document_page_approval.email_template_new_draft_need_approval" ) approver_gid = self.env.ref( "document_page_approval.group_document_approver_user" ) for rec in self: if rec.state != "draft": raise UserError(_("Can't approve pages in '%s' state.") % rec.state) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _( "You are not authorized to do this.\r\n" "Only owners or approvers can request approval." ) ) # request approval if rec.is_approval_required: rec.write({"state": "to approve"}) guids = [g.id for g in rec.page_id.approver_group_ids] users = self.env["res.users"].search( [("groups_id", "in", guids), ("groups_id", "in", approver_gid.id)] ) rec.message_subscribe([u.id for u in users]) rec.message_post_with_template(template.id) else: # auto-approve if approval is not required rec.action_approve() def action_approve(self): """Set a change request as approved.""" for rec in self: if rec.state not in ["draft", "to approve"]: raise UserError(_("Can't approve page in '%s' state.") % rec.state) if not rec.am_i_approver: raise UserError( _( "You are not authorized to do this.\r\n" "Only approvers with these groups can approve this: " ) % ", ".join( [g.display_name for g in rec.page_id.approver_group_ids] ) ) # Update state rec.write( { "state": "approved", "approved_date": fields.datetime.now(), "approved_uid": self.env.uid, } ) # Trigger computed field update rec.page_id._compute_history_head() # Notify state change rec.message_post( subtype_xmlid="mail.mt_comment", body=_("Change request has been approved by %s.") % (self.env.user.name), ) # Notify followers a new version is available rec.page_id.message_post( subtype_xmlid="mail.mt_comment", body=_("New version of the document %s approved.") % (rec.page_id.name), ) def action_cancel(self): """Set a change request as cancelled.""" self.write({"state": "cancelled"}) for rec in self: rec.message_post( subtype_xmlid="mail.mt_comment", body=_("Change request <b>%(name)s</b> has been cancelled by %(user)s.") % ({"name": rec.display_name, "user": self.env.user.name}), ) def action_cancel_and_draft(self): """Set a change request as draft, cancelling it first""" self.action_cancel() self.action_draft() def _compute_am_i_owner(self): """Check if current user is the owner""" for rec in self: rec.am_i_owner = rec.create_uid == self.env.user def _compute_page_url(self): """Compute the page url.""" for page in self: base_url = ( self.env["ir.config_parameter"] .sudo() .get_param("web.base.url", default="http://localhost:8069") ) page.page_url = ( "{}/web#db={}&id={}&" "model=document.page.history" ).format(base_url, self.env.cr.dbname, page.id) def _compute_diff(self): """Shows a diff between this version and the previous version""" history = self.env["document.page.history"] for rec in self: domain = [("page_id", "=", rec.page_id.id), ("state", "=", "approved")] if rec.approved_date: domain.append(("approved_date", "<", rec.approved_date)) prev = history.search(domain, limit=1, order="approved_date DESC") if prev: rec.diff = self._get_diff(prev.id, rec.id) else: rec.diff = self._get_diff(False, rec.id)
38.041667
6,391
1,152
py
PYTHON
15.0
# Copyright 2014 Therp BV (<http://therp.nl>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Preview attachments", "version": "15.0.1.0.0", "author": "Therp BV," "Onestein," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "license": "AGPL-3", "summary": "Preview attachments supported by Viewer.js", "category": "Knowledge Management", "depends": ["web", "mail"], "data": [], "qweb": [], "assets": { "web._assets_primary_variables": [], "web.assets_backend": [ "attachment_preview/static/src/js/models/attachment_card/attachment_card.esm.js", "attachment_preview/static/src/js/attachmentPreviewWidget.esm.js", "attachment_preview/static/src/js/components/chatter/chatter.esm.js", "attachment_preview/static/src/scss/attachment_preview.scss", ], "web.assets_frontend": [], "web.assets_tests": [], "web.qunit_suite_tests": [], "web.assets_qweb": ["attachment_preview/static/src/xml/attachment_preview.xml"], }, "installable": True, }
39.724138
1,152
1,387
py
PYTHON
15.0
# Copyright 2018 Onestein # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import base64 from odoo.tests.common import TransactionCase class TestAttachmentPreview(TransactionCase): def test_get_extension(self): attachment = self.env["ir.attachment"].create( { "datas": base64.b64encode(b"from this, to that."), "name": "doc.txt", } ) attachment2 = self.env["ir.attachment"].create( { "datas": base64.b64encode(b"Png"), "name": "image.png", } ) res = self.env["ir.attachment"].get_attachment_extension(attachment.id) self.assertEqual(res, "txt") res = self.env["ir.attachment"].get_attachment_extension( [attachment.id, attachment2.id] ) self.assertEqual(res[attachment.id], "txt") self.assertEqual(res[attachment2.id], "png") res2 = self.env["ir.attachment"].get_binary_extension( "ir.attachment", attachment.id, "datas" ) self.assertTrue(res2) module = ( self.env["ir.module.module"].search([]).filtered(lambda m: m.icon_image)[0] ) res3 = self.env["ir.attachment"].get_binary_extension( "ir.module.module", module.id, "icon_image" ) self.assertTrue(res3)
32.255814
1,387
2,982
py
PYTHON
15.0
# Copyright 2014 Therp BV (<http://therp.nl>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import collections import logging import mimetypes import os.path from odoo import api, models _logger = logging.getLogger(__name__) class IrAttachment(models.Model): _inherit = "ir.attachment" @api.model def get_binary_extension(self, model, ids, binary_field, filename_field=None): result = {} ids_to_browse = ids if isinstance(ids, collections.abc.Iterable) else [ids] # First pass: load fields in bin_size mode to avoid loading big files # unnecessarily. if filename_field: for this in ( self.env[model].with_context(bin_size=True).browse(ids_to_browse) ): result[this.id] = False extension = "" if this[filename_field]: filename, extension = os.path.splitext(this[filename_field]) if this[binary_field] and extension: result[this.id] = extension _logger.debug( "Got extension %s from filename %s", extension, this[filename_field], ) # Second pass for all attachments which have to be loaded fully # to get the extension from the content ids_to_browse = [_id for _id in ids_to_browse if _id not in result] for this in self.env[model].with_context(bin_size=True).browse(ids_to_browse): result[this.id] = False try: import magic if model == self._name and binary_field == "datas" and this.store_fname: mimetype = magic.from_file( this._full_path(this.store_fname), mime=True ) # _logger.debug( # "Magic determined mimetype %s from file %s", # mimetype, # this.store_fname # ) else: mimetype = magic.from_buffer(this[binary_field], mime=True) _logger.debug("Magic determined mimetype %s from buffer", mimetype) except ImportError: (mimetype, encoding) = mimetypes.guess_type( "data:;base64," + this[binary_field].decode("utf-8"), strict=False ) # _logger.debug("Mimetypes guessed type %s from buffer", mimetype) extension = mimetypes.guess_extension(mimetype.split(";")[0], strict=False) result[this.id] = extension for _id in result: result[_id] = (result[_id] or "").lstrip(".").lower() return result if isinstance(ids, collections.abc.Iterable) else result[ids] @api.model def get_attachment_extension(self, ids): return self.get_binary_extension(self._name, ids, "datas", "name")
41.416667
2,982
658
py
PYTHON
15.0
# Copyright 2015-2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Document Page Tag", "version": "15.0.1.2.0", "author": "Therp BV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "license": "AGPL-3", "category": "Knowledge Management", "summary": "Allows you to assign tags or keywords to pages and search for " "them afterwards", "depends": ["document_page"], "data": [ "views/document_page_tag.xml", "views/document_page.xml", "security/ir.model.access.csv", ], "installable": True, }
34.631579
658
867
py
PYTHON
15.0
# Copyright 2015-2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from psycopg2 import IntegrityError from odoo.tests.common import TransactionCase from odoo.tools.misc import mute_logger class TestDocumentPageTag(TransactionCase): def test_document_page_tag(self): testtag = self.env["document.page.tag"].name_create("test") # check we're charitable on duplicates self.assertEqual( testtag, self.env["document.page.tag"].name_create("Test"), ) # check we can't create nonunique tags with self.assertRaises(IntegrityError): with mute_logger("odoo.sql_db"): testtag2 = self.env["document.page.tag"].create({"name": "test2"}) testtag2.write({"name": "test"}) testtag2.flush()
39.409091
867
801
py
PYTHON
15.0
# Copyright 2015-2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class DocumentPageTag(models.Model): _name = "document.page.tag" _description = "A keyword for document pages" name = fields.Char(required=True, translate=True) color = fields.Integer(string="Color Index") active = fields.Boolean(default=True) _sql_constraints = [ ("unique_name", "unique(name)", "Tags must be unique"), ] @api.model def create(self, vals): """Be nice when trying to create duplicates""" existing = self.search([("name", "=ilike", vals["name"])], limit=1) if existing: return existing return super(DocumentPageTag, self).create(vals)
33.375
801
291
py
PYTHON
15.0
# Copyright 2015-2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class DocumentPage(models.Model): _inherit = "document.page" tag_ids = fields.Many2many("document.page.tag", string="Keywords")
32.333333
291
592
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) - Lois Rilo # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Document Page Project", "summary": "This module links document pages to projects", "version": "15.0.1.0.0", "category": "Project", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "license": "AGPL-3", "depends": ["project", "document_page"], "data": ["views/document_page_views.xml", "views/project_project_views.xml"], "installable": True, }
39.466667
592
1,072
py
PYTHON
15.0
# Copyright (C) 2021 TREVI Software # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common class TestProjectProject(common.TransactionCase): @classmethod def setUpClass(cls): super(TestProjectProject, cls).setUpClass() cls.Page = cls.env["document.page"] cls.Project = cls.env["project.project"] cls.default_page = cls.Page.create({"name": "My page"}) def test_page_count(self): proj = self.Project.create({"name": "Proj A"}) self.assertEqual( proj.document_page_count, 0, "Initial page count should be zero" ) self.default_page.project_id = proj proj._compute_document_page_count() self.assertEqual( proj.document_page_count, 1, "After attaching project to document the page count should be one", ) self.assertIn( self.default_page, proj.document_page_ids, "The page should be in the list of document pages for project", )
29.777778
1,072
314
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class DocumentPage(models.Model): _inherit = "document.page" project_id = fields.Many2one(string="Project", comodel_name="project.project")
31.4
314
577
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProjectProject(models.Model): _inherit = "project.project" document_page_ids = fields.One2many( string="Wiki", comodel_name="document.page", inverse_name="project_id" ) document_page_count = fields.Integer(compute="_compute_document_page_count") def _compute_document_page_count(self): for rec in self: rec.document_page_count = len(rec.document_page_ids)
33.941176
577
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
913
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-knowledge", description="Meta package for oca-knowledge Odoo addons", version=version, install_requires=[ 'odoo-addon-attachment_preview>=15.0dev,<15.1dev', 'odoo-addon-document_page>=15.0dev,<15.1dev', 'odoo-addon-document_page_approval>=15.0dev,<15.1dev', 'odoo-addon-document_page_group>=15.0dev,<15.1dev', 'odoo-addon-document_page_project>=15.0dev,<15.1dev', 'odoo-addon-document_page_reference>=15.0dev,<15.1dev', 'odoo-addon-document_page_tag>=15.0dev,<15.1dev', 'odoo-addon-document_url>=15.0dev,<15.1dev', 'odoo-addon-knowledge>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
35.115385
913
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100