Reemplaza el matching fragil por nombre de archivo con FK reales: - 3 FK nullables (CASCADE) en Document; resolucion central en save() por document_type + nombre (core.document_links), cubre toda ruta de creacion incluida la ingesta del microservicio; set explicito en create_vu_record. - Comando backfill_document_links (idempotente, dry-run) para filas existentes. - Lectura/descarga/borrado SIEMPRE por la FK (id); el nombre solo ESTABLECE la FK en save()/backfill. Prefetch con select_related(pedimento, fuente) sin N+1. - Migraciones: 0004 (campos), 0005 (indices CONCURRENTLY IF NOT EXISTS, idempotente via SeparateDatabaseAndState), 0006 (ANALYZE document para estadisticas del planner). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
132 lines
5.8 KiB
Python
132 lines
5.8 KiB
Python
from django.db import models
|
|
import uuid
|
|
|
|
from api.organization.models import UsoAlmacenamiento
|
|
|
|
# Create your models here.
|
|
|
|
class Document(models.Model):
|
|
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
|
|
|
organizacion = models.ForeignKey('organization.Organizacion', on_delete=models.CASCADE, related_name='documents')
|
|
pedimento = models.ForeignKey('customs.Pedimento', on_delete=models.CASCADE, related_name='documents')
|
|
archivo = models.FileField(upload_to='documents/', max_length=400)
|
|
document_type = models.ForeignKey('DocumentType', on_delete=models.CASCADE, related_name='documents', blank=True, null=True)
|
|
extension = models.CharField(max_length=60, blank=True, null=True)
|
|
size = models.PositiveIntegerField()
|
|
fuente = models.ForeignKey('Fuente', on_delete=models.CASCADE, related_name='documents', blank=True, null=True)
|
|
vu = models.BooleanField(default=False)
|
|
|
|
# Sub-entidad a la que pertenece el documento (None para docs nativos del
|
|
# pedimento: PC, remesa, subidas generales). Se puebla por nombre de archivo
|
|
# en save() vía core.document_links. db_index=False: el índice lo crea una
|
|
# migración aparte con CREATE INDEX CONCURRENTLY (tabla grande en prod).
|
|
partida = models.ForeignKey('customs.Partida', on_delete=models.CASCADE, related_name='documents', blank=True, null=True, db_index=False)
|
|
cove = models.ForeignKey('customs.Cove', on_delete=models.CASCADE, related_name='documents', blank=True, null=True, db_index=False)
|
|
edocument = models.ForeignKey('customs.EDocument', on_delete=models.CASCADE, related_name='documents', blank=True, null=True, db_index=False)
|
|
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
updated_at = models.DateTimeField(auto_now=True)
|
|
|
|
def save(self, *args, **kwargs):
|
|
is_new = self._state.adding
|
|
|
|
# Calcular automáticamente el campo vu
|
|
if self.document_type_id:
|
|
# rango de IDs que indican documentos VU
|
|
self.vu = 13 <= self.document_type_id <= 26
|
|
else:
|
|
self.vu = False
|
|
|
|
# Ligar la sub-entidad (partida/cove/edocument) por nombre de archivo si
|
|
# aún no está ligada. Cubre todas las rutas de creación —incluida la
|
|
# ingesta del microservicio— sin tocar cada call site. Se ejecuta también
|
|
# en update porque el patrón común es create() sin archivo y luego
|
|
# asignar archivo + save(). Fuente única: core.document_links.
|
|
if self.archivo and not (self.partida_id or self.cove_id or self.edocument_id):
|
|
from core.document_links import resolver_fk
|
|
campo, inst = resolver_fk(self)
|
|
if inst is not None:
|
|
setattr(self, campo, inst)
|
|
|
|
# Usar get_or_create en lugar de get para manejar el caso cuando no existe
|
|
uso_almacenamiento, created = UsoAlmacenamiento.objects.get_or_create(
|
|
organizacion=self.organizacion,
|
|
defaults={'espacio_utilizado': 0}
|
|
)
|
|
|
|
almacenamiento_licencia_bytes = self.organizacion.licencia.almacenamiento * 1024 ** 3
|
|
|
|
if is_new:
|
|
if uso_almacenamiento.espacio_utilizado + self.size > almacenamiento_licencia_bytes:
|
|
raise ValueError("La organización no tiene suficiente espacio de almacenamiento disponible")
|
|
|
|
super().save(*args, **kwargs)
|
|
|
|
uso_almacenamiento.espacio_utilizado += self.size
|
|
uso_almacenamiento.save()
|
|
else:
|
|
old_file = Document.objects.get(pk=self.pk)
|
|
if old_file.size != self.size:
|
|
diferencia = self.size - old_file.size
|
|
if uso_almacenamiento.espacio_utilizado + diferencia > almacenamiento_licencia_bytes:
|
|
raise ValueError("No hay suficiente espacio para la actualización")
|
|
|
|
uso_almacenamiento.espacio_utilizado += diferencia
|
|
uso_almacenamiento.save()
|
|
|
|
super().save(*args, **kwargs)
|
|
def delete(self, *args, **kwargs):
|
|
# Usar get_or_create aquí también por si acaso
|
|
uso_almacenamiento, created = UsoAlmacenamiento.objects.get_or_create(
|
|
organizacion=self.organizacion,
|
|
defaults={'espacio_utilizado': 0}
|
|
)
|
|
|
|
uso_almacenamiento.espacio_utilizado -= self.size
|
|
uso_almacenamiento.save()
|
|
|
|
super().delete(*args, **kwargs)
|
|
|
|
def __str__(self):
|
|
return f"{self.archivo.name}"
|
|
|
|
class Meta:
|
|
verbose_name = "Document"
|
|
verbose_name_plural = "Documents"
|
|
db_table = 'document'
|
|
ordering = ['created_at']
|
|
# Índices de las FK de sub-entidad. Se crean con CREATE INDEX CONCURRENTLY
|
|
# en una migración aparte (atomic=False); por eso los campos usan
|
|
# db_index=False y el índice se declara aquí.
|
|
indexes = [
|
|
models.Index(fields=['partida'], name='document_partida_idx'),
|
|
models.Index(fields=['cove'], name='document_cove_idx'),
|
|
models.Index(fields=['edocument'], name='document_edocument_idx'),
|
|
]
|
|
|
|
class DocumentType(models.Model):
|
|
nombre = models.CharField(max_length=100, unique=True)
|
|
descripcion = models.TextField(blank=True, null=True)
|
|
|
|
def __str__(self):
|
|
return self.nombre
|
|
|
|
class Meta:
|
|
verbose_name = "Tipo de Documento"
|
|
verbose_name_plural = "Tipos de Documento"
|
|
db_table = 'document_type'
|
|
ordering = ['nombre']
|
|
|
|
class Fuente(models.Model):
|
|
nombre = models.CharField(max_length=100, unique=True)
|
|
descripcion = models.TextField(blank=True, null=True)
|
|
|
|
def __str__(self):
|
|
return self.nombre
|
|
|
|
class Meta:
|
|
verbose_name = "Fuente"
|
|
verbose_name_plural = "Fuentes"
|
|
db_table = 'fuente'
|
|
ordering = ['nombre'] |