# -*- 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
from number_to_letter import *

# Create your models here.
CANT_CUOTAS = (
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
    ('6', '6'),
    ('7', '7'),
    ('8', '8'),
    ('9', '9'),
    ('10', '10'),
    ('11', '11'),
    ('12', '12'),
    ('13', '13'),
    ('14', '14'),
    ('15', '15'),
    ('16', '16'),
    ('17', '17'),
    ('18', '18'),
    ('19', '19'),
    ('20', '20'),
    ('21', '21'),
    ('22', '22'),
    ('23', '23'),
    ('24', '24'),
)

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'),
)

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

MONEDA_CHILE_CHOICE = (
        ('D', u'U$S'),
        ('CLP', u'$CLP'),
)

MONEDA_PERU_CHOICE = (
        ('D', u'U$S'),
        ('S', u'SOLES'),
)

ESTADO_COBRO = (
        ('AP', 'APROBADO'),
        ('TR', 'TARJETA RECHAZADA'),
        ('TD', 'TARJETA DENEGADA'),
        ('PA', 'PENDIENTE APROB'),
        ('FI', 'FONDOS INSUFICIENTES'),
)

TIPO_SOCIO_CHOICE = (
        ('CA', 'CARTERA'),
        ('CL', 'CLUB'),
        ('VE', 'VENTAS'),
)

ITEMS_TRANSACTION_CHOICE = (
    ('AR', 'AR'),
    ('FO', 'FOLIO'),
    ('CA', 'CARTERA'),
    ('VE', 'VENTAS'),
)

TIPO_TRANSACTION_CHOICE = (
    ('AR', 'AR'),
    ('FO', 'FOLIO'),
    ('CA', 'CARTERA'),
    ('VE', 'VENTAS'),
)

TIPO_INSTRUMENT_CHOICE = (
    ('CA', 'CARTERA'),
    ('CL', 'CLUB'),
    ('AR', 'AR'),
    ('VE', 'VENTAS'),
)

class FormaPago(models.Model):
    forma_pago = models.CharField('Forma de Pago', max_length=15, blank=True,
                 null=True)
    observaciones = models.TextField('Observaciones', blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.forma_pago)

    class Meta:
        verbose_name = ('Forma de Pago')
        verbose_name_plural = ('Formas de Pago')

class Transaction(models.Model):
    code = models.CharField('Code Id', max_length=6)
    descripcion = models.CharField(u'Descripción', max_length=45, blank=True,
                  null=True)
    item = models.CharField('Item', max_length=10,
           choices=TIPO_TRANSACTION_CHOICE)

    def __unicode__(self):
        return '%s | %s | %s' % (self.code, self.descripcion, self.item)

class Banco(models.Model):
    banco = models.CharField('Banco', max_length=5)
    descripcion = models.CharField(u'Descripción', max_length=25, blank=True,
                 null=True)

    def __unicode__(self):
        return '%s | %s' % (self.banco, self.descripcion)

    class Meta:
        verbose_name_plural=('Bancos')

class BancoChile(models.Model):
    banco = models.CharField('Banco', max_length=5)
    descripcion = models.CharField(u'Descripción', max_length=25, blank=True,
                 null=True)

    def __unicode__(self):
        return '%s | %s' % (self.banco, self.descripcion)

    class Meta:
        verbose_name_plural=('Bancos Chile')

class BancoPeru(models.Model):
    banco = models.CharField('Banco', max_length=5)
    descripcion = models.CharField(u'Descripción', max_length=25, blank=True,
                 null=True)

    def __unicode__(self):
        return '%s | %s' % (self.banco, self.descripcion)

    class Meta:
        verbose_name_plural=(u'Bancos Perú')

class Instrument(models.Model):
    instrument_id = models.IntegerField('Instrument Id')
    forma_pago = models.ForeignKey('FormaPago')
    tipo_instrument = models.CharField('Tipo Instrument', max_length=10,
                      choices=TIPO_INSTRUMENT_CHOICE)
    descripcion = models.CharField(u'Descripción', max_length=20, blank=True,
                  null=True)

    def __unicode__(self):
        return u'%s | %s | %s' % (self.instrument_id, self.forma_pago,
                                 self.get_tipo_instrument_display())

class TipoCambioDia(models.Model):
    valor = models.DecimalField('Valor', max_digits=7, decimal_places=3, default=Decimal('0.000'))
    fecha = models.DateField('Fecha', default=datetime.date.today, blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.valor)

    class Meta:
        verbose_name_plural=('Tipo Cambio Dia')

class DetalleTransaction(models.Model):
    daily = models.ForeignKey('Daily')
    items_transaction = models.CharField('Items Transaction', max_length=10,
                        choices=ITEMS_TRANSACTION_CHOICE,) #blank=True, null=True)
    transaction_codeid = models.ForeignKey('Transaction', blank=True, null=True)
    nro_folio = models.CharField('Nro. Folio', max_length=20,) #blank=True, null=True)
    importe_usd = models.DecimalField('USD', max_digits=10, decimal_places=2,
                  validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True
    importe_pesos = models.DecimalField(u'$', max_digits=10, decimal_places=2,
                    validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True

    def usuario(self):
	    return self.daily.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
        return '%s | %s' % (self.items_transaction, self.transaction_codeid)

class DetalleTransactionVentaPeru(models.Model):
    daily_venta = models.ForeignKey('DailyPeru')
    items_transaction = models.CharField('Items Transaction', max_length=10,
                        choices=ITEMS_TRANSACTION_CHOICE,) #blank=True, null=True)
    transaction_codeid = models.ForeignKey('Transaction', blank=True, null=True)
    nro_folio = models.CharField('Nro. Folio', max_length=20,) #blank=True, null=True)
    importe_usd = models.DecimalField('USD', max_digits=10, decimal_places=2,
                  validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True
    importe_pesos = models.DecimalField(u'Soles', max_digits=10, decimal_places=2,
                    validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True

    def usuario(self):
	return self.daily_venta.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
        return '%s | %s' % (self.items_transaction, self.transaction_codeid)

def get_tipocambiodia():
    try:
        return TipoCambioDia.objects.get(fecha=datetime.date.today).id
    except:
        return None

class DetalleTransactionVenta(models.Model):
    daily_venta = models.ForeignKey('DailyVenta')
    items_transaction = models.CharField('Items Transaction', max_length=10,
                        choices=ITEMS_TRANSACTION_CHOICE,) #blank=True, null=True)
    transaction_codeid = models.ForeignKey('Transaction', blank=True, null=True)
    nro_folio = models.CharField('Nro. Folio', max_length=20,) #blank=True, null=True)
    importe_usd = models.DecimalField('USD', max_digits=10, decimal_places=2,
                  validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True
    importe_pesos = models.DecimalField(u'$', max_digits=10, decimal_places=2,
                    validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True

    def usuario(self):
	return self.daily_venta.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
        return '%s | %s' % (self.items_transaction, self.transaction_codeid)

def get_tipocambiodia():
    try:
        return TipoCambioDia.objects.get(fecha=datetime.date.today).id
    except:
        return None

class DetallePago(models.Model):
    daily = models.ForeignKey('Daily', blank=True, null=True)
    instrument_id = models.ForeignKey('Instrument')
    fecha_dep = models.DateField('Fecha Depo',) #default=datetime.date.today)
    tipo_cambio_dia = models.ForeignKey(TipoCambioDia, on_delete=models.DO_NOTHING,
                      default=get_tipocambiodia, blank=True, null=True)
    reference = models.CharField(u'Refer/N.Apro', max_length=15, default=0) #blank=True, null=True)
    nro_lote = models.CharField(u'Nº Lote', max_length=5, default='WEB') #blank=True, null=True)
    nro_cupon = models.CharField(u'Nº Cupon', max_length=5, default=0, blank=True, null=True)
    nro_tarjeta = models.CharField(u'Nº Tarjeta', max_length=4) #blank=True, null=True)
    cant_cuotas = models.CharField(u'Nº Cuotas', max_length=2, default=0,) #blank=True, null=True)
    monto_usd = models.DecimalField(u'MontoU$D', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    monto_pesos = models.DecimalField('MontoArs', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    intereses_pesos = models.DecimalField(u'Int. $', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    nro_cheque = models.CharField(u'Nº Cheque', max_length=20, default=0,) #blank=True, null=True)

    def usuario(self):
	return self.daily.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
        return '%s' % (self.instrument_id)

    def clean(self):
        try:
            self.nro_cupon = '0'
            self.tipo_cambio_dia = TipoCambioDia.objects.get(fecha=self.fecha_dep)
        except:
          pass

def update_reference(sender, instance, **kwargs):
        if hasattr(instance, '_already_saving'):
            del instance._already_saving
            return
        instance._already_saving = True
        if instance.reference == '0':
            instance.reference = instance.daily.pk
        instance.save()
post_save.connect(update_reference, sender=DetallePago)

class Daily(models.Model):
    owner = models.ForeignKey('Socio', blank=True, null=True, on_delete=models.SET_NULL)
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    tipo_socio = models.CharField('T. Socio', max_length=10,
                 choices=TIPO_SOCIO_CHOICE)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    auth_code = models.AutoField('Auth Code', primary_key=True)
    date = models.DateField('Fecha', default=datetime.date.today)
    bank = models.ForeignKey('Banco')#, blank=True, null=True)
    total_amount = models.DecimalField('USD', max_digits=10, decimal_places=2,
                   validators=[MinValueValidator(0)], blank=True, null=True,
                   default=Decimal('0.00'))
    foreign_amount = models.DecimalField('PESOS', max_digits=10, decimal_places=2,
                     validators=[MinValueValidator(0)], default=Decimal('0.00'),
                     blank=True, null=True)
    trxcurrency = models.CharField('TRX Currency', max_length=5,
                  choices=MONEDA_CHOICE)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3,)# blank=True, null=True)
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_contrato, self.socio)

    class Meta:
        verbose_name_plural=('Daily')

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        super(Daily, self).save(*args, **kwargs)
        self.nro_contrato = self.owner.contract_number
        self.socio = self.owner.owner_name
        self.ownerid = self.owner.owner_id
        super(Daily, self).save(*args, **kwargs)
        if self.pk:
            try:
                recibo = self.recibo
            except:
                recibo = Recibo()
            recibo.daily = self
            recibo.nro_recibo_pago = self.auth_code
            recibo.fecha_recibo = self.date
            recibo.socio = self.socio
            recibo.nro_contrato = self.nro_contrato
            recibo.ownerid = self.ownerid
            recibo.direccion = self.owner.street_address
            recibo.tipo_cambio = self.tipo_cambio
            recibo.recibimos_suma = to_word(self.foreign_amount)
            recibo.usuario = self.usuario
            recibo.save()
        else:
            try:
                recibo = self.recibo
                recibo.delete()
            except:
                pass

class Recibo(models.Model):
    daily = models.OneToOneField('Daily')
    nro_recibo_pago = models.AutoField('Nro Recibo', primary_key=True,
                      editable=False)
    fecha_recibo = models.DateField('Fecha', default=datetime.date.today())
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True,
                   null=True)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    direccion = models.CharField('Direccion', max_length=250, blank=True,
                null=True)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3, blank=True, null=True)
    importe_aplicado = models.DecimalField(u'Imp. $Arg',
                       max_digits=10, decimal_places=2,
                       validators=[MinValueValidator(0)], default=Decimal('0.00'))
    cuit = models.CharField('CUIT', max_length=13, blank=True, null=True)
    recibimos_suma = models.CharField('Recibimos', max_length=120, blank=True,
                     null=True)
    anulado = models.BooleanField('Anulado')
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_recibo_pago, self.socio)

    class Meta:
        verbose_name_plural=('Recibos')

class DetallePagoVentaPeru(models.Model):
    daily_venta = models.ForeignKey('DailyPeru', blank=True, null=True)
    instrument_id = models.ForeignKey('Instrument')
    fecha_dep = models.DateField('Fecha Depo',) #default=datetime.date.today)
    tipo_cambio_dia = models.ForeignKey(TipoCambioDia, on_delete=models.DO_NOTHING,
                    default=get_tipocambiodia, blank=True, null=True)
    reference = models.CharField(u'Refer/N.Apro', max_length=15, default=0) #blank=True, null=True)
    nro_lote = models.CharField(u'Nº Lote', max_length=5, default=0) #blank=True, null=True)
    nro_cupon = models.CharField(u'Nº Cupon', max_length=5, default=0) #blank=True, null=True)
    cant_cuotas = models.CharField(u'Nº Cuotas', max_length=2, default=0,) #blank=True, null=True)
    monto_usd = models.DecimalField(u'MontoU$D', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    monto_pesos = models.DecimalField('MontoSoles', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    intereses_pesos = models.DecimalField(u'Intereses', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    nro_cheque = models.CharField(u'Nº Cheque', max_length=20, default=0,) #blank=True, null=True)

    def usuario(self):
	    return self.daily_venta.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
      return '%s' % (self.instrument_id)

class DetallePagoVenta(models.Model):
    daily_venta = models.ForeignKey('DailyVenta', blank=True, null=True)
    instrument_id = models.ForeignKey('Instrument')
    fecha_dep = models.DateField('Fecha Depo',) #default=datetime.date.today)
    tipo_cambio_dia = models.ForeignKey(TipoCambioDia, on_delete=models.DO_NOTHING,
                    default=get_tipocambiodia, blank=True, null=True)
    reference = models.CharField(u'Refer/N.Apro', max_length=15, default=0) #blank=True, null=True)
    nro_lote = models.CharField(u'Nº Lote', max_length=5, default=0) #blank=True, null=True)
    nro_cupon = models.CharField(u'Nº Cupon', max_length=5, default=0) #blank=True, null=True)
    cant_cuotas = models.CharField(u'Nº Cuotas', max_length=2, default=0,) #blank=True, null=True)
    monto_usd = models.DecimalField(u'MontoU$D', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    monto_pesos = models.DecimalField('MontoArs', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    intereses_pesos = models.DecimalField(u'Int. $', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    nro_cheque = models.CharField(u'Nº Cheque', max_length=20, default=0,) #blank=True, null=True)

    def usuario(self):
	    return self.daily_venta.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
      return '%s' % (self.instrument_id)

class DailyVenta(models.Model):
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    tipo_socio = models.CharField('T. Socio', max_length=10,
                 choices=TIPO_SOCIO_CHOICE)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    auth_code_venta = models.AutoField('Auth Code Venta', primary_key=True)
    date = models.DateField('Fecha', default=datetime.date.today)
    bank = models.ForeignKey('Banco')#, blank=True, null=True)
    total_amount = models.DecimalField('USD', max_digits=10, decimal_places=2,
                   validators=[MinValueValidator(0)], blank=True, null=True,
                   default=Decimal('0.00'))
    foreign_amount = models.DecimalField('PESOS', max_digits=10, decimal_places=2,
                     validators=[MinValueValidator(0)], default=Decimal('0.00'),
                     blank=True, null=True)
    trxcurrency = models.CharField('TRX Currency', max_length=5,
                  choices=MONEDA_CHOICE)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3,)# blank=True, null=True)
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_contrato, self.socio)

    class Meta:
        verbose_name_plural=('Daily Ventas')

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        super(DailyVenta, self).save(*args, **kwargs)
        if self.pk:
            try:
                recibo = self.reciboventa
            except:
                recibo = ReciboVenta()
            recibo.daily_venta = self
            recibo.nro_recibo_pago_venta = self.auth_code_venta
            recibo.fecha_recibo_venta = self.date
            recibo.socio = self.socio
            recibo.nro_contrato = self.nro_contrato
            recibo.ownerid = self.ownerid
            recibo.tipo_cambio = self.tipo_cambio
            recibo.recibimos_suma = to_word(self.foreign_amount)
            recibo.usuario = self.usuario
            recibo.save()
        else:
            try:
                recibo = self.recibo
                recibo.delete()
            except:
                pass

class ReciboVenta(models.Model):
    daily_venta = models.OneToOneField('DailyVenta')
    nro_recibo_pago_venta = models.AutoField('Nro Recibo', primary_key=True,
                      editable=False)
    fecha_recibo_venta = models.DateField('Fecha', default=datetime.date.today())
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True,
                   null=True)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    direccion = models.CharField('Direccion', max_length=250, blank=True,
                null=True)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3, blank=True, null=True)
    importe_aplicado = models.DecimalField(u'Imp. $Arg',
                       max_digits=10, decimal_places=2,
                       validators=[MinValueValidator(0)], default=Decimal('0.00'))
    cuit = models.CharField('CUIT', max_length=13, blank=True, null=True)
    recibimos_suma = models.CharField('Recibimos', max_length=120, blank=True,
                     null=True)
    anulado = models.BooleanField('Anulado')
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_recibo_pago_venta, self.socio)

    class Meta:
        verbose_name_plural=('Recibos Ventas')

class ReciboVentaPeru(models.Model):
    daily_peru = models.OneToOneField('DailyPeru')
    nro_recibo_pago_venta = models.AutoField('Nro Recibo', primary_key=True,
                      editable=False)
    fecha_recibo_venta = models.DateField('Fecha', default=datetime.date.today())
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True,
                   null=True)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    direccion = models.CharField('Direccion', max_length=250, blank=True,
                null=True)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3, blank=True, null=True)
    importe_aplicado = models.DecimalField(u'Imp. Soles',
                       max_digits=10, decimal_places=2,
                       validators=[MinValueValidator(0)], default=Decimal('0.00'))
    cuit = models.CharField('CUIT', max_length=13, blank=True, null=True)
    recibimos_suma = models.CharField('Recibimos', max_length=120, blank=True,
                     null=True)
    anulado = models.BooleanField('Anulado')
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_recibo_pago_venta, self.socio)

    class Meta:
        verbose_name_plural=(u'Recibos Ventas Perú')
############################## DAILY PERU ######################################
############################## DEBITOS AUTOMATICOS ##############################
class ReciboDebito(models.Model):
    nro_recibo_pago_debito = models.CharField('Nro Recibo Debito', max_length=15, blank=True, null=True)
    fecha_recibo_debito = models.DateField('Fecha', default=datetime.date.today())
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True,
                   null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    direccion = models.CharField('Direccion', max_length=250, blank=True,
                null=True)
    importe_aplicado = models.DecimalField(u'Imp. $Arg',
                       max_digits=10, decimal_places=2,
                       validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    cuit = models.CharField('CUIT', max_length=13, blank=True, null=True)
    recibimos_suma = models.CharField('Recibimos', max_length=80, blank=True,
                     null=True)
    bank = models.ForeignKey('Banco', blank=True, null=True)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3, blank=True, null=True)
    total_amount = models.DecimalField('USD', max_digits=10, decimal_places=2,
                   validators=[MinValueValidator(0)], blank=True, null=True,
                   default=Decimal('0.00'))
    foreign_amount = models.DecimalField('PESOS', max_digits=10, decimal_places=2,
                     validators=[MinValueValidator(0)], default=Decimal('0.00'),
                     blank=True, null=True)
    trxcurrency = models.CharField('TRX Currency', max_length=5,
                  choices=MONEDA_CHOICE, blank=True, null=True)
    transaction_codeid = models.ForeignKey('Transaction', blank=True, null=True)
    instrument_id = models.ForeignKey('Instrument', blank=True, null=True)

    anulado = models.BooleanField('Anulado')
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_recibo_pago_debito, self.socio)

    class Meta:
        verbose_name_plural=('Recibos Debitos')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        super(ReciboDebito, self).save(*args, **kwargs)
        if self.pk:
            try:
                recibo_debito = self
            except:
                recibo_debito = ReciboDebito()
            recibo_debito.nro_recibo_pago_debito = str(self.pk)
            recibo_debito.importe_aplicado = self.foreign_amount
            recibo_debito.anulado = False
            recibo_debito.recibimos_suma=to_word(self.foreign_amount)
            if self.trxcurrency=='D':
                recibo_debito.tipo_cambio=Decimal(self.foreign_amount/self.total_amount)
            else:
                recibo_debito.tipo_cambio='0.00'

        super(ReciboDebito, self).save(*args, **kwargs)
############################## DEBITOS AUTOMATICOS ##############################
############################## RECIBOS POR VPOS ##############################
class ReciboVPos(models.Model):
    nro_recibo_pago_vpos = models.CharField('Nro Recibo Debito', max_length=15, blank=True, null=True)
    fecha_recibo_vpos = models.DateField('Fecha', default=datetime.date.today())
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True,
                   null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    direccion = models.CharField('Direccion', max_length=250, blank=True,
                null=True)
    importe_aplicado = models.DecimalField(u'Imp. $Arg',
                       max_digits=10, decimal_places=2,
                       validators=[MinValueValidator(0)], default=Decimal('0.00'), blank=True, null=True)
    cuit = models.CharField('CUIT', max_length=13, blank=True, null=True)
    recibimos_suma = models.CharField('Recibimos', max_length=80, blank=True,
                     null=True)
    bank = models.ForeignKey('Banco', blank=True, null=True)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3, blank=True, null=True)
    total_amount = models.DecimalField('USD', max_digits=10, decimal_places=2,
                   validators=[MinValueValidator(0)], blank=True, null=True,
                   default=Decimal('0.00'))
    foreign_amount = models.DecimalField('PESOS', max_digits=10, decimal_places=2,
                     validators=[MinValueValidator(0)], default=Decimal('0.00'),
                     blank=True, null=True)
    trxcurrency = models.CharField('TRX Currency', max_length=5,
                  choices=MONEDA_CHOICE, blank=True, null=True)
    transaction_codeid = models.ForeignKey('Transaction', blank=True, null=True)
    instrument_id = models.ForeignKey('Instrument', blank=True, null=True)

    anulado = models.BooleanField('Anulado')
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_recibo_pago_vpos, self.socio)

    class Meta:
        verbose_name=('Recibo VPos')
        verbose_name_plural=('Recibos VPos')

    def save(self, force_insert=True, force_update=True, *args, **kwargs):
        super(ReciboVPos, self).save(*args, **kwargs)
        if self.pk:
            try:
                recibo_vpos = self
            except:
                recibo_vpos = ReciboDebito()
            recibo_vpos.nro_recibo_pago_vpos = str(self.pk)
            recibo_vpos.importe_aplicado = self.foreign_amount
            recibo_vpos.anulado = False
            recibo_vpos.recibimos_suma=to_word(self.foreign_amount)
            if self.trxcurrency=='D':
                recibo_vpos.tipo_cambio=Decimal(self.foreign_amount/self.total_amount)
            else:
                recibo_vpos.tipo_cambio='0.00'
        super(ReciboVPos, self).save(*args, **kwargs)

############################## RECIBOS POR VPOS ##############################
class Socio(models.Model):
    owner_id = models.CharField('Owner ID', max_length=10, blank=True, null=True)
    contract_number = models.CharField('Contract Number', max_length=25, blank=True, null=True)
    owner_name = models.CharField('Owner Name', max_length=250, blank=True, null=True)
    street_address = models.CharField('Street Address', max_length=250, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s | %s' % (self.owner_id, self.owner_name, self.contract_number)

    class Meta:
        verbose_name=('Socio')
        verbose_name_plural=('Socios')
############################## DAILY Y RECIBOS CHILE ##############################
def get_tipocambiodiachile():
    try:
        return TipoCambioDiaChile.objects.get(fecha=datetime.date.today).id
    except:
        return None

class TipoCambioDiaChile(models.Model):
    valor = models.DecimalField('Valor', max_digits=7, decimal_places=3, default=Decimal('0.000'))
    fecha = models.DateField('Fecha', default=datetime.date.today, blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.valor)

    class Meta:
        verbose_name_plural=('Tipo Cambio Dia Chile')

class DailyChile(models.Model):
    owner = models.ForeignKey('Socio', blank=True, null=True, on_delete=models.SET_NULL)
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    tipo_socio = models.CharField('T. Socio', max_length=10,
                 choices=TIPO_SOCIO_CHOICE)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    auth_code = models.AutoField('Auth Code', primary_key=True)
    date = models.DateField('Fecha', default=datetime.date.today)
    bank = models.ForeignKey('BancoChile')#, blank=True, null=True)
    total_amount = models.DecimalField('USD', max_digits=10, decimal_places=2,
                   validators=[MinValueValidator(0)], blank=True, null=True,
                   default=Decimal('0.00'))
    foreign_amount = models.DecimalField('PESOS', max_digits=10, decimal_places=2,
                     validators=[MinValueValidator(0)], default=Decimal('0.00'),
                     blank=True, null=True)
    trxcurrency = models.CharField('TRX Currency', max_length=5,
                  choices=MONEDA_CHILE_CHOICE)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3,)# blank=True, null=True)
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_contrato, self.socio)

    class Meta:
        verbose_name_plural=('Daily Chile')

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        super(DailyChile, self).save(*args, **kwargs)
        self.nro_contrato = self.owner.contract_number
        self.socio = self.owner.owner_name
        self.ownerid = self.owner.owner_id
        super(DailyChile, self).save(*args, **kwargs)
        if self.pk:
            try:
                recibo = self.recibochile
            except:
                recibo = ReciboChile()
            recibo.daily = self
            recibo.nro_recibo_pago = self.auth_code
            recibo.fecha_recibo = self.date
            recibo.socio = self.socio
            recibo.nro_contrato = self.nro_contrato
            recibo.ownerid = self.ownerid
            recibo.direccion = self.owner.street_address
            recibo.tipo_cambio = self.tipo_cambio
            recibo.usuario = self.usuario
            recibo.save()
        else:
            try:
                recibo = self.recibo
                recibo.delete()
            except:
                pass

class DetalleTransactionChile(models.Model):
    daily = models.ForeignKey('DailyChile')
    items_transaction = models.CharField('Items Transaction', max_length=10,
                        choices=ITEMS_TRANSACTION_CHOICE,) #blank=True, null=True)
    transaction_codeid = models.ForeignKey('Transaction', blank=True, null=True)
    nro_folio = models.CharField('Nro. Folio', max_length=20,) #blank=True, null=True)
    importe_usd = models.DecimalField('USD', max_digits=10, decimal_places=2,
                  validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True
    importe_pesos = models.DecimalField(u'$', max_digits=10, decimal_places=2,
                    validators=[MinValueValidator(0)], default=Decimal('0.00')) #blank=True, null=True

    def usuario(self):
	    return self.daily.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
        return '%s | %s' % (self.items_transaction, self.transaction_codeid)

class DetallePagoChile(models.Model):
    daily = models.ForeignKey('DailyChile', blank=True, null=True)
    instrument_id = models.ForeignKey('Instrument')
    fecha_dep = models.DateField('Fecha Depo',) #default=datetime.date.today)
    tipo_cambio_dia = models.ForeignKey(TipoCambioDiaChile, on_delete=models.DO_NOTHING,
                      default=get_tipocambiodiachile, blank=True, null=True)
    reference = models.CharField(u'Refer/N.Apro', max_length=15, default=0) #blank=True, null=True)
    nro_lote = models.CharField(u'Nº Lote', max_length=5, default=0) #blank=True, null=True)
    nro_cupon = models.CharField(u'Nº Cupon', max_length=5, default=0) #blank=True, null=True)
    cant_cuotas = models.CharField(u'Nº Cuotas', max_length=2, default=0,) #blank=True, null=True)
    monto_usd = models.DecimalField(u'MontoU$D', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    monto_pesos = models.DecimalField('Monto $', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    intereses_pesos = models.DecimalField(u'Int. $', max_digits=10, decimal_places=2, validators=[MinValueValidator(0)], default=Decimal('0.00'), )#blank=True, null=True)
    nro_cheque = models.CharField(u'Nº Cheque', max_length=20, default=0,) #blank=True, null=True)

    def usuario(self):
	    return self.daily.usuario
    usuario.short_description=('Usuario')

    def __unicode__(self):
        return '%s' % (self.instrument_id)

    def clean(self):
        try:
          self.tipo_cambio_dia = TipoCambioDiaChile.objects.get(fecha=self.fecha_dep)
        except:
          pass

class ReciboChile(models.Model):
    daily = models.OneToOneField('DailyChile')
    nro_recibo_pago = models.AutoField('Nro Recibo', primary_key=True,
                      editable=False)
    fecha_recibo = models.DateField('Fecha', default=datetime.date.today())
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True,
                   null=True)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    direccion = models.CharField('Direccion', max_length=250, blank=True,
                null=True)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3, blank=True, null=True)
    importe_aplicado = models.DecimalField(u'Imp. $Cl',
                       max_digits=10, decimal_places=2,
                       validators=[MinValueValidator(0)], default=Decimal('0.00'))
    cuit = models.CharField('CUIT', max_length=13, blank=True, null=True)
    recibimos_suma = models.CharField('Recibimos', max_length=80, blank=True,
                     null=True)
    anulado = models.BooleanField('Anulado')
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_recibo_pago, self.socio)

    class Meta:
        verbose_name_plural=('Recibos Chile')
############################## DAILY Y RECIBOS CHILE ##############################

############################## DAILY Y RECIBOS PERU ##############################
def get_tipocambiodiachile():
    try:
        return TipoCambioDiaPeru.objects.get(fecha=datetime.date.today).id
    except:
        return None

class TipoCambioDiaPeru(models.Model):
    valor = models.DecimalField('Valor', max_digits=7, decimal_places=3, default=Decimal('0.000'))
    fecha = models.DateField('Fecha', default=datetime.date.today, blank=True, null=True)

    def __unicode__(self):
        return '%s' % (self.valor)

    class Meta:
        verbose_name_plural=(u'Tipo Cambio Dia Perú')

class DailyPeru(models.Model):
    nro_contrato = models.CharField('Nro. Contrato', max_length=25, blank=True, null=True)
    socio = models.CharField('Socio', max_length=250, blank=True, null=True)
    tipo_socio = models.CharField('T. Socio', max_length=10,
                 choices=TIPO_SOCIO_CHOICE)
    ownerid = models.CharField('OwnerID', max_length=15, blank=True, null=True)
    auth_code = models.AutoField('Auth Code Venta', primary_key=True)
    date = models.DateField('Fecha', default=datetime.date.today)
    bank = models.ForeignKey('Banco')#, blank=True, null=True)
    total_amount = models.DecimalField('USD', max_digits=10, decimal_places=2,
                   validators=[MinValueValidator(0)], blank=True, null=True,
                   default=Decimal('0.00'))
    foreign_amount = models.DecimalField('Soles', max_digits=10, decimal_places=2,
                     validators=[MinValueValidator(0)], default=Decimal('0.00'),
                     blank=True, null=True)
    trxcurrency = models.CharField('TRX Currency', max_length=5,
                  choices=MONEDA_PERU_CHOICE)
    tipo_cambio = models.DecimalField('Tipo Cambio', max_digits=10,
                  decimal_places=3,)# blank=True, null=True)
    usuario = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return '%s | %s' % (self.nro_contrato, self.socio)

    class Meta:
        verbose_name_plural=(u'Daily Ventas Perú')

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        super(DailyPeru, self).save(*args, **kwargs)
        if self.pk:
            try:
                recibo_peru = self.reciboventaperu
            except:
                recibo_peru = ReciboVentaPeru()
            print self.pk
            recibo_peru.daily_peru = self
            recibo_peru.nro_recibo_pago_venta = self.auth_code
            recibo_peru.fecha_recibo_venta = self.date
            recibo_peru.socio = self.socio
            recibo_peru.nro_contrato = self.nro_contrato
            recibo_peru.ownerid = self.ownerid
            recibo_peru.tipo_cambio = self.tipo_cambio
            recibo_peru.recibimos_suma = to_word(self.foreign_amount)
            recibo_peru.usuario = self.usuario
            recibo_peru.save()
        else:
            try:
                recibo_peru = self.reciboventaperu
                recibo_peru.delete()
            except:
                pass
############################## DAILY Y RECIBOS PERU ##############################
