protected void btnEliminarItem_Command(object sender, CommandEventArgs e)
        {
            try
            {
                ValidaVariables();

                //Obtiene indice de la linea a actualizar
                int index = Convert.ToInt32(e.CommandArgument);

                string desc = grdDetalle.DataKeys[index].Value.ToString();

                NegocioPF.Factura oFactura = (NegocioPF.Factura)Session["oFactura"];

                //Busca la factura a eliminar
                foreach (DataRow r in oFactura.Materiales.Rows)
                {
                    if (r["descripcion"].ToString() == desc)
                    {
                        oFactura.Materiales.Rows.Remove(r);
                        break;
                    }
                }

                Session["oFactura"] = oFactura;

                grdDetalle.DataSource = oFactura.Materiales;
                grdDetalle.DataBind();
            }
            catch (Exception ex)
            {
                MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto(ex.Message));
            }
        }
Esempio n. 2
0
        protected void btnVerPDF_Command(object sender, CommandEventArgs e)
        {
            try
            {
                ValidaVariables();

                //Obtiene indice de la factura a consultar
                int index = Convert.ToInt32(e.CommandArgument) - (grdFacturas.PageIndex * grdFacturas.PageSize);

                int    folio = Convert.ToInt32(grdFacturas.DataKeys[index][0]);
                string cert  = grdFacturas.DataKeys[index][1].ToString();

                NegocioPF.Factura oFactura = new NegocioPF.Factura(folio, cert);
                string            archivo  = oFactura.BajaPDF(Server.MapPath("") + "\\Facturas\\");

                if (archivo.Length > 0)
                {
                    Session["archivo"] = "Facturas/" + oFactura.BajaPDF(Server.MapPath("") + "\\Facturas\\" + archivo);

                    string newWin = "OpenPopupCenter('VisorPDF.aspx','Factura',670,700,0);";

                    ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);
                }
                else
                {
                    MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgPDFInexistente"));
                }
            }
            catch (Exception ex)
            {
                /* */
            }
        }
Esempio n. 3
0
        protected void btnVerXML_Command(object sender, CommandEventArgs e)
        {
            try
            {
                ValidaVariables();

                //Obtiene indice de la factura a consultar
                int index = Convert.ToInt32(e.CommandArgument) - (grdFacturas.PageIndex * grdFacturas.PageSize);

                int    folio = Convert.ToInt32(grdFacturas.DataKeys[index][0]);
                string cert  = grdFacturas.DataKeys[index][1].ToString();

                NegocioPF.Factura oFactura = new NegocioPF.Factura(folio, cert);
                string            archivo  = oFactura.BajaXML(Server.MapPath("") + "\\Facturas\\");

                if (archivo.Length > 0)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(Server.MapPath("") + "\\Facturas\\" + archivo);
                    string s = doc.ToString();

//                    Session["archivo"] = "Facturas/" + oFactura.BajaPDF(Server.MapPath("") + "\\Facturas\\" + archivo);
//                    string newWin = "OpenPopupCenter('VisorPDF.aspx','Factura',670,700,0);";
//                    ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);

                    //Response.Clear();
                    //Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", archivo));
                    //Response.ContentType = "application/octet-stream";
                    //Response.WriteFile(archivo);
                    //Response.End();

                    Response.Clear();
                    Response.AddHeader("content-disposition", "attachment;filename=" + archivo);
                    Response.ContentType     = "text/xml";
                    Response.ContentEncoding = System.Text.Encoding.UTF8;

                    //Response.Write(File.ReadAllText(Server.MapPath("~/temp.xml"))); //you may want to write the XML directly to output stream instead of creating an XML file first.
                    //Response.Write(doc.ToString());
                    doc.Save(Response.Output);
                    Response.End();
                }
                else
                {
                    MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgPDFInexistente"));
                }
            }
            catch (Exception ex)
            {
                /* */
            }
        }
        protected void btnAceptarItem_Click(object sender, EventArgs e)
        {
            try
            {
                //Determina la tasa de impuestos
                Double            tasa     = Convert.ToDouble(txtImpuestos.Text) / Convert.ToDouble(txtImpSinIva.Text);
                NegocioPF.Factura oFactura = (NegocioPF.Factura)Session["oFactura"];
                DataRow           r        = oFactura.Materiales.NewRow();
                r["Factura"]     = txtFactura.Text;
                r["Fecha"]       = txtFecha.Text;
                r["Descripcion"] = txtMaterial.Text;
                r["Cantidad"]    = txtCantidad.Text;
                r["Unidad"]      = cboUnidad.SelectedValue;
                //r["ValorUnitario"] = Convert.ToDouble(txtImporteMat.Text) / Convert.ToInt32(txtCantidad.Text);
                r["Importe"]   = txtImporteMat.Text;
                r["Impuestos"] = Convert.ToDouble(txtImporteMat.Text) * tasa;
                r["ImpNeto"]   = Convert.ToDouble(r["Importe"]) + Convert.ToDouble(r["Impuestos"]);
                r["Moneda"]    = cboMoneda.SelectedValue;
                r["Nota_ent"]  = "";
                r["Posicion"]  = "0";
                r["Entrega"]   = "";
                r["Anio_ent"]  = "0";
                r["Pos_ent"]   = "0";
                r["TipoCond"]  = "";

                txtMaterial.Text        = "";
                txtCantidad.Text        = "";
                cboUnidad.SelectedValue = "0";
                txtImporteMat.Text      = "";

                oFactura.Materiales.Rows.Add(r);

                grdDetalle.DataSource = oFactura.Materiales;
                grdDetalle.DataBind();
            }
            catch (Exception ex)
            {
                MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto(ex.Message));
            }
        }
        protected void btnAceptarImportar_Click(object sender, EventArgs e)
        {
            string tmp;

            try
            {
                //Copia los archivos en la carpeta destino
                //string dirDestino = @System.Configuration.ConfigurationSettings.AppSettings["PathArchivos"].ToString();
                string dirDestino = Server.MapPath("") + "\\Facturas\\";
                string dirDestPDF = dirDestino;
                string dirDestXML = dirDestino;

                if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
                {
                    dirDestPDF += System.IO.Path.GetFileName(File1.PostedFile.FileName);
                    try
                    {
                        File1.PostedFile.SaveAs(dirDestPDF);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                if ((File2.PostedFile != null) && (File2.PostedFile.ContentLength > 0))
                {
                    dirDestXML += System.IO.Path.GetFileName(File2.PostedFile.FileName);
                    try
                    {
                        File2.PostedFile.SaveAs(dirDestXML);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                if ((File3.PostedFile != null) && (File3.PostedFile.ContentLength > 0))
                {
                    dirDestino += System.IO.Path.GetFileName(File3.PostedFile.FileName);
                    try
                    {
                        File3.PostedFile.SaveAs(dirDestino);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }
                if ((File4.PostedFile != null) && (File4.PostedFile.ContentLength > 0))
                {
                    dirDestino += System.IO.Path.GetFileName(File4.PostedFile.FileName);
                    try
                    {
                        File4.PostedFile.SaveAs(dirDestino);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                if ((File5.PostedFile != null) && (File5.PostedFile.ContentLength > 0))
                {
                    dirDestino += System.IO.Path.GetFileName(File5.PostedFile.FileName);
                    try
                    {
                        File5.PostedFile.SaveAs(dirDestino);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                NegocioPF.Factura oFactura = new NegocioPF.Factura();

                XmlReader xmlReader = XmlReader.Create(dirDestXML);

                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(xmlReader);
                    //doc.Load(dirDestino);

                    oFactura.Sociedad = cboSociedades.SelectedValue;

                    string version = Rutinas.ObtenerValorAtributo(ref doc, "Version");

                    tmp = Rutinas.ObtenerValorAtributo(ref doc, "folio");
                    oFactura.NumFactura = (tmp != "" ? tmp : "");

                    tmp            = Rutinas.ObtenerValorAtributo(ref doc, "serie");
                    oFactura.Serie = tmp;

                    tmp            = Rutinas.ObtenerValorAtributo(ref doc, "fecha");
                    oFactura.Fecha = (tmp != "" ? new DateTime(Convert.ToInt32(tmp.Substring(0, 4)), Convert.ToInt32(tmp.Substring(5, 2)), Convert.ToInt32(tmp.Substring(8, 2))) : new DateTime(1900, 1, 1));

                    tmp = Rutinas.ObtenerValorAtributo(ref doc, "total");
                    if (tmp != "")
                    {
                        oFactura.Importe = Convert.ToDouble(tmp);
                    }

                    tmp             = Rutinas.ObtenerValorAtributo(ref doc, "moneda");
                    oFactura.Moneda = tmp;

                    NegocioPF.UnidadMedida oUnidadMedida = new UnidadMedida();

                    foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                    {
                        if (node.Name == "cfdi:Emisor")
                        {
                            oFactura.Emisor    = Rutinas.ObtenerValorAtributoNodo(node, "rfc");
                            oFactura.NomEmisor = Rutinas.ObtenerValorAtributoNodo(node, "nombre");
                        }
                        if (node.Name == "cfdi:Receptor")
                        {
                            oFactura.Receptor    = Rutinas.ObtenerValorAtributoNodo(node, "rfc");
                            oFactura.NomReceptor = Rutinas.ObtenerValorAtributoNodo(node, "nombre");
                        }
                        if (node.Name == "cfdi:Conceptos")
                        {
                            foreach (XmlNode child in node.ChildNodes)
                            {
                                if (child.Name == "cfdi:Concepto")
                                {
                                    DataRow r = oFactura.Materiales.NewRow();
                                    r["Posicion"]    = 0;
                                    r["Descripcion"] = Rutinas.ObtenerValorAtributoNodo(child, "descripcion"); //child.Attributes["descripcion"].Value;
                                    tmp = Rutinas.ObtenerValorAtributoNodo(child, "cantidad");
                                    if (tmp != "")
                                    {
                                        r["Cantidad"] = Convert.ToDouble(tmp); //Convert.ToDouble(child.Attributes["cantidad"].Value);
                                    }
                                    tmp = Rutinas.ObtenerValorAtributoNodo(child, "valorUnitario");
                                    if (tmp != "")
                                    {
                                        r["ValorUnitario"] = Convert.ToDouble(tmp); //child.Attributes["valorUnitario"].Value
                                    }
                                    tmp = Rutinas.ObtenerValorAtributoNodo(child, "importe");
                                    if (tmp != "")
                                    {
                                        r["Importe"] = Convert.ToDouble(tmp);
                                    }

                                    tmp = Rutinas.ObtenerValorAtributoNodo(child, "unidad");
                                    if (tmp != "")
                                    {
                                        oUnidadMedida.Buscar(tmp);
                                        r["Unidad"] = oUnidadMedida.UnidadSAP;
                                    }
                                    r["Anio_ent"] = "0";
                                    r["Entrega"]  = "";
                                    r["Pos_ent"]  = 0;
                                    oFactura.Materiales.Rows.Add(r);
                                }
                            }
                        }
                        if (node.Name == "cfdi:Impuestos")
                        {
                            //oFactura.Impuestos = Convert.ToDouble(node.Attributes["totalImpuestosTrasladados"].Value);

                            foreach (XmlNode child in node.ChildNodes)
                            {
                                if (child.Name == "cfdi:Traslados")
                                {
                                    foreach (XmlNode child1 in child.ChildNodes)
                                    {
                                        if (child1.Name == "cfdi:Traslado")
                                        {
                                            tmp = Rutinas.ObtenerValorAtributoNodo(child1, "tasa");
                                            if (tmp != "")
                                            {
                                                oFactura.Tasa = Convert.ToInt32(Convert.ToDouble(tmp));
                                            }
                                            else
                                            {
                                                tmp = Rutinas.ObtenerValorAtributoNodo(child1, "tasaOCuota");
                                                if (tmp != "")
                                                {
                                                    oFactura.Tasa = Convert.ToInt32(Convert.ToDouble(tmp) * 100);
                                                }
                                            }
                                            if (oFactura.Tasa < 1)
                                            {
                                                oFactura.Tasa = oFactura.Tasa * 100;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (node.Name == "cfdi:Complemento")
                        {
                            foreach (XmlNode child in node.ChildNodes)
                            {
                                if (child.Name == "tfd:TimbreFiscalDigital")
                                {
                                    oFactura.UUID = Rutinas.ObtenerValorAtributoNodo(child, "UUID");
                                }
                            }
                        }
                    }

                    xmlReader.Dispose();

                    //Busca la clave SAP de la moneda
                    NegocioPF.Moneda oMoneda = new NegocioPF.Moneda();
                    oMoneda.Buscar(oFactura.Moneda);
                    if (oMoneda.ID != "")
                    {
                        oFactura.Moneda         = oMoneda.MonedaSAP;
                        cboMoneda.SelectedValue = oMoneda.MonedaSAP;
                    }

                    //Busca la clave del indicador de impuesto
                    NegocioPF.Indicador oIndicador = new Indicador();
                    oIndicador.Buscar(oFactura.Tasa);
                    if (oIndicador.ID != "")
                    {
                        oFactura.IndImpuestos = oIndicador.ID;
                    }

                    //Valida que esté cargando una factura el proveedor
                    NegocioPF.Proveedor oProveedor = new Proveedor(((Usuario)Session["oUsuario"]).Id);
                    oProveedor.Cargar();

                    //Si es un proveedor
                    if (oProveedor.RFC != "")
                    {
                        if (oProveedor.RFC != oFactura.Emisor)
                        {
                            if (oProveedor.Intermediario == false)
                            {
                                throw new Exception("MsgErrFacDifProv");
                            }
                        }
                    }

                    //Escribe los datos de la factura en los controles
                    txtFactura.Text         = oFactura.NumFactura.ToString();
                    txtFecha.Text           = oFactura.Fecha.ToString("yyyy-MM-dd");
                    txtImporte.Text         = oFactura.Importe.ToString("###,##0.#0");
                    txtEmisor.Text          = oFactura.Emisor + " " + oFactura.NomEmisor;
                    txtReceptor.Text        = oFactura.Receptor + " " + oFactura.NomReceptor;
                    txtUUID.Text            = oFactura.UUID;
                    cboMoneda.SelectedValue = "0";
                    try
                    {
                        cboMoneda.SelectedValue = oFactura.Moneda;
                    }
                    catch { /*Maneja error*/ }

                    //Inhabilita los controles
                    txtFactura.Enabled  = (txtFactura.Text.Trim().Length == 0);
                    txtFecha.Enabled    = (txtFecha.Text.Trim().Length == 0);
                    txtImporte.Enabled  = (txtImporte.Text.Trim().Length == 0);
                    cboMoneda.Enabled   = (cboMoneda.SelectedValue == "0");
                    txtEmisor.Enabled   = (txtEmisor.Text.Trim().Length == 0);
                    txtReceptor.Enabled = (txtReceptor.Text.Trim().Length == 0);
                    txtUUID.Enabled     = false;

                    Session["oFactura"] = oFactura;
                }
                catch (Exception ex)
                {
                    xmlReader.Dispose();
                    if (ex.Message.Length > 3)
                    {
                        if (ex.Message.Substring(0, 3) == "Msg")
                        {
                            throw new Exception(ex.Message);
                        }
                        else
                        {
                            throw new Exception("MsgErrLeerXML");
                        }
                    }
                }

                //Verifica si existe ya en el grid
                foreach (GridViewRow f in grdFacturas.Rows)
                {
                    if (f.Cells[1].Text == oFactura.UUID)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgFactDuplicada"));
                        return;
                    }
                    //Valida si es el mismo proveedor
                    if (f.Cells[3].Text != oFactura.Emisor)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgFactDifProveedor"));
                        return;
                    }
                }

                //Valida si debe hacer la validación ante el SAT
                NegocioPF.Configuracion oConfig = new NegocioPF.Configuracion();
                oConfig.Cargar();

                if (oConfig.ValidacionSAT)
                {
                    //Manda a validar el archivo CFD
                    //wsSAT.WsValidacionCFDsExtSoapClient obj = new WsValidacionCFDsExtSoapClient();
                    //resultado = obj.ValidarXmlCFD(doc.InnerXml);
                    //resultado = obj.ValidarXmlCFD(xml);

                    //Manda a verificar si exite el folio en el SAT
                    wsValidaCFDIs.Acuse objAcuse;
                    wsValidaCFDIs.ConsultaCFDIServiceClient obj = new ConsultaCFDIServiceClient();

                    //Arma la cadena
                    string cadena = "?re=" + oFactura.Emisor + "&rr=" + oFactura.Receptor + "&tt=" + oFactura.Importe.ToString() + "&id=" + oFactura.UUID;
                    //objAcuse = obj.Consulta("?re=CBJ030505UR7&rr=DEM8801152E9&tt=244.00&id=5B8281DD-4CE8-4CCB-8077-445B9D2AD750");
                    objAcuse           = obj.Consulta(cadena);
                    txtValidacion.Text = objAcuse.CodigoEstatus;

                    obj.Close();

                    btnAgregarFactura.Visible = (objAcuse.CodigoEstatus.Substring(0, 1) == "S");
                }
                else
                {
                    btnAgregarFactura.Visible = true;
                }


                //Muestra la factura en el visor
                if (File1.PostedFile.FileName.Length > 0)
                {
                    oViewer.Attributes.Add("src", "Facturas/" + System.IO.Path.GetFileName(File1.PostedFile.FileName));
                    oViewer.Visible  = true;
                    divVisor.Visible = true;
                }

                oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File1.PostedFile.FileName), 1));
                oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File2.PostedFile.FileName), 2));
                if (File3.PostedFile.FileName != "")
                {
                    oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File3.PostedFile.FileName), 3));
                }
                if (File4.PostedFile.FileName != "")
                {
                    oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File4.PostedFile.FileName), 4));
                }
                if (File5.PostedFile.FileName != "")
                {
                    oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File5.PostedFile.FileName), 5));
                }

                //oFactura.PDF = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                //oFactura.XML = System.IO.Path.GetFileName(File2.PostedFile.FileName);

                Session["pdf"] = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                Session["xml"] = System.IO.Path.GetFileName(File2.PostedFile.FileName);

                divDetalle.Visible  = true;
                divImportar.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto(ex.Message));
            }
        }
        protected void btnAceptarAgregar_Click(object sender, EventArgs e)
        {
            try
            {
                NegocioPF.Factura oFactura = (Factura)Session["oFactura"];
                if (oFactura.Existe())
                {
                    MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgFactYaRegistrada"));
                    return;
                }

                oFactura.Moneda = cboMoneda.SelectedValue;

                //Valida si existe el Emisor en el catálogo de proveedores
                NegocioPF.Proveedor oProveedor = new Proveedor();
                oProveedor.Cargar(txtEmisor.Text.Substring(0, txtEmisor.Text.IndexOf(" ")));
                if (oProveedor.Nombre == "" || oProveedor.Nombre == null)
                {
                    throw new Exception("MsgEmisorInexistente");
                }

                //Valida que el receptor corresponda a la sociedad seleccionada
                NegocioPF.Sociedad oSociedad = new NegocioPF.Sociedad(cboSociedades.SelectedValue);
                oSociedad.Cargar();

                if (oSociedad.RFC != txtReceptor.Text.Substring(0, txtReceptor.Text.IndexOf(" ")))
                {
                    throw new Exception("MsgErrFactNoCorrSociedad");
                }

                //Valida que la sociedad esté activa para el proveedor
                bool existe = false;
                foreach (string sociedad in oProveedor.Sociedades)
                {
                    if (sociedad == cboSociedades.SelectedValue)
                    {
                        existe = true;
                    }
                }

                if (!existe)
                {
                    throw new Exception("MsgSocNoActProv");
                }

                //Valida la fecha de la factura
                NegocioPF.Configuracion oConfig = new NegocioPF.Configuracion();
                oConfig.Cargar();

                DateTime dFechaMinima = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                dFechaMinima = dFechaMinima.AddMonths(oConfig.MesesAtras * -1);

                DateTime dFechaMaxima = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                dFechaMaxima = dFechaMaxima.AddMonths(oConfig.MesesAdelante);

                DateTime dFecha = new DateTime(Convert.ToInt32(txtFecha.Text.Substring(0, 4)),
                                               Convert.ToInt32(txtFecha.Text.Substring(5, 2)),
                                               Convert.ToInt32(txtFecha.Text.Substring(8, 2)));

                if (dFecha < dFechaMinima)
                {
                    throw new Exception("MsgErrFactMuyAtrasada");
                }

                if (dFecha > dFechaMaxima)
                {
                    throw new Exception("MsgErrFactFecMuyAdelantada");
                }

                if (oProveedor.RFC != oFactura.Emisor)
                {
                    throw new Exception("MsgErrPedDifProv");
                }

                //Establece el tipo de factura
                oFactura.TipoFactura = "NFI";

                NegocioPF.Facturas oFacturas = (NegocioPF.Facturas)Session["oFacturas"];
                DataRow            r         = oFacturas.Datos.Tables[0].NewRow();
                r["id_sociedad"] = cboSociedades.SelectedValue;
                r["folio"]       = 0;
                r["UUID"]        = txtUUID.Text;
                r["folioFact"]   = txtFactura.Text;
                r["emisor"]      = txtEmisor.Text.Substring(0, txtEmisor.Text.IndexOf(" "));
                r["receptor"]    = txtReceptor.Text.Substring(0, txtReceptor.Text.IndexOf(" "));
                r["ordenCompra"] = "";
                r["fecha"]       = txtFecha.Text;
                r["importe"]     = txtImporte.Text;
                r["id_moneda"]   = cboMoneda.SelectedValue;
                r["pdf"]         = Session["pdf"].ToString();
                r["xml"]         = Session["xml"].ToString();
                oFacturas.Datos.Tables[0].Rows.Add(r);
                oFacturas.Relacion.Add(oFactura);
                Session["oFacturas"] = oFacturas;

                grdFacturas.DataSource = oFacturas.Datos;
                grdFacturas.DataBind();

                oViewer.Visible     = false;
                divDetalle.Visible  = false;
                divFacturas.Visible = true;

                btnAceptar.Visible  = (oFacturas.Datos.Tables[0].Rows.Count > 0);
                btnCancelar.Visible = (oFacturas.Datos.Tables[0].Rows.Count > 0);

                divImportar.Visible = true;

                //ScriptManager.RegisterStartupScript(this, typeof(Page), "confirm", "<script>confirmation();</script>", false);
            }
            catch (Exception ex)
            {
                if (ex.Message.Substring(0, 3) == "Msg")
                {
                    MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto(ex.Message));
                }
                else
                {
                    MessageBox(sender, e, ex.Message);
                }
            }
        }
        protected void btnAceptarAgregar_Click(object sender, EventArgs e)
        {
            bool existe = false;

            try
            {
                if (txtMaterial.Text != "")
                {
                    btnAceptarItem_Click(null, null);
                }

                NegocioPF.Factura oFactura = (Factura)Session["oFactura"];

                NegocioPF.Proveedor oProveedor = new Proveedor(((Usuario)Session["oUsuario"]).Id);
                oProveedor.Cargar();

                //Recupera el emisor
                string emisor;
                if (txtEmisor.Text.IndexOf(" ") >= 0)
                {
                    emisor = txtEmisor.Text.Substring(0, txtEmisor.Text.IndexOf(" "));
                }
                else
                {
                    emisor = txtEmisor.Text.Trim();
                }

                //Si es un proveedor, valida si puede subir la factura, propia o de un tercero
                if (oProveedor.RFC != "")
                {
                    if (oProveedor.RFC != emisor)
                    {
                        if (oProveedor.Intermediario == false)
                        {
                            throw new Exception("MsgErrFacDifProv");
                        }
                    }
                }

                //Carga al emisor
                oProveedor.Cargar(emisor);

                //Valida que el proveedor exista
                if (oProveedor.RFC == "")
                {
                    throw new Exception("MsgProvInexistente");
                }
                else
                {
                    txtEmisor.Text = oProveedor.RFC + " " + oProveedor.Nombre;
                }

                //Valida que el Emisor pueda facturar en la sociedad seleccionada
                existe = false;
                foreach (string sociedad in oProveedor.Sociedades)
                {
                    if (sociedad == cboSociedades.SelectedValue)
                    {
                        existe = true;
                    }
                }

                if (!existe)
                {
                    throw new Exception("MsgSocNoActProv");
                }

                //Establece el emisor en la factura
                oFactura.Emisor = emisor;

                //Valida si la factura ya fue registrada
                oFactura.UUID = txtFactura.Text;

                if (oFactura.Existe())
                {
                    MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgFactYaRegistrada"));
                    return;
                }

                //Valida la fecha de la factura
                NegocioPF.Configuracion oConfig = new NegocioPF.Configuracion();
                oConfig.Cargar();

                DateTime dFechaMinima = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                dFechaMinima = dFechaMinima.AddMonths(oConfig.MesesAtras * -1);

                DateTime dFechaMaxima = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                dFechaMaxima = dFechaMaxima.AddMonths(oConfig.MesesAdelante);

                DateTime dFecha = NegocioPF.Rutinas.ConvierteTextToFecha(txtFecha.Text);

                if (dFecha < dFechaMinima)
                {
                    throw new Exception("MsgErrFactMuyAtrasada");
                }

                if (dFecha > dFechaMaxima)
                {
                    throw new Exception("MsgErrFactFecMuyAdelantada");
                }

                //Establece los datos de la factura
                oFactura.Sociedad    = cboSociedades.SelectedValue;
                oFactura.NumFactura  = txtFactura.Text;
                oFactura.Fecha       = NegocioPF.Rutinas.ConvierteTextToFecha(txtFecha.Text);
                oFactura.Importe     = Convert.ToDouble(txtImpSinIva.Text);
                oFactura.Impuestos   = Convert.ToDouble(txtImpuestos.Text);
                oFactura.Moneda      = cboMoneda.SelectedValue;
                oFactura.TipoFactura = "EFI";

                //Determina el indicador de impuestos
                if (oFactura.Impuestos > 0)
                {
                    oFactura.Tasa = Convert.ToInt32((Convert.ToDouble(txtImpuestos.Text) / Convert.ToDouble(txtImpSinIva.Text)) * 100);
                    NegocioPF.Indicador oIndicador = new Indicador();
                    oIndicador.Buscar(oFactura.Tasa);
                    if (oIndicador.ID != "")
                    {
                        oFactura.IndImpuestos = oIndicador.ID;
                    }
                    else
                    {
                        throw new Exception("MsgErrImpuestos");
                    }
                }

                //Agrega la factura a la colección de facturas
                NegocioPF.Facturas oFacturas = (NegocioPF.Facturas)Session["oFacturas"];
                DataRow            r         = oFacturas.Datos.Tables[0].NewRow();
                r["id_sociedad"] = cboSociedades.SelectedValue;
                r["folio"]       = 0;
                r["UUID"]        = txtFactura.Text;
                r["folioFact"]   = txtFactura.Text;
                r["emisor"]      = txtEmisor.Text.Substring(0, txtEmisor.Text.IndexOf(" "));
                r["receptor"]    = txtReceptor.Text.Substring(0, txtReceptor.Text.IndexOf(" "));
                r["ordenCompra"] = "";
                r["fecha"]       = NegocioPF.Rutinas.ConvierteTextToFecha(txtFecha.Text);
                r["importe"]     = txtTotal.Text;
                r["id_moneda"]   = cboMoneda.SelectedValue;
                r["pdf"]         = Session["pdf"].ToString();
                oFacturas.Datos.Tables[0].Rows.Add(r);
                oFacturas.Relacion.Add(oFactura);
                Session["oFacturas"] = oFacturas;

                grdFacturas.DataSource = oFacturas.Datos;
                grdFacturas.DataBind();

                oViewer.Visible     = false;
                divDetalle.Visible  = false;
                divFacturas.Visible = true;

                btnAceptar.Visible  = (oFacturas.Datos.Tables[0].Rows.Count > 0);
                btnCancelar.Visible = (oFacturas.Datos.Tables[0].Rows.Count > 0);

                divImportar.Visible = true;

                //ScriptManager.RegisterStartupScript(this, typeof(Page), "confirm", "<script>confirmation();</script>", false);
            }
            catch (Exception ex)
            {
                if (ex.Message.Substring(0, 3) == "Msg")
                {
                    MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto(ex.Message));
                }
                else
                {
                    MessageBox(sender, e, ex.Message);
                }
            }
        }
        protected void btnAceptarImportar_Click(object sender, EventArgs e)
        {
            //string tmp;
            bool existe;

            try
            {
                //Limpia los controles
                txtFactura.Text         = "";
                txtFecha.Text           = "";
                cboMoneda.SelectedValue = "0";
                txtImpSinIva.Text       = "";
                txtImpuestos.Text       = "";
                txtTotal.Text           = "";

                //Copia los archivos en la carpeta destino
                //string dirDestino = @System.Configuration.ConfigurationSettings.AppSettings["PathArchivos"].ToString();
                string dirDestino = Server.MapPath("") + "\\Facturas\\";
                string dirDestPDF = dirDestino;

                if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
                {
                    dirDestPDF += System.IO.Path.GetFileName(File1.PostedFile.FileName);
                    try
                    {
                        File1.PostedFile.SaveAs(dirDestPDF);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                if ((File3.PostedFile != null) && (File3.PostedFile.ContentLength > 0))
                {
                    dirDestino += System.IO.Path.GetFileName(File3.PostedFile.FileName);
                    try
                    {
                        File3.PostedFile.SaveAs(dirDestino);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                if ((File4.PostedFile != null) && (File4.PostedFile.ContentLength > 0))
                {
                    dirDestino += System.IO.Path.GetFileName(File4.PostedFile.FileName);
                    try
                    {
                        File4.PostedFile.SaveAs(dirDestino);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                if ((File5.PostedFile != null) && (File5.PostedFile.ContentLength > 0))
                {
                    dirDestino += System.IO.Path.GetFileName(File5.PostedFile.FileName);
                    try
                    {
                        File5.PostedFile.SaveAs(dirDestino);
                    }
                    catch (Exception ex)
                    {
                        MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto("MsgErrorCopiarArchivo"));
                    }
                }

                NegocioPF.Factura oFactura = new NegocioPF.Factura();

                NegocioPF.Sociedad oSociedad = new Sociedad(cboSociedades.SelectedValue);
                oSociedad.Cargar();

                txtReceptor.Text = oSociedad.RFC + " " + oSociedad.Nombre;

                oFactura.PDF      = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                oFactura.Sociedad = cboSociedades.SelectedValue;
                oFactura.Receptor = oSociedad.RFC;
                //oFactura.Emisor = oProveedor.RFC;

                //oFactura.PDF = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File1.PostedFile.FileName), 1));
                if (File3.PostedFile.FileName != "")
                {
                    oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File3.PostedFile.FileName), 3));
                }
                if (File4.PostedFile.FileName != "")
                {
                    oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File4.PostedFile.FileName), 4));
                }
                if (File5.PostedFile.FileName != "")
                {
                    oFactura.Archivos.Add(new NegocioPF.Archivo(System.IO.Path.GetFileName(File5.PostedFile.FileName), 5));
                }

                Session["pdf"]      = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                Session["oFactura"] = oFactura;

                //Muestra la factura en el visor
                if (File1.PostedFile.FileName.Length > 0)
                {
                    oViewer.Attributes.Add("src", "Facturas/" + System.IO.Path.GetFileName(File1.PostedFile.FileName));
                    oViewer.Visible  = true;
                    divVisor.Visible = true;
                }

                divImportar.Visible = false;
                divDetalle.Visible  = true;
            }
            catch (Exception ex)
            {
                MessageBox(sender, e, ((Idioma)Session["oIdioma"]).Texto(ex.Message));
            }
        }