Ejemplo n.º 1
0
 /// <summary>
 /// Devueleve lo que queda por facturar de un pedido de suscripción, excluyendo
 /// la factura pasada
 /// </summary>
 /// <param name="pedido">Pedido de suscripción</param>
 /// <param name="factura">Factura de referencia</param>
 /// <param name="ctx">Contexto OpenAccess</param>
 /// <returns>Importe pendiente o cero si no se puede facturar.</returns>
 public static decimal PedidoSuscripcionImporteFacturable(Pedido pedido, CabFactura factura, PortalProContext ctx)
 {
     decimal r = 0;
     DateTime fecha = (DateTime)factura.FechaEmision;
     // si no es un pedido de suscripción no lo tratamos.
     if (pedido.TipoPedido != "SUSCRIPCION")
         return r;
     // si hemos superado la fecha límite, tampoco facturamos
     // solo comprobamos si la fecha no es nula
     if (pedido.FechaLimite != null && (fecha > pedido.FechaLimite))
         return r;
     // calcular el primer y último dia del mes
     DateTime primerDiaDelMes = new DateTime(fecha.Year, fecha.Month, 1);
     DateTime ultimoDiaDelMes = primerDiaDelMes.AddMonths(1).AddDays(-1);
     // comprobar el total facturado contra ese pedido
     // en ese mes
     var rs = from lf in ctx.LinFacturas
              where lf.NumeroPedido == pedido.NumPedido &&
                    (lf.FechaEmision >= primerDiaDelMes && lf.FechaEmision <= ultimoDiaDelMes)
                    && lf.CabFactura.CabFacturaId != factura.CabFacturaId
              select lf;
     decimal totalFacturado = rs.AsEnumerable().Sum(x => x.Importe);
     decimal totalPedido = pedido.TotalPedido;
     // ahora la comprobación devolvemos pendiente
     if (totalFacturado < totalPedido)
         r = (totalPedido - totalFacturado);
     return r;
 }
Ejemplo n.º 2
0
 // este método se ejecutará de manera asíncrona.
 public string LaunchFactura(out int threadId)
 {
     threadId = Thread.CurrentThread.ManagedThreadId;
     // abrir conexiones 
     PortalProContext ctx = new PortalProContext();
     string strConnect = ConfigurationManager.ConnectionStrings["PortalProTestConnection"].ConnectionString;
     SqlConnection con = new SqlConnection(strConnect);
     con.Open();
     string sql = "SELECT COUNT(*) FROM [PortalProTest].[dbo].[Cau_PortalPro_VCabFactura]";
     SqlCommand cmd = new SqlCommand(sql, con);
     int totreg = (int)cmd.ExecuteScalar();
     int numreg = 0;
     sql = @"SELECT  
                 [ACCOUNTNUM]
                 ,[IDEMPRESA]
                 ,[INVOICEID]
                 ,[INVOICEDATE]
                 ,[INVOICEAMOUNT]
                 ,[FECHAPAGO]
                 ,[ESTADI]
                 ,[FECHAVENCIMIENTO]
             FROM [PortalProTest].[dbo].[Cau_PortalPro_VCabFactura]";
     cmd = new SqlCommand(sql, con);
     SqlDataReader dr = cmd.ExecuteReader();
     while (dr.Read())
     {
         numreg++;
         string codAxProveedor = dr.GetString(0);
         string numFactura = dr.GetString(2);
         DateTime fechaFactura = dr.GetDateTime(3);
         Proveedor proveedor = (from pr in ctx.Proveedors
                                where pr.CodAx == codAxProveedor
                                select pr).FirstOrDefault<Proveedor>();
         // Buscamos si la fcatura ya existe
         CabFactura fac = (from f in ctx.CabFacturas
                           where f.NumFactura == numFactura &&
                                 f.FechaEmision == fechaFactura
                           select f).FirstOrDefault<CabFactura>();
         if (fac == null)
         {
             fac = new CabFactura();
             fac.FechaAlta = DateTime.Now;
             ctx.Add(fac);
         }
         fac.Proveedor = proveedor;
         fac.NumFactura = numFactura;
         fac.FechaEmision = fechaFactura;
         fac.Empresa = (from e in ctx.Empresas
                        where e.CodAx == dr.GetString(1)
                        select e).FirstOrDefault<Empresa>();
         string estado = dr.GetString(6);
         switch (estado)
         {
             case "Pagado":
                 fac.Estado = "PAGADA";
                 break;
             case "Recibido":
                 fac.Estado = "PROCESADA";
                 break;
         }
         fac.TotalFactura = dr.GetDecimal(4);
         if (!dr.IsDBNull(5))
             fac.FechaCobro = dr.GetDateTime(5);
         if (!dr.IsDBNull(7))
             fac.FechaPrevistaCobro = dr.GetDateTime(7);
         try
         {
             ctx.SaveChanges();
         }
         catch (Exception ex)
         {
         }
         // cargar las lineas
         try
         {
             LoadAssociateLines(numFactura, fechaFactura);
         }
         catch (Exception ex)
         {
         }
         // Actualizar los registros de proceso
         Progresos progreso = (from p in ctx.Progresos
                               where p.ProgresoId == 4
                               select p).FirstOrDefault<Progresos>();
         if (progreso != null)
         {
             progreso.NumReg = numreg;
             progreso.TotReg = totreg;
             ctx.SaveChanges();
         }
     }
     dr.Close();
     ctx.Dispose();
     con.Close();
     con.Dispose();
     return "";
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Modificar una cabecera de factura. En el cuerpo del mensaje se envía en el formato adecuado el objeto con los datos modificados
 /// </summary>
 /// <param name="id"> Identificador único de la cabecera de factura </param>
 /// <param name="factura">Cabecera de factura los valores que se desean en sus atributos</param>
 /// <param name="tk"> Tique de autorización (Ver 'Login')</param>
 /// <returns></returns>
 public virtual CabFactura Put(int id, CabFactura factura, string tk)
 {
     using (PortalProContext ctx = new PortalProContext())
     {
         // comprobar el tique
         if (!CntWebApiSeguridad.CheckTicket(tk, ctx))
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (CabFactura)"));
         }
         // comprobar los formatos
         if (factura == null || id != factura.CabFacturaId)
         {
             throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
         }
         // primero buscamos si un factura con ese id existe
         CabFactura cfac = (from f in ctx.CabFacturas
                            where f.CabFacturaId == id
                            select f).FirstOrDefault<CabFactura>();
         // existe?
         if (cfac == null)
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay una factura con el id proporcionado (CabFactura)"));
         }
         if (factura.Estado == "PROCESADA")
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Las facturas procesadas no pueden ser modificadas (CabFactura)"));
         }
         // comprobamos que no hay una factura para el mismo proveedor en ese año y con
         // el mismo número de factura
         CabFactura fc = PortalProWebUtility.YaExisteUnaFacturaComoEsta(factura, ctx);
         if (fc != null)
         {
             string m = String.Format("Ya hay una factura del proveedor para este año {0:yyyy} con el mismo número {1}", fc.FechaEmision, fc.NumFactura);
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, m));
         }
         // Controlamos las propiedades que son en realidad objetos.
         int proveedorId = 0;
         if (factura.Proveedor != null)
         {
             proveedorId = factura.Proveedor.ProveedorId;
             factura.Proveedor = null;
         }
         int documentoPdfId = 0;
         if (factura.DocumentoPdf != null)
         {
             documentoPdfId = factura.DocumentoPdf.DocumentoId;
             factura.DocumentoPdf = null;
         }
         int documentoXmlId = 0;
         if (factura.DocumentoXml != null)
         {
             documentoXmlId = factura.DocumentoXml.DocumentoId;
             factura.DocumentoXml = null;
         }
         int empresaId = 0;
         if (factura.Empresa != null)
         {
             empresaId = factura.Empresa.EmpresaId;
             factura.Empresa = null;
         }
         int responsableId = 0;
         if (factura.Responsable != null)
         {
             responsableId = factura.Responsable.ResponsableId;
             factura.Responsable = null;
         }
         // modificar el objeto
         if (factura.Estado == null)
             factura.Estado = "ACEPTADA";
         ctx.AttachCopy<CabFactura>(factura);
         // volvemos a leer el objecto para que lo maneje este contexto.
         factura = (from f in ctx.CabFacturas
                    where f.CabFacturaId == id
                    select f).FirstOrDefault<CabFactura>();
         if (proveedorId != 0)
         {
             factura.Proveedor = (from p in ctx.Proveedors
                                  where p.ProveedorId == proveedorId
                                  select p).FirstOrDefault<Proveedor>();
         }
         if (documentoPdfId != 0)
         {
             factura.DocumentoPdf = (from d in ctx.Documentos
                                     where d.DocumentoId == documentoPdfId
                                     select d).FirstOrDefault<Documento>();
         }
         if (documentoXmlId != 0)
         {
             factura.DocumentoXml = (from d in ctx.Documentos
                                     where d.DocumentoId == documentoXmlId
                                     select d).FirstOrDefault<Documento>();
         }
         if (empresaId != 0)
         {
             factura.Empresa = (from e in ctx.Empresas
                                where e.EmpresaId == empresaId
                                select e).FirstOrDefault<Empresa>();
         }
         if (responsableId != 0)
         {
             factura.Responsable = (from r in ctx.Responsables
                                    where r.ResponsableId == responsableId
                                    select r).FirstOrDefault<Responsable>();
         }
         factura.Historial += String.Format("{0:dd/MM/yyyy hh:mm:ss} La factura {1} con Total {2:0.0} € has sido modificada con estado {3} <br/>",
             DateTime.Now, factura.NumFactura, factura.TotalFactura, factura.Estado);
         factura.Generada = false;
         ctx.SaveChanges();
         return ctx.CreateDetachedCopy<CabFactura>(factura, x => x.Proveedor, x => x.DocumentoPdf, x => x.DocumentoXml);
     }
 }
Ejemplo n.º 4
0
 public virtual CabFactura Post(CabFactura factura, string userId, string tk)
 {
     using (PortalProContext ctx = new PortalProContext())
     {
         // comprobar el tique
         if (!CntWebApiSeguridad.CheckTicket(tk, ctx))
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (CabFactura)"));
         }
         // comprobar las precondiciones
         if (factura == null)
         {
             throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
         }
         // comprobamos que no hay una factura para el mismo proveedor en ese año y con
         // el mismo número de factura
         CabFactura f = PortalProWebUtility.YaExisteUnaFacturaComoEsta(factura, ctx);
         if (f != null)
         {
             string m = String.Format("Ya hay una factura del proveedor para este año {0:yyyy} con el mismo número {1}", f.FechaEmision, f.NumFactura);
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, m));
         }
         // La aplicación ahora depende del comienzo del usuario
         string application = "PortalPro";
         switch (userId.Substring(0, 1))
         {
             case "U":
                 application = "PortalPro2";
                 break;
             case "G":
                 application = "PortalPro";
                 break;
         }
         // comprobamos si existen los ficheros que necesitamos
         string fPdf = PortalProWebUtility.BuscarArchivoCargado(application, userId, "Factura", "PDF");
         if (fPdf == "")
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Se necesita un fichero PDF asociado a la factura (CabFactura)"));
         }
         // el archivo Xml no es obligatorio, pero si lo han subido cargamos el fichero
         string fXml = PortalProWebUtility.BuscarArchivoCargado(application, userId, "Factura", "XML");
         // Controlamos las propiedades que son en realidad objetos.
         int proveedorId = 0;
         if (factura.Proveedor != null)
         {
             proveedorId = factura.Proveedor.ProveedorId;
             factura.Proveedor = null;
         }
         int documentoPdfId = 0;
         if (factura.DocumentoPdf != null)
         {
             documentoPdfId = factura.DocumentoPdf.DocumentoId;
             factura.DocumentoPdf = null;
         }
         int documentoXmlId = 0;
         if (factura.DocumentoXml != null)
         {
             documentoXmlId = factura.DocumentoXml.DocumentoId;
             factura.DocumentoXml = null;
         }
         int empresaId = 0;
         if (factura.Empresa != null)
         {
             empresaId = factura.Empresa.EmpresaId;
             factura.Empresa = null;
         }
         int responsableId = 0;
         if (factura.Responsable != null)
         {
             responsableId = factura.Responsable.ResponsableId;
             factura.Responsable = null;
         }
         // dar de alta el objeto en la base de datos y devolverlo en el mensaje
         factura.Estado = "ACEPTADA";
         ctx.Add(factura);
         if (proveedorId != 0)
         {
             factura.Proveedor = (from p in ctx.Proveedors
                                  where p.ProveedorId == proveedorId
                                  select p).FirstOrDefault<Proveedor>();
         }
         if (documentoPdfId != 0)
         {
             factura.DocumentoPdf = (from d in ctx.Documentos
                                     where d.DocumentoId == documentoPdfId
                                     select d).FirstOrDefault<Documento>();
         }
         if (documentoXmlId != 0)
         {
             factura.DocumentoXml = (from d in ctx.Documentos
                                     where d.DocumentoId == documentoXmlId
                                     select d).FirstOrDefault<Documento>();
         }
         if (fPdf != "")
         {
             factura.DocumentoPdf = PortalProWebUtility.CrearDocumentoDesdeArchivoCargado(application, fPdf, ctx);
         }
         if (fXml != "")
         {
             factura.DocumentoXml = PortalProWebUtility.CrearDocumentoDesdeArchivoCargado(application, fXml, ctx);
         }
         if (empresaId != 0)
         {
             factura.Empresa = (from e in ctx.Empresas
                                where e.EmpresaId == empresaId
                                select e).FirstOrDefault<Empresa>();
         }
         if (responsableId != 0)
         {
             factura.Responsable = (from r in ctx.Responsables
                                    where r.ResponsableId == responsableId
                                    select r).FirstOrDefault<Responsable>();
         }
         factura.FechaAlta = DateTime.Now;
         factura.Historial += String.Format("{0:dd/MM/yyyy hh:mm:ss} La factura {1} con Total {2:0.0} € has sido creada con estado {3} <br/>",
             DateTime.Now, factura.NumFactura, factura.TotalFactura, factura.Estado);
         ctx.SaveChanges();
         return ctx.CreateDetachedCopy<CabFactura>(factura, x => x.Proveedor, x => x.DocumentoPdf, x => x.DocumentoXml);
     }
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Crear un nueva cabecera de factura
 /// </summary>
 /// <param name="CabFactura">Objeto a crear, el atributo CabFacturaId lo genera la aplicación y es devuelto en el objeto incluido en la respuesta.</param>
 /// <param name="tk"> Tique de autorzación (se debe obtener con la accion Login)</param>
 /// <returns></returns>
 public virtual CabFactura Post(CabFactura factura, string tk)
 {
     using (PortalProContext ctx = new PortalProContext())
     {
         // comprobar el tique
         if (!CntWebApiSeguridad.CheckTicket(tk, ctx))
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (CabFactura)"));
         }
         // comprobar las precondiciones
         if (factura == null)
         {
             throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
         }
         // comprobamos que no hay una factura para el mismo proveedor en ese año y con
         // el mismo número de factura
         CabFactura f = PortalProWebUtility.YaExisteUnaFacturaComoEsta(factura, ctx);
         if (f != null)
         {
             string m = String.Format("Ya hay una factura del proveedor para este año {0:yyyy} con el mismo número {1}", f.FechaEmision, f.NumFactura);
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, m));
         }
         // Controlamos las propiedades que son en realidad objetos.
         int proveedorId = 0;
         if (factura.Proveedor != null)
         {
             proveedorId = factura.Proveedor.ProveedorId;
             factura.Proveedor = null;
         }
         int documentoPdfId = 0;
         if (factura.DocumentoPdf != null)
         {
             documentoPdfId = factura.DocumentoPdf.DocumentoId;
             factura.DocumentoPdf = null;
         }
         int documentoXmlId = 0;
         if (factura.DocumentoXml != null)
         {
             documentoXmlId = factura.DocumentoXml.DocumentoId;
             factura.DocumentoXml = null;
         }
         int empresaId = 0;
         if (factura.Empresa != null) 
         {
             empresaId = factura.Empresa.EmpresaId;
             factura.Empresa = null;
         }
         int responsableId = 0;
         if (factura.Responsable != null)
         {
             responsableId = factura.Responsable.ResponsableId;
             factura.Responsable = null;
         }
         // las facturas por defecto tienen el estado recibida
         factura.Estado = "ACEPTADA";
         // dar de alta el objeto en la base de datos y devolverlo en el mensaje
         ctx.Add(factura);
         if (proveedorId != 0)
         {
             factura.Proveedor = (from p in ctx.Proveedors
                                  where p.ProveedorId == proveedorId
                                  select p).FirstOrDefault<Proveedor>();
         }
         if (documentoPdfId != 0)
         {
             factura.DocumentoPdf = (from d in ctx.Documentos
                                     where d.DocumentoId == documentoPdfId
                                     select d).FirstOrDefault<Documento>();
         }
         if (documentoXmlId != 0)
         {
             factura.DocumentoXml = (from d in ctx.Documentos
                                     where d.DocumentoId == documentoXmlId
                                     select d).FirstOrDefault<Documento>();
         }
         if (empresaId != 0)
         {
             factura.Empresa = (from e in ctx.Empresas
                                where e.EmpresaId == empresaId
                                select e).FirstOrDefault<Empresa>();
         }
         if (responsableId != 0)
         {
             factura.Responsable = (from r in ctx.Responsables
                                    where r.ResponsableId == responsableId
                                    select r).FirstOrDefault<Responsable>();
         }
         factura.FechaAlta = DateTime.Now;
         factura.Historial += String.Format("{0:dd/MM/yyyy hh:mm:ss} La factura {1} con Total {2:0.0} € has sido creada con estado {3} <br/>",
             DateTime.Now, factura.NumFactura, factura.TotalFactura, factura.Estado);
         ctx.SaveChanges();
         return ctx.CreateDetachedCopy<CabFactura>(factura, x => x.Proveedor, x => x.DocumentoPdf, x => x.DocumentoXml);
     }
 }
Ejemplo n.º 6
0
 public static void CrearLineasFacturaDesdeUnPedido(CabFactura factura, Pedido pedido, PortalProContext ctx)
 {
     // procesamos secuencialmente las lineas de este pedido.
     foreach (LinPedido lp in pedido.LinPedidos)
     {
         // la primera condición es que quede algo que facturar
         if (lp.Facturado < lp.Importe)
         {
             decimal importe = lp.Importe - lp.Facturado;
             LinFactura lf = new LinFactura();
             lf.CabFactura = factura;
             lf.Descripcion = lp.Descripcion;
             lf.Importe = importe;
             lf.NumeroPedido = lp.NumPedido;
             lf.NumLineaPedido = lp.NumLinea;
             factura.TotalFactura += importe;
             ctx.Add(lf);
             ctx.SaveChanges();
         }
     }
 }
Ejemplo n.º 7
0
 public static void CrearLineasFacturaDesdePedidos(CabFactura factura, int[] pedidos, PortalProContext ctx)
 {
     for (int i = 0; i < pedidos.Length; i++)
     {
         Pedido ped = (from p in ctx.Pedidos
                       where p.PedidoId == pedidos[i]
                       select p).FirstOrDefault<Pedido>();
         CrearLineasFacturaDesdeUnPedido(factura, ped, ctx);
     }
 }
Ejemplo n.º 8
0
 public static CabFactura GenerarFacturaDesdePedidos(int[] pedidos, PortalProContext ctx)
 {
     CabFactura factura = null; // provisional
     if (pedidos.Length == 0) return factura; // está vacío el array de ids
     if (!TodosLosPedidosExisten(pedidos, ctx)) return factura; // no existen todos los pedidos de la lista
     // creamos la cabecera de factura
     factura = new CabFactura();
     factura.Generada = true;
     factura.FechaAlta = DateTime.Now;
     // obtenemos el proveedor del primer pedido, en teoría todos son del mismo
     Pedido ped = (from p in ctx.Pedidos
                   where p.PedidoId == pedidos[0]
                   select p).FirstOrDefault<Pedido>();
     factura.Proveedor = ped.Proveedor;
     ctx.Add(factura);
     ctx.SaveChanges();
     CrearLineasFacturaDesdePedidos(factura, pedidos, ctx);
     return factura;
 }
Ejemplo n.º 9
0
 public static CabFactura YaExisteUnaFacturaComoEsta(CabFactura factura, PortalProContext ctx)
 {
     // obtener el año de la fecha de factura.
     DateTime fechaEmision = (DateTime)factura.FechaEmision;
     int ano = fechaEmision.Year;
     // primer y último día de ese año.
     DateTime primerDia = new DateTime(ano, 1, 1);
     DateTime ultimoDia = new DateTime(ano, 12, 31);
     CabFactura fac = null;
     if (factura.CabFacturaId != 0)
     {
         fac = (from f in ctx.CabFacturas
                where f.Proveedor.ProveedorId == factura.Proveedor.ProveedorId &&
                      f.NumFactura == factura.NumFactura &&
                      f.FechaEmision >= primerDia &&
                      f.FechaEmision <= ultimoDia &&
                      f.CabFacturaId != factura.CabFacturaId
                select f).FirstOrDefault<CabFactura>();
     }
     else
     {
         fac = (from f in ctx.CabFacturas
                where f.Proveedor.ProveedorId == factura.Proveedor.ProveedorId &&
                      f.NumFactura == factura.NumFactura &&
                      f.FechaEmision >= primerDia &&
                      f.FechaEmision <= ultimoDia
                select f).FirstOrDefault<CabFactura>();
     }
     return fac;
 }
Ejemplo n.º 10
0
 public static string ComprobarLineaFacturaContraPedido(CabFactura factura, LinFactura l, PortalProContext ctx)
 {
     string m = "";
     // (1) comprobar que el pedido existe
     Pedido p = (from ped in ctx.Pedidos
                 where ped.NumPedido == l.NumeroPedido
                 select ped).FirstOrDefault<Pedido>();
     if (p == null)
     {
         m = String.Format("El pedido {0} no existe.", l.NumeroPedido);
         return m;
     }
     // ahora se compara contra línea, luego hay que buscar la línea correspondiente
     LinPedido lp = (from linped in ctx.LinPedidos
                     where linped.NumPedido == l.NumeroPedido
                     && linped.NumLinea == l.NumLineaPedido
                     select linped).FirstOrDefault<LinPedido>();
     if (lp == null)
     {
         m = String.Format("El linea {0} del pedido {1} no existe.",l.NumLineaPedido, l.NumeroPedido);
         return m;
     }
     // Obtener parámetros y datos de proveedor para verificar márgenes
     Parametro parametro = (from par in ctx.Parametros1
                            where par.ParametroId == 1
                            select par).FirstOrDefault<Parametro>();
     Proveedor proveedor = p.Proveedor;
     //
     bool facAbierto = parametro.FacturaAbierto;
     facAbierto = proveedor.FacAbierto;
     int margen = parametro.MargenFactura;
     if (p.Estado == "FACTURADO" || p.Estado == "CANCELADO")
     {
         m = String.Format("El pedido {0} ya ha sido facturado o está cancelado.", l.NumeroPedido);
         return m;
     }
     if (p.Proveedor.ProveedorId != factura.Proveedor.ProveedorId)
     {
         m = String.Format("El pedido {0} no corresponde al proveedor {1}", l.NumeroPedido, factura.Proveedor.NombreComercial);
         return m;
     }
     // (2) comprobar que el importe que se va a facturar es menor o igual que el del pedido
     if (l.Importe > ((lp.Importe - lp.Facturado) + margen))
     {
         m = String.Format("El importe {0:##,###,##0.00} supera el resto por facturar del pedido {1} linea {2}.", l.Importe, l.NumeroPedido, l.NumLineaPedido);
         return m;
     }
     // el estado por defecto de una factura es ACEPTADA, pero si es de un pedido ABIERTO  deberá ser RECIBIDA
     if (lp.Estado == "ABIERTO")
     {
         if (facAbierto)
         {
             factura.Estado = "RECIBIDA2";
             factura.Historial += String.Format("{0:dd/MM/yyyy hh:mm:ss} La factura {1} pasa a estado {3} debido a que el pedido {4} linea {5} no está recibido, se espera a su aceptación manual <br/>",
                 DateTime.Now, factura.NumFactura, factura.TotalFactura, factura.Estado, lp.NumPedido, lp.NumLinea);
         }
         else
         {
             m = String.Format("El pedido {0} linea {1} no está recibido, no puede emitir la factura contra él", lp.NumPedido, lp.NumLinea);
             return m;
         }
     }
     // si llega aquí es una linea a dar de alta.
     lp.Facturado = l.Importe;
     factura.TotalFactura += l.Importe;
     p.TotalFacturado += l.Importe;
     // actualizar empresa y responsables
     factura.Empresa = p.Empresa;
     factura.Responsable = p.Responsable;
     l.CabFactura = factura;
     ctx.Add(l);
     ctx.SaveChanges();
     return m;
 }
Ejemplo n.º 11
0
        public static CabFactura GenerarFacturaDesdePedido(Pedido p, PortalProContext ctx)
        {
            CabFactura f = new CabFactura()
            {
                CabFacturaId = 0,
                Proveedor = p.Proveedor,
                FechaAlta = DateTime.Now,
                Empresa = p.Empresa,
                Responsable = p.Responsable,
                Estado = "INCIDENCIA"
            };
            ctx.Add(f);
            ctx.SaveChanges();
            decimal totalF = 0;
            if (p.TotalFacturado == 0)
            {
                // caso (1) es el más sencillo, una factura con tantas líneas como tenga el pedido
                foreach (LinPedido lp in p.LinPedidos)
                {
                    ctx.Add(new LinFactura()
                    {
                        LinFacturaId = 0,
                        NumeroPedido = p.NumPedido,
                        Importe = lp.Importe,
                        Descripcion = lp.Descripcion,
                        PorcentajeIva = 0,
                        CabFactura = f
                    });
                    f.TotalFactura += lp.Importe;
                    p.TotalFacturado += lp.Importe;
                    ctx.SaveChanges();
                }
            }
            else
            {
                // caso (2) generaremos una única linea con el resto del pedido
                ctx.Add(new LinFactura()
                {
                    LinFacturaId = 0,
                    NumeroPedido = p.NumPedido,
                    Importe = p.TotalPedido - p.TotalFacturado,
                    Descripcion = "Resto de pedido",
                    PorcentajeIva = 0,
                    CabFactura = f
                });
                f.TotalFactura = p.TotalPedido - p.TotalFacturado;
                p.TotalFacturado = p.TotalPedido;
                ctx.SaveChanges();
            }

            return f;
        }
Ejemplo n.º 12
0
 public static string ComprobarLineaFacturaContraPedidoSuscripcion(CabFactura factura, LinFactura l, PortalProContext ctx)
 {
     string m = "";
     // (1) comprobar que el pedido existe
     Pedido p = (from ped in ctx.Pedidos
                 where ped.NumPedido == l.NumeroPedido
                 select ped).FirstOrDefault<Pedido>();
     if (p == null)
     {
         m = String.Format("El pedido {0} no existe.", l.NumeroPedido);
         return m;
     }
     // ahora se compara contra línea, luego hay que buscar la línea correspondiente
     LinPedido lp = (from linped in ctx.LinPedidos
                     where linped.NumPedido == l.NumeroPedido
                     && linped.NumLinea == l.NumLineaPedido
                     select linped).FirstOrDefault<LinPedido>();
     if (lp == null)
     {
         m = String.Format("El linea {0} del pedido {1} no existe.", l.NumLineaPedido, l.NumeroPedido);
         return m;
     }
     // Obtener parámetros y datos de proveedor para verificar márgenes
     Parametro parametro = (from par in ctx.Parametros1
                            where par.ParametroId == 1
                            select par).FirstOrDefault<Parametro>();
     Proveedor proveedor = p.Proveedor;
     // comprobamos las reglas para pedido de suscripcion
     decimal importeAFacturar = PedidoSuscripcionImporteFacturable(p, factura, ctx);
     if (importeAFacturar == 0)
     {
         m = String.Format("NO se puede facturar con esta fecha e importe contra el pedido de suscripción {0}", p.NumPedido);
         return m;
     }
     l.NumeroPedido = p.NumPedido;
     l.NumLineaPedido = lp.NumLinea;
     l.Importe = importeAFacturar;
     l.Descripcion = lp.Descripcion;
     l.PorcentajeIva = lp.PorcentajeIva;
     // actualizar empresa y responsables
     factura.Empresa = p.Empresa;
     factura.Responsable = p.Responsable;
     factura.TotalFactura += l.Importe;
     l.CabFactura = factura;
     // antes de salir conmprobamos si el total facturado supera
     // el margen de control PDF
     if (factura.TotalFactura > parametro.MaxImportePdf)
     {
         factura.Estado = "RECIBIDA2";
         factura.Historial += String.Format("{0:dd/MM/yyyy hh:mm:ss} La factura {1} pasa a estado INCIDENCIA debido a que su total {2} supera al margen de control PDF {4} <br/>",
             DateTime.Now, factura.NumFactura, factura.TotalFactura, factura.Estado, parametro.MaxImportePdf);
     }
     ctx.Add(l);
     ctx.SaveChanges();
     return m;
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Genera una factura de una sola linea con el importe
 /// pasado y a partir del pedido indicado.
 /// </summary>
 /// <param name="pedido">Pedido para el que se genera la factura</param>
 /// <param name="importe">Importe a facturar</param>
 /// <param name="ctx">Contexto OpenAccess</param>
 /// <returns></returns>
 public static CabFactura PedidoSuscripcionGenerarFactura(Pedido pedido, decimal importe, PortalProContext ctx)
 {
     CabFactura factura = null;
     // evitamos que se cuele un importe a 0
     if (importe == 0) return factura;
     // el pedido debe tener lineas
     if (pedido.LinPedidos.Count < 1) return factura;
     // creamos la factura.
     factura = new CabFactura();
     factura.FechaAlta = DateTime.Now;
     factura.TotalFactura = importe;
     factura.Estado = "RECIBIDA";
     factura.Generada = true;
     factura.Proveedor = pedido.Proveedor;
     factura.Empresa = pedido.Empresa;
     factura.Responsable = pedido.Responsable;
     ctx.Add(factura);
     ctx.SaveChanges();
     // creamos una línea única con el importe
     LinFactura lfactura = new LinFactura();
     lfactura.CabFactura = factura;
     lfactura.NumeroPedido = pedido.NumPedido;
     lfactura.Importe = importe;
     // usamos la primera línea que obtengamos del pedido
     // como modelo
     LinPedido lpedido = pedido.LinPedidos[0];
     lfactura.Descripcion = lpedido.Descripcion;
     lfactura.PorcentajeIva = lpedido.PorcentajeIva;
     lfactura.NumeroPedido = lpedido.NumPedido;
     lfactura.NumLineaPedido = lpedido.NumLinea;
     lpedido.Facturado += importe;
     if (factura.FechaEmision != null)
         lfactura.FechaEmision = (DateTime)factura.FechaEmision;
     ctx.Add(lfactura);
     ctx.SaveChanges();
     return factura;
 }
Ejemplo n.º 14
0
        public virtual CabFactura Put(int id, CabFactura factura, string userId, string tk, string gen)
        {
            using (PortalProContext ctx = new PortalProContext())
            {
                // comprobar el tique
                if (!CntWebApiSeguridad.CheckTicket(tk, ctx))
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (CabFactura)"));
                }
                // comprobar los formatos
                if (factura == null || id != factura.CabFacturaId)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
                }
                // primero buscamos si un factura con ese id existe
                CabFactura cfac = (from f in ctx.CabFacturas
                                   where f.CabFacturaId == id
                                   select f).FirstOrDefault<CabFactura>();
                // existe?
                if (cfac == null)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay una factura con el id proporcionado (CabFactura)"));
                }
                if (factura.Estado == "PROCESADA")
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Las facturas procesadas no pueden ser modificadas (CabFactura)"));
                }
                // comprobamos que no hay una factura para el mismo proveedor en ese año y con
                // el mismo número de factura
                CabFactura fc = PortalProWebUtility.YaExisteUnaFacturaComoEsta(factura, ctx);
                if (fc != null)
                {
                    string m = String.Format("Ya hay una factura del proveedor para este año {0:yyyy} con el mismo número {1}", fc.FechaEmision, fc.NumFactura);
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, m));
                }

                string application = "PortalPro";
                switch (userId.Substring(0, 1))
                {
                    case "U":
                        application = "PortalPro2";
                        break;
                    case "G":
                        application = "PortalPro";
                        break;
                }
                // En la actualización a lo mejor no han cargado ningún archivo
                string fPdf = PortalProWebUtility.BuscarArchivoCargado(application, userId, "Factura", "PDF");
                if (fPdf == "")
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Se necesita un fichero PDF asociado a la factura (CabFactura)"));
                }
                // el archivo Xml no es obligatorio, pero si lo han subido cargamos el fichero
                string fXml = PortalProWebUtility.BuscarArchivoCargado(application, userId, "Factura", "XML");
                // Controlamos las propiedades que son en realidad objetos.
                int proveedorId = 0;
                if (factura.Proveedor != null)
                {
                    proveedorId = factura.Proveedor.ProveedorId;
                    factura.Proveedor = null;
                }
                int documentoPdfId = 0;
                if (factura.DocumentoPdf != null)
                {
                    documentoPdfId = factura.DocumentoPdf.DocumentoId;
                    factura.DocumentoPdf = null;
                }
                int documentoXmlId = 0;
                if (factura.DocumentoXml != null)
                {
                    documentoXmlId = factura.DocumentoXml.DocumentoId;
                    factura.DocumentoXml = null;
                }
                int empresaId = 0;
                if (factura.Empresa != null)
                {
                    empresaId = factura.Empresa.EmpresaId;
                    factura.Empresa = null;
                }
                int responsableId = 0;
                if (factura.Responsable != null)
                {
                    responsableId = factura.Responsable.ResponsableId;
                    factura.Responsable = null;
                }
                if (factura.Estado == null)
                    factura.Estado = "ACEPTADA";
                // modificar el objeto
                ctx.AttachCopy<CabFactura>(factura);
                // volvemos a leer el objecto para que lo maneje este contexto.
                factura = (from f in ctx.CabFacturas
                           where f.CabFacturaId == id
                           select f).FirstOrDefault<CabFactura>();
                if (proveedorId != 0)
                {
                    factura.Proveedor = (from p in ctx.Proveedors
                                         where p.ProveedorId == proveedorId
                                         select p).FirstOrDefault<Proveedor>();
                }
                if (documentoPdfId != 0)
                {
                    factura.DocumentoPdf = (from d in ctx.Documentos
                                            where d.DocumentoId == documentoPdfId
                                            select d).FirstOrDefault<Documento>();
                }
                if (documentoXmlId != 0)
                {
                    factura.DocumentoXml = (from d in ctx.Documentos
                                            where d.DocumentoId == documentoXmlId
                                            select d).FirstOrDefault<Documento>();
                }
                if (empresaId != 0)
                {
                    factura.Empresa = (from e in ctx.Empresas
                                       where e.EmpresaId == empresaId
                                       select e).FirstOrDefault<Empresa>();
                }
                if (responsableId != 0)
                {
                    factura.Responsable = (from r in ctx.Responsables
                                           where r.ResponsableId == responsableId
                                           select r).FirstOrDefault<Responsable>();
                }
                Documento doc = null; // para cargar temporalmente documentos
                // si se cumplen estas condiciones es que han cambiado el archivo asociado.
                if (fPdf != "")
                {
                    doc = factura.DocumentoPdf;
                    factura.DocumentoPdf = PortalProWebUtility.CrearDocumentoDesdeArchivoCargado(application, fPdf, ctx);
                    PortalProWebUtility.EliminarDocumento(doc, ctx);
                }
                if (fXml != "")
                {
                    doc = factura.DocumentoXml;
                    factura.DocumentoXml = PortalProWebUtility.CrearDocumentoDesdeArchivoCargado(application, fXml, ctx);
                    PortalProWebUtility.EliminarDocumento(doc, ctx);
                }
                factura.Historial += String.Format("{0:dd/MM/yyyy hh:mm:ss} La factura {1} con Total {2:0.0} € has sido modificada con estado {3} <br/>",
                    DateTime.Now, factura.NumFactura, factura.TotalFactura, factura.Estado);
                factura.Generada = false; ;
                ctx.SaveChanges();
                return ctx.CreateDetachedCopy<CabFactura>(factura, x => x.Proveedor, x => x.DocumentoPdf, x => x.DocumentoXml);
            }
        }