# -*- encoding: utf-8 -*-
import datetime
from decimal import Decimal
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import gettext as _
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator

# Create your models here.
MESES_CHOICES = (
  ('1', 'Enero'),
  ('2', 'Febrero'),
  ('3', 'Marzo'),
  ('4', 'Abril'),
  ('5', 'Mayo'),
  ('6', 'Junio'),
  ('7', 'Julio'),
  ('8', 'Agosto'),
  ('9', 'Septiembre'),
  ('10', 'Octubre'),
  ('11', 'Noviembre'),
  ('12', 'Diciembre'),
)

IVA_CHOICES = (
	('10.5', '10.5%'),
	('21.0', '21%'),
	('27.0', '27%'),
    ('EXENTO', 'EXENTO'),
)

TIPO_FACTURA_CHOICES = (
        ('A', 'A'),
        ('B', 'B'),
        ('C', 'C'),
)

MONEDA_CHOICE = (
        ('D', u'U$S'),
        ('P', u'$ARG'),
        ('CL', u'$CL'),
)

PERTENECE_CHOICES = (
        ('S', 'SERVICIOS'),
        ('V', 'VENTAS'),
)

TIPO_GASTO_CHOICE = (
        ('P', u'Proveedores'),
        ('V', u'Viaticos'),
        ('A', u'A Rendir'),
        ('H', u'Honorarios'),
        ('O', u'Otros'),
)

TIPO_PROVINCIA_CHOICE = (
        ('CB', u'Capital Federal'),
        ('BA', u'Buenos Aires'),
        ('EN', 'Entre Rios'),
        ('CR', 'Corrientes'),
        ('MI', 'Misiones'),
        ('FO', 'Formosa'),
        ('CH', 'Chaco'),
        ('SF', 'Santa Fe'),
        ('CO', 'Cordoba'),
        ('SE', 'Santiago del Estero'),
        ('SA', 'Salta'),
        ('JU', 'Jujuy'),
        ('TU', 'Tucuman'),
        ('CA', 'Catamarca'),
        ('LR', 'La Rioja'),
        ('SJ', 'San Juan'),
        ('SL', 'San Luis'),
        ('LP', 'La Pampa'),
        ('NE', 'Neuquen'),
        ('RN', 'Rio Negro'),
        ('CH', 'Chubut'),
        ('SC', 'Santa Cruz'),
        ('TF', 'Tierra del Fuego'),
)

class ClaseConURL(object):
  def get_absolute_url(self):
    return urlresolvers.reverse('admin:%s_%s_change' %(self._meta.app_label, self._meta.module_name), args=[self.id])

class Proveedor(models.Model):
    cuit = models.CharField('CUIT', max_length=11)
    razonsocial = models.CharField('Razon Social', max_length=50)
    domicilio_fiscal = models.CharField('Domicilio Fiscal', max_length=80, blank=True, null=True)
    provincia = models.CharField('Provincia', max_length=20, choices=TIPO_PROVINCIA_CHOICE, blank=True, null=True)
    nroproveedor = models.CharField('Nro. Proveedor', max_length=7, blank=True, null=True)
    ret_iibb = models.BooleanField('Ret. IIBB', default=False)
    porcentaje_ret = models.DecimalField('Porcentaje', max_digits=5, decimal_places=2, blank=True, null=True)
    nro_iibb = models.CharField('Nro IIBB', max_length=15, blank=True, null=True)

    def __unicode__(self):
	return '%s | %s' % (self.cuit, self.razonsocial)

    class Meta:
        verbose_name = ('Proveedor')
        verbose_name_plural = ('Proveedores')

class CentroCosto(models.Model):
    cuenta = models.CharField('Cuenta', max_length=8)
    subcuenta = models.CharField('Subcuenta', max_length=8, blank=True, null=True)
    sublibrotipo = models.CharField(u'Sublibro/Subtipo', max_length=8, blank=True, null=True)
    observaciones = models.TextField('Observaciones', blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.cuenta,)

    class Meta:
        verbose_name = ('Centro de Costo')
        verbose_name_plural = ('Centro de Costos')

class DetalleFactura(models.Model):
    factura = models.ForeignKey('Factura')
    orden_pago = models.ForeignKey('OrdenPago', blank=True, null=True, editable=False)
    porcentaje_iva = models.CharField('Porcentaje IVA', max_length=15, choices=IVA_CHOICES, blank=True, null=True)
    importe_neto = models.DecimalField('Importe Neto', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    iva = models.DecimalField('IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iva = models.DecimalField('Ret IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iibb = models.DecimalField('Ret IIBB', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iva = models.DecimalField('Percep IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_caba =  models.DecimalField('Percep IIBB CABA', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_bsas =  models.DecimalField('Percep IIBB BSAS', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)

    class Meta:
        verbose_name = ('Detalle Factura')
        verbose_name_plural = ('Detalles Facturas')

    def __unicode__(self):
	    return '%s | %s' % (self.factura, self.orden_pago)

class DetalleFacturaVenta(models.Model):
    factura = models.ForeignKey('FacturaVenta')
    orden_pago = models.ForeignKey('OrdenPagoVenta', blank=True, null=True, editable=False)
    porcentaje_iva = models.CharField('Porcentaje IVA', max_length=15, choices=IVA_CHOICES, blank=True, null=True)
    importe_neto = models.DecimalField('Importe Neto', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    iva = models.DecimalField('IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iva = models.DecimalField('Ret IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iibb = models.DecimalField('Ret IIBB', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iva = models.DecimalField('Percep IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_caba =  models.DecimalField('Percep IIBB CABA', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_bsas =  models.DecimalField('Percep IIBB BSAS', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)

    class Meta:
        verbose_name = ('Detalle Factura Venta')
        verbose_name_plural = ('Detalles Facturas Ventas')

class Factura(models.Model):
    orden_pago = models.ForeignKey('OrdenPago', blank=True, null=True, editable=False)
    nrofactura = models.CharField('Nro. Factura', max_length=25)
    concepto = models.CharField('Concepto', max_length=60, blank=True, null=True)
    importe_neto_total = models.DecimalField('Imp. Neto Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    importe_total = models.DecimalField('Importe Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    tipo_factura = models.CharField('Tipo', max_length=2, choices=TIPO_FACTURA_CHOICES)
    proveedor = models.ForeignKey('Proveedor')
    fecha_factura = models.DateField('Fecha Factura', default=datetime.date.today())
    pendiente = models.BooleanField('Pendiente')# editable=False)

    def __unicode__(self):
        return '%s | %s | %s | $ %s' % ( self.proveedor.cuit, self.fecha_factura, self.nrofactura, self.importe_total)

    class Meta:
        verbose_name = ('Factura')
        verbose_name_plural = ('Facturas')

class DetalleNotaCredito(models.Model):
    notacredito = models.ForeignKey('NotaCredito')
    orden_pago = models.ForeignKey('OrdenPago', blank=True, null=True, editable=False)
    porcentaje_iva = models.CharField('Porcentaje IVA', max_length=15, choices=IVA_CHOICES, blank=True, null=True)
    importe_neto = models.DecimalField('Importe Neto', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    iva = models.DecimalField('IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iva = models.DecimalField('Ret IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iibb = models.DecimalField('Ret IIBB', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iva = models.DecimalField('Percep IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_caba =  models.DecimalField('Percep IIBB CABA', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_bsas =  models.DecimalField('Percep IIBB BSAS', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)

    class Meta:
        verbose_name = ('Detalle Nota Credito')
        verbose_name_plural = ('Detalles Notas Creditos')

class DetalleNotaCreditoVenta(models.Model):
    notacredito = models.ForeignKey('NotaCreditoVenta')
    orden_pago = models.ForeignKey('OrdenPagoVenta', blank=True, null=True, editable=False)
    porcentaje_iva = models.CharField('Porcentaje IVA', max_length=15, choices=IVA_CHOICES, blank=True, null=True)
    importe_neto = models.DecimalField('Importe Neto', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    iva = models.DecimalField('IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iva = models.DecimalField('Ret IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    ret_iibb = models.DecimalField('Ret IIBB', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iva = models.DecimalField('Percep IVA', max_digits=15, decimal_places=2,
    validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_caba =  models.DecimalField('Percep IIBB CABA', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    percep_iibb_bsas =  models.DecimalField('Percep IIBB BSAS', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)

    class Meta:
        verbose_name = ('Detalle Nota Credito')
        verbose_name_plural = ('Detalles Notas Creditos')

class NotaCredito(models.Model):
    orden_pago = models.ForeignKey('OrdenPago', blank=True, null=True, editable=False)
    nronotacredito = models.CharField('Nro. Nota Credito', max_length=25)
    concepto = models.CharField('Concepto', max_length=60, blank=True, null=True)
    importe_neto_total = models.DecimalField('Importe Neto Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    importe_total = models.DecimalField('Importe Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    tipo_nota_credito = models.CharField('Tipo', max_length=2, choices=TIPO_FACTURA_CHOICES)
    proveedor = models.ForeignKey('Proveedor')
    fecha_nota_credito = models.DateField('Fecha Nota Credito', default=datetime.date.today())
    pendiente = models.BooleanField('Pendiente')#, editable=False)

    def __unicode__(self):
        return '%s | %s | %s | $ %s' % ( self.proveedor.cuit, self.fecha_nota_credito, self.nronotacredito, self.importe_total)

    class Meta:
        verbose_name = ('Nota Credito')
        verbose_name_plural = ('Notas Creditos')

class NotaCreditoVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta', blank=True, null=True, editable=False)
    nronotacredito = models.CharField('Nro. Nota Credito', max_length=25)
    concepto = models.CharField('Concepto', max_length=60, blank=True, null=True)
    importe_neto_total = models.DecimalField('Importe Neto Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    importe_total = models.DecimalField('Importe Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    tipo_nota_credito = models.CharField('Tipo', max_length=2, choices=TIPO_FACTURA_CHOICES)
    proveedor = models.ForeignKey('Proveedor')
    fecha_nota_credito = models.DateField('Fecha Nota Credito', default=datetime.date.today())
    pendiente = models.BooleanField('Pendiente')#, editable=False)

    def __unicode__(self):
        return '%s | %s | %s | $ %s' % ( self.proveedor.cuit, self.fecha_nota_credito, self.nronotacredito, self.importe_total)

    class Meta:
        verbose_name = ('Nota Credito Venta')
        verbose_name_plural = ('Notas Creditos Ventas')

class FacturaVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta', blank=True, null=True, editable=False)
    nrofactura = models.CharField('Nro. Factura', max_length=25)
    concepto = models.CharField('Concepto', max_length=60, blank=True, null=True)
    importe_neto_total = models.DecimalField('Importe Neto Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    importe_total = models.DecimalField('Importe Total', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    tipo_factura = models.CharField('Tipo', max_length=2, choices=TIPO_FACTURA_CHOICES)
    proveedor = models.ForeignKey('Proveedor')
    fecha_factura = models.DateField('Fecha Factura', default=datetime.date.today())
    pendiente = models.BooleanField('Pendiente')#, editable=False)

    def __unicode__(self):
        return '%s | %s | %s | $ %s' % ( self.proveedor.cuit, self.fecha_factura, self.nrofactura, self.importe_total)

    class Meta:
        verbose_name = ('Factura Venta')
        verbose_name_plural = ('Facturas Ventas')

class OrdenPago(models.Model):
    nro_orden_pago = models.AutoField('Nro Orden Pago', primary_key=True)
    proveedor = models.ForeignKey('Proveedor')
    fecha_orden_pago = models.DateField('Fecha', default=datetime.date.today())
    moneda = models.CharField('Moneda', max_length=4, choices=MONEDA_CHOICE, blank=True, null=True)
    total_a_pagar = models.DecimalField(u'Total a Pagar', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    descripcion = models.CharField('Descripcion', max_length=50, blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.nro_orden_pago,)

    class Meta:
        verbose_name = ('Orden de Pago')
        verbose_name_plural = ('Ordenes de Pago')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        imp_facturas = 0
        imp_notacredito = 0
        for fac in self.detalleordenpagofac_set.all():
            imp_facturas += fac.factura.importe_total
        try:
            for nc in self.detalleordenpagonc_set.all():
                imp_notacredito += nc.notacredito.importe_total
        except:
            imp_notacredito = 0
        self.total_a_pagar = (imp_facturas - imp_notacredito)
        super(OrdenPago, self).save(*args, **kwargs)

class OrdenPagoVenta(models.Model):
    nro_orden_pago = models.AutoField('Nro Orden Pago', primary_key=True)
    proveedor = models.ForeignKey('Proveedor')
    fecha_orden_pago = models.DateField('Fecha', default=datetime.date.today())
    moneda = models.CharField('Moneda', max_length=4, choices=MONEDA_CHOICE, blank=True, null=True)
    total_a_pagar = models.DecimalField(u'Total a Pagar', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'))
    descripcion = models.CharField('Descripcion', max_length=50, blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.nro_orden_pago,)

    class Meta:
        verbose_name = ('Orden de Pago Venta')
        verbose_name_plural = ('Ordenes de Pago Venta')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        imp_facturas = 0
        imp_notacredito = 0
        for fac in self.detalleordenpagofacventa_set.all():
            imp_facturas += fac.factura.importe_total
        try:
            for nc in self.detalleordenpagoncventa_set.all():
                imp_notacredito += nc.notacredito.importe_total
        except:
            imp_notacredito = 0
        self.total_a_pagar = (imp_facturas - imp_notacredito)
        super(OrdenPagoVenta, self).save(*args, **kwargs)

class DetalleOrdenPago(models.Model):
    orden_pago = models.ForeignKey('OrdenPago')
    banco = models.ForeignKey('reservas_abm.banco')
    forma_pago = models.ForeignKey('reservas_abm.formapago')
    tipo_gasto = models.CharField('Tipo Gasto', max_length=2,
    choices=TIPO_GASTO_CHOICE, blank=True, null=True)
    nro_cheque = models.CharField(u'Nº Cheque', max_length=20, default=0,
    blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.get_tipo_gasto_display(),)

    class Meta:
        verbose_name = ('Detalle Orden de Pago')
        verbose_name_plural = ('Detalles Ordenes de Pago')

class DetalleOrdenPagoVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta')
    banco = models.ForeignKey('reservas_abm.banco')
    forma_pago = models.ForeignKey('reservas_abm.formapago')
    tipo_gasto = models.CharField('Tipo Gasto', max_length=2,
    choices=TIPO_GASTO_CHOICE, blank=True, null=True)
    nro_cheque = models.CharField(u'Nº Cheque', max_length=20, default=0,
    blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.get_tipo_gasto_display(),)

    class Meta:
        verbose_name = ('Detalle Orden de Pago Venta')
        verbose_name_plural = ('Detalles Ordenes de Pago Ventas')

class DetalleOrdenPagoCC(models.Model):
    orden_pago = models.ForeignKey('OrdenPago')
    centro_costo = models.ForeignKey('CentroCosto')
    porcentaje_aplicacion = models.DecimalField(u'% Aplic', max_digits=6,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('100.00'))

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name = ('Detalle Orden de Pago Centro Costo')
        verbose_name_plural = ('Detalles Ordenes de Pago Centro Costo')

class DetalleOrdenPagoCCVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta')
    centro_costo = models.ForeignKey('CentroCosto')
    porcentaje_aplicacion = models.DecimalField(u'% Aplic', max_digits=6,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('100.00'))

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name = ('Detalle Orden de Pago Centro Costo Venta')
        verbose_name_plural = ('Detalles Ordenes de Pago Centro Costo Ventas')

class DetalleOrdenPagoNC(models.Model):
    orden_pago = models.ForeignKey('OrdenPago')
    notacredito = models.ForeignKey('NotaCredito')

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name = ('Detalle Orden de Pago NC')
        verbose_name_plural = ('Detalles Ordenes de Pago NC')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        super(DetalleOrdenPagoNC, self).save(*args, **kwargs)
        self.notacredito.pendiente = True
        self.notacredito.save()
        imp_facturas = 0
        imp_notacredito = 0
        for fac in self.orden_pago.detalleordenpagofac_set.all():
            imp_facturas += fac.factura.importe_total
        try:
            for nc in self.orden_pago.detalleordenpagonc_set.all():
                imp_notacredito += nc.notacredito.importe_total
        except:
            imp_notacredito = 0
        self.orden_pago.total_a_pagar = (imp_facturas - imp_notacredito)
        self.orden_pago.save()
        super(DetalleOrdenPagoNC, self).save(*args, **kwargs)

class DetalleOrdenPagoNCVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta')
    notacredito = models.ForeignKey('NotaCreditoVenta')

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name = ('Detalle Orden de Pago NC Venta')
        verbose_name_plural = ('Detalles Ordenes de Pago NC Ventas')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        super(DetalleOrdenPagoNCVenta, self).save(*args, **kwargs)
        self.notacredito.pendiente = True
        self.notacredito.save()
        imp_facturas = 0
        imp_notacredito = 0
        for fac in self.orden_pago.detalleordenpagofacventa_set.all():
            imp_facturas += fac.factura.importe_total
        try:
            for nc in self.orden_pago.detalleordenpagoncventa_set.all():
                imp_notacredito += nc.notacredito.importe_total
        except:
            imp_notacredito = 0
        self.orden_pago.total_a_pagar = (imp_facturas - imp_notacredito)
        self.orden_pago.save()
        super(DetalleOrdenPagoNCVenta, self).save(*args, **kwargs)

class DetalleOrdenPagoFAC(models.Model):
    orden_pago = models.ForeignKey('OrdenPago')
    factura = models.ForeignKey('Factura')

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name = ('Detalle Orden de Pago Factura')
        verbose_name_plural = ('Detalles Ordenes de Pago Facturas')

    def save(self, *args, **kwargs):
        super(DetalleOrdenPagoFAC, self).save(*args, **kwargs)
        self.factura.pendiente = True
        self.factura.save()
        imp_facturas = 0
        imp_notacredito = 0
        for fac in self.orden_pago.detalleordenpagofac_set.all():
            imp_facturas += fac.factura.importe_total
        try:
            for nc in self.orden_pago.detalleordenpagonc_set.all():
                imp_notacredito += nc.notacredito.importe_total
        except:
            imp_notacredito = 0
        self.orden_pago.total_a_pagar = (imp_facturas - imp_notacredito)
        self.orden_pago.save()
        super(DetalleOrdenPagoFAC, self).save(*args, **kwargs)

class DetalleOrdenPagoFACVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta')
    factura = models.ForeignKey('FacturaVenta')

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name = ('Detalle Orden de Pago Factura')
        verbose_name_plural = ('Detalles Ordenes de Pago Facturas')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        super(DetalleOrdenPagoFACVenta, self).save(*args, **kwargs)
        self.factura.pendiente = True
        self.factura.save()
        imp_facturas = 0
        imp_notacredito = 0
        for fac in self.orden_pago.detalleordenpagofacventa_set.all():
            imp_facturas += fac.factura.importe_total
        try:
            for nc in self.orden_pago.detalleordenpagoncventa_set.all():
                imp_notacredito += nc.notacredito.importe_total
        except:
            imp_notacredito = 0
        self.orden_pago.total_a_pagar = (imp_facturas - imp_notacredito)
        self.orden_pago.save()
        super(DetalleOrdenPagoFACVenta, self).save(*args, **kwargs)

class DetalleOrdenPagoRet(models.Model):
    orden_pago = models.ForeignKey('OrdenPago')
    importe_ret_iibb = models.DecimalField('Ret IIBB', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    nro_ret_iibb = models.CharField('Nro', max_length=18, blank=True, null=True)
    importe_ret_ganancias = models.DecimalField('Ret GAN', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    nro_ret_ganancias = models.CharField('Nro', max_length=15, blank=True, null=True)

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        total_importe_facturas = 0
        total_importe_neto_facturas = 0
        total_importe_notacredito = 0
        for importe_factura in DetalleOrdenPagoFAC.objects.filter(orden_pago=self.orden_pago.pk):
            total_importe_facturas = total_importe_facturas + importe_factura.factura.importe_total
        for importe_neto_factura in DetalleOrdenPagoFAC.objects.filter(orden_pago=self.orden_pago.pk):
            total_importe_neto_facturas = total_importe_neto_facturas + importe_neto_factura.factura.importe_neto_total
        for importe_notacredito in DetalleOrdenPagoNC.objects.filter(orden_pago=self.orden_pago.pk):
            total_importe_notacredito = total_importe_notacredito + importe_notacredito.notacredito.importe_neto_total
        if self.orden_pago.proveedor.porcentaje_ret == None:
            self.importe_ret_iibb = 0
        else:
            self.importe_ret_iibb = ((total_importe_neto_facturas - total_importe_notacredito) * self.orden_pago.proveedor.porcentaje_ret)/100
        self.orden_pago.total_a_pagar = total_importe_facturas - total_importe_notacredito - self.importe_ret_iibb
        self.orden_pago.save()
        #self.orden_pago.ingresosbrutos.pertenece = 'S'
        self.orden_pago.ingresosbrutos.clean()
        self.orden_pago.ingresosbrutos.save()
        self.nro_ret_iibb = self.orden_pago.ingresosbrutos.nro_certificado
        super(DetalleOrdenPagoRet, self).save(*args, **kwargs)

class DetalleOrdenPagoRetVenta(models.Model):
    orden_pago = models.ForeignKey('OrdenPagoVenta')
    importe_ret_iibb = models.DecimalField('Ret IIBB', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    nro_ret_iibb = models.CharField('Nro', max_length=18, blank=True, null=True)
    importe_ret_ganancias = models.DecimalField('Ret GAN', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    nro_ret_ganancias = models.CharField('Nro', max_length=15, blank=True, null=True)

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        total_importe_facturas = 0
        total_importe_neto_facturas = 0
        total_importe_notacredito = 0
        for importe_factura in DetalleOrdenPagoFACVenta.objects.filter(orden_pago=self.orden_pago.pk):
            total_importe_facturas = total_importe_facturas + importe_factura.factura.importe_total
        for importe_neto_factura in DetalleOrdenPagoFACVenta.objects.filter(orden_pago=self.orden_pago.pk):
            if not importe_neto_factura.factura.importe_neto_total == None:
                total_importe_neto_facturas = total_importe_neto_facturas + importe_neto_factura.factura.importe_neto_total
        for importe_notacredito in DetalleOrdenPagoNCVenta.objects.filter(orden_pago=self.orden_pago.pk):
            total_importe_notacredito = total_importe_notacredito + importe_notacredito.notacredito.importe_neto_total
        if self.orden_pago.proveedor.porcentaje_ret == None:
            self.importe_ret_iibb = 0
        else:
            self.importe_ret_iibb = ((total_importe_neto_facturas - total_importe_notacredito) * self.orden_pago.proveedor.porcentaje_ret)/100
        self.orden_pago.total_a_pagar = (total_importe_facturas - total_importe_notacredito - self.importe_ret_iibb)
        self.orden_pago.save()
        #self.orden_pago.ingresosbrutos.pertenece = 'V'
        self.orden_pago.ingresosbrutos.clean()
        self.orden_pago.ingresosbrutos.save()
        self.nro_ret_iibb = self.orden_pago.ingresosbrutos.nro_certificado
        super(DetalleOrdenPagoRetVenta, self).save(*args, **kwargs)

class IngresosBrutos(models.Model):
    orden_pago = models.OneToOneField('OrdenPago', blank=True, null=True)
    orden_pago_venta = models.OneToOneField('OrdenPagoVenta', blank=True, null=True)
    nro_certificado = models.CharField('Nro. Cert', max_length=18, blank=True, null=True)
    proveedor = models.ForeignKey('Proveedor')
    fecha_iibb = models.DateField('Fecha', default=datetime.date.today(),
    blank=True, null=True)
    importe_pagado = models.DecimalField(u'Importe Pagado', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'),
    blank=True, null=True)
    importe_retenido = models.DecimalField(u'Importe Ret', max_digits=15,
    decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'),
    blank=True, null=True)
    pertenece = models.CharField('Pertenece a', max_length=1, choices=PERTENECE_CHOICES,
    blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.orden_pago,)

    class Meta:
        verbose_name_plural = ('Ingresos Brutos')

    def clean(self):
        mascara = '0001-' + str(datetime.date.today().year) + '-'
        nro_id = str('%08d' % (self.id))
        self.nro_certificado = mascara + nro_id
        if self.orden_pago == None:
            self.pertenece = 'V'
        else:
            self.pertenece = 'S'
