public string InsertItem(ref QuickbooksQueries quickbooksQueries, ref BillLineItem item, int recursive_int = 1) { //specialAccounts = specialAccounts = new Dictionary <BillLineItemType, string>(); foreach (KeyValuePair <string, Account> account in quickbooksQueries.Accounts) { switch (account.Value.satAccount.NumCta) { case "50301": specialAccounts[BillLineItemType.Descuentos] = account.Value.listId; break; case "21610": specialAccounts[BillLineItemType.RetencionesIVA] = account.Value.listId; break; case "216": specialAccounts[BillLineItemType.RetencionesISR] = account.Value.listId; break; case "11901": specialAccounts[BillLineItemType.TrasladosIVA] = account.Value.listId; break; case "11903": specialAccounts[BillLineItemType.TrasladosIEPS] = account.Value.listId; break; case "40101": specialAccounts[BillLineItemType.TaxedAccount] = account.Value.listId; break; case "40104": specialAccounts[BillLineItemType.NonTaxedAccount] = account.Value.listId; break; case "11501": specialAccounts[BillLineItemType.Inventario] = account.Value.listId; break; case "CLASIFICACION PENDIENTE": specialAccounts[BillLineItemType.ClasificacionPendiente] = account.Value.listId; break; } } //Creates item XmlDocument inputItemXMLDoc; XmlElement qbXMLMsgsRq; QuickbooksUtils.BuildXMLQueryBase(out inputItemXMLDoc, out qbXMLMsgsRq); // Mark as query type XmlElement ItemsAddRq = inputItemXMLDoc.CreateElement("ItemNonInventoryAddRq"); qbXMLMsgsRq.AppendChild(ItemsAddRq); XmlElement itemXML = inputItemXMLDoc.CreateElement("ItemNonInventoryAdd"); ItemsAddRq.AppendChild(itemXML); XmlElement itemNameXML = inputItemXMLDoc.CreateElement("Name"); itemNameXML.InnerText = item.descripcion.Substring(0, Math.Min(28, item.descripcion.Length)); itemXML.AppendChild(itemNameXML); XmlElement itemProductKeyXML = inputItemXMLDoc.CreateElement("ManufacturerPartNumber"); itemProductKeyXML.InnerText = item.claveprodserv; itemXML.AppendChild(itemProductKeyXML); if (quickbooksQueries.Uoms.ContainsKey(item.claveunidad)) { XmlElement uomXML = inputItemXMLDoc.CreateElement("UnitOfMeasureSetRef"); itemXML.AppendChild(uomXML); XmlElement uomNameXML = inputItemXMLDoc.CreateElement("ListID"); uomNameXML.InnerText = quickbooksQueries.Uoms[item.claveunidad].listId; uomXML.AppendChild(uomNameXML); } //Fields For non item inventory TESTING WORKING /* * XmlElement salesOrPurchaseXML = inputItemXMLDoc.CreateElement("SalesOrPurchase"); * itemXML.AppendChild(salesOrPurchaseXML); * * * XmlElement salesDescXML = inputItemXMLDoc.CreateElement("Desc"); * salesDescXML.InnerText = item.descripcion; * salesOrPurchaseXML.AppendChild(salesDescXML); * * * XmlElement salesPriceXML = inputItemXMLDoc.CreateElement("Price"); * salesPriceXML.InnerText = item.importe.ToString(); * salesOrPurchaseXML.AppendChild(salesPriceXML); * * XmlElement incomeAccountXML = inputItemXMLDoc.CreateElement("AccountRef"); * salesOrPurchaseXML.AppendChild(incomeAccountXML); * * XmlElement incomeAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); * incomeAccountListIdXML.InnerText = specialAccounts[BillLineItemType.ClasificacionPendiente]; * incomeAccountXML.AppendChild(incomeAccountListIdXML); * */ XmlElement salesTaxCodeXML = inputItemXMLDoc.CreateElement("SalesTaxCodeRef"); itemXML.AppendChild(salesTaxCodeXML); XmlElement salesTaxIdXML = inputItemXMLDoc.CreateElement("ListID"); if (item.createsTax) { salesTaxIdXML.InnerText = quickbooksQueries.Taxes["Tax"].listId; } else { salesTaxIdXML.InnerText = quickbooksQueries.Taxes["Non"].listId; } salesTaxCodeXML.AppendChild(salesTaxIdXML); //Fields For non item inventory TESTING XmlElement salesAndPurchaseXML = inputItemXMLDoc.CreateElement("SalesAndPurchase"); itemXML.AppendChild(salesAndPurchaseXML); XmlElement salesDescXML = inputItemXMLDoc.CreateElement("SalesDesc"); salesDescXML.InnerText = item.descripcion; salesAndPurchaseXML.AppendChild(salesDescXML); XmlElement salesPriceXML = inputItemXMLDoc.CreateElement("SalesPrice"); salesPriceXML.InnerText = "0";//item.importe.ToString(); salesAndPurchaseXML.AppendChild(salesPriceXML); XmlElement incomeAccountXML = inputItemXMLDoc.CreateElement("IncomeAccountRef"); salesAndPurchaseXML.AppendChild(incomeAccountXML); XmlElement incomeAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); if (item.createsTax) { incomeAccountListIdXML.InnerText = specialAccounts[BillLineItemType.TaxedAccount]; } else { incomeAccountListIdXML.InnerText = specialAccounts[BillLineItemType.NonTaxedAccount]; } incomeAccountXML.AppendChild(incomeAccountListIdXML); XmlElement purchaseDescXML = inputItemXMLDoc.CreateElement("PurchaseDesc"); purchaseDescXML.InnerText = item.descripcion; salesAndPurchaseXML.AppendChild(purchaseDescXML); XmlElement purchaseCostXML = inputItemXMLDoc.CreateElement("PurchaseCost"); purchaseCostXML.InnerText = "0"; //item.importe.ToString(); salesAndPurchaseXML.AppendChild(purchaseCostXML); XmlElement expenseAccountXML = inputItemXMLDoc.CreateElement("ExpenseAccountRef"); salesAndPurchaseXML.AppendChild(expenseAccountXML); XmlElement expenseAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); if (item.is_invoice) { expenseAccountListIdXML.InnerText = specialAccounts[BillLineItemType.Inventario]; } else { expenseAccountListIdXML.InnerText = specialAccounts[BillLineItemType.ClasificacionPendiente]; } expenseAccountXML.AppendChild(expenseAccountListIdXML); //XmlElement prodKey = inputItemXMLDoc.CreateElement("IncludeRetElement"); //prodKey.InnerText = "CLAVEPROD"; //itemXML.AppendChild(prodKey); /* * XmlElement vendorAccountXML = inputItemXMLDoc.CreateElement("PrefVendorRef"); * salesAndPurchaseXML.AppendChild(vendorAccountXML); * * XmlElement vendorAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); * vendorAccountListIdXML.InnerText = specialAccounts[BillLineItemType.ClasificacionPendiente]; * vendorAccountXML.AppendChild(vendorAccountListIdXML); */ //string updateResponse; //Fields for item inventory /* * * XmlElement incomeAccountXML = inputItemXMLDoc.CreateElement("IncomeAccountRef"); * itemXML.AppendChild(incomeAccountXML); * * XmlElement incomeAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); * incomeAccountListIdXML.InnerText = specialAccounts[BillLineItemType.ClasificacionPendiente]; * incomeAccountXML.AppendChild(incomeAccountListIdXML); * * XmlElement cogsAccountXML = inputItemXMLDoc.CreateElement("COGSAccountRef"); * itemXML.AppendChild(cogsAccountXML); * * XmlElement cogsAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); * cogsAccountListIdXML.InnerText = specialAccounts[BillLineItemType.ClasificacionPendiente]; * cogsAccountXML.AppendChild(cogsAccountListIdXML); * * * * * XmlElement assetAccountXML = inputItemXMLDoc.CreateElement("AssetAccountRef"); * itemXML.AppendChild(assetAccountXML); * * XmlElement assetAccountListIdXML = inputItemXMLDoc.CreateElement("ListID"); * assetAccountListIdXML.InnerText = specialAccounts[BillLineItemType.ClasificacionPendiente]; * assetAccountXML.AppendChild(assetAccountListIdXML); */ string msg = "some_msg"; string qbResponse; ItemAdder itemAdder = new ItemAdder(); if (quickbooksQueries.QueryQB(inputItemXMLDoc.OuterXml, out qbResponse)) { QuicbooksResponse qbResultQuery = new QuicbooksResponse(qbResponse, "ItemNonInventoryAddRs"); if (qbResultQuery.GetNumberOfResulst() > 0) { if (qbResultQuery.success) { //qbXMLMsgsRsNodeList //itemlistId = ""; msg = "Item created"; XmlNodeList responseNodeList = qbResultQuery.GetXmlNodeList().Item(0).ChildNodes; foreach (XmlNode responseNode in responseNodeList) { Item new_item = new Item(); if (responseNode["ListID"] != null) { new_item.listId = responseNode["ListID"].InnerText; } if (responseNode["Name"] != null) { new_item.name = responseNode["Name"].InnerText; } if (responseNode["FullName"] != null) { new_item.fullName = responseNode["FullName"].InnerText; } if (responseNode["ManufacturerPartNumber"] != null) { new_item.productKey = responseNode["ManufacturerPartNumber"].InnerText; } if (responseNode["UnitOfMeasureSetRef"] != null) { foreach (XmlNode DataRowNode in responseNode["UnitOfMeasureSetRef"]) { if (DataRowNode["ListID"] != null) { new_item.uomListId = DataRowNode["ListID"].InnerText; } if (DataRowNode["FullName"] != null) { new_item.uomFullName = DataRowNode["FullName"].InnerText; } } } if (!String.IsNullOrEmpty(new_item.listId)) { //itemlistId = new_item.listId; //Items[new_item.productKey] = new_item; quickbooksQueries.Items[new_item.productKey] = new_item; return(null); } else { return("Item no tiene List id " + new_item.name); } } } else { if (recursive_int < 7) { ++recursive_int; item.descripcion = item.descripcion.Substring(0, Math.Min(26, item.descripcion.Length)) + "-" + recursive_int.ToString(); //item.descripcion = item.descripcion + " - " + recursive_int.ToString(); string itemAdderResult = itemAdder.InsertItem(ref quickbooksQueries, ref item, recursive_int); return(itemAdderResult); } else { return("No se puede agregar item " + item.descripcion); } } } else { // It could be a same item name..// QB doesnt allow 2 items with same name msg = "Quickbooks regresó una respuesta vacía al agregar item "; } } else { msg = "Se produjo un error al agregar insertar item "; } string some_string = msg;// To debug return(some_string); }
private void startBillImport(string[] files) { List <BillParser> billParsers = new List <BillParser>(); string[] headers = { "RFC", "Nombre", "Total", "Descuentos", "Retenciones IVA", "Retenciones ISR", "Traslados IVA", "Traslados IEPS", "Status Proveedor", "Status Factura", "Tipo", "UUID", "Numero" }; List <List <string> > values = new List <List <string> >(); int fileIndex = 0; foreach (var filename in files) { ++fileIndex; BillParser billParser = new BillParser(); billParser.Load(filename); if (billParser.Parse(mainRfc)) { Vendor vendor = billParser.GetVendor(); Client client = billParser.GetClient(); string not_invoice_error_msg = ""; if (mainRfc != vendor.rfc && mainRfc != client.rfc) { not_invoice_error_msg = "El RFC del emisor: " + vendor.rfc + " y el RFC del receptor: " + client.rfc + " no corresponden con el RFC de QB: " + mainRfc; } string vendor_or_client_rfc = "Error!";//Load this in a single var string vendor_or_client_name = "Error!"; string invoice_or_bill = "Error!"; billParsers.Add(billParser); Bill bill = billParser.GetBill(); List <string> gridRow = new List <string>(); if (bill.tipoComprobante == "n") { invoice_or_bill = "NOMINA!"; vendor_or_client_rfc = "NOMINA!"; vendor_or_client_name = "NOMINA!"; not_invoice_error_msg = "NOMINA!"; } else { if (vendor.rfc == mainRfc) { invoice_or_bill = "Invoice"; vendor_or_client_rfc = client.rfc; vendor_or_client_name = client.nombre; } else if (client.rfc == mainRfc) { invoice_or_bill = "Bill"; vendor_or_client_rfc = vendor.rfc; vendor_or_client_name = vendor.nombre; } } gridRow.Add(vendor_or_client_rfc); gridRow.Add(vendor_or_client_name); gridRow.Add(bill.total.ToString("C2")); gridRow.Add(bill.descuento.ToString("C2")); gridRow.Add(bill.retencionesIVA.ToString("C2")); gridRow.Add(bill.retencionesISR.ToString("C2")); gridRow.Add(bill.trasladosIVA.ToString("C2")); gridRow.Add(bill.trasladosIEPS.ToString("C2")); gridRow.Add(""); gridRow.Add(not_invoice_error_msg); gridRow.Add(invoice_or_bill); gridRow.Add(bill.uuid); gridRow.Add(fileIndex.ToString()); values.Add(gridRow); } } int[] widths = { 100, 240, 70, 60, 60, 60, 60, 60, 100, 100 }; ImportResults importResults = new ImportResults(); importResults.StartPosition = FormStartPosition.Manual; importResults.Location = new Point(this.Location.X + this.Size.Width, this.Location.Y + 20); importResults.SetGrid(headers, values); importResults.SetWidths(widths); importResults.SetOption1Checkbox("Sólo importar CATALOGOS", false); importResults.SetOption2Checkbox("Modo SIMULACIÓN", false); var results = importResults.ShowDialog(); if (results == DialogResult.OK) { pBar pbar = new pBar(); pbar.StartPosition = FormStartPosition.Manual; pbar.Location = new Point(this.Location.X + this.Size.Width, this.Location.Y + 20); //pbar.ShowDialog(); pbar.Show(); ProgressBar pbar1 = pbar.progressBar1; pbar1.Minimum = 0; pbar1.Maximum = billParsers.Count(); int billIndex = -1; foreach (BillParser billParser in billParsers) { ++billIndex; pbar1.Value = billIndex; //Importar Clientes/Provedores Vendor vendor = billParser.GetVendor(); Client client = billParser.GetClient(); List <BillLineItem> lineItems = billParser.GetLineItems(); Bill bill = billParser.GetBill(); bool is_invoice = (mainRfc == vendor.rfc); bool is_bill = (mainRfc == client.rfc); bool is_payroll = bill.tipoComprobante == "n"; if ((is_invoice || is_bill) && !is_payroll) { if (is_invoice) { // Crear Client, si no existe /*aqui puede ser */ /*Genera una cadena agregando el nombre y dlls*/ /*if (client.rfc == "XEXX010101000")*/ if (bill.moneda != "mxn") { client.nombre = client.nombre + "-DLLS"; var splited = client.nombre.ToUpper().Split('-')[0]; client.rfc = client.rfc + "-DLLS-" + splited; } else { client.rfc = client.rfc + "-" + client.nombre; } if (!quickbooksQueries.Clients.ContainsKey(client.rfc)) { ClientAdder customerAdder = new ClientAdder(); if (!importResults.GetOption2Checkbox()) { string customerAdderResult = customerAdder.InsertClient(ref quickbooksQueries, ref client, 1, bill.moneda); if (String.IsNullOrWhiteSpace(customerAdderResult)) { Console.Write(values.ElementAt(billIndex)); values.ElementAt(billIndex)[8] = "Creado"; // Add validation ElemenaAt(billIndex) not null quickbooksQueries.Clients[client.rfc] = client; } else { values.ElementAt(billIndex)[8] = customerAdderResult; continue; } } else { values.ElementAt(billIndex)[8] = "Crear"; } } else { Debug.Write(values.ElementAt(billIndex)); values.ElementAt(billIndex)[8] = "Existente"; } } else if (is_bill) { /*aqui puede ser */ if (bill.moneda != "mxn") { vendor.nombre = vendor.nombre + "-DLLS"; var splited = vendor.nombre.ToUpper().Split('-')[0]; vendor.rfc = vendor.rfc + "-DLLS-" + splited; } else { client.rfc = client.rfc + "-" + client.nombre; } // Crear Vendor, si no existe if (!quickbooksQueries.Vendors.ContainsKey(vendor.rfc)) { VendorAdder vendorAdder = new VendorAdder(); if (!importResults.GetOption2Checkbox()) { string vendorAdderResult = vendorAdder.InsertVendor(ref quickbooksQueries, ref vendor); if (String.IsNullOrWhiteSpace(vendorAdderResult)) { Console.Write(values.ElementAt(billIndex)); values.ElementAt(billIndex)[8] = "Creado"; // Add validation ElemenaAt(billIndex) not null quickbooksQueries.Vendors[vendor.rfc] = vendor; } else { values.ElementAt(billIndex)[8] = vendorAdderResult; continue; } } else { values.ElementAt(billIndex)[8] = "Crear"; } } else { Debug.Write(values.ElementAt(billIndex)); values.ElementAt(billIndex)[8] = "Existente"; } } //Loop Items List <bool> created_items = new List <bool>(); foreach (BillLineItem item in lineItems) { // Crear Item, si no existe BillLineItem new_item = item; string item_msg = "Factura " + bill.uuid + " " + item.claveprodserv + " => " + item.unidad + " " + item.descripcion; string unit_msg = "Factura " + bill.uuid + " " + item.claveunidad + " => " + item.unidad + " " + item.descripcion; //foreach (LineItemContribution item_contribution in item.contributions) //{ // string perc_string = (item_contribution.percentage * 100).ToString(); // string claveProd = item.descripcion + "-" + item_contribution.name + "-" + perc_string; //} if (!quickbooksQueries.Uoms.ContainsKey(item.claveunidad)) { System.Diagnostics.Trace.WriteLine("UNIT NO existe " + unit_msg); UomAdder uomAdder = new UomAdder(); if (!importResults.GetOption2Checkbox()) { string itemAdderResult = uomAdder.InsertUom(ref quickbooksQueries, ref new_item); if (String.IsNullOrWhiteSpace(itemAdderResult)) { System.Diagnostics.Trace.WriteLine("UNIT creado exitosamente"); } else { System.Diagnostics.Trace.WriteLine("UNIT no puedo ser creado :/"); } } } else { System.Diagnostics.Trace.WriteLine("UNIT existe " + unit_msg); } if (!quickbooksQueries.Items.ContainsKey(item.claveprodserv)) { //string new_msg = System.Diagnostics.Trace.WriteLine("Item NO existe " + item_msg); ItemAdder itemAdder = new ItemAdder(); if (!importResults.GetOption2Checkbox()) { string itemAdderResult = itemAdder.InsertItem(ref quickbooksQueries, ref new_item); if (String.IsNullOrWhiteSpace(itemAdderResult)) { //Insert claveprodserv in customField DataExtAdder dataExtAdder = new DataExtAdder(); string itemListID = quickbooksQueries.Items[item.claveprodserv].listId; string dataExtAdderResult = dataExtAdder.insertData(ref quickbooksQueries, itemListID, item.claveprodserv); if (String.IsNullOrWhiteSpace(dataExtAdderResult)) { string str_dataAdderms = "some msg"; } } else { created_items.Add(false); //values.ElementAt(billIndex)[8] = vendorAdderResult; //continue; } } else { //values.ElementAt(billIndex)[8] = "Crear"; } } else { System.Diagnostics.Trace.WriteLine("Item EXISTE " + item_msg); } } if (!importResults.GetOption1Checkbox() && !importResults.GetOption2Checkbox() && !created_items.Contains(false)) { if (is_invoice) { } if (is_invoice) { InvoiceAdder billAdder = new InvoiceAdder(ref quickbooksQueries.Accounts, quickbooksQueries.Clients[client.rfc]); string billAdderResult = billAdder.InsertInvoice(ref quickbooksQueries, bill); if (String.IsNullOrWhiteSpace(billAdderResult)) { values.ElementAt(billIndex)[9] = "Creada"; } else { values.ElementAt(billIndex)[9] = billAdderResult; } } else if (is_bill) { // Crear el Bill BillAdder billAdder = new BillAdder(ref quickbooksQueries.Accounts, quickbooksQueries.Vendors[vendor.rfc]); string billAdderResult = billAdder.InsertBill(ref quickbooksQueries, bill); if (String.IsNullOrWhiteSpace(billAdderResult)) { values.ElementAt(billIndex)[9] = "Creada"; } else { values.ElementAt(billIndex)[9] = billAdderResult; } } } else { values.ElementAt(billIndex)[9] = "Ignorada"; } } } pbar.Close(); // Resultados de la importacion importResults = new ImportResults(); importResults.StartPosition = FormStartPosition.Manual; importResults.Location = new Point(this.Location.X + this.Size.Width, this.Location.Y + 20); importResults.SetAcknowledge(); importResults.SetGrid(headers, values); importResults.SetWidths(widths); results = importResults.ShowDialog(); // Recargar vendors al final startProcessing(); } }