public bool TransferirStock(string origen, string destino, string producto, string lote, double cantidad) { string numTrans; //Hacer la transferencia SAPbobsCOM.StockTransfer stockTransfer = (SAPbobsCOM.StockTransfer)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oStockTransfer); stockTransfer.DocDate = DateTime.Now; stockTransfer.FromWarehouse = origen; stockTransfer.ToWarehouse = destino; stockTransfer.Lines.ItemCode = producto; stockTransfer.Lines.WarehouseCode = destino; stockTransfer.Lines.Quantity = cantidad; stockTransfer.Lines.BatchNumbers.BatchNumber = lote; stockTransfer.Lines.BatchNumbers.Quantity = cantidad; stockTransfer.Lines.BatchNumbers.Add(); stockTransfer.Lines.Add(); stockTransfer.Add(); numTrans = oCompany.GetNewObjectKey(); if (stockTransfer.Add() == 0) { return(true); } else { return(false); } //Traer el nĂºmero de transferencia //numTrans = oCompany.GetNewObjectKey(); }
private void DIA_CreateBP_Click(object sender, EventArgs e) { try { if (this.objCompany == null || !objCompany.Connected) { this.connect(); } if (this.objCompany != null && objCompany.Connected) { SAPbobsCOM.BusinessPartners oBP = null; int retCode = -1; String retMess = ""; oBP = objCompany.GetBusinessObject( SAPbobsCOM.BoObjectTypes.oBusinessPartners); oBP.CardCode = DIA_BPCode.Text; oBP.CardName = "Insert via DIAPI - " + DIA_BPCode.Text; oBP.CardType = SAPbobsCOM.BoCardTypes.cCustomer; retCode = oBP.Add(); if (retCode != 0) { retMess = objCompany.GetLastErrorDescription(); } else { retMess = "BP inserted successfully! - " + objCompany.GetNewObjectKey(); } MessageBox.Show(retMess); } } catch (Exception er) { MessageBox.Show(er.Message); } }
public int InsertOrder(Pedido pedido, out string messageError) { this.log = new Log(); try { int oOrderNum = 0; log.WriteLogPedido("Inserindo Pedido de Venda"); SAPbobsCOM.Documents oOrder = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders); int filial = Convert.ToInt32(ConfigurationManager.AppSettings["Empresa"]); string usage = ConfigurationManager.AppSettings["Usage"]; string WhsCode = ConfigurationManager.AppSettings["WhsCode"]; int SlpCode = Convert.ToInt32(ConfigurationManager.AppSettings["SlpCode"]); string comments = ConfigurationManager.AppSettings["Comments"]; string plataforma = ConfigurationManager.AppSettings["Plataforma"]; string carrier = ConfigurationManager.AppSettings["Carrier"]; string packDesc = ConfigurationManager.AppSettings["PackDesc"]; int qoP = Convert.ToInt32(ConfigurationManager.AppSettings["QoP"]); int expnsCode = Convert.ToInt32(ConfigurationManager.AppSettings["ExpnsCode"]); string expnsTax = ConfigurationManager.AppSettings["ExpnsTax"]; string cardCodePrefix = ConfigurationManager.AppSettings["CardCodePrefix"]; string pickRemark = ConfigurationManager.AppSettings["PickRemark"]; oOrder.BPL_IDAssignedToInvoice = filial; oOrder.NumAtCard = pedido.orderId; oOrder.SalesPersonCode = SlpCode; oOrder.Comments = comments; oOrder.UserFields.Fields.Item("U_PLATF").Value = plataforma; oOrder.UserFields.Fields.Item("U_NumPedEXT").Value = pedido.orderId; oOrder.TaxExtension.Carrier = carrier; oOrder.TaxExtension.PackDescription = packDesc; oOrder.TaxExtension.PackQuantity = qoP; oOrder.Expenses.ExpenseCode = expnsCode; oOrder.Expenses.TaxCode = expnsTax; if (!string.IsNullOrEmpty(pedido.clientProfileData.document)) { if (!string.IsNullOrEmpty(pedido.clientProfileData.corporateDocument)) { oOrder.CardCode = cardCodePrefix + pedido.clientProfileData.corporateDocument; } else { oOrder.CardCode = cardCodePrefix + pedido.clientProfileData.document; } //Log.WriteLogPedido("Verificando documento do Cliente (CardCode) "+ cardCodePrefix + pedido.clientProfileData.document); //oOrder.CardCode = "E22268140865"; } if (pedido.shippingData.logisticsInfo.Length > 0) { foreach (Logisticsinfo logInfo in pedido.shippingData.logisticsInfo) { oOrder.DocDueDate = DateTime.Parse(logInfo.shippingEstimateDate); //PickRemark - Recuperando tipo de Frete if (!string.IsNullOrEmpty(logInfo.deliveryCompany)) { oOrder.PickRemark = logInfo.deliveryCompany; } } } double _valorFrete = 0.00; double _valorDescont = 0.00; double _valorTaxa = 0.00; //despesas adicionais if (pedido.totals.Length > 0) { foreach (Total total in pedido.totals) { if (total.id.Equals("Discounts")) { if (total.value != 0) { _valorDescont = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); } } if (total.id.Equals("Shipping")) { if (total.value != 0) { _valorFrete = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); } } if (total.id.Equals("Tax")) { if (total.value != 0) { _valorTaxa = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); } } } } oOrder.Expenses.LineGross = _valorFrete; //DocumentLines if (pedido.items.Length > 0) { //_valorFrete.ToString().Insert(1,"."); int _lineNum = 0; foreach (ItemVtex item in pedido.items) { if (item.refId != null) { oOrder.Lines.ItemCode = item.refId; oOrder.Lines.Quantity = item.quantity; oOrder.Lines.WarehouseCode = WhsCode; oOrder.Lines.Usage = usage; oOrder.Lines.SetCurrentLine(_lineNum); oOrder.Lines.Add(); } _lineNum++; } } oOrderNum = oOrder.Add(); if (oOrderNum != 0) { messageError = oCompany.GetLastErrorDescription(); log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.orderId, "", EnumStatusIntegracao.Erro, messageError); log.WriteLogPedido("InsertOrder error SAP: " + messageError); System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder); return(oOrderNum); } else { messageError = ""; string docNum = oCompany.GetNewObjectKey(); log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.orderId, docNum, EnumStatusIntegracao.Sucesso, "Pedido de venda inserido com sucesso."); log.WriteLogPedido("Pedido de venda inserido com sucesso."); System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder); return(oOrderNum); } } catch (Exception e) { log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.orderId, "", EnumStatusIntegracao.Erro, e.Message); log.WriteLogPedido("Excpetion InsertOrder. " + e.Message); throw; } }
public void CrearPedido(SAPbobsCOM.Documents oDoc, string nro_comprobante, int Respuesta, string MsgErrSBO, string identi, bool esPedido, bool creditoOK, bool stockOK, bool precioOK, string almacen, int listaPrecio) { DBOracle consultas = new DBOracle(ServerOracle, UserOracle, PassOracle); DBOracle dbOracleUpdate = new DBOracle(ServerOracle, UserOracle, PassOracle); SAPbobsCOM.Recordset oRecordset = null; oRecordset = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset); string empresa = string.Empty; string empresaSAp = ""; string nroPedido = ""; int filas = 0; if (esPedido) { oDoc = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders); } else { oDoc = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oQuotations); } //oRecordset.DoQuery(ConsultasSap.GetCardCode(dbOracleCab.oDataReader["ruc"].ToString())); //if (oRecordset.RecordCount > 0) //{ // oDoc.CardCode = oRecordset.Fields.Item("CardCode").Value.ToString(); //} empresa = dbOracleCab.oDataReader["cod_empresa"].ToString(); consultas.EjecutaSQL(ConsultasOracle.EmpresaEquivalencia(empresa)); if (consultas.oDataReader.Read()) { oDoc.BPL_IDAssignedToInvoice = Convert.ToInt32(consultas.oDataReader["codEmpresaSAP"].ToString()); empresaSAp = consultas.oDataReader["codEmpresaSAP"].ToString(); } consultas.EjecutaSQL(ConsultasOracle.EmpleadoEquivalencia(dbOracleCab.oDataReader["cod_cliente"].ToString(), empresaSAp)); if (consultas.oDataReader.Read()) { oDoc.CardCode = consultas.oDataReader["codCliente"].ToString(); } oDoc.DocDate = Convert.ToDateTime(dbOracleCab.oDataReader["fec_comprobante"].ToString()); oDoc.DocDueDate = Convert.ToDateTime(dbOracleCab.oDataReader["fec_comprobante"].ToString()); //oDoc.SalesPersonCode = Convert.ToInt32(dbOracleCab.oDataReader["cod_vendedor"].ToString()); consultas.EjecutaSQL(ConsultasOracle.CondicionVentaEquivalencia(empresa, dbOracleCab.oDataReader["cod_condicion_venta"].ToString())); if (consultas.oDataReader.Read()) { oDoc.PaymentGroupCode = Convert.ToInt32(consultas.oDataReader["codCondicionSAP"].ToString()); } consultas.EjecutaSQL(ConsultasOracle.MonedaEquivalencia(dbOracleCab.oDataReader["cod_moneda"].ToString())); if (consultas.oDataReader.Read()) { oDoc.DocCurrency = consultas.oDataReader["codMonedaSAP"].ToString(); } if (!dbOracleCab.oDataReader["tip_cambio"].ToString().Equals("")) { oDoc.DocRate = Convert.ToDouble(dbOracleCab.oDataReader["tip_cambio"].ToString()); } //oDoc.DocumentStatus = SAPbobsCOM.BoStatus.bost_Open;// dbOracleCab.oDataReader["estado"].ToString(); oDoc.Comments = dbOracleCab.oDataReader["comentario"].ToString(); oDoc.FederalTaxID = dbOracleCab.oDataReader["ruc"].ToString(); oDoc.Address = dbOracleCab.oDataReader["dir_cliente"].ToString(); //oDoc.DocTotal = Convert.ToDouble(dbOracleCab.oDataReader["monto_total"].ToString()); nroPedido = dbOracleCab.oDataReader["tip_comprobante"].ToString() + "-" + dbOracleCab.oDataReader["ser_comprobante"].ToString() + "-" + dbOracleCab.oDataReader["nro_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_Tipo").Value = dbOracleCab.oDataReader["tip_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_Serie").Value = dbOracleCab.oDataReader["ser_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_Numero").Value = dbOracleCab.oDataReader["nro_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_cod_provincia").Value = dbOracleCab.oDataReader["cod_provincia"].ToString(); oDoc.UserFields.Fields.Item("U_cod_ciudad").Value = dbOracleCab.oDataReader["cod_ciudad"].ToString(); oDoc.UserFields.Fields.Item("U_enviar_ypane").Value = dbOracleCab.oDataReader["enviar_ypane"].ToString(); oDoc.UserFields.Fields.Item("U_wms_preparado").Value = dbOracleCab.oDataReader["wms_preparado"].ToString(); oDoc.UserFields.Fields.Item("U_wms_id_transaccion").Value = dbOracleCab.oDataReader["wms_id_transaccion"].ToString(); oDoc.UserFields.Fields.Item("U_control").Value = dbOracleCab.oDataReader["solo_credito"].ToString(); string origen = ""; if (dbOracleCab.oDataReader["origen"].ToString().Equals("")) { origen = "CAST"; } else { origen = "INVENTIVA"; } oDoc.UserFields.Fields.Item("U_DocOrigen").Value = origen; if (!creditoOK) { oDoc.UserFields.Fields.Item("U_LimiCrediVal").Value = "S"; } if (!stockOK) { oDoc.UserFields.Fields.Item("U_StockVal").Value = "S"; } if (!precioOK) { oDoc.UserFields.Fields.Item("U_PrecioVal").Value = "S"; } oDoc.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items; dbOracleDet = new DBOracle(ServerOracle, UserOracle, PassOracle); int i = 0; if (dbOracleDet.EjecutaSQL(ConsultasOracle.GetPedidosDet(nro_comprobante))) { while (dbOracleDet.oDataReader.Read()) { oDoc.Lines.ItemCode = dbOracleDet.oDataReader["cod_articulo"].ToString(); oDoc.Lines.Quantity = Convert.ToDouble(dbOracleDet.oDataReader["cantidad"].ToString()); oDoc.Lines.UnitPrice = Convert.ToDouble(dbOracleDet.oDataReader["precio_unitario"].ToString()); oDoc.Lines.TaxCode = "IVA_10"; if (!stockOK && !precioOK) { double cantidad = 0; double precio = 0; oRecordset.DoQuery(ConsultasSap.GetItemStock(oDoc.Lines.ItemCode, almacen)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.Quantity > Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString())) { cantidad = Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString()); } } oRecordset.DoQuery(ConsultasSap.GetPrecioLista(oDoc.Lines.ItemCode, listaPrecio)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.UnitPrice < Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString())) { precio = Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString()); } } oDoc.Lines.UserFields.Fields.Item("U_MotivoOferta").Value = String.Format("Cantidad solicitada: {0}, disponible: {1}. Precio venta: {2}, lista: {3}.", oDoc.Lines.Quantity, cantidad, oDoc.Lines.UnitPrice, precio); } else { if (!stockOK) { oRecordset.DoQuery(ConsultasSap.GetItemStock(oDoc.Lines.ItemCode, almacen)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.Quantity > Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString())) { oDoc.Lines.UserFields.Fields.Item("U_MotivoOferta").Value = String.Format("Cantidad solicitada ({0}) supera el stock disponible ({1}).", oDoc.Lines.Quantity, Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString())); } } } if (!precioOK) { oRecordset.DoQuery(ConsultasSap.GetPrecioLista(oDoc.Lines.ItemCode, listaPrecio)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.UnitPrice < Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString())) { oDoc.Lines.UserFields.Fields.Item("U_MotivoOferta").Value = String.Format("Precio de venta ({0}) es menor al de la lista de precio predeterminada ({1}).", oDoc.Lines.UnitPrice, Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString())); } } } } oDoc.Lines.SetCurrentLine(i); oDoc.Lines.Add(); i++; } } Respuesta = oDoc.Add(); if (Respuesta != 0) { oCompany.GetLastError(out Respuesta, out MsgErrSBO); CrearRegistroLog(Respuesta.ToString(), MsgErrSBO, nro_comprobante); filas = 0; dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoCab(nro_comprobante), ref filas); filas = 0; dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoDet(nro_comprobante), ref filas); WriteErrorLog("CrearPedido:" + nroPedido + " Error: " + Respuesta + " " + MsgErrSBO); } else { identi = oCompany.GetNewObjectKey(); dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoCab(nro_comprobante), ref filas); filas = 0; dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoDet(nro_comprobante), ref filas); } dbSap.LiberarObjeto(oRecordset); }
public string InsertDraft(DraftDocumentEntity draft, out string messageError) { int addDraftNumber = 0; LogDAL _log = new LogDAL(); try { SAPbobsCOM.Documents oDocDraft = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts); oDocDraft.CardCode = draft.CardCode; oDocDraft.DocObjectCode = (SAPbobsCOM.BoObjectTypes) 13; oDocDraft.BPL_IDAssignedToInvoice = Convert.ToInt16(draft.BPLId); oDocDraft.OpeningRemarks = draft.OpeningRemarks; oDocDraft.ClosingRemarks = draft.ClosingRemarks; oDocDraft.Comments = draft.Comments; oDocDraft.DocDate = DateTime.ParseExact(draft.DocDate.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(draft.DocDueDate)) { oDocDraft.DocDueDate = DateTime.ParseExact(draft.DocDueDate.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture); } oDocDraft.DocCurrency = draft.DocCurrency; oDocDraft.DocRate = draft.DocRate; oDocDraft.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items; oDocDraft.UserFields.Fields.Item("U_UPP_N_OS").Value = draft.N_Os; oDocDraft.UserFields.Fields.Item("U_Identificacao").Value = draft.DocCode; oDocDraft.UserFields.Fields.Item("U_UPBL").Value = draft.U_UPBL; oDocDraft.UserFields.Fields.Item("U_UPAticDraft").Value = draft.U_UPAticDraft; int _first = 0; foreach (DraftLineEntity _line in draft.Document_Line) { oDocDraft.Lines.ItemCode = _line.ItemCode; oDocDraft.Lines.CostingCode = _line.CostingCode; oDocDraft.Lines.Currency = _line.Currency; oDocDraft.Lines.Quantity = _line.Quantity; oDocDraft.Lines.UnitPrice = _line.UnitPrice; oDocDraft.Lines.DiscountPercent = _line.DiscountPercent; oDocDraft.Lines.Usage = _line.Usage; oDocDraft.Lines.WarehouseCode = _line.WharehouseCode; oDocDraft.Lines.Add(); oDocDraft.Lines.SetCurrentLine(oDocDraft.Lines.Count - 1); _first++; } addDraftNumber = oDocDraft.Add(); } catch (Exception ex) { _log.WriteEntry("InsertDraft exception: " + ex.Message); throw; } if (addDraftNumber != 0) { messageError = oCompany.GetLastErrorDescription(); _log.WriteEntry("InsertDraft error SAP: " + messageError); return("-3"); } else { draft.Sketch_Invoice = oCompany.GetNewObjectKey(); messageError = ""; return("0"); } }
private void Form_DataAddAfter(ref SAPbouiCOM.BusinessObjectInfo pVal) { if (((SAPbouiCOM.BusinessObjectInfo)pVal).ActionSuccess) { SAPbobsCOM.Company oCom = ((SAPbobsCOM.Company)(Application.SBO_Application.Company.GetDICompany())); SAPbobsCOM.Recordset oR_RecordSet = (SAPbobsCOM.Recordset)oCom.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset); oR_RecordSet.DoQuery("Select * from [@ADDONCFG]"); string uid = oR_RecordSet.Fields.Item("Code").Value.ToString(); string pwd = oR_RecordSet.Fields.Item("Name").Value.ToString(); //Get ObjectKey has created XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(((SAPbouiCOM.BusinessObjectInfo)pVal).ObjectKey); XmlNodeList nodeList = xmldoc.GetElementsByTagName("DocEntry"); string Object_Key = string.Empty; if (nodeList.Count > 0) { Object_Key = nodeList.Item(0).InnerText; } SqlCommand cmd = null; SqlConnection conn = new SqlConnection(string.Format("Data Source={0}; Initial Catalog={1}; User id={2}; Password={3};", oCom.Server, oCom.CompanyDB, uid, pwd)); //Delete JournalEntry GoodsReceipt PO try { cmd = new SqlCommand("DeleteJournalEntry_GoodReceiptPO", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocNum", Object_Key); conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Application.SBO_Application.MessageBox("Delete JournalEntry GoodsReceipt PO Error: " + ex.Message); } finally { conn.Close(); cmd.Dispose(); } //Get Info From Goods Receipt PO by UI SAPbouiCOM.Form oForm = Application.SBO_Application.Forms.ActiveForm; string p_post_date = ((SAPbouiCOM.EditText)oForm.Items.Item("10").Specific).Value; string p_document_date = ((SAPbouiCOM.EditText)oForm.Items.Item("46").Specific).Value; List <Inventory_Item> Inven_Lst = new List <Inventory_Item>(); oForm.Freeze(true); oForm.PaneLevel = 1; try { SAPbouiCOM.Matrix oMtx = ((SAPbouiCOM.Matrix)oForm.Items.Item("38").Specific); for (int i = 1; i <= oMtx.RowCount; i++) { if (!String.IsNullOrEmpty(((SAPbouiCOM.EditText)oMtx.Columns.Item(3).Cells.Item(i).Specific).Value)) { Inventory_Item tmp = new Inventory_Item(); tmp.Item_No = ((SAPbouiCOM.EditText)oMtx.Columns.Item(3).Cells.Item(i).Specific).Value; double.TryParse(((SAPbouiCOM.EditText)oMtx.Columns.Item(13).Cells.Item(i).Specific).Value, out tmp.Quantity); string tmp_unit_price = ((SAPbouiCOM.EditText)oMtx.Columns.Item(20).Cells.Item(i).Specific).Value.Replace(" VND", ""); if (!String.IsNullOrEmpty(tmp_unit_price)) { double.TryParse(tmp_unit_price.Split(',')[0].Replace('.', ','), out tmp.Unitprice); } tmp.Whse = ((SAPbouiCOM.EditText)oMtx.Columns.Item(32).Cells.Item(i).Specific).Value; Inven_Lst.Add(tmp); } } } catch { } finally { oForm.Freeze(false); } //Using DI Create Goods Receipt SAPbobsCOM.Documents oGrp = (SAPbobsCOM.Documents)oCom.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenEntry); oGrp.DocDate = DateTime.ParseExact(p_document_date, "yyyyMMdd", CultureInfo.InvariantCulture); oGrp.TaxDate = DateTime.ParseExact(p_post_date, "yyyyMMdd", CultureInfo.InvariantCulture); oGrp.Reference2 = Object_Key; int tmp_i = 0; int FixedAsset_Count = 0; foreach (Inventory_Item t in Inven_Lst) { tmp_i++; //string str_query = string.Format("Select count(*) as IsFixedAsset from OITM where ItemCode in (Select U_FA from OITM where ItemCode = '{0}')and ItemType ='F'", t.Item_No); string str_query = string.Format("Select a.ItemCode,a.U_FA,(Select b.ItemType from OITM b where b.ItemCode = a.U_FA) as ItemType, a.ItmsGrpCod,(Select b.ItmsGrpCod from OITM b where b.ItemCode = a.U_FA) as ItmsGrpCod_FA from OITM a where a.U_FA = '{0}'", t.Item_No); oR_RecordSet.DoQuery(str_query); if (oR_RecordSet.RecordCount > 0) { if (oR_RecordSet.Fields.Item("ItemType").Value.ToString() == "F" && ((oR_RecordSet.Fields.Item("ItmsGrpCod").Value.ToString() == "103" && oR_RecordSet.Fields.Item("ItmsGrpCod_FA").Value.ToString() == "103") || (oR_RecordSet.Fields.Item("ItmsGrpCod").Value.ToString() == "105" && oR_RecordSet.Fields.Item("ItmsGrpCod_FA").Value.ToString() == "105"))) { t.FixedAsset_ItemNo = oR_RecordSet.Fields.Item("ItemCode").Value.ToString(); if (!string.IsNullOrEmpty(t.FixedAsset_ItemNo)) { oGrp.Lines.ItemCode = t.FixedAsset_ItemNo; oGrp.Lines.Quantity = t.Quantity; oGrp.Lines.UnitPrice = 0; oGrp.Lines.Price = 0; oGrp.Lines.WarehouseCode = t.Whse; t.LineNum = FixedAsset_Count++; if (tmp_i < Inven_Lst.Count) { oGrp.Lines.Add(); } } } } } if (FixedAsset_Count > 0) { int RetVal = oGrp.Add(); if (RetVal == 0) { string New_Object_Key = oCom.GetNewObjectKey(); //Update Unit Price cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; double receipt_total = 0; //Update IGN1 SQL foreach (Inventory_Item t in Inven_Lst) { if (t.LineNum >= 0) { double tmp_sum = t.Unitprice * t.Quantity; receipt_total += tmp_sum; string update_IGN1_query = string.Format("Update IGN1 set Price={0},LineTotal={1},OpenSum={2},PriceBefDi={3},TotalSumSy={4},OpenSumSys={5},INMPrice={6},StockPrice={7},StockSum={8},StockSumSc={9} where DocEntry={10} and ItemCode='{11}' and LineNum={12};" , t.Unitprice, tmp_sum, tmp_sum, t.Unitprice, tmp_sum, tmp_sum, t.Unitprice, t.Unitprice, tmp_sum, tmp_sum, New_Object_Key, t.FixedAsset_ItemNo, t.LineNum); cmd.CommandText += update_IGN1_query; } } //Update OIGN SQL string update_OIGN_query = string.Format("Update OIGN set DocTotal={0},DocTotalSy={1},Max1099={2} where DocEntry={3};", receipt_total, receipt_total, receipt_total, New_Object_Key); cmd.CommandText += update_OIGN_query; try { cmd.Connection = conn; conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Application.SBO_Application.MessageBox(string.Format("Addon: Error when update GoodsRecipt: {0}", ex.Message)); } finally { conn.Close(); cmd.Dispose(); } } else { int ErrCode; string ErrMsg; oCom.GetLastError(out ErrCode, out ErrMsg); Application.SBO_Application.StatusBar.SetText(string.Format("Addon: Failed create Good Receipt from Good Receipt PO: {0}|{1}", ErrCode, ErrMsg), SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error); } } } }
public int InsertOrder(OrderIntegraCommerce pedido, out string messageError) { this.log = new Log(); try { int oOrderNum = 0; log.WriteLogPedido("Inserindo Pedido de Venda " + pedido.IdOrder); SAPbobsCOM.Documents oOrder = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders); int filial = Convert.ToInt32(ConfigurationManager.AppSettings["Empresa"]); string usage = ConfigurationManager.AppSettings["Usage"]; string WhsCode = ConfigurationManager.AppSettings["WhsCode"]; int SlpCode = Convert.ToInt32(ConfigurationManager.AppSettings["SlpCode"]); string comments = ConfigurationManager.AppSettings["Comments"]; string plataforma = ConfigurationManager.AppSettings["Plataforma"]; string carrier = ConfigurationManager.AppSettings["Carrier"]; string packDesc = ConfigurationManager.AppSettings["PackDesc"]; int qoP = Convert.ToInt32(ConfigurationManager.AppSettings["QoP"]); int expnsCode = Convert.ToInt32(ConfigurationManager.AppSettings["ExpnsCode"]); string expnsTax = ConfigurationManager.AppSettings["ExpnsTax"]; string cardCodePrefix = ConfigurationManager.AppSettings["CardCodePrefix"]; string pickRemark = ConfigurationManager.AppSettings["PickRemark"]; string document = String.Empty; oOrder.BPL_IDAssignedToInvoice = filial; oOrder.NumAtCard = pedido.IdOrder; oOrder.SalesPersonCode = SlpCode; oOrder.Comments = comments; oOrder.UserFields.Fields.Item("U_PLATF").Value = plataforma; oOrder.UserFields.Fields.Item("U_NumPedEXT").Value = pedido.IdOrder; oOrder.TaxExtension.Carrier = carrier; oOrder.TaxExtension.PackDescription = packDesc; oOrder.TaxExtension.PackQuantity = qoP; oOrder.Expenses.ExpenseCode = expnsCode; oOrder.Expenses.TaxCode = expnsTax; if (!String.IsNullOrEmpty(pedido.CustomerPjCnpj)) { document = pedido.CustomerPjCnpj; } else if (!String.IsNullOrEmpty(pedido.CustomerPfCpf)) { document = pedido.CustomerPfCpf; } oOrder.CardCode = cardCodePrefix + document; if (!string.IsNullOrEmpty(pedido.ShippedEstimatedDelivery)) { oOrder.DocDueDate = DateTime.Parse(pedido.ShippedEstimatedDelivery); } else { oOrder.DocDueDate = DateTime.Today.AddDays(5); } if (!String.IsNullOrEmpty(pedido.ShippedCarrierName)) { oOrder.PickRemark = pedido.ShippedCarrierName; } /* * double _valorFrete = 0.00; * double _valorDescont = 0.00; * double _valorTaxa = 0.00; * * despesas adicionais * if (pedido.totals.Length > 0) * { * foreach (Total total in pedido.totals) * { * if (total.id.Equals("Discounts")) * { * if (total.value != 0) * { * _valorDescont = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); * } * } * if (total.id.Equals("Shipping")) * { * if (total.value != 0) * { * _valorFrete = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); * } * } * if (total.id.Equals("Tax")) * { * if (total.value != 0) * { * _valorTaxa = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); * } * } * } * } * oOrder.Expenses.LineGross = _valorFrete; */ //DocumentLines if (pedido.Products.Length > 0) { //_valorFrete.ToString().Insert(1,"."); int _lineNum = 0; foreach (Product item in pedido.Products) { if (!String.IsNullOrEmpty(item.IdSku)) { //Recuperar Item Repositorio repositorio = new Repositorio(); Task <HttpResponseMessage> responseSku = repositorio.BuscarItemPorSKU(item.IdSku, this.oCompany); if (responseSku.Result.IsSuccessStatusCode) { string jsonResponseSku = responseSku.Result.Content.ReadAsStringAsync().Result; var itemResponseSku = JsonConvert.DeserializeObject <Item>(jsonResponseSku); if (!String.IsNullOrEmpty(itemResponseSku.IdSkuErp)) { oOrder.Lines.ItemCode = itemResponseSku.IdSkuErp; } } oOrder.Lines.Quantity = item.Quantity; oOrder.Lines.WarehouseCode = WhsCode; oOrder.Lines.Usage = usage; oOrder.Lines.SetCurrentLine(_lineNum); oOrder.Lines.Add(); } _lineNum++; } } oOrderNum = oOrder.Add(); if (oOrderNum != 0) { messageError = oCompany.GetLastErrorDescription(); log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.IdOrder, "", EnumStatusIntegracao.Erro, messageError); log.WriteLogPedido("InsertOrder error SAP: " + messageError); System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder); return(oOrderNum); } else { messageError = ""; string docNum = oCompany.GetNewObjectKey(); log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.IdOrder, docNum, EnumStatusIntegracao.Sucesso, "Pedido de venda inserido com sucesso."); log.WriteLogPedido("Pedido de venda inserido com sucesso."); System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder); return(oOrderNum); } } catch (Exception e) { log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.IdOrder, "", EnumStatusIntegracao.Erro, e.Message); log.WriteLogPedido("Excpetion InsertOrder. " + e.Message); throw; } }
public int InsertOrder(Order pedido, out string messageError) { this.log = new Log(); try { int oOrderNum = 0; log.WriteLogPedido("Inserindo Pedido de Venda"); SAPbobsCOM.Documents oOrder = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders); int filial = Convert.ToInt32(ConfigurationManager.AppSettings["Empresa"]); string usage = ConfigurationManager.AppSettings["Usage"]; string WhsCode = ConfigurationManager.AppSettings["WhsCode"]; int SlpCode = Convert.ToInt32(ConfigurationManager.AppSettings["SlpCode"]); string comments = ConfigurationManager.AppSettings["Comments"]; string plataforma = ConfigurationManager.AppSettings["Plataforma"]; string carrier = ConfigurationManager.AppSettings["Carrier"]; string packDesc = ConfigurationManager.AppSettings["PackDesc"]; int qoP = Convert.ToInt32(ConfigurationManager.AppSettings["QoP"]); int expnsCode = Convert.ToInt32(ConfigurationManager.AppSettings["ExpnsCode"]); string expnsTax = ConfigurationManager.AppSettings["ExpnsTax"]; string cardCodePrefix = ConfigurationManager.AppSettings["CardCodePrefix"]; string pickRemark = ConfigurationManager.AppSettings["PickRemark"]; oOrder.BPL_IDAssignedToInvoice = filial; oOrder.NumAtCard = pedido.id.ToString(); oOrder.SalesPersonCode = SlpCode; oOrder.Comments = comments; oOrder.UserFields.Fields.Item("U_PLATF").Value = plataforma; oOrder.UserFields.Fields.Item("U_NumPedEXT").Value = pedido.id.ToString(); oOrder.TaxExtension.Carrier = carrier; oOrder.TaxExtension.PackDescription = packDesc; oOrder.TaxExtension.PackQuantity = qoP; oOrder.Expenses.ExpenseCode = expnsCode; oOrder.Expenses.TaxCode = expnsTax; if (!string.IsNullOrEmpty(pedido.buyer.billing_info.doc_number)) { oOrder.CardCode = cardCodePrefix + pedido.buyer.billing_info.doc_number; //Log.WriteLogPedido("Verificando documento do Cliente (CardCode) "+ cardCodePrefix + pedido.clientProfileData.document); //oOrder.CardCode = "E22268140865"; } /* * if (pedido.shippingData.logisticsInfo.Length > 0) * { * foreach(Logisticsinfo logInfo in pedido.shippingData.logisticsInfo) { * oOrder.DocDueDate = DateTime.Parse(logInfo.shippingEstimateDate); * * //PickRemark - Recuperando tipo de Frete * if (!string.IsNullOrEmpty(logInfo.deliveryCompany)) * { * oOrder.PickRemark = logInfo.deliveryCompany; * } * } * }*/ //oOrder.DocDueDate = pedido.shipping.date_created; Repositorio repositorio = new Repositorio(); Shipments shipment = null; Task <HttpResponseMessage> responseShipment = repositorio.BuscarShipmentById(pedido.shipping.id); if (responseShipment.Result.IsSuccessStatusCode) { var jsonShipment = responseShipment.Result.Content.ReadAsStringAsync().Result; shipment = JsonConvert.DeserializeObject <Shipments>(jsonShipment); } if (shipment != null) { oOrder.DocDueDate = shipment.shipping_option.estimated_delivery_time.date; oOrder.PickRemark = shipment.shipping_option.name; } double _valorFrete = 0.00; double _valorDescont = 0.00; double _valorTaxa = 0.00; /* * //despesas adicionais * if (pedido.totals.Length > 0) * { * foreach (Total total in pedido.totals) * { * if (total.id.Equals("Discounts")) * { * if (total.value != 0) * { * _valorDescont = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); * } * } * if (total.id.Equals("Shipping")) * { * if (total.value != 0) * { * _valorFrete = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); * } * } * if (total.id.Equals("Tax")) * { * if (total.value != 0) * { * _valorTaxa = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ",")); * } * } * } * }*/ oOrder.Expenses.LineGross = pedido.shipping.cost; //DocumentLines if (pedido.order_items.Length > 0) { //_valorFrete.ToString().Insert(1,"."); int _lineNum = 0; foreach (Order_Items item in pedido.order_items) { if (item.item.seller_custom_field != null) { oOrder.Lines.ItemCode = item.item.seller_custom_field; oOrder.Lines.Quantity = item.quantity; oOrder.Lines.WarehouseCode = WhsCode; oOrder.Lines.Usage = usage; oOrder.Lines.SetCurrentLine(_lineNum); oOrder.Lines.Add(); } _lineNum++; } } oOrderNum = oOrder.Add(); if (oOrderNum != 0) { messageError = oCompany.GetLastErrorDescription(); log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.id.ToString(), "", EnumStatusIntegracao.Erro, messageError); log.WriteLogPedido("InsertOrder error SAP: " + messageError); System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder); return(oOrderNum); } else { messageError = ""; string docNum = oCompany.GetNewObjectKey(); log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.id.ToString(), docNum, EnumStatusIntegracao.Sucesso, "Pedido de venda inserido com sucesso.");; log.WriteLogPedido("Pedido de venda inserido com sucesso."); System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder); return(oOrderNum); } } catch (Exception e) { log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.id.ToString(), "", EnumStatusIntegracao.Erro, e.Message); log.WriteLogPedido("Excpetion InsertOrder. " + e.Message); throw; } }
public void CoreInsertOrderStationerySap() { int lretcode; int nResult; SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company(); oCompany.CompanyDB = "###"; oCompany.Server = "###"; oCompany.language = SAPbobsCOM.BoSuppLangs.ln_Spanish; oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; oCompany.UseTrusted = false; oCompany.DbUserName = "******"; oCompany.UserName = "******"; oCompany.Password = "******"; oCompany.LicenseServer = "###"; oCompany.Disconnect(); nResult = oCompany.Connect(); if (nResult == 0) { List <Papeleria> DetalleHeader = new List <Papeleria>(); DbCommand cmd = this.Database.GetStoredProcCommand("spOrdersStationeryHeader"); cmd.CommandTimeout = 0; IDataReader dr = this.Database.ExecuteReader(cmd); int Sequence; while (dr.Read()) { //CABECERA SAPbobsCOM.Documents oInvoiceDoc = null; oInvoiceDoc = (SAPbobsCOM.Documents)(oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenExit)); oInvoiceDoc.DocDate = DateTime.Now; oInvoiceDoc.Reference2 = "PAPELERIA"; Sequence = (Int32)dr["Sequence"]; //DETALLE List <Papeleria> Detalle = new List <Papeleria>(); DbCommand cmd2 = this.Database.GetStoredProcCommand("spOrdersStationery2"); this.Database.AddInParameter(cmd2, "@Folio", DbType.Int32, Sequence); cmd.CommandTimeout = 0; IDataReader dr2 = this.Database.ExecuteReader(cmd2); int Row = 0; while (dr2.Read()) { int BatchRow = 0; oInvoiceDoc.Comments = (string)dr2["Comentario"]; oInvoiceDoc.Lines.ItemCode = (string)dr2["ItemCode"]; oInvoiceDoc.Lines.WarehouseCode = "CEDIS"; oInvoiceDoc.Lines.Quantity = (int)dr2["CantidadAprobada"]; oInvoiceDoc.Lines.SetCurrentLine(Row); oInvoiceDoc.Lines.BaseType = 0; oInvoiceDoc.Lines.UnitPrice = 0; oInvoiceDoc.Lines.AccountCode = (string)dr2["Departamento"]; oInvoiceDoc.Lines.BatchNumbers.SetCurrentLine(BatchRow); oInvoiceDoc.Lines.BatchNumbers.BatchNumber = (string)dr2["Distnumber"]; oInvoiceDoc.Lines.BatchNumbers.Quantity = (int)dr2["CantidadAprobada"]; oInvoiceDoc.Lines.BatchNumbers.Add(); oInvoiceDoc.Lines.Add(); Row++; } dr2.Close(); lretcode = oInvoiceDoc.Add(); if (lretcode != 0) { oCompany.GetLastError(out int lErrCode, out string sErrMsg); //string errocode = oCompany.GetLastErrorDescription(); // CoreErrorSapOrderStationery(myresult, errocode); } else { string FolioSap = oCompany.GetNewObjectKey(); Convert.ToInt16(FolioSap); CoreUpdateOrderStationerySap(Sequence, FolioSap); } } dr.Close(); } }