public bool SavePaquete(Paquetes paquete)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             if (db.Paquetes.Any(p => p.Descripcion == paquete.Descripcion))
             {
                 throw new FaultException("Descripción duplicada");
             }
             if (paquete.IdPaquete == 0)
             {
                 db.AddToPaquetes(paquete);
                 db.SaveChanges();
             }
             else
             {
                 var pa = db.Paquetes.Where(p => p.IdPaquete == paquete.IdPaquete).FirstOrDefault();
                 db.Paquetes.ApplyCurrentValues(paquete);
                 db.SaveChanges();
             }
             return(true);
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(false);
     }
 }
示例#2
0
        public bool EliminarCliente(clientes cliente)
        {
            try
            {
                Logger.Info(cliente);

                using (var db = new NtLinkLocalServiceEntities())
                {
                    var existe = db.facturas.Any(p => p.idcliente == cliente.idCliente);
                    if (existe)
                    {
                        throw new FaultException("El cliente tiene facturas capturadas, no es posible eliminar");
                    }
                    var cli = db.clientes.FirstOrDefault(c => c.idCliente == cliente.idCliente);
                    db.clientes.DeleteObject(cli);
                    db.SaveChanges();
                    return(true);
                }
            }
            catch (FaultException fe)
            {
                throw;
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
 public void GuardarDisContrato(DistContratos contrato)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             if (contrato.IdContrato == 0)
             {
                 db.DistContratos.AddObject(contrato);
             }
             else
             {
                 db.DistContratos.FirstOrDefault(p => p.IdContrato == contrato.IdContrato);
                 db.DistContratos.ApplyCurrentValues(contrato);
             }
             db.SaveChanges();
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
     }
 }
示例#4
0
 public int GuardarPago(decimal importe, DateTime fecha, string observaciones, decimal pendiente, string referencia)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             var pago = new Pagos
             {
                 Fecha         = fecha,
                 Importe       = importe,
                 Observaciones = observaciones,
                 Referencia    = referencia,
                 Pendiente     = pendiente
             };
             db.Pagos.AddObject(pago);
             db.SaveChanges();
             return(pago.IdPago);
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(-1);
     }
 }
 public bool SaveSucursal(Sucursales sucursal)
 {
     try
     {
         if (Validar(sucursal))
         {
             using (var db = new NtLinkLocalServiceEntities())
             {
                 if (sucursal.IdSucursal == 0)
                 {
                     db.Sucursales.AddObject(sucursal);
                 }
                 else
                 {
                     var y = db.Sucursales.Where(p => p.IdSucursal == sucursal.IdSucursal).FirstOrDefault();
                     db.Sucursales.ApplyCurrentValues(sucursal);
                 }
                 db.SaveChanges();
                 return(true);
             }
         }
         return(false);
     }
     catch (FaultException fe)
     {
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         return(false);
     }
 }
示例#6
0
 public bool SaveProducto(producto prod)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             if (prod.IdProducto == 0)
             {
                 prod.Creacion     = DateTime.Now;
                 prod.Modificacion = DateTime.Now;
                 //TODO: Buscar usuario de modificacion
                 prod.IdUsuario = 1;
                 db.producto.AddObject(prod);
             }
             else
             {
                 var x = db.producto.FirstOrDefault(p => p.IdProducto == prod.IdProducto);
                 prod.Creacion     = x.Creacion;
                 prod.Modificacion = DateTime.Now;
                 db.producto.ApplyCurrentValues(prod);
             }
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException.Message);
         }
         return(false);
     }
 }
        public int Activar(ActivacionConvertidor A)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    if (A.Id == 0)
                    {
                        db.ActivacionConvertidor.AddObject(A);
                    }
                    else
                    {
                        db.ActivacionConvertidor.Where(p => p.Id == A.Id).FirstOrDefault();
                        db.ActivacionConvertidor.ApplyCurrentValues(A);
                    }
                    db.SaveChanges();
                    return(1);
                }
            }

            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(0);
            }
        }
        public bool Save(empresa e, byte[] logo)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    if (Validar(e))
                    {
                        if (e.IdEmpresa == 0)
                        {
                            if (db.empresa.Any(l => l.RFC.Equals(e.RFC) && l.idSistema == e.idSistema))
                            {
                                throw new FaultException("El RFC ya ha sido dato de alta");
                            }
                            db.empresa.AddObject(e);
                        }
                        else
                        {
                            db.empresa.FirstOrDefault(p => p.IdEmpresa == e.IdEmpresa);
                            db.empresa.ApplyCurrentValues(e);
                        }
                        db.SaveChanges();
                        CreaRutas(e.RFC);

                        string path = Path.Combine(ConfigurationManager.AppSettings["Resources"], e.RFC);
                        if (logo != null)
                        {
                            File.WriteAllBytes(Path.Combine(path, "Logo.png"), logo);
                        }
                        if (e.Baja != true)
                        {
                            throw new FaultException("El RFC ha sido dato de alta");//para que retorne algo si fue exitoso
                        }
                        else
                        {
                            throw new FaultException("El RFC ha sido dato de Baja");//para que retorne algo si fue exitoso
                        }
                        return(true);
                    }
                    return(false);
                }
            }
            catch (ApplicationException ae)
            {
                throw new FaultException(ae.Message);
            }
            catch (FaultException fe)
            {
                throw;
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException.Message);
                }
                return(false);
            }
        }
示例#9
0
 public bool GuardarClientesPromotores(int idCliente, int idPromotor)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             ClientesPromotores cp = new ClientesPromotores
             {
                 IdCliente  = idCliente,
                 IdPromotor = idPromotor
             };
             db.ClientesPromotores.AddObject(cp);
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(false);
     }
 }
示例#10
0
 public bool SaveComisionista(Comisionistas comisionista)
 {
     try
     {
         if (Validar(comisionista))
         {
             using (var db = new NtLinkLocalServiceEntities())
             {
                 if (comisionista.IdComisionista == 0)
                 {
                     db.Comisionistas.AddObject(comisionista);
                 }
                 else
                 {
                     var y = db.Comisionistas.Where(p => p.IdComisionista == comisionista.IdComisionista).FirstOrDefault();
                     db.Comisionistas.ApplyCurrentValues(comisionista);
                 }
                 db.SaveChanges();
                 return(true);
             }
         }
         return(false);
     }
     catch (FaultException fe)
     {
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         return(false);
     }
 }
示例#11
0
 public bool SaveDatosNomina(DatosNomina datos)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             if (datos.IdDatoNomina == 0)
             {
                 db.DatosNomina.AddObject(datos);
             }
             else
             {
                 var y = db.DatosNomina.FirstOrDefault(p => p.IdDatoNomina == datos.IdDatoNomina);
                 db.DatosNomina.ApplyCurrentValues(datos);
             }
             db.SaveChanges();
             return(true);
         }
     }
     catch (FaultException fe)
     {
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(false);
     }
 }
示例#12
0
 public bool SaveList(List <vventas> lista)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             foreach (vventas ventas in lista)
             {
                 vventas  ventas1 = ventas;
                 facturas f       = db.facturas.Where(p => p.idVenta == ventas1.idVenta).First();
                 f.Cancelado      = ventas.Cancelado;
                 f.FechaPago      = ventas.FechaPago;
                 f.ReferenciaPago = ventas.ReferenciaPago;
                 f.Vencimiento    = ventas.Vencimiento;
                 f.Proyecto       = ventas.Proyecto;
                 //_entities.facturas.ApplyCurrentValues(f);
             }
             db.SaveChanges();
         }
         return(true);
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         return(false);
     }
 }
示例#13
0
 public bool Save(empresa e, byte[] cert, byte[] llave, string passwordLlave, byte[] logo)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             if (Validar(e))
             {
                 CreaRutas(e.RFC);
                 string path = Path.Combine(ConfigurationManager.AppSettings["Resources"], e.RFC);
                 if (logo != null)
                 {
                     File.WriteAllBytes(Path.Combine(path, "Logo.png"), logo);
                 }
                 if (!ValidaRfcEmisor(e.RFC, cert))
                 {
                     throw new FaultException("El rfc del emisor no corresponde con el certificado");
                 }
                 string pathCer = Path.Combine(path, "Certs", "csd.cer");
                 string pathKey = Path.Combine(path, "Certs", "csd.key");
                 File.WriteAllBytes(pathCer, cert);
                 File.WriteAllBytes(pathKey, llave);
                 //CertUtil.CreaP12(pathKey, pathCer, passwordLlave, Path.ChangeExtension(pathCer, ".p12"));
                 if (e.IdEmpresa == 0)
                 {
                     if (db.empresa.Any(l => l.RFC.Equals(e.RFC) && l.idSistema == e.idSistema))
                     {
                         throw new FaultException("El RFC ya ha sido dato de alta");
                     }
                     db.empresa.AddObject(e);
                 }
                 else
                 {
                     db.empresa.Where(p => p.IdEmpresa == e.IdEmpresa).FirstOrDefault();
                     db.empresa.ApplyCurrentValues(e);
                 }
                 db.SaveChanges();
                 return(true);
             }
             Logger.Error("Fallo de validación");
             return(false);
         }
     }
     catch (ApplicationException ae)
     {
         throw new FaultException(ae.Message);
     }
     catch (FaultException fe)
     {
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         return(false);
     }
 }
示例#14
0
        public static bool CreateUser(string userName, string password, string eMail, int idEmpresa, string perfil, string nombreCompleto, string iniciales)
        {
            MembershipCreateStatus status = MembershipCreateStatus.ProviderError;

            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    Membership.CreateUser(userName, password, eMail, "uno", "dos", true, out status);
                    Logger.Debug(status.ToString());
                    if (status == MembershipCreateStatus.Success)
                    {
                        UserProfile p = UserProfile.GetUserProfile(userName);
                        p.NombreCompleto = nombreCompleto;
                        p.Iniciales      = iniciales;
                        p.Save();

                        MembershipUser mu = Membership.GetUser(userName);
                        if (mu != null && mu.ProviderUserKey != null)
                        {
                            usuarios_empresas ue = new usuarios_empresas
                            {
                                IdEmpresa = idEmpresa, UserId = mu.ProviderUserKey.ToString()
                            };
                            db.usuarios_empresas.AddObject(ue);
                        }
                        db.SaveChanges();
                        Roles.AddUserToRole(userName, perfil);
                        return(true);
                    }
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
            }
            if (status == MembershipCreateStatus.DuplicateEmail)
            {
                throw new FaultException("Email Duplicado");
            }
            if (status == MembershipCreateStatus.DuplicateUserName)
            {
                throw new FaultException("Usuario Duplicado");
            }
            if (status == MembershipCreateStatus.InvalidPassword)
            {
                throw new FaultException("El password no cumple con las politicas de seguridad");
            }
            return(false);
        }
示例#15
0
 public bool Save(Distribuidores e)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             if (Validar(e))
             {
                 if (e.IdDistribuidor == 0)
                 {
                     if (db.Distribuidores.Any(l => l.Rfc.Equals(e.Rfc) && l.IdDistribuidor == e.IdDistribuidor))
                     {
                         throw new FaultException("El RFC ya ha sido dato de alta");
                     }
                     db.Distribuidores.AddObject(e);
                 }
                 else
                 {
                     db.Distribuidores.FirstOrDefault(p => p.IdDistribuidor == e.IdDistribuidor);
                     db.Distribuidores.ApplyCurrentValues(e);
                 }
                 db.SaveChanges();
                 return(true);
             }
             return(false);
         }
     }
     catch (ApplicationException ae)
     {
         throw new FaultException(ae.Message);
     }
     catch (FaultException fe)
     {
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException.Message);
         }
         return(false);
     }
 }
示例#16
0
        //Guardar Promotores
        public bool GuardarPromotor(Promotores promotor)
        {
            try
            {
                Regex inv = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
                if (!inv.IsMatch(promotor.Email))
                {
                    throw new FaultException("Email incorrecto");
                }

                using (var db = new NtLinkLocalServiceEntities())
                {
                    if (promotor.IdPromotor == 0)
                    {
                        if (db.Promotores.Any(p => p.Email == promotor.Email))
                        {
                            throw new FaultException("Email Duplicado");
                        }
                        db.Promotores.AddObject(promotor);
                    }
                    else
                    {
                        var o = db.Promotores.Where(p => p.IdPromotor == promotor.IdPromotor).FirstOrDefault();
                        db.Promotores.ApplyCurrentValues(promotor);
                    }
                    db.SaveChanges();
                    return(true);
                }
            }
            catch (FaultException fe)
            {
                throw;
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
示例#17
0
        public bool AplicarPago(int idPago, List <FacturasPagos> facturas, DateTime fechaPago)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    foreach (FacturasPagos fp in facturas)
                    {
                        var factura = db.facturas.Where(p => p.idVenta == fp.IdVenta).FirstOrDefault();
                        if (factura != null)
                        {
                            factura.Pagado = (factura.Pagado.HasValue ? factura.Pagado.Value : 0) + fp.Acuenta;
                            if (factura.Pagado >= factura.Importe)
                            {
                                factura.StatusPago = true;
                                factura.FechaPago  = fechaPago;
                            }
                            else
                            {
                                factura.StatusPago = false;
                            }

                            factura.Resta = factura.Importe - factura.Pagado;
                            fp.IdPago     = idPago;
                            db.FacturasPagos.AddObject(fp);
                            db.facturas.ApplyCurrentValues(factura);
                            db.SaveChanges();
                        }
                    }
                    return(true);
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
        public bool GuardarTimbre(TimbreWs33 timbre)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    db.CommandTimeout = 90;

                    if (timbre.IdTimbre == 0)
                    {
                        db.TimbreWs33.AddObject(timbre);
                    }
                    else
                    {
                        if (timbre.StrError == "Hist")
                        {
                            var thist = db.TimbreWsHistorico.FirstOrDefault(p => p.IdTimbre == timbre.IdTimbre);
                            thist.Status           = 2;
                            thist.AcuseCancelacion = timbre.AcuseCancelacion;
                            db.TimbreWsHistorico.ApplyCurrentValues(thist);
                        }
                        else
                        {
                            var t = db.TimbreWs33.FirstOrDefault(p => p.IdTimbre == timbre.IdTimbre);
                            db.TimbreWs33.ApplyCurrentValues(timbre);
                        }
                    }
                    db.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                //throw;
                return(false);
            }
        }
示例#19
0
        public bool CancelarPago(int idPago)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    var pago = db.Pagos.FirstOrDefault(p => p.IdPago == idPago);
                    pago.Cancelado = true;
                    db.Pagos.ApplyCurrentValues(pago);

                    var facturas = db.FacturasPagos.Where(p => p.IdPago == idPago).ToList();
                    foreach (FacturasPagos fp in facturas)
                    {
                        var factura = db.facturas.Where(p => p.idVenta == fp.IdVenta).FirstOrDefault();
                        if (factura != null)
                        {
                            factura.Pagado     = 0;
                            factura.StatusPago = false;
                            factura.FechaPago  = null;
                            factura.StatusPago = false;
                            factura.Resta      = factura.Resta - fp.Acuenta;
                            fp.IdPago          = idPago;
                            db.FacturasPagos.ApplyCurrentValues(fp);
                            db.facturas.ApplyCurrentValues(factura);
                            //db.SaveChanges();
                        }
                    }
                    db.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
示例#20
0
 public bool SaveConceptoCartaPorte(ConceptosCartaPorte concepto)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             db.AddToConceptosCartaPorte(concepto);
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(false);
     }
 }
示例#21
0
 public int GuardarPago(Pagos pago)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             db.Pagos.AddObject(pago);
             db.SaveChanges();
             return(pago.IdPago);
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(0);
     }
 }
示例#22
0
 public void UpdateDistribuidor(int idContrato)
 {
     try
     {
         using (var db = new NtLinkLocalServiceEntities())
         {
             DistContratos contratos = new DistContratos();
             var           y         = db.DistContratos.Where(p => p.IdContrato == idContrato).FirstOrDefault();
             y.Status = "Pagado";
             db.DistContratos.ApplyCurrentValues(y);
             db.SaveChanges();
         }
     }
     catch (Exception ee)
     {
         Logger.Error(ee.Message);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
     }
 }
示例#23
0
        public bool SavePantallas(List <empresaPantalla> pantallas)
        {
            try
            {
                if (pantallas != null && pantallas.Count > 0)
                {
                    int idEmpresa = pantallas.First().idEmpresa;
                    using (var db = new NtLinkLocalServiceEntities())
                    {
                        List <empresaPantalla> currPantallas =
                            db.empresaPantalla.Where(l => l.idEmpresa == idEmpresa).ToList();

                        foreach (var pantalla in currPantallas)
                        {
                            db.empresaPantalla.DeleteObject(pantalla);
                        }

                        foreach (var pantalla in pantallas)
                        {
                            db.empresaPantalla.AddObject(pantalla);
                        }

                        db.SaveChanges();
                    }
                }

                return(true);
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
示例#24
0
        //--------------------------------------------
        public bool SaveConfirmacion(ConfirmacionTimbreWs33 ConfirmacionTimbre)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    var confirma = db.ConfirmacionTimbreWs33.Where(p => p.Folio == ConfirmacionTimbre.Folio && p.RfcEmisor == ConfirmacionTimbre.RfcEmisor && p.RfcReceptor == ConfirmacionTimbre.RfcReceptor).FirstOrDefault();
                    if (confirma == null)
                    {
                        db.ConfirmacionTimbreWs33.AddObject(ConfirmacionTimbre);

                        db.SaveChanges();
                    }
                }


                return(true);
            }
            catch (Exception ee)
            {
                return(false);
            }
        }
示例#25
0
        public bool BorrarClientesPromotores(int idCP)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    ClientesPromotores cp = db.ClientesPromotores.FirstOrDefault(p => p.IdCP == idCP);

                    db.ClientesPromotores.DeleteObject(cp);
                    db.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
示例#26
0
 public int SaveCliente(clientes cliente)
 {
     try
     {
         if (Validar(cliente))
         {
             using (var db = new NtLinkLocalServiceEntities())
             {
                 if (cliente.idCliente == 0)
                 {
                     db.clientes.AddObject(cliente);
                 }
                 else
                 {
                     var y = db.clientes.Where(p => p.idCliente == cliente.idCliente).FirstOrDefault();
                     db.clientes.ApplyCurrentValues(cliente);
                 }
                 db.SaveChanges();
                 return(cliente.idCliente);
             }
         }
         return(0);
     }
     catch (FaultException fe)
     {
         throw;
     }
     catch (Exception ee)
     {
         Logger.Error(ee);
         if (ee.InnerException != null)
         {
             Logger.Error(ee.InnerException);
         }
         return(0);
     }
 }
示例#27
0
        public static string TimbraCfdiString(string comprobante, empresa emp)
        {
            ValidadorCFDi32 val    = new ValidadorCFDi32();
            string          result = null;

            ServicioLocal.Business.TimbreFiscalDigital timbre = null;
            string      acuseSat          = "";
            string      hash              = null;
            XElement    element           = XElement.Parse(comprobante);
            Comprobante comp              = TimbradoUtils.DesSerializar(element);
            Dictionary <int, string> dict = val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
            string result2;

            if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
            {
                if (!string.IsNullOrEmpty(comp.Confirmacion))
                {
                    using (NtLinkLocalServiceEntities db = new NtLinkLocalServiceEntities())
                    {
                        ConfirmacionTimbreWs33 C = db.ConfirmacionTimbreWs33.FirstOrDefault((ConfirmacionTimbreWs33 p) => p.Folio == comp.Folio && p.RfcEmisor == comp.Emisor.Rfc && p.RfcReceptor == comp.Receptor.Rfc);
                        C.procesado = new bool?(true);
                        db.ConfirmacionTimbreWs33.ApplyCurrentValues(C);
                        db.SaveChanges();
                    }
                }
                SerializadorTimbres sert = new SerializadorTimbres();
                if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                {
                    timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                }
                string res          = sert.GetTimbreXml(timbre);
                string cfdiTimbrado = result;
                if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                {
                    if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, emp, true, false))
                    {
                        throw new Exception("Error al abrir el comprobante");
                    }
                }
                result2 = res;
            }
            else
            {
                if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                {
                    XElement el          = XElement.Parse(result);
                    XElement complemento = el.Elements(Constantes.CFDVersionNamespace + "Complemento").FirstOrDefault <XElement>();
                    if (complemento != null)
                    {
                        XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                        if (t != null)
                        {
                            SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                            t.Save(sw, SaveOptions.DisableFormatting);
                            result2 = sw.ToString();
                            return(result2);
                        }
                    }
                }
                if (dict.Count > 0)
                {
                    StringBuilder res2 = new StringBuilder();
                    foreach (KeyValuePair <int, string> d in dict)
                    {
                        res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                    }
                    result2 = res2.ToString();
                }
                else
                {
                    TimbradoUtils.Logger.Error("Error al abrir el comprobante:" + comprobante);
                    result2 = "Error al abrir el comprobante";
                }
            }
            return(result2);
        }
示例#28
0
        public bool SaveDistribuidor(Distribuidores distribuidor, ref string resultado, string nombreCompleto,
                                     string iniciales)
        {
            try
            {
                if (Validar(distribuidor))
                {
                    using (var db = new NtLinkLocalServiceEntities())
                    {
                        if (distribuidor.IdDistribuidor == 0)
                        {
                            // Crear random password
                            if (db.aspnet_Membership.Any(p => p.LoweredEmail == distribuidor.Email.ToLower()))
                            {
                                throw new FaultException("El Email ya fue registrado");
                            }
                            db.Distribuidores.AddObject(distribuidor);
                            db.SaveChanges();
                            var password = Membership.GeneratePassword(8, 2);
                            var userName = distribuidor.Email;
                            NtLinkUsuarios.CreateUserDis(userName, password, distribuidor.Email,
                                                         (int)distribuidor.IdDistribuidor, "Administrador",
                                                         nombreCompleto, iniciales);
                            Logger.Info("se creó el usuario: " + userName + " con el password: "******"se creó el usuario: " + userName + " con el password: "******"Registro actualizado correctamente";
                        }


                        return(true);
                    }
                }
                return(false);
            }
            catch (FaultException fe)
            {
                throw;
            }
            catch (Exception ee)
            {
                resultado = "Error al guardar el registro";
                Logger.Error(ee);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                return(false);
            }
        }
        public TimbradoResponse TimbraCfdiMovil(string userName, string password, string comprobante)
        {
            TimbradoResponse result2;

            try
            {
                string erroresNomina = "0";
                ServicioTimbradoMovil.Logger.Debug(userName);
                MembershipUser x = NtLinkLogin.ValidateUser(userName, password);
                if (x == null)
                {
                    throw new FaultException("Nombre de usuario o contraseña incorrecta");
                }
                XElement element = XElement.Load(new StringReader(comprobante));
                ServicioLocal.Business.Comprobante comp = this.DesSerializar(element);
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<ine:INE "))
                {
                    string     erroINE = "";
                    INE        I       = this.DesSerializarINE(element, ref erroINE);
                    ValidarINE VI      = new ValidarINE();
                    erroINE = VI.ProcesarINE(I);
                    if (erroINE != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroINE
                        };
                        return(result2);
                    }
                }
                if (comprobante.Contains("<ecc11:EstadoDeCuentaCombustible"))
                {
                    string erroECC = "";
                    EstadoDeCuentaCombustible E = this.DesSerializarECC(element, ref erroECC);
                    ValidarECC VE = new ValidarECC();
                    erroECC = VE.ProcesarECC(E, comp.TipoDeComprobante, comp.Version);
                    if (erroECC != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroECC
                        };
                        return(result2);
                    }
                }
                if (comprobante.Contains("<implocal:ImpuestosLocales"))
                {
                    IL = this.DesSerializarImpuestosLocales(element);
                }
                bool pago10 = comprobante.Contains("pago10:Pagos");
                if (pago10)
                {
                    ServicioLocal.Business.Pagoo.Comprobante pagoDatos = this.DesSerializarP(element);
                    ServicioLocal.Business.Complemento.Pagos pagoss    = this.DesSerializarPagos(element);
                    ValidarPago VP         = new ValidarPago();
                    string      ErrorPagos = VP.ProcesarPago(comp, pagoss, pagoDatos);
                    if (ErrorPagos != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = ErrorPagos
                        };
                        return(result2);
                    }
                }
                NtLinkClientes nlc     = new NtLinkClientes();
                clientes       cliente = nlc.GetCliente(comp.Receptor.Rfc);
                bool           nomin12 = comprobante.Contains("nomina12:Nomina");
                List <Nomina>  nom     = new List <Nomina>();

                if (nomin12)
                {
                    string erroresNom = null;
                    var    nomx       = this.DesSerializarNomina12(element, ref erroresNom);
                    nom.Add(nomx);
                    if (erroresNom != null)
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroresNom
                        };
                        return(result2);
                    }
                }
                bool ComerExt = comprobante.Contains("cce11:ComercioExterior");
                if (comp.Emisor != null && comp.Emisor.Rfc != null)
                {
                    empresa empresa = new empresa();
                    if (!TimbradoUtils.EmpresaMultipleRFC(comp.Emisor.Rfc))
                    {
                        empresa = TimbradoUtils.ValidarUsuario(comp.Emisor.Rfc);
                    }
                    else
                    {
                        empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
                        empresa = TimbradoUtils.ValidarUsuarioMultiple(empresa);
                    }
                    if (empresa == null)
                    {
                        result2 = null;
                    }
                    else
                    {
                        string result = null;
                        TimbreFiscalDigital timbre = null;
                        string acuseSat            = "";
                        string hash = null;
                        if (ComerExt && erroresNomina == "0")
                        {
                            string erroresComer           = null;
                            ValidarComercioExterior val   = new ValidarComercioExterior();
                            ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                            if (erroresComer != null)
                            {
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = erroresComer
                                };
                                return(result2);
                            }
                            erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                        }
                        if (nomin12 && erroresNomina == "0")
                        {
                            erroresNomina = this._val.ProcesarNomina(nom, comp);
                        }
                        if (erroresNomina == "0")
                        {
                            try
                            {
                                string           path      = Path.Combine(ConfigurationManager.AppSettings["Resources"], empresa.RFC, "Certs");
                                X509Certificate2 cert      = new X509Certificate2(Path.Combine(path, "csd.cer"));
                                string           rutaLlave = Path.Combine(path, "csd.key");
                                if (File.Exists(rutaLlave + ".pem"))
                                {
                                    rutaLlave += ".pem";
                                }
                                ServicioTimbradoMovil.Logger.Debug("Ruta Llave " + rutaLlave);
                                if (!File.Exists(rutaLlave))
                                {
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error certificado de la empresa no está cargado en el sistema"
                                    };
                                    return(result2);
                                }
                                GeneradorCfdi gen     = new GeneradorCfdi();
                                string        sellado = gen.GenerarCfdSinTimbre(comp, cert, rutaLlave, empresa.PassKey, comprobante);
                                if (sellado == null)
                                {
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error al sellar el comprobante: al sellar"
                                    };
                                    return(result2);
                                }
                                comprobante = sellado;
                            }
                            catch (FaultException ex)
                            {
                                ServicioTimbradoMovil.Logger.Error(ex);
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = ex.Message
                                };
                                return(result2);
                            }
                            ValidarCFDI33 valida      = new ValidarCFDI33();
                            string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                            if (errorCFDI33 != "0")
                            {
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = errorCFDI33
                                };
                            }
                            else
                            {
                                Dictionary <int, string> dict = this._val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
                                if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
                                {
                                    if (!string.IsNullOrEmpty(comp.Confirmacion))
                                    {
                                        using (NtLinkLocalServiceEntities db = new NtLinkLocalServiceEntities())
                                        {
                                            ConfirmacionTimbreWs33 C = db.ConfirmacionTimbreWs33.FirstOrDefault((ConfirmacionTimbreWs33 p) => p.Folio == comp.Folio && p.RfcEmisor == comp.Emisor.Rfc && p.RfcReceptor == comp.Receptor.Rfc);
                                            C.procesado = new bool?(true);
                                            db.ConfirmacionTimbreWs33.ApplyCurrentValues(C);
                                            db.SaveChanges();
                                        }
                                    }
                                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                                    {
                                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                                    }
                                    string cfdiTimbrado = result;
                                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                                    {
                                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empresa, true, false))
                                        {
                                            throw new Exception("Error al abrir el comprobante");
                                        }
                                        NtLinkFactura fac = new NtLinkFactura(0);
                                        if (string.IsNullOrEmpty(empresa.RegimenFiscal))
                                        {
                                            throw new FaultException("Debes capturar el regimen fiscal de la empresa");
                                        }
                                        fac.Emisor      = empresa;
                                        fac.Receptor    = cliente;
                                        fac.Factura     = this.CrearFactura(comp, empresa.IdEmpresa, cliente.idCliente);
                                        fac.Factura.Uid = timbre.UUID;
                                        fac.Save();
                                        comp.Complemento = new ComprobanteComplemento();
                                        comp.Complemento.timbreFiscalDigital = timbre;
                                        comp.XmlString            = cfdiTimbrado;
                                        comp.CadenaOriginalTimbre = timbre.cadenaOriginal;
                                        string saldo = comp.Total.ToString(CultureInfo.InvariantCulture);
                                        comp.CantidadLetra = CantidadLetra.Enletras(saldo.ToString(), comp.Moneda);
                                        comp.Regimen       = empresa.RegimenFiscal;
                                        if (comp.TipoDeComprobante.ToString() == "ingreso")
                                        {
                                            comp.Titulo = "Factura";
                                        }
                                        else if (comp.TipoDeComprobante.ToString() == "egreso")
                                        {
                                            comp.Titulo = "Nota de Crédito";
                                        }
                                        string ruta = Path.Combine(ConfigurationManager.AppSettings["Salida"], empresa.RFC);
                                        if (!Directory.Exists(ruta))
                                        {
                                            Directory.CreateDirectory(ruta);
                                        }
                                        string xmlFile = Path.Combine(ruta, timbre.UUID + ".xml");
                                        ServicioTimbradoMovil.Logger.Debug(comp.XmlString);
                                        StreamWriter sw = new StreamWriter(xmlFile, false, Encoding.UTF8);
                                        sw.Write(comp.XmlString);
                                        sw.Close();
                                        byte[] pdf = new byte[0];
                                        try
                                        {
                                            long          id  = 0L;
                                            GeneradorCfdi gen = new GeneradorCfdi();
                                            pdf = gen.GetPdfFromComprobante(comp, empresa.Orientacion, fac.Factura.TipoDocumento, ref id, fac.Factura.Metodo);
                                            string pdfFile = Path.Combine(ruta, timbre.UUID + ".pdf");
                                            File.WriteAllBytes(pdfFile, pdf);
                                        }
                                        catch (Exception ee)
                                        {
                                            ServicioTimbradoMovil.Logger.Error(ee);
                                            if (ee.InnerException != null)
                                            {
                                                ServicioTimbradoMovil.Logger.Error(ee.InnerException);
                                            }
                                        }
                                    }
                                    string totalLetra = comp.Total.ToString(CultureInfo.InvariantCulture);
                                    string enteros;
                                    string decimales;
                                    if (totalLetra.IndexOf('.') == -1)
                                    {
                                        enteros   = "0";
                                        decimales = "0";
                                    }
                                    else
                                    {
                                        enteros   = totalLetra.Substring(0, totalLetra.IndexOf('.'));
                                        decimales = totalLetra.Substring(totalLetra.IndexOf('.') + 1);
                                    }
                                    string total        = enteros.PadLeft(18, '0') + "." + decimales.PadRight(6, '0');
                                    int    tam_var      = comp.Sello.Length;
                                    string Var_Sub      = comp.Sello.Substring(tam_var - 8, 8);
                                    string URL          = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx";
                                    string cadenaCodigo = string.Concat(new string[]
                                    {
                                        URL,
                                        "?&id=",
                                        timbre.UUID,
                                        "&fe=",
                                        Var_Sub,
                                        "&re=",
                                        comp.Emisor.Rfc,
                                        "&rr=",
                                        comp.Receptor.Rfc,
                                        "&tt=",
                                        total
                                    });
                                    string qr = this.GetQrCode(cadenaCodigo);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido       = true,
                                        QrCodeBase64 = qr,
                                        CadenaTimbre = timbre.cadenaOriginal,
                                        Cfdi         = cfdiTimbrado
                                    };
                                }
                                else if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                                {
                                    string totalLetra = comp.Total.ToString(CultureInfo.InvariantCulture);
                                    string enteros;
                                    string decimales;
                                    if (totalLetra.IndexOf('.') == -1)
                                    {
                                        enteros   = "0";
                                        decimales = "0";
                                    }
                                    else
                                    {
                                        enteros   = totalLetra.Substring(0, totalLetra.IndexOf('.'));
                                        decimales = totalLetra.Substring(totalLetra.IndexOf('.') + 1);
                                    }
                                    string total        = enteros.PadLeft(18, '0') + "." + decimales.PadRight(6, '0');
                                    int    tam_var      = comp.Sello.Length;
                                    string Var_Sub      = comp.Sello.Substring(tam_var - 8, 8);
                                    string URL          = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx";
                                    string cadenaCodigo = string.Concat(new string[]
                                    {
                                        URL,
                                        "?&id=",
                                        timbre.UUID,
                                        "&fe=",
                                        Var_Sub,
                                        "&re=",
                                        comp.Emisor.Rfc,
                                        "&rr=",
                                        comp.Receptor.Rfc,
                                        "&tt=",
                                        total
                                    });
                                    string qr = this.GetQrCode(cadenaCodigo);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido       = true,
                                        QrCodeBase64 = qr,
                                        CadenaTimbre = timbre.cadenaOriginal,
                                        Cfdi         = result
                                    };
                                }
                                else if (dict.Count > 0)
                                {
                                    StringBuilder res = new StringBuilder();
                                    foreach (KeyValuePair <int, string> d in dict)
                                    {
                                        res.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                                    }
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = res.ToString()
                                    };
                                }
                                else
                                {
                                    ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante:" + comprobante);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error al abrir el comprobante"
                                    };
                                }
                            }
                        }
                        else
                        {
                            ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante: " + erroresNomina);
                            result2 = new TimbradoResponse
                            {
                                Valido           = false,
                                DescripcionError = erroresNomina
                            };
                        }
                    }
                }
                else
                {
                    ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante:" + comprobante);
                    result2 = new TimbradoResponse
                    {
                        Valido           = false,
                        DescripcionError = "Error al abrir el comprobante"
                    };
                }
            }
            catch (FaultException ex)
            {
                ServicioTimbradoMovil.Logger.Error(ex);
                result2 = new TimbradoResponse
                {
                    Valido           = false,
                    DescripcionError = ex.Message
                };
            }
            catch (Exception ex2)
            {
                ServicioTimbradoMovil.Logger.Error(ex2);
                throw new FaultException("Error al abrir el comprobante");
            }
            return(result2);
        }
        public bool IncrementaSaldo(int idEmpresa, int idSistema)
        {
            try
            {
                using (var db = new NtLinkLocalServiceEntities())
                {
                    var sistemaMensual = db.TimbradoSistemaMensual.FirstOrDefault(p => p.IdSistema == idSistema && p.Anio == DateTime.Now.Year && p.Mes == DateTime.Now.Month);
                    if (sistemaMensual == null)
                    {
                        sistemaMensual = new TimbradoSistemaMensual()
                        {
                            IdSistema = idSistema,
                            Mes       = DateTime.Now.Month,
                            Anio      = DateTime.Now.Year,
                            Timbres   = 1
                        };
                        db.TimbradoSistemaMensual.AddObject(sistemaMensual);
                    }
                    else
                    {
                        sistemaMensual.Timbres = sistemaMensual.Timbres + 1;
                        db.TimbradoSistemaMensual.ApplyCurrentValues(sistemaMensual);
                    }

                    var empresaMensual =
                        db.TimbradoEmpresaMensual.FirstOrDefault(
                            p => p.IdEmpresa == idEmpresa && p.Anio == DateTime.Now.Year && p.Mes == DateTime.Now.Month);
                    if (empresaMensual == null)
                    {
                        empresaMensual = new TimbradoEmpresaMensual()
                        {
                            IdEmpresa = idEmpresa,
                            Mes       = DateTime.Now.Month,
                            Anio      = DateTime.Now.Year,
                            Timbres   = 1
                        };
                        db.TimbradoEmpresaMensual.AddObject(empresaMensual);
                    }
                    else
                    {
                        empresaMensual.Timbres = empresaMensual.Timbres + 1;
                        db.TimbradoEmpresaMensual.ApplyCurrentValues(empresaMensual);
                    }

                    // Debemos de decrementar el saldo de timbrado que esta en la tabla de Sistema.SaldoTimbrado, ya que este es el que se ejecuta
                    var sistema = db.Sistemas.Single(l => l.IdSistema == idSistema);
                    sistema.SaldoTimbrado = sistema.SaldoTimbrado - 1;
                    if (sistema.ConsumoTimbrado == null)//no tenia pa incrementar el saldo timbrado agregado rgv
                    {
                        sistema.ConsumoTimbrado = 1;
                    }
                    else
                    {
                        sistema.ConsumoTimbrado = sistema.ConsumoTimbrado + 1;
                    }
                    db.Sistemas.ApplyCurrentValues(sistema);
                    //rgv
                    db.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee.Message);
                if (ee.InnerException != null)
                {
                    Logger.Error(ee.InnerException);
                }
                //throw;
                return(false);
            }
        }