Skip to content
Snippets Groups Projects
document_attachment.py 2.16 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'

    name = fields.Char(
        string='Description',
        size=256,
        required=True
    )

    model = fields.Char(
        string='Model',
        size=128,
        required=True,
    )


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

    _name = 'document_attachment'

    type_id = fields.Many2one(
        comodel_name='document_attachment.type',
        string='Type',
        required=True,
    )

    file_id = fields.Many2one(
        comodel_name='ir.attachment',
        string='File',
        ondelete='cascade',
        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:
            raise exceptions.Warning(
                _("You must send the 'res_model' through the m2m context")
            )

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

        vals['name'] = vals['datas_fname']

        vals['res_model'] = context['res_model']
        vals['res_id'] = context['res_id']

        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']

        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)
        attachments.unlink()

        return ret