Skip to content

Instantly share code, notes, and snippets.

@justinmassiot
Last active December 13, 2023 17:14
Show Gist options
  • Save justinmassiot/9c97ff4994a2e6891236cf7b4918ead9 to your computer and use it in GitHub Desktop.
Save justinmassiot/9c97ff4994a2e6891236cf7b4918ead9 to your computer and use it in GitHub Desktop.
target_list_id = 6 # "[FR] Newsletter"
for rec in records: # contacts on which to work (user selection)
existing_contacts = env['mailing.contact'].search([('email', '=', rec.email)])
if len(existing_contacts) > 1:
raise UserError(rec.name + " has multiple entries in the mailing contacts.\nPlease clean things up and get back here after having removed the duplicates.")
elif len(existing_contacts) == 1:
for recipient in existing_contacts: # should get exactly 1 recipient
list_ids = [listid.id for listid in recipient.list_ids] # get all the lists the user is subscribed to
if target_list_id in list_ids:
raise UserError(rec.name + " (" + rec.email + ") already receives the newsletter.")
else:
recipient.write({ # add the newsletter to the list of subscription
'list_ids': [ tuple(list_ids) + (target_list_id,) ]
})
elif rec.email:
env['mailing.contact'].create({
'name': rec.name,
'email': rec.email,
'company_name': rec.parent_id.name,
'country_id': rec.country_id.id,
'list_ids': [(target_list_id)]
})
# else: no email address provided -> discard!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment