<?xml version="1.0" encoding="utf-8" ?>
<odoo>
    <record id="action_create_sepa_mandates" model="ir.actions.server">
        <field name="name">Create SEPA mandates</field>
        <field name="model_id" ref="base.model_res_partner" />
        <field name="binding_model_id" ref="base.model_res_partner" />
        <field name="binding_view_types">list,form</field>
        <field name="state">code</field>
        <field name="code"><![CDATA[
# Bulk-create and validate recurrent SEPA Core mandates for the selected
# partners. Filter the contacts list (e.g. is_client = True), select all,
# then run this action. One mandate per partner; partners that already have
# a draft/valid mandate or no bank account are skipped.
Mandate = env["account.banking.mandate"]
today = datetime.date.today()

created = 0
no_bank = 0
already = 0

for partner in records:
    bank = partner.bank_ids[:1]
    if not bank:
        no_bank += 1
        continue
    if Mandate.search_count([
        ("partner_id", "=", partner.id),
        ("state", "in", ("draft", "valid")),
    ]):
        already += 1
        continue
    mandate = Mandate.create({
        "partner_bank_id": bank.id,
        "format": "sepa",
        "type": "recurrent",
        "scheme": "CORE",
        "signature_date": today,
    })
    mandate.validate()
    created += 1

message = (
    "SEPA mandates created: %s\n"
    "Already had a mandate: %s\n"
    "Skipped (no bank account): %s"
) % (created, already, no_bank)

action = {
    "type": "ir.actions.client",
    "tag": "display_notification",
    "params": {
        "title": "SEPA mandates",
        "message": message,
        "type": "success" if created else "warning",
        "sticky": False,
    },
}
]]></field>
    </record>
</odoo>
