private string toJson(BusinessPartners businesspartners) { string result = string.Empty; dynamic record = new ExpandoObject(); record.ContactEmployees = businesspartners.ContactEmployees; record.BillToBuildingFloorRoom = businesspartners.BillToBuildingFloorRoom; record.AliasName = businesspartners.AliasName; record.CardCode = businesspartners.CardCode; record.CardName = businesspartners.CardName; record.CardType = businesspartners.CardType; record.County = businesspartners.County; if (businesspartners.FatherCard != null & businesspartners.FatherCard != "" && !businesspartners.FatherCard.Contains("000000")) { record.FatherCard = businesspartners.FatherCard; } record.RelationshipDateFrom = businesspartners.RelationshipDateFrom; record.RelationshipDateTill = businesspartners.RelationshipDateTill; record.BPAddresses = businesspartners.BPAddresses; record.BPFiscalTaxIDCollection = businesspartners.BPFiscalTaxIDCollection; record.BPBankAccounts = businesspartners.BPBankAccounts; record.Address = businesspartners.Address; result = JsonConvert.SerializeObject(record); return(result); }
/// <summary> /// To Try with DB Context /// FOR THE GANTTPLAN!!!111 /// </summary> /// <param name="articleId"></param> /// <param name="amount"></param> /// <param name="creationTime"></param> /// <param name="dueTime"></param> /// <returns></returns> public T_CustomerOrder CreateNewOrder(int orderid, int orderpartid, int articleId, int amount, long creationTime, long dueTime) { var olist = new List <T_CustomerOrderPart>(); olist.Add(item: new T_CustomerOrderPart { Id = orderpartid, ArticleId = articleId, IsPlanned = false, Quantity = amount, }); var bp = BusinessPartners.First(predicate: x => x.Debitor); var order = new T_CustomerOrder() { Id = orderid, BusinessPartnerId = bp.Id, DueTime = (int)dueTime, CreationTime = (int)creationTime, Name = Articles.Single(predicate: x => x.Id == articleId).Name, CustomerOrderParts = olist }; this.CustomerOrders.Add(entity: order); return(order); }
public Model.BusinessPartnerModel Get(string cardCode) { Model.BusinessPartnerModel businessPartnerModel = new Model.BusinessPartnerModel(); BusinessPartners businessPartner = (BusinessPartners)Controller.ConnectionController.Instance.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners); try { if (businessPartner.GetByKey(cardCode)) { businessPartnerModel.CardCode = businessPartner.CardCode; businessPartnerModel.SlpCode = businessPartner.SalesPersonCode; for (int userField = 0; userField < businessPartner.UserFields.Fields.Count; userField++) { businessPartnerModel.UserFields.Add(businessPartner.UserFields.Fields.Item(userField).Name, businessPartner.UserFields.Fields.Item(userField).Value); } } } finally { Marshal.ReleaseComObject(businessPartner); GC.Collect(); } return(businessPartnerModel); }
/// <summary> /// Set Next Card Code /// </summary> /// <param name="card">BusinessPartners object</param> /// <param name="serieId">NNM1 Serie Id</param> public static void SetNextCardCode(this BusinessPartners card, int?serieId = null) { var response = DocumentSeriesHelper.GetNextNumber(BoObjectTypes.oBusinessPartners, "C", serieId); card.CardCode = response.NextNumber; card.Series = response.Series; }
private void DeleteBusinessPartner(object obj) { if (MessageBox.Show("Are you Sure You want to Delete this Record?", "Pinna Fitness", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes) { try { SelectedBusinessPartner.Enabled = false; var stat = _businessPartnerService.Disable(SelectedBusinessPartner); if (stat == string.Empty) { BusinessPartners.Remove(SelectedBusinessPartner); } else { MessageBox.Show("Can't Delete, may be the data is already in use..." + Environment.NewLine + stat, "Can't Delete", MessageBoxButton.OK, MessageBoxImage.Error); } } catch (Exception ex) { MessageBox.Show("Can't Delete, may be the data is already in use..." + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, "Can't Delete", MessageBoxButton.OK, MessageBoxImage.Error); } } }
private void SaveBusinessPartner(object obj) { try { var newObject = SelectedBusinessPartner.Id; var stat = _businessPartnerService.InsertOrUpdate(SelectedBusinessPartner); if (stat != string.Empty) { MessageBox.Show("Can't save" + Environment.NewLine + stat, "Can't save", MessageBoxButton.OK, MessageBoxImage.Error); } else if (newObject == 0) { BusinessPartners.Insert(0, SelectedBusinessPartner); } } catch (Exception exception) { MessageBox.Show("Can't save" + Environment.NewLine + exception.Message, "Can't save", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void FinalizeObject() { Marshal.ReleaseComObject(_businessObject); _businessObject = null; GC.Collect(); }
public int AddMultiple(List <oBusinessPartner> objs) { BusinessPartners _bp = null; try { SboComObject.StartTransaction(); int retCode = 0; foreach (oBusinessPartner obj in objs) { _bp.CardCode = obj.CardCode; _bp.CardName = obj.CardName; _bp.Address = obj.Address; _bp.CardType = obj.CardType == "C" ? BoCardTypes.cCustomer : BoCardTypes.cSupplier; _bp.ContactPerson = obj.CntctPerson; _bp.Cellular = obj.Cellular; _bp.Phone1 = obj.Phone1; _bp.Phone2 = obj.Phone2; _bp.EmailAddress = obj.Email; _bp.DebitorAccount = obj.DebPayAcct; retCode = _bp.Add(); if (retCode > 0) { break; } } if (retCode > 0) { int errCode = 0; string errMessage = ""; SboComObject.GetLastError(out errCode, out errMessage); GlobalInstance.Instance.SBOErrorCode = errCode; GlobalInstance.Instance.SBOErrorMessage = errMessage; SboComObject.EndTransaction(BoWfTransOpt.wf_RollBack); } else { SboComObject.EndTransaction(BoWfTransOpt.wf_Commit); } return(retCode); } catch { throw new Exception(GlobalInstance.Instance.SBOErrorMessage); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(_bp); } }
private void LoadXml() { var novo = new StreamReader(xml).ReadToEnd().Replace("C20000", "C29999").Replace("94.549.548/0001-39", "99.998.989/1111-99"); _con.Comany.XMLAsString = true; BusinessPartners d = _con.Comany.GetBusinessObjectFromXML(novo, 0); d.Add(); MessageBox.Show(_con.Message); }
public BusinessPartners Get(Int64 ixBusinessPartner) { BusinessPartners businesspartners = _context.BusinessPartners.AsNoTracking().Where(x => x.ixBusinessPartner == ixBusinessPartner).First(); businesspartners.Addresses = _context.Addresses.Find(businesspartners.ixAddress); businesspartners.BusinessPartnerTypes = _context.BusinessPartnerTypes.Find(businesspartners.ixBusinessPartnerType); businesspartners.Companies = _context.Companies.Find(businesspartners.ixCompany); return(businesspartners); }
private void CriarParceiro() { BusinessPartners parceiro = _con.Comany.GetBusinessObject(BoObjectTypes.oBusinessPartners); parceiro.CardCode = "3333"; parceiro.CardName = "Eita Lele"; parceiro.CardType = BoCardTypes.cCustomer; parceiro.Add(); MessageBox.Show(_con.Message); }
private string toJsonTeste(BusinessPartners businesspartners) { string result = string.Empty; dynamic record = new ExpandoObject(); //record.Code = businessplaces.RecId.ToString(); record.AdditionalIdNumber = null; result = JsonConvert.SerializeObject(record); return(result); }
private string toJsonBusinessPartners(BusinessPartners businessPartners) { string result = string.Empty; dynamic record = new ExpandoObject(); record.CardCode = businessPartners.CardCode; record.CardType = businessPartners.CardType; record.CardName = businessPartners.CardName; result = JsonConvert.SerializeObject(record); return(result); }
public int Update(oBusinessPartner obj) { BusinessPartners _bp = (BusinessPartners)SboComObject.GetBusinessObject(BoObjectTypes.oBusinessPartners); try { SboComObject.StartTransaction(); int retCode = 0; _bp.GetByKey(obj.CardCode); _bp.CardName = obj.CardName; _bp.Address = obj.Address; _bp.ContactPerson = obj.CntctPerson; _bp.Cellular = obj.Cellular; _bp.Phone1 = obj.Phone1; _bp.Phone2 = obj.Phone2; _bp.EmailAddress = obj.Email; retCode = _bp.Update(); if (retCode != 0) { int errCode = 0; string errMessage = ""; SboComObject.GetLastError(out errCode, out errMessage); GlobalInstance.Instance.SBOErrorCode = errCode; GlobalInstance.Instance.SBOErrorMessage = errMessage; SboComObject.EndTransaction(BoWfTransOpt.wf_RollBack); } else { SboComObject.EndTransaction(BoWfTransOpt.wf_Commit); } return(retCode); } catch (Exception ex) { System.Runtime.InteropServices.Marshal.ReleaseComObject(_bp); throw new Exception(GlobalInstance.Instance.SBOErrorMessage == null ? ex.Message : GlobalInstance.Instance.SBOErrorMessage); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(_bp); } }
public string GetBPUF(string cardCode) { BusinessPartners bp = (BusinessPartners)SBOApp.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners); string uf = String.Empty; if (bp.GetByKey(cardCode)) { for (int i = 0; i < bp.Addresses.Count; i++) { bp.Addresses.SetCurrentLine(i); if (bp.Addresses.AddressName == bp.ShipToDefault) { uf = bp.Addresses.State; } } } return(uf); }
async public Task Update(BusinessPartners entity) { IBatchProducer batch = _serviceLayerConnector.CreateBatch(); batch = _serviceLayerConnector.CreateBatch(); string record = toJson(entity); batch.Post(HttpMethod.Patch, "/BusinessPartners(CardCode='C20000')", record); ServiceLayerResponse response = await _serviceLayerConnector.Post("BusinessPartners", record); if (!response.success) { string message = $"Erro ao enviar transação de '{entity.EntityName}': {response.errorCode}-{response.errorMessage}"; Console.WriteLine(message); throw new ApplicationException(message); } throw new NotImplementedException(); }
public Order CreateNewOrder(int articleId, int amount, int creationTime, int dueTime) { var order = new Order() { BusinessPartnerId = BusinessPartners.First(x => x.Debitor).Id, DueTime = dueTime, CreationTime = creationTime, Name = Articles.Single(x => x.Id == articleId).Name, OrderParts = new List <OrderPart> { new OrderPart { ArticleId = articleId, IsPlanned = false, Quantity = amount, } } }; return(order); }
public IHttpActionResult AddCustomer(FormDataCollection formData) { try { ServerConnection connection = new ServerConnection(); // attempt connection; 0 = success if (connection.Connect() == 0) { int retVal = 0; var success = "Started at " + DateTime.Now; BusinessPartners businessPartner = null; businessPartner = connection.GetCompany().GetBusinessObject(BoObjectTypes.oBusinessPartners); businessPartner.CardCode = formData["CardCode"]; businessPartner.CardName = formData["CardName"]; businessPartner.Phone1 = formData["Phone1"]; businessPartner.CardType = BoCardTypes.cCustomer; businessPartner.SubjectToWithholdingTax = BoYesNoEnum.tNO; retVal = businessPartner.Add(); // if (retVal == 0) { success += " Ended at " + DateTime.Now; connection.GetCompany().Disconnect(); return(Success(success)); } else { connection.GetCompany().Disconnect(); throw new Exception(connection.GetCompany().GetLastErrorCode() + " : " + connection.GetCompany().GetLastErrorDescription()); } } else { throw new Exception(connection.GetErrorCode() + " : " + connection.GetErrorMessage()); } } catch (Exception ex) { throw ex; } }
/// <summary> /// SetCurrentLine by "Contact ID" /// </summary> /// <param name="businessPartners"></param> /// <param name="contactId"></param> /// <returns></returns> public static bool SetContactEmployeesLineByContactId(this BusinessPartners businessPartners, string contactId) { var cardCode = businessPartners.CardCode; var contactEmployees = businessPartners.ContactEmployees; using (var query = new SboRecordsetQuery(FrameworkQueries.Instance.SetContactEmployeesLineByContactIdQuery(cardCode, contactId))) { if (query.Count == 0) { return(false); } var lineNum = (int)query.Result.First().Item(0).Value; SboApp.Logger.Debug($"Contact ID '{contactId}' is LineNum {lineNum} for CardCode {cardCode}"); contactEmployees.SetCurrentLine(lineNum); return(true); } }
public void CT1_Insert(string testCaseName, BusinessPartners businessPartners) { Assert.DoesNotThrowAsync(async() => await _service.Insert(businessPartners)); List <Criteria> criterias = new List <Criteria>() { { new Criteria() { Field = "Codigo", Operator = "eq", Value = businessPartners.Codigo } } }; BusinessPartners record = null; Assert.DoesNotThrowAsync(async() => record = await _service.Find <BusinessPartners>(criterias)); Assert.IsNotNull(record); Assert.IsTrue(record.Codigo == businessPartners.Codigo); }
public void Save(Model.BusinessPartnerModel businessPartnerModel) { BusinessPartners businessPartner = (BusinessPartners)Controller.ConnectionController.Instance.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners); try { if (businessPartner.GetByKey(businessPartnerModel.CardCode)) { if (businessPartnerModel.SlpCode == 0) { businessPartner.SalesPersonCode = -1; } else { businessPartner.SalesPersonCode = businessPartnerModel.SlpCode; } if (businessPartnerModel.OwnerCode == 0) { businessPartner.OwnerCode = -1; } else { businessPartner.OwnerCode = businessPartnerModel.OwnerCode; } foreach (KeyValuePair <string, dynamic> userField in businessPartnerModel.UserFields) { businessPartner.UserFields.Fields.Item(userField.Key).Value = userField.Value; } businessPartner.Update(); Controller.ConnectionController.Instance.VerifyBussinesObjectSuccess(); } } finally { Marshal.ReleaseComObject(businessPartner); GC.Collect(); } }
async public Task Insert(BusinessPartners entity) { try { var Cards = listCardCodes(entity.NATUREZA, entity.CODIGO); bool sucesso = true; foreach (var card in Cards) { IBatchProducer batch = _serviceLayerConnector.CreateBatch(); entity.CardCode = card.CardName; entity.CardType = card.CardType; string record = toJson(entity); batch.Post(HttpMethod.Post, "/BusinessPartners", record); ServiceLayerResponse response = await _serviceLayerConnector.Post("BusinessPartners", record); //códigos de erro para se o produto ja existe if (!response.success) { sucesso = false; } } if (sucesso) { var idEntidade = entity.RecId; var cad = toJsonEntidades(); string query = Global.BuildQuery($"U_VSITENTIDADE('{idEntidade}')"); var response = await _serviceLayerConnector.Patch(query, cad, true); } else { var idEntidade = entity.RecId; var cad = toJsonError(); string query = Global.BuildQuery($"U_VSITENTIDADE('{idEntidade}')"); var response = await _serviceLayerConnector.Patch(query, cad, true); } } catch (Exception e) { } }
private void ExcuteAddNewBusinessPartnerCommand() { try { var bPDetailWindow = new BusinessPartnerDetail(BusinessPartnerTypes.Customer); bPDetailWindow.ShowDialog(); var dialogueResult = bPDetailWindow.DialogResult; if (dialogueResult != null && (bool)dialogueResult) { LoadBusinessPartners(); SelectedBusinessPartner = BusinessPartners.LastOrDefault(); } } catch (Exception exception) { MessageBox.Show("Can't add customer" + Environment.NewLine + exception.Message, "Can't add customer", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void CreateXml() { BusinessPartners cliente = _con.Comany.GetBusinessObject(BoObjectTypes.oBusinessPartners); _con.Comany.XmlExportType = BoXmlExportTypes.xet_ExportImportMode; var exist = cliente.GetByKey("C20000"); if (exist) { xml = String.Format("{0}/{1}.xml", AppDomain.CurrentDomain.BaseDirectory, cliente.CardCode); cliente.SaveXML(xml); linkLabel1.Text = xml; } else { MessageBox.Show("Parceiro não cadastrado"); } }
/// <summary> /// SetCurrentLine by "Contact ID" /// </summary> /// <param name="businessPartners"></param> /// <param name="contactId"></param> /// <returns></returns> public static bool SetContactEmployeesLineByContactId(this BusinessPartners businessPartners, string contactId) { var cardCode = businessPartners.CardCode; var contactEmployees = businessPartners.ContactEmployees; using (var query = new SboRecordsetQuery( "SELECT [LineNum] FROM (SELECT ROW_NUMBER() OVER (ORDER BY [CntctCode] ASC) - 1 AS [LineNum], [Name] FROM [OCPR] " + $"WHERE [CardCode]='{cardCode}') AS [T0] WHERE [Name]='{contactId}'")) { if (query.Count == 0) { return(false); } var lineNum = (int)query.Result.First().Item(0).Value; SboApp.Logger.Debug($"Contact ID '{contactId}' is LineNum {lineNum} for CardCode {cardCode}"); contactEmployees.SetCurrentLine(lineNum); return(true); } }
public void InitializeObject(string cardCode, BoCardTypes cardType = BoCardTypes.cCustomer, bool autoSeries = false) { _businessObject = (BusinessPartners)Controller.ConnectionController.Instance.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners); if (cardCode == null) { cardCode = string.Empty; } if (!_businessObject.GetByKey(cardCode)) { _newObject = true; _businessObject.CardCode = cardCode; _businessObject.CardType = cardType; if (autoSeries) { _businessObject.Series = B1Base.Controller.ConnectionController.Instance.ExecuteSqlForObject <int>("GetAutoSeries", ((int)Model.EnumObjType.BusinessPartner).ToString(), cardType == BoCardTypes.cCustomer ? "C" : "S"); } } }
async public Task <BusinessPartners> Find(List <Criteria> criterias) { string recid = criterias[0].Value; string query = Global.BuildQuery($"BusinessPartners('{recid}')"); string data = await _serviceLayerConnector.getQueryResult(query); ExpandoObject record = Global.parseQueryToObject(data); BusinessPartners businesspartners = toRecord(record); // Recupera as linhas da nota iscal string[] filter = new string[] { $"CardCode eq '{recid}'" }; query = Global.MakeODataQuery("BusinessPartners", null, filter); data = await _serviceLayerConnector.getQueryResult(query); return(businesspartners); }
/// <summary> /// Mass Invoicing /// </summary> /// <param name="invoice"></param> /// <returns></returns> public static ResultDTO CreateDraft(DocumentDTO invoice, UserValues user, FloorService floorServiceItem, string type) { var result = new ResultDTO(); var massInvoicingDAO = new MassInvoicingDAO(); var distributionDAO = new DistributionDAO(); var objectCode = "13"; var containMainUsage = true; try { Documents lObjDocInvDrf = (Documents)DIApplication.Company.GetBusinessObject(BoObjectTypes.oDrafts); //ODRF var task = Task.Run(() => { lObjDocInvDrf.CardCode = invoice.Document.Code; lObjDocInvDrf.CardName = invoice.Document.Name; lObjDocInvDrf.PaymentMethod = "99"; BusinessPartners BPartner = (BusinessPartners)DIApplication.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners); BPartner.GetByKey(lObjDocInvDrf.CardCode); if (BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value.ToString() == "") { BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = "P01"; containMainUsage = false; } lObjDocInvDrf.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value; //lObjDocInvDrf.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = "Por Definir"; lObjDocInvDrf.UserFields.Fields.Item("U_PE_Origin").Value = type; lObjDocInvDrf.DocObjectCode = BoObjectTypes.oInvoices; lObjDocInvDrf.PaymentGroupCode = massInvoicingDAO.GetPayCondition(invoice.Document.Code); lObjDocInvDrf.Series = distributionDAO.GetSeries(user.WhsCode, objectCode); lObjDocInvDrf.EDocGenerationType = EDocGenerationTypeEnum.edocGenerate; }); var task2 = Task.Factory.StartNew(() => { foreach (var line in invoice.FloorServiceLines) { lObjDocInvDrf.Lines.ItemCode = floorServiceItem.ItemCode; lObjDocInvDrf.Lines.WarehouseCode = line.Corral; lObjDocInvDrf.Lines.Quantity = (line.Existence * line.TotalDays); lObjDocInvDrf.Lines.Price = floorServiceItem.Price; lObjDocInvDrf.Lines.CostingCode = user.Area; lObjDocInvDrf.Lines.UserFields.Fields.Item("U_SU_BatchAuc").Value = line.Batch; lObjDocInvDrf.Lines.Add(); } foreach (var line in invoice.DeliveryLines) { lObjDocInvDrf.Lines.ItemCode = line.ItemCode; lObjDocInvDrf.Lines.Quantity = line.Quantity; lObjDocInvDrf.Lines.Price = line.Price; lObjDocInvDrf.Lines.CostingCode = user.Area; lObjDocInvDrf.Lines.BaseEntry = line.DocEntry; lObjDocInvDrf.Lines.BaseLine = line.LineNum; lObjDocInvDrf.Lines.BaseType = 15; //ODLN lObjDocInvDrf.Lines.Add(); } }); //lObjDocInvDrf.EDocGenerationType = SAPbobsCOM.EDocGenerationTypeEnum.edocGenerate; //lObjDocInvDrf.EDocExportFormat = 9; Task.WaitAll(task, task2); if (lObjDocInvDrf.Add() != 0) { LogService.WriteError("InvoiceDI (Draft) " + DIApplication.Company.GetLastErrorDescription()); result.Success = false; result.Message = "Error: " + DIApplication.Company.GetLastErrorDescription(); } else { string lStrDocEntry = DIApplication.Company.GetNewObjectKey(); result.Success = true; result.Message = DIApplication.Company.GetNewObjectKey(); if (containMainUsage == false) { result.Success = true; result.Message = DIApplication.Company.GetNewObjectKey(); SAPbouiCOM.Framework.Application.SBO_Application.StatusBar.SetText("El socio de negocios no contenia Uso de CFDI, se asigno le asigno por default 'Por Definir'" , SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success); } } } catch (AggregateException ae) { LogService.WriteInfo(String.Format("Error: {0}", ae.Message)); LogService.WriteError(ae); ae.Handle(e => { HandleException(e, "InvoiceDI(Draft)"); result.Message = "Error: " + e.Message; result.Success = false; return(true); }); } catch (Exception ex) { HandleException(ex, "InvoiceDI(Draft)"); result.Message = "Error: " + ex.Message; result.Success = false; } return(result); }
public void InserirBusinessPartner(SAPbobsCOM.Company company, Order pedido, out string messageError) { int addBPNumber = 0; string document = string.Empty; Boolean isCorporate = false; if (pedido.buyer.billing_info.doc_type != null && pedido.buyer.billing_info.doc_type.Equals("CNPJ")) { if (pedido.buyer.billing_info.doc_number != null) { document = pedido.buyer.billing_info.doc_number; isCorporate = true; } } else if (pedido.buyer.billing_info.doc_type != null && pedido.buyer.billing_info.doc_type.Equals("CPF")) { if (pedido.buyer.billing_info.doc_number != null) { document = pedido.buyer.billing_info.doc_number; } } try { CountyDAL countyDAL = new CountyDAL(); this.oCompany = company; int _groupCode = Convert.ToInt32(ConfigurationManager.AppSettings["GroupCode"]); int _splCode = Convert.ToInt32(ConfigurationManager.AppSettings["SlpCode"]); int _QoP = Convert.ToInt32(ConfigurationManager.AppSettings["QoP"]); int groupNum = Convert.ToInt32(ConfigurationManager.AppSettings["GroupNum"]); string indicadorIE = ConfigurationManager.AppSettings["IndicadorIE"]; string indicadorOpConsumidor = ConfigurationManager.AppSettings["IndicadorOpConsumidor"]; string gerente = ConfigurationManager.AppSettings["Gerente"]; int priceList = Convert.ToInt32(ConfigurationManager.AppSettings["PriceList"]); string cardCodePrefix = ConfigurationManager.AppSettings["CardCodePrefix"]; int categoriaCliente = Convert.ToInt32(ConfigurationManager.AppSettings["CategoriaCliente"]); this.log.WriteLogPedido("Inserindo Cliente " + cardCodePrefix + document); BusinessPartners oBusinessPartner = null; oBusinessPartner = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners); BusinessPartners oBusinessPartnerUpdateTest = null; oBusinessPartnerUpdateTest = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners); if (oBusinessPartnerUpdateTest.GetByKey(cardCodePrefix + document)) { oBusinessPartner = oBusinessPartnerUpdateTest; } //Setando campos padrões oBusinessPartner.CardCode = cardCodePrefix + document; oBusinessPartner.CardName = pedido.buyer.first_name + " " + pedido.buyer.last_name; oBusinessPartner.EmailAddress = pedido.buyer.email; oBusinessPartner.CardType = BoCardTypes.cCustomer; oBusinessPartner.GroupCode = _groupCode; oBusinessPartner.SalesPersonCode = _splCode; oBusinessPartner.PayTermsGrpCode = groupNum; oBusinessPartner.PriceListNum = priceList; //oBusinessPartner.CardForeignName = "Teste"; //Setando campos de usuário oBusinessPartner.UserFields.Fields.Item("U_TX_IndIEDest").Value = indicadorIE; oBusinessPartner.UserFields.Fields.Item("U_TX_IndFinal").Value = indicadorOpConsumidor; oBusinessPartner.UserFields.Fields.Item("U_Gerente").Value = gerente; oBusinessPartner.UserFields.Fields.Item("U_CategoriaCliente").Value = gerente; //removendo o +55 if (pedido.buyer.phone != null) { if (pedido.buyer.phone.number != null) { oBusinessPartner.Phone1 = pedido.buyer.phone.number; } } string codMunicipio = string.Empty; 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.receiver_address != null) { codMunicipio = countyDAL.RecuperarCodigoMunicipio(shipment.receiver_address.city.name, this.oCompany); } } //Inserindo endereços //COBRANÇA oBusinessPartner.Addresses.SetCurrentLine(0); oBusinessPartner.Addresses.AddressType = BoAddressType.bo_BillTo; oBusinessPartner.Addresses.AddressName = "COBRANCA"; if (shipment != null) { oBusinessPartner.Addresses.City = shipment.receiver_address.city.name; if (shipment.receiver_address.comment != null && shipment.receiver_address.comment.Length <= 100) { oBusinessPartner.Addresses.BuildingFloorRoom = shipment.receiver_address.comment; } //oBusinessPartner.Addresses.Country = "1058"; if (shipment.receiver_address.neighborhood.name != null) { oBusinessPartner.Addresses.Block = shipment.receiver_address.neighborhood.name; } oBusinessPartner.Addresses.StreetNo = shipment.receiver_address.street_number; oBusinessPartner.Addresses.ZipCode = shipment.receiver_address.zip_code; oBusinessPartner.Addresses.State = shipment.receiver_address.state.id.Substring(3); oBusinessPartner.Addresses.Street = shipment.receiver_address.street_name; oBusinessPartner.Addresses.County = codMunicipio; //oBusinessPartner.Addresses.Country = "br"; } //FATURAMENTO oBusinessPartner.Addresses.SetCurrentLine(1); oBusinessPartner.Addresses.AddressType = BoAddressType.bo_ShipTo; oBusinessPartner.Addresses.AddressName = "FATURAMENTO"; if (shipment != null) { oBusinessPartner.Addresses.City = shipment.receiver_address.city.name; if (shipment.receiver_address.comment != null && shipment.receiver_address.comment.Length <= 100) { oBusinessPartner.Addresses.BuildingFloorRoom = shipment.receiver_address.comment; } //oBusinessPartner.Addresses.Country = "1058"; if (shipment.receiver_address.neighborhood.name != null) { oBusinessPartner.Addresses.Block = shipment.receiver_address.neighborhood.name; } oBusinessPartner.Addresses.StreetNo = shipment.receiver_address.street_number; oBusinessPartner.Addresses.ZipCode = shipment.receiver_address.zip_code; oBusinessPartner.Addresses.State = shipment.receiver_address.state.id.Substring(3); oBusinessPartner.Addresses.Street = shipment.receiver_address.street_name; oBusinessPartner.Addresses.County = codMunicipio; //oBusinessPartner.Addresses.Country = "br"; } #region ENDEREÇO FOR /* * for (int i = 0; i < 2; i++) * { * if (i > 0) * { * oBusinessPartner.Addresses.SetCurrentLine(i); * oBusinessPartner.Addresses.AddressType = BoAddressType.bo_ShipTo; * oBusinessPartner.Addresses.AddressName = "FATURAMENTO"; * } * else * { * oBusinessPartner.Addresses.SetCurrentLine(i); * oBusinessPartner.Addresses.AddressType = BoAddressType.bo_BillTo; * oBusinessPartner.Addresses.AddressName = "COBRANCA"; * * if (!oBusinessPartnerUpdateTest.GetByKey(cardCodePrefix + document)) * { * oBusinessPartner.Addresses.Add(); * } * } * * if (shipment != null) * { * oBusinessPartner.Addresses.City = shipment.receiver_address.city.name; * * if (shipment.receiver_address.comment != null && shipment.receiver_address.comment.Length <= 100) * { * oBusinessPartner.Addresses.BuildingFloorRoom = shipment.receiver_address.comment; * } * * //oBusinessPartner.Addresses.Country = "1058"; * if (shipment.receiver_address.neighborhood.name != null) * { * oBusinessPartner.Addresses.Block = shipment.receiver_address.neighborhood.name; * } * * oBusinessPartner.Addresses.StreetNo = shipment.receiver_address.street_number; * oBusinessPartner.Addresses.ZipCode = shipment.receiver_address.zip_code; * oBusinessPartner.Addresses.State = shipment.receiver_address.state.id.Substring(3); * oBusinessPartner.Addresses.Street = shipment.receiver_address.street_name; * oBusinessPartner.Addresses.County = codMunicipio; * //oBusinessPartner.Addresses.Country = "br"; * } * * }*/ #endregion #region código de endereço antigo /*oBusinessPartner.Addresses.SetCurrentLine(0); * oBusinessPartner.Addresses.AddressName = "COBRANCA"; * oBusinessPartner.Addresses.AddressType = SAPbobsCOM.BoAddressType.bo_BillTo; * * oBusinessPartner.Addresses.Street = endereco.street; * oBusinessPartner.Addresses.Block = endereco.neighborhood; * oBusinessPartner.Addresses.ZipCode = endereco.postalCode; * oBusinessPartner.Addresses.City = endereco.city; * oBusinessPartner.Addresses.Country = "BR"; * oBusinessPartner.Addresses.State = endereco.state; * oBusinessPartner.Addresses.BuildingFloorRoom = endereco.complement; * oBusinessPartner.Addresses.StreetNo = endereco.number; * * oBusinessPartner.Addresses.Add(); * * oBusinessPartner.Addresses.SetCurrentLine(1); * oBusinessPartner.Addresses.AddressName = "FATURAMENTO"; * oBusinessPartner.Addresses.AddressType = SAPbobsCOM.BoAddressType.bo_ShipTo; * * oBusinessPartner.Addresses.Street = endereco.street; * oBusinessPartner.Addresses.Block = endereco.neighborhood; * oBusinessPartner.Addresses.ZipCode = endereco.postalCode; * oBusinessPartner.Addresses.City = endereco.city; * oBusinessPartner.Addresses.Country = "BR"; * oBusinessPartner.Addresses.State = endereco.state; * oBusinessPartner.Addresses.BuildingFloorRoom = endereco.complement; * oBusinessPartner.Addresses.StreetNo = endereco.number;*/ //oBusinessPartner.Addresses.Add(); #endregion oBusinessPartner.BilltoDefault = "COBRANCA"; oBusinessPartner.ShipToDefault = "FATURAMENTO"; BusinessPartners oBusinessPartnerUpdate = null; oBusinessPartnerUpdate = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners); if (oBusinessPartnerUpdate.GetByKey(cardCodePrefix + document)) { addBPNumber = oBusinessPartner.Update(); if (addBPNumber != 0) { messageError = oCompany.GetLastErrorDescription(); this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, cardCodePrefix + document, EnumStatusIntegracao.Erro, messageError); //this.log.WriteLogCliente("InserirBusinessPartner error SAP: " + messageError); } else { messageError = ""; this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, cardCodePrefix + document, EnumStatusIntegracao.Sucesso, "Cliente atualizado com sucesso."); //this.Log.WriteLogCliente("BusinessPartner " + cardCodePrefix + document + " atualizado com sucesso."); System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartner); System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdate); System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdateTest); } } else { //Setando informações Fiscais //oBusinessPartner.FiscalTaxID.SetCurrentLine(0); if (isCorporate) { oBusinessPartner.FiscalTaxID.TaxId0 = document; } else { oBusinessPartner.FiscalTaxID.TaxId4 = document; oBusinessPartner.FiscalTaxID.TaxId1 = "Isento"; } //oBusinessPartner.FiscalTaxID.Address = "FATURAMENTO"; //oBusinessPartner.FiscalTaxID.Add(); addBPNumber = oBusinessPartner.Add(); if (addBPNumber != 0) { messageError = oCompany.GetLastErrorDescription(); this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, "", EnumStatusIntegracao.Erro, messageError); //Log.WriteLogCliente("InserirBusinessPartner error SAP: " + messageError); } else { string CardCode = oCompany.GetNewObjectKey(); this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, CardCode, EnumStatusIntegracao.Sucesso, "Cliente inserido com sucesso."); //Log.WriteLogCliente("BusinessPartner " + cardCodePrefix +CardCode + " inserido com sucesso."); messageError = ""; } } System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartner); System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdateTest); System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdate); } catch (Exception e) { this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, "", EnumStatusIntegracao.Erro, e.Message); this.log.WriteLogPedido("InserirBusinessPartner Exception: " + e.Message); throw; } }
/// <summary> /// Cancelar LCM /// </summary> /// <param name="Caminho"></param> /// public void LerArquivo(string Caminho) { using (OpenFileDialog openfileDialog = new OpenFileDialog()) { string PorLinha = null; openfileDialog.Title = "Integração SAP"; openfileDialog.InitialDirectory = Convert.ToString(Caminho); openfileDialog.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"; openfileDialog.FilterIndex = 2; openfileDialog.RestoreDirectory = true; if (openfileDialog.ShowDialog() == DialogResult.OK) { arquivo = openfileDialog.FileName; } if (string.IsNullOrEmpty(arquivo)) { MessageBox.Show("Arquivo Invalido", "Salvar Como", MessageBoxButtons.OK); } else { using (StreamReader texto = new StreamReader(arquivo)) { List <string> TextoPorLinha = new List <string>(); while ((PorLinha = texto.ReadLine()) != null) { TextoPorLinha.Add(PorLinha); } if (GlobalConection.oCompany.Connected == true) { foreach (var nota in TextoPorLinha) { // var cJE = (JournalEntries)GlobalConection.oCompany.GetBusinessObject(BoObjectTypes.oJournalVouchers); //JournalEntries cJE = (JournalEntries)GlobalConection.oCompany.GetBusinessObject(BoObjectTypes.oJournalEntries); // cJE.GetByKey(Convert.ToInt32(nota)); //Items citms = (Items)GlobalConection.oCompany.GetBusinessObject(BoObjectTypes.oItems); BusinessPartners cPN = (BusinessPartners)GlobalConection.oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners); cPN.GetByKey(nota); //citms.GetByKey(nota); //Documents cancelJE = cJE.CreateCancellationDocument(); bool resultado; //resultado = citms.GetByKey(nota); resultado = cPN.GetByKey(nota); if (resultado == false) { string msg = GlobalConection.oCompany.GetLastErrorDescription(); //MessageBox.Show(msg); } else { // MessageBox.Show("LCM cancelado com sucesso"); //citms.Remove(); cPN.Remove(); // MessageBox.Show("item cancelado com sucesso"); } } //MessageBox.Show("item cancelado com sucesso"); } else { MessageBox.Show("Não está conectado!!"); } } } } }