Initial commit
This commit is contained in:
95
gestion_pedidos/services/pdf_parser.py
Normal file
95
gestion_pedidos/services/pdf_parser.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
Servicio para procesar PDFs de pedidos de cliente
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
from django.utils import timezone
|
||||
from datetime import datetime
|
||||
from .ocr_service import OCRService
|
||||
from ..models import Cliente, PedidoCliente, ReferenciaPedidoCliente
|
||||
|
||||
|
||||
class PDFPedidoParser:
|
||||
"""Parser para procesar PDFs de pedidos de cliente"""
|
||||
|
||||
def __init__(self):
|
||||
self.ocr_service = OCRService()
|
||||
|
||||
def parse_pdf(self, pdf_path: Path) -> Dict:
|
||||
"""
|
||||
Parsea un PDF de pedido de cliente
|
||||
|
||||
Returns:
|
||||
Dict con los datos extraídos
|
||||
"""
|
||||
return self.ocr_service.process_pdf_pedido_cliente(pdf_path)
|
||||
|
||||
def create_pedido_from_pdf(self, pdf_path: Path) -> PedidoCliente:
|
||||
"""
|
||||
Crea un PedidoCliente y sus referencias desde un PDF
|
||||
|
||||
Returns:
|
||||
PedidoCliente creado
|
||||
"""
|
||||
# Parsear PDF
|
||||
datos = self.parse_pdf(pdf_path)
|
||||
|
||||
# Obtener o crear cliente
|
||||
matricula = datos.get('matricula', '').strip().upper()
|
||||
if not matricula:
|
||||
raise ValueError("No se pudo extraer la matrícula del PDF")
|
||||
|
||||
cliente, _ = Cliente.objects.get_or_create(
|
||||
matricula_vehiculo=matricula,
|
||||
defaults={
|
||||
'nombre': datos.get('nombre_cliente', f'Cliente {matricula}'),
|
||||
}
|
||||
)
|
||||
|
||||
# Parsear fecha de cita
|
||||
fecha_cita = None
|
||||
fecha_cita_str = datos.get('fecha_cita')
|
||||
if fecha_cita_str:
|
||||
try:
|
||||
# Intentar diferentes formatos
|
||||
for fmt in ['%Y-%m-%d %H:%M', '%Y-%m-%d', '%d/%m/%Y %H:%M', '%d/%m/%Y']:
|
||||
try:
|
||||
fecha_cita = datetime.strptime(fecha_cita_str, fmt)
|
||||
fecha_cita = timezone.make_aware(fecha_cita)
|
||||
break
|
||||
except ValueError:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Crear pedido
|
||||
numero_pedido = datos.get('numero_pedido', '').strip()
|
||||
if not numero_pedido:
|
||||
raise ValueError("No se pudo extraer el número de pedido del PDF")
|
||||
|
||||
# Verificar si ya existe
|
||||
if PedidoCliente.objects.filter(numero_pedido=numero_pedido).exists():
|
||||
raise ValueError(f"El pedido {numero_pedido} ya existe")
|
||||
|
||||
pedido = PedidoCliente.objects.create(
|
||||
numero_pedido=numero_pedido,
|
||||
cliente=cliente,
|
||||
fecha_cita=fecha_cita,
|
||||
estado='pendiente_revision',
|
||||
archivo_pdf_path=str(pdf_path),
|
||||
)
|
||||
|
||||
# Crear referencias
|
||||
referencias_data = datos.get('referencias', [])
|
||||
for ref_data in referencias_data:
|
||||
ReferenciaPedidoCliente.objects.create(
|
||||
pedido_cliente=pedido,
|
||||
referencia=ref_data.get('referencia', '').strip(),
|
||||
denominacion=ref_data.get('denominacion', '').strip(),
|
||||
unidades_solicitadas=int(ref_data.get('unidades', 1)),
|
||||
unidades_en_stock=0,
|
||||
)
|
||||
|
||||
return pedido
|
||||
|
||||
Reference in New Issue
Block a user