Skip to content
Snippets Groups Projects
document_attachment.py 2.08 KiB
Newer Older
szeka.wong's avatar
szeka.wong committed
from odoo import _, api, exceptions, fields, models


class DocumentAttachmentType(models.Model):
    """Kind of document that can be attached."""

    _name = "document_attachment.type"
szeka.wong's avatar
szeka.wong committed

    name = fields.Char(string="Description", size=256, required=True)
szeka.wong's avatar
szeka.wong committed

    model = fields.Char(string="Model", size=128, required=True)
szeka.wong's avatar
szeka.wong committed


class DocumentAttachment(models.Model):
    """A document that can be attached.
    Inherit[s] from ir.attachment to store documents as attachments.
    """

    _name = "document_attachment"
szeka.wong's avatar
szeka.wong committed

    type_id = fields.Many2one(
        comodel_name="document_attachment.type", string="Type", required=True
szeka.wong's avatar
szeka.wong committed
    )

    file_id = fields.Many2one(
        comodel_name="ir.attachment",
        string="File",
        ondelete="cascade",
szeka.wong's avatar
szeka.wong committed
        required=True,
        delegate=True,
    )

    @api.model
    def create(self, vals):
        """- Fill the "name" from the original filename.
        - Associate the new attachment with the current object.
        """

        context = self._context

        if "res_model" not in context:
szeka.wong's avatar
szeka.wong committed
            raise exceptions.Warning(
                _("You must send the 'res_model' through the m2m context")
            )

        if "res_id" not in context:
szeka.wong's avatar
szeka.wong committed
            raise exceptions.Warning(
                _("You must send the 'res_id' through the m2m context")
            )

        vals["name"] = vals["datas_fname"]
szeka.wong's avatar
szeka.wong committed

        vals["res_model"] = context["res_model"]
        vals["res_id"] = context["res_id"]
szeka.wong's avatar
szeka.wong committed

        return super(DocumentAttachment, self).create(vals)

    @api.multi
    def write(self, vals):
        """Fill the "name" from the original filename."""

        if "datas_fname" in vals:
            vals["name"] = vals["datas_fname"]
szeka.wong's avatar
szeka.wong committed

        return super(DocumentAttachment, self).write(vals)

    @api.multi
    def unlink(self):
        """Delete the attachment associated with records being deleted."""

        attachment_ids = [doc.file_id.id for doc in self]

        ret = super(DocumentAttachment, self).unlink()

        attachments = self.env["ir.attachment"].browse(attachment_ids)
szeka.wong's avatar
szeka.wong committed
        attachments.unlink()

        return ret