示例#1
0
        public void GeneraXmlsINVOICE()
        {
            string      errores     = "";
            AppDbContex appDbContex = new AppDbContex();

            DataSetRproTableAdapters.VYVARTICULOSTableAdapter adapter = new DataSetRproTableAdapters.VYVARTICULOSTableAdapter();



            try
            {
                string xmlDoc        = "";
                string sbs           = "";
                string store         = "";
                string shiptoStoreNo = "";
                string AlusError     = "";
                string invoiceSid    = "";
                string invoiceNo     = "";

                //Cliente
                string CustXml    = "";
                string CustID     = "";
                string CustSid    = "";
                string rut        = ""; //normalizado
                string orderRut   = "";
                string ArchivoLog = "";
                //acumula clientes nuevos;
                string xmlCustomer = "";



                DateTime created_date = DateTime.Now;



                DataSetRpro.VYVARTICULOSDataTable ItemTable = new DataSetRpro.VYVARTICULOSDataTable();

                List <VentaDTOs> VentasList = appDbContex.VentaDTOs.Where(e => (e.folio != null &&
                                                                                e.InvoiceSid == null &&
                                                                                e.pdf != null)).Take(20).ToList <VentaDTOs>();

                Log("Pendientes: " + (Convert.ToString(VentasList.Count)), "Pendientes.txt");
                Log("Pendientes: ", "debug.txt");
                var cfg = Properties.Settings.Default;

                foreach (VentaDTOs pedidoRef in VentasList)
                {
                    VentaDTOs pedido = appDbContex.VentaDTOs.Find(pedidoRef.id);
                    ArchivoLog = pedido.id + "-" + pedido.folio.ToString() + ".txt";
                    EliminaLog(ArchivoLog);
                    pedido.FechaDocele = DateTime.Now;

                    try
                    {
                        appDbContex.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        errores += e.Message;
                        continue;
                    }


                    string createdDate = Convert.ToDateTime(pedido.created_date).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
                    string xml         = InvoiceCAB();

                    try
                    {
                        //parte limpio

                        Log("Verifica archivos pendientes en:  " + cfg.Invoice_CarpetaStation + @"\INVOICE999.xml", ArchivoLog, false);

                        //Impersonation.RunAsUser(credentials, LogonType.NewCredentials, () =>
                        //{

                        if (File.Exists(cfg.Invoice_CarpetaStation + @"\INVOICE999.xml"))
                        {
                            File.WriteAllText(ruta + @"\Info.txt", "Existen Xmls pendientes en carpeta " + cfg.Invoice_CarpetaStation + @"\INVOICE999.xml", Encoding.UTF8);

                            Log("Existen Xmls pendientes en carpeta " + cfg.Invoice_CarpetaStation + @"\INVOICE999.xml", ArchivoLog, true);

                            continue;
                        }

                        //});



                        Log("Invoice Cabecera", ArchivoLog, true);

                        int iSbs   = Convert.ToInt32(pedido.sbs_no);
                        int iStore = Convert.ToInt32(pedido.store_no);

                        sbs   = iSbs.ToString("00#");
                        store = iStore.ToString("00#");


                        //sSID:='1'+'0000'+ AdoQuery.FieldByname('invc_no').AsStng;

                        //  SBS   Store  TIpoDoc  1=Boleta 2=fatura etc... Folio 12 digitos
                        //  001   001     1


                        invoiceSid = sbs + store + "1" + Convert.ToString(pedido.folio).Trim().PadLeft(12, '0');
                        invoiceNo  = Convert.ToString(pedido.folio).Trim().PadLeft(9, '0');// item.folio.Trim();//. code.PadLeft(14, '0');

                        shiptoStoreNo = store;


                        //CLiente
                        try
                        {
                            string dv = "";
                            CustID = validarRut(pedido.cust_rut, out dv);

                            ////Rut Completo

                            rut = "";

                            if (!string.IsNullOrEmpty(CustID))
                            {
                                rut = CustID + "-" + dv;

                                if (dv.ToUpper() == "K")
                                {
                                    //-3204210179006066692
                                    //      11000140055692
                                    CustSid = "11000" + CustID + "0";
                                }
                                else
                                {
                                    CustSid = "11000" + CustID + dv;
                                }

                                var queriesTableAdapter = new ClientesTableAdapter();

                                var ClientesDb = queriesTableAdapter.GetData(Convert.ToDecimal(sbs), rut);

                                CustXml = "";

                                if (ClientesDb.Count() == 0)
                                {
                                    // Si no existe Sid para ese rut genera xml de creacion de cliente
                                    CustXml = CustomerXML();

                                    CustXml = CustXml.Replace("{cust_sid}", CustSid);
                                    CustXml = CustXml.Replace("{cust_id}", CustID);
                                    CustXml = CustXml.Replace("{sbs_no}", sbs);
                                    CustXml = CustXml.Replace("{store_no}", store);
                                    CustXml = CustXml.Replace("{first_name}", pedido.first_name.Norm(40));
                                    CustXml = CustXml.Replace("{last_name}", pedido.last_name.Norm(40));
                                    CustXml = CustXml.Replace("{info1}", rut);

                                    CustXml = CustXml.Replace("{created_date}", (DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss")));
                                    CustXml = CustXml.Replace("{modified_date}", (DateTime.Now.AddSeconds(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss")));

                                    CustXml = CustXml.Replace("{address1}", pedido.direccion1.Norm(40));
                                    CustXml = CustXml.Replace("{address2}", pedido.comuna.Norm(40));
                                    CustXml = CustXml.Replace("{address3}", pedido.ciudad.Norm(40));
                                    CustXml = CustXml.Replace("{address4}", "");
                                    CustXml = CustXml.Replace("{address5}", "");
                                    CustXml = CustXml.Replace("{address6}", "");
                                    CustXml = CustXml.Replace("{zip}", "");
                                    CustXml = CustXml.Replace("{phone1}", pedido.phone1.Norm(40)); // order.objFactura.DatosCliente.Telefono.Norm(40));
                                    CustXml = CustXml.Replace("{phone2}", pedido.phone2.Norm(40)); // order.objFactura.DatosCliente.Celular.Norm(40));
                                    CustXml = CustXml.Replace("{email_addr}", pedido.email_addr);  //order.objFactura.DatosCliente.Correo.Norm(40));
                                    CustXml = CustXml.Replace(@"{notes}", "");

                                    //CustXml = CustXml.Replace("{CustUdf1}", "");
                                    //CustXml = CustXml.Replace("{CustUdf2}", "");
                                    //CustXml = CustXml.Replace("{CustUdf3}", "");
                                    //CustXml = CustXml.Replace("{CustUdf4}", "");
                                    //CustXml = CustXml.Replace("{CustUdf5}", "");
                                    //CustXml = CustXml.Replace("{CustUdf6}", "");
                                    //CustXml = CustXml.Replace("{CustUdf7}", "");
                                    //CustXml = CustXml.Replace("{CustUdf8}", "");
                                    //CustXml = CustXml.Replace("{CustUdf9}", "");
                                    //CustXml = CustXml.Replace("{CustUdf10}", "");
                                    //CustXml = CustXml.Replace("{CustUdf11}", "");
                                    //CustXml = CustXml.Replace("{CustUdf12}", "");
                                    //CustXml = CustXml.Replace("{CustUdf13}", "");
                                    //CustXml = CustXml.Replace("{CustUdf14}", "");
                                    //CustXml = CustXml.Replace("{CustUdf15}", "");
                                    //CustXml = CustXml.Replace("{CustUdf16}", "");
                                    //CustXml = CustXml.Replace("{CustUdf17}", "");
                                    //CustXml = CustXml.Replace("{CustUdf18}", "");
                                    //CustXml = CustXml.Replace("{CustUdf19}", "");
                                    //CustXml = CustXml.Replace("{CustUdf20}", "");
                                }
                                else //cliente deberia existir trae custSid y CUstID para el rut
                                {
                                    DataSetRpro.ClientesRow clieRpro = ClientesDb.First();
                                    //devuelve custsid y cusId
                                    CustSid = clieRpro.CUST_SID;
                                    CustID  = clieRpro.CUST_ID;
                                }
                            }

                            string XmlInvcCust = InvoiceCustomer();

                            //incluye cliente
                            if (rut != "")
                            {
                                XmlInvcCust = XmlInvcCust.Replace("{cust_sid}", CustSid);
                                XmlInvcCust = XmlInvcCust.Replace("{cust_id}", CustID);
                                XmlInvcCust = XmlInvcCust.Replace("{store_no}", store);
                                XmlInvcCust = XmlInvcCust.Replace("{first_name}", pedido.first_name.Norm(40));
                                XmlInvcCust = XmlInvcCust.Replace("{last_name}", pedido.last_name.Norm(40));
                                XmlInvcCust = XmlInvcCust.Replace("{info1}", rut);
                                XmlInvcCust = XmlInvcCust.Replace("{modified_date}", DateTime.Now.AddSeconds(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"));
                                XmlInvcCust = XmlInvcCust.Replace("{sbs_no}", sbs);
                                XmlInvcCust = XmlInvcCust.Replace("{address1}", pedido.direccion1.Norm(40));
                                XmlInvcCust = XmlInvcCust.Replace("{address2}", pedido.comuna.Norm(40));
                                XmlInvcCust = XmlInvcCust.Replace("{address3}", pedido.ciudad.Norm(40));
                                XmlInvcCust = XmlInvcCust.Replace("{address4}", "");
                                XmlInvcCust = XmlInvcCust.Replace("{phone1}", pedido.phone1.Norm(40));
                                XmlInvcCust = XmlInvcCust.Replace("{phone2}", pedido.phone2.Norm(40));



                                xml = xml.Replace("<CUSTOMER/>", XmlInvcCust);
                                xml = xml.Replace("<SHIPTO_CUSTOMER/>", "");

                                xml = xml.Replace("{cust_sid}", CustSid);
                                xml = xml.Replace("{addr_no}", "1");
                                //llena la salida
                            }


                            xmlCustomer = xmlCustomer + CustXml;
                        }
                        catch (Exception)
                        {
                        }

                        //Fin CLiente

                        xml = xml.Replace("{invc_sid}", invoiceSid);
                        xml = xml.Replace("{sbs_no}", sbs);
                        xml = xml.Replace("{store_no}", store);
                        xml = xml.Replace("{invc_no}", invoiceNo);
                        xml = xml.Replace("{modified_date}", createdDate);
                        xml = xml.Replace("{created_date}", createdDate);
                        xml = xml.Replace("{tracking_no}", Convert.ToString(pedido.folio).Trim());
                        xml = xml.Replace("{fiscal_doc_id}", Convert.ToString(pedido.folio).Trim());

                        // cust_fld
                        xml = xml.Replace("{cust_fld}", "");

                        // CANAL ORIGEN
                        xml = xml.Replace("{comment_no_1}", "Venta Web");


                        xml = xml.Replace("{comment_no_2}", pedido.id);

                        xml = xml.Replace("{note}", "");


                        //pago

                        try
                        {
                            string cardName = "";
                            xml = xml.Replace("{udf_no1}", cfg.Invoice_FlagName);

                            Log("Pago " + errores, ArchivoLog, true);



                            foreach (var pago in pedido.Pagos)
                            {
                                try
                                {
                                    if (string.IsNullOrEmpty(pago.tender_type))
                                    {
                                        Log("Pago tender_type no especificado: ", ArchivoLog, true);
                                    }
                                }
                                catch (Exception)
                                {
                                }


                                //if ((pago.tender_type.ToUpper() == "EFECTIVO")|| (pago.tender_type.ToUpper() == "EFECIVO"))
                                //{
                                //    xml = xml.Replace("{tender_type}", "0");//0 efectivo 2 credito
                                //    xml = xml.Replace("{montoPago}", pedido.total_amt.ToString());
                                //    xml = xml.Replace("{auth}", "");
                                //    xml = xml.Replace("{crd_name}", "");
                                //    xml = xml.Replace("{eftdata0}", "");
                                //    xml = xml.Replace("{eftdata1}", "");
                                //    xml = xml.Replace("{eftdata2}", "");
                                //    xml = xml.Replace("{eftdata3}", "");
                                //    xml = xml.Replace("{eftdata4}", "");
                                //    xml = xml.Replace("{eftdata5}", "");
                                //    xml = xml.Replace("{eftdata6}", "");
                                //    xml = xml.Replace("{eftdata7}", "");
                                //    xml = xml.Replace("{eftdata8}", "");
                                //    xml = xml.Replace("{eftdata9}", "");
                                //    xml = xml.Replace("{eftdata10}", "");
                                //}
                                //else
                                string crdName = "";

                                if (pago.tender_type.ToUpper() == "DEBITO")
                                {
                                    crdName = "DWEB";
                                    xml     = xml.Replace("{tender_type}", "11");
                                    xml     = xml.Replace("{montoPago}", pedido.total_amt.ToString());
                                    xml     = xml.Replace("{auth}", pago.auth_no);
                                    xml     = xml.Replace("{crd_name}", crdName);
                                    xml     = xml.Replace("{eftdata0}", "DB");
                                    xml     = xml.Replace("{eftdata1}", "0");
                                    xml     = xml.Replace("{eftdata2}", crdName);
                                    xml     = xml.Replace("{eftdata3}", pago.op_no);
                                    xml     = xml.Replace("{eftdata4}", "0");
                                    xml     = xml.Replace("{eftdata5}", pago.comments);
                                    xml     = xml.Replace("{eftdata6}", "0");
                                    xml     = xml.Replace("{eftdata7}", "0");
                                    xml     = xml.Replace("{eftdata8}", "0");
                                    xml     = xml.Replace("{eftdata9}", "0");
                                    xml     = xml.Replace("{eftdata10}", "0");
                                }
                                else
                                {
                                    crdName = "CWEB";
                                    xml     = xml.Replace("{tender_type}", "2"); // 2 credito
                                    xml     = xml.Replace("{montoPago}", pedido.total_amt.ToString());
                                    xml     = xml.Replace("{auth}", pago.auth_no);
                                    xml     = xml.Replace("{crd_name}", crdName);
                                    xml     = xml.Replace("{eftdata0}", "CR");
                                    if (string.IsNullOrEmpty(pago.cuotas))
                                    {
                                        xml = xml.Replace("{eftdata1}", "1");
                                    }
                                    else
                                    {
                                        xml = xml.Replace("{eftdata1}", pago.cuotas.ToString());
                                    }

                                    xml = xml.Replace("{eftdata2}", crdName);
                                    xml = xml.Replace("{eftdata3}", pago.op_no);
                                    xml = xml.Replace("{eftdata4}", "0");
                                    xml = xml.Replace("{eftdata5}", pago.comments);
                                    xml = xml.Replace("{eftdata6}", "0");
                                    xml = xml.Replace("{eftdata7}", "0");
                                    xml = xml.Replace("{eftdata8}", "0");
                                    xml = xml.Replace("{eftdata9}", "0");
                                    xml = xml.Replace("{eftdata10}", "0");
                                }


                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Pago con error en: " + ex, ArchivoLog, true);
                        }


                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'TENDER_TYPE', ttCreditCard);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'AMT', AttrValue.Monto);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'DOC_NO', AttrValue.NumeroTarjeta);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'AUTH', AttrValue.Autorizacion);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'CRD_TYPE', AttrValue.Crd_Type);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA0', AttrValue.TipoTarjeta);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA1', AttrValue.Cuotas);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA2', AttrValue.NombreTarjeta);
                        //
                        //campos adicionales en pos integrado
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA3', AttrValue.NrOperacion);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA4', AttrValue.MontoCuota);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA5', AttrValue.Cuenta);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA6', AttrValue.FechaOperacion);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA7', AttrValue.HoraOperacion);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA8', AttrValue.CodComercio);
                        //fAdapter.BOSetAttributeValueByName(TenderHnd, 'EFTDATA9', AttrValue.TerminalID);


                        int    index        = 0;
                        double ItemUnitario = 0;
                        double dif          = 0;
                        AlusError = "";

                        Log("Articulos  ", ArchivoLog);
                        foreach (var linea in pedido.Items)
                        {
                            index = index + 1;
                            string tempItem = InvoiceITEM();
                            ItemUnitario = Convert.ToDouble(linea.PriceLine / linea.qty);



                            tempItem = tempItem.Replace("{item_pos}", index.ToString());
                            tempItem = tempItem.Replace("{store_no}", shiptoStoreNo);
                            tempItem = tempItem.Replace("{price}", Convert.ToInt32(Math.Round(ItemUnitario)).ToString());
                            tempItem = tempItem.Replace("{orig_price}", Convert.ToInt32(Math.Round(ItemUnitario)).ToString());

                            //totalItems += checkoutitem.totalWithDiscount;

                            tempItem = tempItem.Replace("{qty}", Convert.ToInt32(linea.qty).ToString());
                            tempItem = tempItem.Replace("{alu}", linea.itemcode);



                            Log("FillByAlu:  " + linea.itemcode, ArchivoLog, true);

                            try
                            {
                                adapter.FillBySbsAlu(ItemTable, linea.itemcode, iSbs.ToString());
                            }
                            catch (Exception oraEx)
                            {
                                Log("verifique vista VyVProductos " + oraEx.Message + " " + oraEx.InnerException, "OracleError.txt");
                            }



                            Log("ItemTable.Count: :  ", ArchivoLog, true);
                            if (ItemTable.Count > 0)
                            {
                                DataSetRpro.VYVARTICULOSRow rowItem = ItemTable.First();

                                tempItem = tempItem.Replace("{item_sid}", rowItem.ITEM_SID);
                                //tempItem = tempItem.Replace("{descripcion1}", rowItem.DESCRIPTION1);
                                tempItem = tempItem.Replace("{tax_code}", rowItem.TAX_CODE.ToString());



                                tempItem = tempItem.Replace("{tax_amt}", (Convert.ToDecimal(ItemUnitario) * (rowItem.TAX_PERC1 / 100)).ToString("#.00")).Replace(",", ".");

                                tempItem = tempItem.Replace("{tax_perc}", Convert.ToString(rowItem.TAX_PERC1).Replace(",", "."));

                                tempItem = tempItem.Replace("{cost}", Math.Round(rowItem.COST).ToString());
                                tempItem = tempItem.Replace("{price_level}", "1");
                            }
                            else
                            {
                                //checkoutitem.ProductVersion.code
                                AlusError += linea.itemcode + "\r\n";
                            }

                            xml += tempItem;
                            Log("xml: " + xml, "debug.txt");
                        }
                    }
                    catch (Exception e3)
                    {
                        errores += pedido.id + " " + e3.Message + " " + xml + "\r\n";
                        xml      = "";
                    }


                    if (AlusError != "")
                    {
                        //alus con error no se procesa

                        //ile.WriteAllText(ruta + @"\logs\AluError_" + entry._id + ".txt", AlusError, Encoding.UTF8);
                        Log("AluError: " + AlusError, ArchivoLog, true);

                        xml = "";

                        try
                        {
                            pedido.InvoiceSid   = null;
                            pedido.ErrorInvoice = "articulo no existe " + AlusError;
                            appDbContex.SaveChanges();
                        }
                        catch (Exception e1)
                        {
                            File.WriteAllText(ruta + @"SaveInvoiceError.txt", e1.Message, Encoding.UTF8);
                            Log("SaveChangesInvoiceError " + e1.Message, ArchivoLog, true);
                        }
                    }

                    if (string.IsNullOrEmpty(xml))
                    {
                        continue;
                    }

                    xml += @"</INVC_ITEMS><INVC_FEES/><INVC_COMMENTS/></INVOICE>";

                    xmlDoc += xml;

                    //Actualizamos SId

                    try
                    {
                        Log("SaveChanges: ", ArchivoLog);

                        pedido.InvoiceSid   = invoiceSid;
                        pedido.ErrorInvoice = "OK";
                        appDbContex.SaveChanges();
                        Log("Save: OK ", ArchivoLog, true);
                    }
                    catch (Exception e)
                    {
                        Log("Save: ERROR " + e.Message, ArchivoLog, true);
                        errores += e.Message;
                    }
                }

                if (string.IsNullOrEmpty(xmlDoc))
                {
                    return;
                }


                try
                {
                    xmlDoc = InvoiceDOC() + xmlDoc + "</INVOICES></DOCUMENT>";

                    if (!string.IsNullOrEmpty(xmlCustomer))
                    {
                        xmlCustomer = CustDOC() + xmlCustomer + @"</CUSTOMERS></DOCUMENT>";

                        File.WriteAllText(cfg.Invoice_CarpetaStation + @"\CUSTOMER666.xml", xmlCustomer, Encoding.UTF8);
                        File.WriteAllText(ruta + @"\CUSTOMER666.xml", xmlCustomer, Encoding.UTF8);
                    }

                    // var credentials = new UserCredentials("frch", "retail", "SAP.0209");
                    // Impersonation.RunAsUser(credentials, LogonType.NewCredentials

                    //escribe en carpeta de integracion ECM con autentificacion para RUTAS EN RED

                    //Impersonation.RunAsUser(credentials, LogonType.NewCredentials, () =>
                    // {
                    File.WriteAllText(cfg.Invoice_CarpetaStation + @"\INVOICE999.xml", xmlDoc, Encoding.UTF8);
                    File.WriteAllText(ruta + @"\INVOICE999.xml", xmlDoc, Encoding.UTF8);

                    //});
                }
                catch (Exception e)
                {
                    errores = errores + e.Message;
                }

                if (errores != "")
                {
                    Log("Errores: " + errores, ArchivoLog, true);
                    File.WriteAllText(ruta + @"\Errores.txt", errores);
                }


                if (errores != "")
                {
                    Log("Errores: " + errores, ArchivoLog, true);
                    File.WriteAllText(ruta + @"\Errores.txt", errores);
                }
            }
            catch (Exception e)
            {
                File.WriteAllText(ruta + @"\GeneraXmlsInvoiceError.txt", "Linea: " + e.StackTrace + " " + e.InnerException + " " + e.Message, Encoding.UTF8);
                if (errores != "")
                {
                    File.WriteAllText(ruta + @"\ErrorInvc.txt", errores);
                }
            }
            finally
            {
                appDbContex.Dispose();
            }

            return;
        }
示例#2
0
 public static vodastarDataSet.ClientesDataTable ObtenerClientes()
 {
     clientesTabla = clientesAdapter.GetData();
     return(clientesTabla);
 }