Hi,
Steps:
Go to Settings → Technical → Automation → Automated Actions.
Create a new one:
Model = CRM Lead
Trigger = On Update
Condition = stage_id == 'X'
Action to do: Execute Python Code.
Code:
# This runs in the context of crm.lead record(s)
for lead in records:
partner = lead.partner_id
if not partner:
continue
# Decide which products to add
product_ids = []
if lead.x_my_checkbox: # your custom field
product_ids = [env.ref('your_module.product_a').id,
env.ref('your_module.product_b').id]
else:
product_ids = [env.ref('your_module.product_a').id]
# Create invoice (draft)
invoice = env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': partner.id,
'invoice_line_ids': [
(0, 0, {
'product_id': pid,
'quantity': 1,
'price_unit': env['product.product'].browse(pid).lst_price,
}) for pid in product_ids
]
})
# Post and send by email
invoice.action_post()
template = env.ref('account.email_template_edi_invoice')
invoice.message_post_with_template(template.id)
Hope it helps.
You have no idea how much time this has saved me. Thank you so very much! I made a few adjustments: I added logic to link to an existing invoice if one already matches (so it won’t create duplicates), built product lines dynamically based on a selection and quantity, added a small discount for extra units, wrapped everything in error handling with chatter feedback, and made the email sending a bit more robust. Works perfectly now!
Thanks again 🙏