| 1 |
import base64 |
| 2 |
import pytz |
| 3 |
from datetime import date, datetime |
| 4 |
|
| 5 |
from odoo import _, api, exceptions, fields, models, modules |
| 6 |
|
| 7 |
from .card_template import TEMPLATE_DIMENSIONS |
| 8 |
|
| 9 |
|
| 10 |
class CardCampaign(models.Model): |
| 11 |
_name = 'card.campaign' |
| 12 |
_description = 'Marketing Card Campaign' |
| 13 |
_inherit = ['mail.activity.mixin', 'mail.render.mixin', 'mail.thread'] |
| 14 |
_order = 'id DESC' |
| 15 |
_unrestricted_rendering = True |
| 16 |
|
| 17 |
def _default_card_template_id(self): |
| 18 |
return self.env['card.template'].search([], limit=1) |
| 19 |
|
| 20 |
def _get_model_selection(self): |
| 21 |
"""Hardcoded list of models, checked against actually-present models.""" |
| 22 |
allowed_models = ['res.partner', 'event.track', 'event.booth', 'event.registration'] |
| 23 |
models = self.env['ir.model'].sudo().search_fetch([('model', 'in', allowed_models)], ['model', 'name']) |
| 24 |
return [(model.model, model.name) for model in models] |
| 25 |
|
| 26 |
name = fields.Char(required=True) |
| 27 |
active = fields.Boolean(default=True) |
| 28 |
body_html = fields.Html(related='card_template_id.body', render_engine="qweb", readonly=False) |
| 29 |
|
| 30 |
card_count = fields.Integer(compute='_compute_card_stats') |
| 31 |
card_click_count = fields.Integer(compute='_compute_card_stats') |
| 32 |
card_share_count = fields.Integer(compute='_compute_card_stats') |
| 33 |
|
| 34 |
mailing_ids = fields.One2many('mailing.mailing', 'card_campaign_id') |
| 35 |
mailing_count = fields.Integer(compute='_compute_mailing_count') |
| 36 |
|
| 37 |
card_ids = fields.One2many('card.card', inverse_name='campaign_id') |
| 38 |
card_template_id = fields.Many2one('card.template', string="Design", default=_default_card_template_id, required=True) |
| 39 |
image_preview = fields.Image(compute='_compute_image_preview', compute_sudo=False, readonly=True, store=True, attachment=False) |
| 40 |
link_tracker_id = fields.Many2one('link.tracker', ondelete="restrict") |
| 41 |
res_model = fields.Selection( |
| 42 |
string="Model Name", compute='_compute_res_model', selection='_get_model_selection', |
| 43 |
precompute=True, readonly=True, required=True, store=True, |
| 44 |
) |
| 45 |
|
| 46 |
post_suggestion = fields.Text(help="Description below the card and default text when sharing on X") |
| 47 |
preview_record_ref = fields.Reference(string="Preview On", selection="_get_model_selection", required=True) |
| 48 |
tag_ids = fields.Many2many('card.campaign.tag', string='Tags') |
| 49 |
target_url = fields.Char(string='Post Link') |
| 50 |
target_url_click_count = fields.Integer(related="link_tracker_id.count") |
| 51 |
|
| 52 |
user_id = fields.Many2one('res.users', string='Responsible', default=lambda self: self.env.user, domain="[('share', '=', False)]") |
| 53 |
|
| 54 |
reward_message = fields.Html(string='Thank You Message') |
| 55 |
reward_target_url = fields.Char(string='Reward Link') |
| 56 |
request_title = fields.Char('Request', default=lambda self: _('Help us share the news')) |
| 57 |
request_description = fields.Text('Request Description') |
| 58 |
|
| 59 |
# Static Content fields |
| 60 |
content_background = fields.Image('Background') |
| 61 |
content_button = fields.Char('Button') |
| 62 |
|
| 63 |
# Dynamic Content fields |
| 64 |
content_header = fields.Char('Header') |
| 65 |
content_header_dyn = fields.Boolean('Is Dynamic Header') |
| 66 |
content_header_path = fields.Char('Header Path') |
| 67 |
content_header_color = fields.Char('Header Color') |
| 68 |
|
| 69 |
content_sub_header = fields.Char('Sub-Header') |
| 70 |
content_sub_header_dyn = fields.Boolean('Is Dynamic Sub-Header') |
| 71 |
content_sub_header_path = fields.Char('Sub-Header Path') |
| 72 |
content_sub_header_color = fields.Char('Sub Header Color') |
| 73 |
|
| 74 |
content_section = fields.Char('Section') |
| 75 |
content_section_dyn = fields.Boolean('Is Dynamic Section') |
| 76 |
content_section_path = fields.Char('Section Path') |
| 77 |
|
| 78 |
content_sub_section1 = fields.Char('Sub-Section 1') |
| 79 |
content_sub_section1_dyn = fields.Boolean('Is Dynamic Sub-Section 1') |
| 80 |
content_sub_section1_path = fields.Char('Sub-Section 1 Path') |
| 81 |
|
| 82 |
content_sub_section2 = fields.Char('Sub-Section 2') |
| 83 |
content_sub_section2_dyn = fields.Boolean('Is Dynamic Sub-Section 2') |
| 84 |
content_sub_section2_path = fields.Char('Sub-Section 2 Path') |
| 85 |
|
| 86 |
# images are always dynamic |
| 87 |
content_image1_path = fields.Char('Dynamic Image 1') |
| 88 |
content_image2_path = fields.Char('Dynamic Image 2') |
| 89 |
|
| 90 |
@api.depends('card_ids') |
| 91 |
def _compute_card_stats(self): |
| 92 |
cards_by_status_count = self.env['card.card']._read_group( |
| 93 |
domain=[('campaign_id', 'in', self.ids)], |
| 94 |
groupby=['campaign_id', 'share_status'], |
| 95 |
aggregates=['__count'], |
| 96 |
order='campaign_id ASC', |
| 97 |
) |
| 98 |
self.update({ |
| 99 |
'card_count': 0, |
| 100 |
'card_click_count': 0, |
| 101 |
'card_share_count': 0, |
| 102 |
}) |
| 103 |
for campaign, status, card_count in cards_by_status_count: |
| 104 |
# shared cards are implicitly visited |
| 105 |
if status == 'shared': |
| 106 |
campaign.card_share_count += card_count |
| 107 |
if status in ('shared', 'visited'): |
| 108 |
campaign.card_click_count += card_count |
| 109 |
campaign.card_count += card_count |
| 110 |
|
| 111 |
@api.model |
| 112 |
def _get_render_fields(self): |
| 113 |
return [ |
| 114 |
'body_html', 'content_background', 'content_image1_path', 'content_image2_path', 'content_button', 'content_header', |
| 115 |
'content_header_dyn', 'content_header_path', 'content_header_color', 'content_sub_header', |
| 116 |
'content_sub_header_dyn', 'content_sub_header_path', 'content_section', 'content_section_dyn', |
| 117 |
'content_section_path', 'content_sub_section1', 'content_sub_section1_dyn', 'content_sub_header_color', |
| 118 |
'content_sub_section1_path', 'content_sub_section2', 'content_sub_section2_dyn', 'content_sub_section2_path', |
| 119 |
'card_template_id', |
| 120 |
] |
| 121 |
|
| 122 |
def _check_access_right_dynamic_template(self): |
| 123 |
""" `_unrestricted_rendering` being True means we trust the value on model |
| 124 |
when rendering. This means once created, rendering is done without restriction. |
| 125 |
But this attribute triggers a check at create / write / translation update that |
| 126 |
current user is an admin or has full edition rights (group_mail_template_editor). |
| 127 |
|
| 128 |
However here a Marketing Card Manager must be able to edit the fields other |
| 129 |
than the rendering fields. The qweb rendered field `body_html` cannot be |
| 130 |
modified by users other than the `base.group_system` users, as |
| 131 |
- it's a related field to `card.template.body`, |
| 132 |
- store=False |
| 133 |
- the model `card.template` can only be altered by `base.group_system` |
| 134 |
|
| 135 |
Hence the security is delegated to the 'card.template' model, hence the |
| 136 |
check done by `_check_access_right_dynamic_template` can be bypassed. |
| 137 |
""" |
| 138 |
return |
| 139 |
|
| 140 |
@api.depends(lambda self: self._get_render_fields() + ['preview_record_ref']) |
| 141 |
def _compute_image_preview(self): |
| 142 |
for campaign in self: |
| 143 |
if campaign.preview_record_ref and campaign.preview_record_ref.exists(): |
| 144 |
image = campaign._get_image_b64(campaign.preview_record_ref) |
| 145 |
else: |
| 146 |
image = False |
| 147 |
campaign.image_preview = image |
| 148 |
|
| 149 |
@api.depends('mailing_ids') |
| 150 |
def _compute_mailing_count(self): |
| 151 |
self.mailing_count = 0 |
| 152 |
mailing_counts = self.env['mailing.mailing']._read_group( |
| 153 |
[('card_campaign_id', 'in', self.ids)], ['card_campaign_id'], ['__count'] |
| 154 |
) |
| 155 |
for campaign, mailing_count in mailing_counts: |
| 156 |
campaign.mailing_count = mailing_count |
| 157 |
|
| 158 |
@api.depends('preview_record_ref') |
| 159 |
def _compute_res_model(self): |
| 160 |
for campaign in self: |
| 161 |
preview_model = campaign.preview_record_ref and campaign.preview_record_ref._name |
| 162 |
campaign.res_model = preview_model or campaign.res_model or 'res.partner' |
| 163 |
|
| 164 |
@api.model_create_multi |
| 165 |
def create(self, vals_list): |
| 166 |
utm_source = self.env.ref('marketing_card.utm_source_marketing_card', raise_if_not_found=False) |
| 167 |
link_trackers = self.env['link.tracker'].sudo().create([ |
| 168 |
{ |
| 169 |
'url': vals.get('target_url') or self.env['card.campaign'].get_base_url(), |
| 170 |
'title': vals['name'], # not having this will trigger a request in the create |
| 171 |
'source_id': utm_source.id if utm_source else None, |
| 172 |
'label': f"marketing_card_campaign_{vals.get('name', '')}_{fields.Datetime.now()}", |
| 173 |
} |
| 174 |
for vals in vals_list |
| 175 |
]) |
| 176 |
return super().create([{ |
| 177 |
**vals, |
| 178 |
'link_tracker_id': link_tracker_id, |
| 179 |
} for vals, link_tracker_id in zip(vals_list, link_trackers.ids)]) |
| 180 |
|
| 181 |
def write(self, vals): |
| 182 |
link_tracker_vals = {} |
| 183 |
if vals.keys() & set(self._get_render_fields()): |
| 184 |
self.env['card.card'].with_context(active_test=False).search([('campaign_id', 'in', self.ids)]).requires_sync = True |
| 185 |
if 'target_url' in vals: |
| 186 |
link_tracker_vals['url'] = vals['target_url'] or self.env['card.campaign'].get_base_url() |
| 187 |
if link_tracker_vals: |
| 188 |
self.link_tracker_id.sudo().write(link_tracker_vals) |
| 189 |
|
| 190 |
# write and detect model changes on actively-used campaigns |
| 191 |
original_models = self.mapped('res_model') |
| 192 |
|
| 193 |
write_res = super().write(vals) |
| 194 |
|
| 195 |
updated_model_campaigns = self.env['card.campaign'].browse([ |
| 196 |
campaign.id for campaign, new_model, old_model |
| 197 |
in zip(self, self.mapped('res_model'), original_models) |
| 198 |
if new_model != old_model |
| 199 |
]) |
| 200 |
for campaign in updated_model_campaigns: |
| 201 |
if campaign.card_count: |
| 202 |
raise exceptions.ValidationError(_( |
| 203 |
"Model of campaign %(campaign)s may not be changed as it already has cards", |
| 204 |
campaign=campaign.display_name, |
| 205 |
)) |
| 206 |
return write_res |
| 207 |
|
| 208 |
def action_view_cards(self): |
| 209 |
self.ensure_one() |
| 210 |
return self.env["ir.actions.actions"]._for_xml_id("marketing_card.cards_card_action") | { |
| 211 |
'context': {}, |
| 212 |
'domain': [('campaign_id', '=', self.id)], |
| 213 |
} |
| 214 |
|
| 215 |
def action_view_cards_clicked(self): |
| 216 |
self.ensure_one() |
| 217 |
return self.env["ir.actions.actions"]._for_xml_id("marketing_card.cards_card_action") | { |
| 218 |
'context': {'search_default_filter_visited': True}, |
| 219 |
'domain': [('campaign_id', '=', self.id)], |
| 220 |
} |
| 221 |
|
| 222 |
def action_view_cards_shared(self): |
| 223 |
self.ensure_one() |
| 224 |
return self.env["ir.actions.actions"]._for_xml_id("marketing_card.cards_card_action") | { |
| 225 |
'context': {'search_default_filter_shared': True}, |
| 226 |
'domain': [('campaign_id', '=', self.id)], |
| 227 |
} |
| 228 |
|
| 229 |
def action_view_mailings(self): |
| 230 |
self.ensure_one() |
| 231 |
return { |
| 232 |
'name': _('%(card_campaign_name)s Mailings', card_campaign_name=self.name), |
| 233 |
'type': 'ir.actions.act_window', |
| 234 |
'res_model': 'mailing.mailing', |
| 235 |
'domain': [('card_campaign_id', '=', self.id)], |
| 236 |
'view_mode': 'list,form', |
| 237 |
'target': 'current', |
| 238 |
} |
| 239 |
|
| 240 |
def action_preview(self): |
| 241 |
self.ensure_one() |
| 242 |
card = self._fetch_or_create_preview_card() |
| 243 |
return {'type': 'ir.actions.act_url', 'url': card._get_path('preview'), 'target': 'new'} |
| 244 |
|
| 245 |
def action_share(self): |
| 246 |
self.ensure_one() |
| 247 |
return { |
| 248 |
'type': 'ir.actions.act_window', |
| 249 |
'name': _('Send Cards'), |
| 250 |
'res_model': 'mailing.mailing', |
| 251 |
'context': { |
| 252 |
'create': False, |
| 253 |
'default_subject': self.name, |
| 254 |
'default_card_campaign_id': self.id, |
| 255 |
'default_mailing_model_id': self.env['ir.model']._get_id(self.res_model), |
| 256 |
'default_body_arch': self._action_share_get_default_body(), |
| 257 |
}, |
| 258 |
'views': [[False, 'form']], |
| 259 |
'target': 'current', |
| 260 |
} |
| 261 |
|
| 262 |
def _fetch_or_create_preview_card(self): |
| 263 |
"""Fetch the card corresponding to the preview record, or create one if none exists. |
| 264 |
|
| 265 |
The image also gets the preview render if it has none. It is also archived to ensure |
| 266 |
it is rerendered later if sent. |
| 267 |
""" |
| 268 |
self.ensure_one() |
| 269 |
card = self.env['card.card'].with_context(active_test=False).search([ |
| 270 |
('campaign_id', '=', self.id), |
| 271 |
('res_id', '=', self.preview_record_ref.id), |
| 272 |
]) |
| 273 |
image = self.image_preview |
| 274 |
if card: |
| 275 |
card.write({ |
| 276 |
'image': image, |
| 277 |
'active': False, |
| 278 |
}) |
| 279 |
else: |
| 280 |
card = self.env['card.card'].create({ |
| 281 |
'campaign_id': self.id, |
| 282 |
'res_id': self.preview_record_ref.id, |
| 283 |
'image': image, |
| 284 |
'active': False, |
| 285 |
}) |
| 286 |
return card |
| 287 |
|
| 288 |
def _action_share_get_default_body(self): |
| 289 |
# try to pick a relevant card if users try to visit during preview/test mailings |
| 290 |
preview_card = self._fetch_or_create_preview_card() if self else self.env['card.card'] |
| 291 |
return f""" |
| 292 |
<div class="o_layout oe_unremovable oe_unmovable o_empty_theme" data-name="Mailing"> |
| 293 |
<style id="design-element"></style> |
| 294 |
<div class="container o_mail_wrapper o_mail_regular oe_unremovable"> |
| 295 |
<div class="row"> |
| 296 |
<div class="col o_mail_no_options o_mail_wrapper_td bg-white oe_structure o_editable theme_selection_done"> |
| 297 |
|
| 298 |
<div class="s_text_block o_mail_snippet_general pt24 pb24" style="padding-left: 15px; padding-right: 15px;" data-snippet="s_text_block" data-name="Text"> |
| 299 |
<div class="container s_allow_columns"> |
| 300 |
<p">{_("Hello everyone")}</p> |
| 301 |
<p>{_("Here's the link to advertise your participation.")} |
| 302 |
<br>{_("Your help with this promotion would be greatly appreciated!")}</p> |
| 303 |
<p>{_("Many thanks")}</p> |
| 304 |
</div> |
| 305 |
</div> |
| 306 |
|
| 307 |
<div class="s_call_to_share_card o_mail_snippet_general" style="padding-top: 10px; padding-bottom: 10px;"> |
| 308 |
<table width="100%" border="0" cellspacing="0" cellpadding="0"> |
| 309 |
<tbody> |
| 310 |
<tr> |
| 311 |
<td align="center"> |
| 312 |
<a href="/cards/{preview_card.id or 0}/preview" style="padding-left: 3px !important; padding-right: 3px !important"> |
| 313 |
<img src="/web/image/card.campaign/{self.id or 0}/image_preview" alt="{_("Card Preview")}" class="img-fluid" style="width: 540px;" |
| 314 |
data-original-src="/web/image/card.campaign/{self.id or 0}/image_preview"/> |
| 315 |
</a> |
| 316 |
</td> |
| 317 |
</tr> |
| 318 |
</tbody> |
| 319 |
</table> |
| 320 |
</div> |
| 321 |
|
| 322 |
</div></div></div></div> |
| 323 |
""" |
| 324 |
|
| 325 |
# ========================================================================== |
| 326 |
# Image generation |
| 327 |
# ========================================================================== |
| 328 |
|
| 329 |
def _get_image_b64(self, record): |
| 330 |
if not self.card_template_id.body: |
| 331 |
return '' |
| 332 |
|
| 333 |
image_bytes = self.env['ir.actions.report']._run_wkhtmltoimage( |
| 334 |
[self._render_field('body_html', record.ids, add_context={'card_campaign': self})[record.id]], |
| 335 |
*TEMPLATE_DIMENSIONS |
| 336 |
)[0] |
| 337 |
|
| 338 |
# None means there was a logged error at image rendering time. |
| 339 |
# Tests also do not render by default, in that case ignore. |
| 340 |
if image_bytes is None and not modules.module.current_test: |
| 341 |
raise exceptions.UserError(_( |
| 342 |
'An error occured while rendering a card for %(record_name)s. ' |
| 343 |
'Try again or check the server logs for more details.', |
| 344 |
record_name=record.display_name |
| 345 |
)) |
| 346 |
return image_bytes and base64.b64encode(image_bytes) |
| 347 |
|
| 348 |
# ========================================================================== |
| 349 |
# Card creation |
| 350 |
# ========================================================================== |
| 351 |
|
| 352 |
def _update_cards(self, domain, auto_commit=False): |
| 353 |
"""Create missing cards and update cards if necessary based for the domain.""" |
| 354 |
self.ensure_one() |
| 355 |
TargetModel = self.env[self.res_model] |
| 356 |
res_ids = TargetModel.search(domain).ids |
| 357 |
cards = self.env['card.card'].with_context(active_test=False).search_fetch([ |
| 358 |
('campaign_id', '=', self.id), |
| 359 |
('res_id', 'in', res_ids), |
| 360 |
], ['res_id', 'requires_sync']) |
| 361 |
# update active and res_model for preview cards |
| 362 |
cards.active = True |
| 363 |
self.env['card.card'].create([ |
| 364 |
{'campaign_id': self.id, 'res_id': res_id} |
| 365 |
for res_id in set(res_ids) - set(cards.mapped('res_id')) |
| 366 |
]) |
| 367 |
|
| 368 |
# render by batch of 100 to avoid losing progress in case of time out |
| 369 |
updated_cards = self.env['card.card'] |
| 370 |
while cards := self.env['card.card'].search_fetch([ |
| 371 |
('requires_sync', '=', True), |
| 372 |
('campaign_id', '=', self.id), |
| 373 |
('res_id', 'in', res_ids), |
| 374 |
], ['res_id'], limit=100): |
| 375 |
# no need to autocommit if it can be done in one batch |
| 376 |
if auto_commit and updated_cards: |
| 377 |
self.env.cr.commit() |
| 378 |
# avoid keeping hundreds of jpegs in memory |
| 379 |
self.env['card.card'].invalidate_model(['image']) |
| 380 |
TargetModelPrefetch = TargetModel.with_prefetch(cards.mapped('res_id')) |
| 381 |
for card in cards.filtered('requires_sync'): |
| 382 |
card.write({ |
| 383 |
'image': self._get_image_b64(TargetModelPrefetch.browse(card.res_id)), |
| 384 |
'requires_sync': False, |
| 385 |
'active': True, |
| 386 |
}) |
| 387 |
cards.flush_recordset() |
| 388 |
updated_cards += cards |
| 389 |
return updated_cards |
| 390 |
|
| 391 |
def _get_url_from_res_id(self, res_id, suffix='preview'): |
| 392 |
card = self.env['card.card'].search([('campaign_id', '=', self.id), ('res_id', '=', res_id)]) |
| 393 |
return card and card._get_path(suffix) or self.target_url |
| 394 |
|
| 395 |
# ========================================================================== |
| 396 |
# Mail render mixin / Render utils |
| 397 |
# ========================================================================== |
| 398 |
|
| 399 |
@api.depends('res_model') |
| 400 |
def _compute_render_model(self): |
| 401 |
""" override for mail.render.mixin """ |
| 402 |
for campaign in self: |
| 403 |
campaign.render_model = campaign.res_model |
| 404 |
|
| 405 |
def _get_card_element_values(self, record): |
| 406 |
"""Helper to get the right value for dynamic fields.""" |
| 407 |
self.ensure_one() |
| 408 |
result = { |
| 409 |
'image1': images[0] if (images := self.content_image1_path and self.content_image1_path in record and record.mapped(self.content_image1_path)) else False, |
| 410 |
'image2': images[0] if (images := self.content_image2_path and self.content_image2_path in record and record.mapped(self.content_image2_path)) else False, |
| 411 |
} |
| 412 |
campaign_text_element_fields = ( |
| 413 |
('header', 'content_header', 'content_header_dyn', 'content_header_path'), |
| 414 |
('sub_header', 'content_sub_header', 'content_sub_header_dyn', 'content_sub_header_path'), |
| 415 |
('section', 'content_section', 'content_section_dyn', 'content_section_path'), |
| 416 |
('sub_section1', 'content_sub_section1', 'content_sub_section1_dyn', 'content_sub_section1_path'), |
| 417 |
('sub_section2', 'content_sub_section2', 'content_sub_section2_dyn', 'content_sub_section2_path'), |
| 418 |
) |
| 419 |
for el, text_field, dyn_field, path_field in campaign_text_element_fields: |
| 420 |
if not self[dyn_field]: |
| 421 |
result[el] = self[text_field] |
| 422 |
elif not (field_path := self[path_field]): |
| 423 |
result[el] = record |
| 424 |
else: |
| 425 |
fnames = field_path.split('.') |
| 426 |
try: |
| 427 |
value = record |
| 428 |
while fnames and (fname := fnames.pop(0)): |
| 429 |
value.fetch([fname]) |
| 430 |
value = value[fname] |
| 431 |
m = record.mapped(field_path) |
| 432 |
result[el] = m and m[0] or False |
| 433 |
except (AttributeError, ValueError): |
| 434 |
# for generic image, or if field incorrect, return name of field |
| 435 |
result[el] = field_path |
| 436 |
# force dates to their relevant timezone as that's what is usually wanted |
| 437 |
if ( |
| 438 |
isinstance(result[el], (date, datetime)) |
| 439 |
and (tz := record._mail_get_timezone()) |
| 440 |
): |
| 441 |
result[el] = pytz.utc.localize(result[el]).astimezone(pytz.timezone(tz)).replace(tzinfo=None) |
| 442 |
return result |