public static void eliminarUnidad(edificio Edificio, unidad Unidad)
 {
     unidad u = new unidad();
     u.dir_edificio = Edificio.direccion;
     u.id_unidad = Unidad.id_unidad;
     CatalogoUnidades.removeUnidad(u);
 }
        public static void actualizarSectoresEdificio(edificio edificio, List<sector> sectores)
        {
            try {
                admEntities db = Datos.getDB();
                var s = db.edificios_sectores.Where(x => x.dir_edificio == edificio.direccion).ToList();

                foreach (var sectB in s)
                {
                    db.edificios_sectores.Remove(sectB);
                }

                foreach (sector sect in sectores)
                {
                    edificios_sectores es = new edificios_sectores();
                    es.dir_edificio = edificio.direccion;
                    es.id_sector = sect.idsector;
                    db.edificios_sectores.Add(es);
                }
                db.SaveChanges();
            }
            catch (Exception e)
            {
                string str = e.InnerException == null ? e.Message : e.InnerException.Message;
                Logger.Log.write(str);
                throw e;
            }
        }
 public static void actualizarMovimientoCaja(edificio edificio, DateTime periodo, string concepto, double importe)
 {
     movimiento_caja mc = new movimiento_caja();
     mc.concepto = concepto;
     mc.importe = importe;
     mc.fecha = periodo;
     mc.dir_edificio = edificio.direccion;
     CatalogoCajaEdificio.updateMovimiento(mc);
 }
 public static void agregarEdificio(string cuit, string direccion, decimal ascensores, decimal matafuegos, decimal luces)
 {
     edificio e = new edificio();
     e.cuit_edificio = cuit;
     e.direccion = direccion;
     e.cant_asc = (int)ascensores;
     e.cant_mat = (int)matafuegos;
     e.cant_luces = (int)luces;
     CatalogoEdificios.addEdificio(e);
 }
 public static List<movimiento_caja> getMovmientosEdificio(edificio e, DateTime p)
 {
     try {
         admEntities db = Datos.getDB();
         return db.movimiento_caja.Where(x => x.dir_edificio == e.direccion && x.fecha.Month == p.Month && x.fecha.Year == p.Year).ToList();
     }
     catch (Exception ex)
     {
         Logger.Log.write(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
         throw ex;
     }
 }
        public static List<movimiento_caja> getAllEstadoCaja(edificio edificio, DateTime periodo)
        {
            DateTime p = DateTime.Parse("1/" + periodo.Month + "/" + periodo.Year);
            List<movimiento_caja> movimientos = new List<movimiento_caja>();

            movimiento_caja mc = new movimiento_caja();
            mc.fecha = p;
            mc.concepto = "Saldo mes anterior";
            mc.importe = getSaldoMesAnterior(edificio, p);
            movimientos.Add(mc);
            movimientos.AddRange(CatalogoCajaEdificio.getMovmientosEdificio(edificio, p));
            return movimientos;
        }
 public static bool agregarFacturaExtraordinaria(edificio edificio, unidad unidad, string ID, DateTime fecha, object Provedor, object TipoGasto, object Sector)
 {
     factura fact = new factura();
     fact.dir_edificio = edificio.direccion;
     fact.id_unidad = unidad.id_unidad;
     fact.numero_factura = ID;
     fact.fecha = fecha;
     fact.razon_provedor = ((provedor)Provedor).razon_social;
     fact.id_tipogasto = ((tipo_gasto)TipoGasto).idtipo_gasto;
     fact.id_sector = ((sector)Sector).idsector;
     CatalogoFacturas.addFactura(fact);
     return true;
 }
 public static object getAllFacturas(edificio edificio, object provedor, DateTime fecha)
 {
     if (provedor == null)
     {
         return CatalogoFacturas.getAllFacturasEdificio(edificio, fecha);
     }
     else if (((provedor)provedor).razon_social != "Sin Filtro")
     {
         return CatalogoFacturas.getAllFacturasEdificio(edificio, (provedor)provedor, fecha);
     }
     else
         return CatalogoFacturas.getAllFacturasEdificio(edificio, fecha);
 }
 public static List<provedor> getAllProveedores(edificio edificio)
 {
     try
     {
         admEntities db = Datos.getDB();
         var edi = db.edificio.Where(x => x.direccion == edificio.direccion).SingleOrDefault();
         return edi.provedor.ToList();
     }
     catch (Exception e)
     {
         Log.write(e.InnerException.Message);
         throw e;
     }
 }
 public static List<unidad> getAllUnidades(edificio e)
 {
     try {
         List<unidad> unidades = null;
         admEntities db = Datos.getDB();
         unidades = (from u in db.unidad select u).Where(x => x.dir_edificio == e.direccion).OrderBy(x=> x.id_unidad).ToList();
         return unidades;
     }
     catch (Exception ex)
     {
         Logger.Log.write(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
         throw ex;
     }
 }
 public static List<movimiento_caja> getMovimientosCaja(edificio e, DateTime fechaDesde, DateTime fechaHasta)
 {
     try
     {
         fechaHasta = DateTime.Parse(fechaHasta.AddMonths(1).AddDays(-fechaHasta.Day).Day + "/" + fechaHasta.Month + "/" + fechaHasta.Year);
         admEntities db = Datos.getDB();
         return db.movimiento_caja.Where(x => x.dir_edificio == e.direccion && x.fecha >= fechaDesde && x.fecha <= fechaHasta).ToList();
     }
     catch (Exception ex)
     {
         Logger.Log.write(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
         throw ex;
     }
 }
 public static void addEdificio(edificio e)
 {
     Mensaje msj = new Entidades.Mensaje();
     admEntities db = Datos.getDB();
     try
     {
         db.edificio.Add(e);
         db.SaveChanges();
     }
     catch (Exception ex)
     {
         Log.write(ex.InnerException.Message);
         throw ex;
     }
 }
 public static void agregarFactura(edificio edificio, string numeroFactura, DateTime fecha, object Provedor, object TipoGasto, object Sector, string detalle, string importe)
 {
     factura fact = new factura();
     fact.dir_edificio = edificio.direccion;
     fact.numero_factura = numeroFactura;
     fact.fecha = fecha;
     fact.importe = double.Parse(importe);
     fact.detalle = detalle;
     if (((provedor)Provedor).razon_social != "Ninguno")
     {
         fact.razon_provedor = ((provedor)Provedor).razon_social;
     }
     fact.id_tipogasto = ((tipo_gasto)TipoGasto).idtipo_gasto;
     fact.id_sector = ((sector)Sector).idsector;
     CatalogoFacturas.addFactura(fact);
 }
        public static bool ActualizarCoeficientes(edificio e, List<Coeficientes> coeficientes)
        {
            List<sector> sectores = CatalogoSectores.getAllSectores(e);

            foreach (Coeficientes c in coeficientes)
            {
                unidades_sectores us = new unidades_sectores();
                us.dir_edificio = e.direccion;
                us.id_unidad = c.Unidad;

                foreach (sector s in sectores)
                {
                    switch (s.idsector)
                    {
                        case 1:
                            us.id_sector = 1;
                            us.porcentaje = c.Rubro1;
                            CatalogoUnidadesSectores.updateUnidadSector(us);
                            break;
                        case 2:
                            us.id_sector = 2;
                            us.porcentaje = c.Rubro2;
                            CatalogoUnidadesSectores.updateUnidadSector(us);
                            break;
                        case 3:
                            us.id_sector = 3;
                            us.porcentaje = c.Rubro3;
                            CatalogoUnidadesSectores.updateUnidadSector(us);
                            break;
                        case 4:
                            us.id_sector = 4;
                            us.porcentaje = c.Rubro4;
                            CatalogoUnidadesSectores.updateUnidadSector(us);
                            break;
                        case 5:
                            us.id_sector = 5;
                            us.porcentaje = c.Rubro5;
                            CatalogoUnidadesSectores.updateUnidadSector(us);
                            break;
                    }
                }
            }

            return true;
        }
        /*
        public static List<Resumen> getResumen(edificio edificio, DateTime periodo)
        {
            try
            {
                admEntities db = Datos.getDB();
                return db.Database.SqlQuery<Resumen>
                   (
                        @"select  gg.nombre 'Grupo', tg.descripcion 'Descripcion', sum(importe) 'Importe'  from factura f
                    join tipo_gasto tg
                    on f.id_tipogasto = tg.idtipo_gasto
                    join grupo_gastos gg
                    on tg.grupo_gastos = gg.idgrupo_gastos
                    where year(f.fecha) = " + periodo.Year + @" and f.dir_edificio = '" + edificio.direccion + @"'
                    group by gg.nombre, f.id_tipogasto"
                    )
                    .ToList();
            }
            catch (Exception e)
            {
                Logger.Log.write(e.InnerException == null ? e.Message : e.InnerException.Message);
                throw e;
            }
        }
        */
        public static List<Grupo> getResumen(edificio edificio, DateTime fechaDesde, DateTime fechaHasta)
        {
            try
            {
                admEntities db = Datos.getDB();
                string query = @"select  gg.nombre Grupo, tg.descripcion Descripcion, sum(f.importe) Importe from factura f
                        join tipo_gasto tg
                        on f.id_tipogasto = tg.idtipo_gasto
                        join grupo_gastos gg
                        on tg.grupo_gastos = gg.idgrupo_gastos
                        where
                        f.fecha BETWEEN '" + getFechaForGetResumen(fechaDesde, false) + @"' AND '" + getFechaForGetResumen(fechaHasta, true) + @"'
                        and f.dir_edificio = '" + edificio.direccion + @"'
                        group by tg.idtipo_gasto";

                var resumen = db.Database.SqlQuery<Resumen>(query).OrderBy(x => x.Grupo).ToList();
                List<Grupo> grupos = new List<Grupo>();
                Grupo grupo = new Grupo();
                foreach (var r in resumen)
                {
                    Gastos gasto = new Gastos();
                    gasto.Descripcion = r.Descripcion;
                    gasto.Importe = r.Importe;

                    var g = grupos.Where(x => x.Nombre == r.Grupo).SingleOrDefault();
                    if (g == null)
                    {
                        grupo = new Grupo();
                        grupo.Nombre = r.Grupo;
                        grupo.Gastos = new List<Gastos>();
                        grupo.Gastos.Add(gasto);
                        grupos.Add(grupo);
                    }
                    else
                        grupos.Where(x => x.Nombre == r.Grupo).SingleOrDefault().Gastos.Add(gasto);
                }

                return grupos;
            }
            catch (Exception e)
            {
                Logger.Log.write(e.InnerException == null ? e.Message : e.InnerException.Message);
                throw e;
            }
        }
 public static void removeEdificio(edificio e)
 {
     try
     {
         admEntities db = Datos.getDB();
         var edificio = db.edificio.SingleOrDefault(x => x.direccion == e.direccion);
         if (edificio != null)
         {
             db.edificio.Remove(edificio);
             db.SaveChanges();
         }
     }
     catch (Exception ex)
     {
         Log.write(ex.InnerException.Message);
         throw ex;
     }
 }
        public static int getLastNroParcela(edificio e)
        {
            try
            {
                using (admEntities db = new admEntities())
                {
                    String dir = e.direccion;
                    int parcela = db.Database.SqlQuery<int>(@"select max(CAST(parcela AS signed INTEGER)) from unidad u where u.dir_edificio = '" + dir + "' group by(u.dir_edificio)").SingleOrDefault();
                    return parcela;
                }

            }
            catch (Exception ex)
            {

                Logger.Log.write(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
                throw ex;
            }
        }
 public static double getSaldoCajaMes(edificio edificio, DateTime fecha)
 {
     try {
         admEntities db = Datos.getDB();
         try
         {
             var d = db.movimiento_caja.Where(x => x.dir_edificio == edificio.direccion && x.fecha <= fecha).Sum(x=> x.importe);
             return d == null ? 0 : (double)d;
         }
         catch (Exception e)
         {
             throw e;
         }
     }
     catch (Exception e)
     {
         Logger.Log.write(e.InnerException == null ? e.Message : e.InnerException.Message);
         throw e;
     }
 }
        public static void actualizarSectoresEdificioWeb(edificio edificio, List<sector> sectoresNuevos)
        {
            try
            {
                admEntities db = Datos.getDB();
                var ESActuales = db.edificios_sectores.Where(x => x.dir_edificio == edificio.direccion).ToList();
                var ed = db.edificio.Where(x => x.direccion == edificio.direccion).SingleOrDefault();
                var allSectores = db.sector.ToList();

                List<edificios_sectores> ESaBorrar = new List<edificios_sectores>();
                List<sector> SectoresAAgregar = new List<sector>();

                foreach (var s in sectoresNuevos)
                    if (ESActuales.Where(x => x.sector.descripcion == s.descripcion).SingleOrDefault() == null)
                        SectoresAAgregar.Add(s);

                foreach (var es in ESActuales)
                    if (sectoresNuevos.Where(x => x.descripcion == es.sector.descripcion).SingleOrDefault() == null)
                        db.edificios_sectores.Remove(es);

                foreach(var s in SectoresAAgregar)
                {
                    edificios_sectores es = new edificios_sectores();
                    es.dir_edificio = ed.direccion;
                    es.id_sector = s.idsector;
                    es.sector = db.sector.Where(x => x.descripcion == s.descripcion).SingleOrDefault();
                    db.edificios_sectores.Add(es);
                }

                db.SaveChanges();
            }
            catch (Exception e)
            {
                string str = e.InnerException == null ? e.Message : e.InnerException.Message;
                Logger.Log.write(str);
                throw e;
            }
        }
 public static List<unidad> getAllUnidadesConTitular(edificio e)
 {
     try
     {
         List<unidad> unidades = null;
         admEntities db = Datos.getDB();
         unidades = db.unidad.Where(x => x.dir_edificio == e.direccion).OrderBy(x => x.id_unidad).ToList();
         foreach(var u in unidades)
         {
             if (u.titular == null)
             {
                 titular t = new titular();
                 t.nombre = "<Ninguno>";
                 u.titular = t;
             }
         }
         return unidades;
     }
     catch (Exception ex)
     {
         Logger.Log.write(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
         throw ex;
     }
 }
 public static List<factura> getAllFacturas(edificio edificio, DateTime now)
 {
     return CatalogoFacturas.getAllFacturasDelEdificio(edificio, now);
 }
 public static void agregarFacturasWeb(List<factura> facturas, edificio edificio, DateTime periodo)
 {
     CatalogoFacturas.agregarFacturasWeb(facturas, edificio,periodo);
 }
 public static void setMovimientosCaja(edificio ed, DateTime periodo, List<movimiento_caja> movimientos)
 {
     CatalogoCajaEdificio.setMovimientosCaja(ed, periodo, movimientos);
 }
 public static List<provedor> getAllProvedores(edificio edificio)
 {
     return CatalogoEdificios.getAllProveedores(edificio);
 }
 public static List<movimiento_caja> getAllMovimientos(edificio edificio, DateTime periodo)
 {
     DateTime p = DateTime.Parse("1/" + periodo.Month + "/" + periodo.Year);
     return CatalogoCajaEdificio.getMovmientosEdificio(edificio, p);
 }
 public static void eliminarEdificio(string direccion)
 {
     edificio e = new edificio();
     e.direccion = direccion;
     CatalogoEdificios.removeEdificio(e);
 }
        public static ResumenFinal getResumenFinal(edificio e, DateTime fechaDesde, DateTime fechaHasta)
        {
            try
            {
                admEntities db = Datos.getDB();
                ResumenFinal resumenFinal = new ResumenFinal();
                fechaHasta = DateTime.Parse(fechaHasta.AddMonths(1).AddDays(-fechaHasta.Day).Day + "/" + fechaHasta.Month + "/" + fechaHasta.Year);

                var sectoresDB = db.sector.ToList();

                var facturas = db.factura.Where(x => x.dir_edificio == e.direccion && x.fecha >= fechaDesde && x.fecha <= fechaHasta).ToList();

                //var facturasAgrupadas = facturas.GroupBy(x => x.fecha.ToString("MM yyyy")).Select(x=> new { Importe = x.Sum(y=> y.importe) });

                DateTime tmpFecha = fechaDesde;
                List<Periodo> periodos = new List<Periodo>();
                bool seguir = true;

                do
                {
                    List<Sector> sectores = new List<Sector>();
                    var Conceptos = db.Database.SqlQuery<Conceptos>(@"select  s.descripcion 'Sector', f.numero_factura 'NumeroFactura', p.razon_social 'Proveedor', concat(tg.descripcion, ' ', f.detalle) 'concepto', f.importe from factura f                                                     left join provedor p                            on p.razon_social = f.razon_provedor   join sector s on id_sector = s.idsector      join tipo_gasto tg  on f.id_tipogasto = tg.idtipo_gasto                    where dir_edificio = '" + e.direccion + "' and month(f.fecha) = " + tmpFecha.Month + " and year(f.fecha) = " + tmpFecha.Year).ToList();
                    foreach(var c in Conceptos.OrderBy(x=> x.Sector))
                    {
                        var s = sectores.Where(x => x.Nombre == c.Sector).SingleOrDefault();
                        if (s == null)
                        {
                            Sector sect = new Sector();
                            sect.Nombre = c.Sector;
                            sect.Importe += c.Importe;
                            sectores.Add(sect);
                        }
                        else
                            s.Importe += c.Importe;
                    }

                    sectores = OrdenarSectores(sectores,sectoresDB);

                    Periodo p = new Periodo();
                    p.Sectores = sectores;
                    p.Total = sectores.Sum(x => x.Importe);
                    p.Nombre = tmpFecha.Month + "/" + tmpFecha.Year;

                    if (sectores.Count > 0)
                        periodos.Add(p);

                    if (tmpFecha <= fechaHasta)
                        seguir = true;
                    else
                        seguir = false;

                    tmpFecha = tmpFecha.AddMonths(1);
                }
                while (seguir);

                resumenFinal.Periodos = periodos;

                var deudaDelEdificio = CatalogoDeudores.getDeudoresFromEdificioRegenerarUnidad(e, fechaHasta).Sum(x=> x.Importe);
                var totalExpensas = periodos.Sum(x => x.Total);

                var entradasDeCaja = getMovimientosCaja(e, fechaDesde, fechaHasta).Sum(x => x.importe > 0 ? (Double)x.importe : 0);

                var salidasDeCaja = getMovimientosCaja(e, fechaDesde, fechaHasta).Sum(x => x.importe < 0 ? (Double)x.importe : 0);

                if (salidasDeCaja < 0)
                    salidasDeCaja *= -1;

                resumenFinal.CobroDeExpensas = totalExpensas - deudaDelEdificio;
                resumenFinal.CobroFondosEspeciales = entradasDeCaja;
                resumenFinal.TotalIngresos = totalExpensas - deudaDelEdificio + entradasDeCaja;

                resumenFinal.GastosComunes = totalExpensas;
                resumenFinal.GastosEspeciales = salidasDeCaja;
                resumenFinal.TotalEgresos = totalExpensas + salidasDeCaja;

                resumenFinal.SaldoEnCaja = resumenFinal.TotalIngresos - resumenFinal.TotalEgresos;

                return resumenFinal;

            }
            catch (Exception ex)
            {
                Logger.Log.write(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
                throw ex;
            }
        }
 public static void setProveedoresEdificio(edificio edificio, List<provedor> provedores)
 {
     CatalogoEdificios.setProveedores(edificio, provedores);
 }
 public static List<sector> getAllSectores(edificio Edificio)
 {
     try {
         List<sector> sectores = null;
         admEntities db = Datos.getDB();
         {
             sectores = (from es in db.edificios_sectores
                         join e in db.edificio on es.dir_edificio equals e.direccion
                         join s in db.sector on es.id_sector equals s.idsector
                         where e.direccion == Edificio.direccion
                         select s).ToList();
         }
         return sectores;
     }
     catch (Exception e)
     {
         Logger.Log.write(e.InnerException == null ? e.Message : e.InnerException.Message);
         throw e;
     }
 }
 public static double getSaldoMesAnterior(edificio edificio, DateTime value)
 {
     return CatalogoCajaEdificio.getSaldoCajaMes(edificio, value);
 }