/// <summary> /// 新增或编辑 logcall /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > AddOrEditEntity(LogCallRequest request) { var validateResult = new ValidateResult <CrmEntity>(); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); try { Guid guid = string.IsNullOrEmpty(request.mcs_logcallid) ? Guid.NewGuid() : Guid.Parse(request.mcs_logcallid); CrmExecuteEntity Entity = new CrmExecuteEntity("mcs_logcall", guid); if (!string.IsNullOrEmpty(request.mcs_onlyleadid)) { Entity.Attributes.Add("mcs_onlyleadid", new CrmEntityReference("mcs_onlylead", Guid.Parse(request.mcs_onlyleadid))); } if (!string.IsNullOrEmpty(request.accountid)) { Entity.Attributes.Add("mcs_accountid", new CrmEntityReference("account", Guid.Parse(request.accountid))); } if (!string.IsNullOrEmpty(request.mcs_content)) { Entity.Attributes.Add("mcs_content", request.mcs_content); } if (!string.IsNullOrEmpty(request.mcs_fullname)) { Entity.Attributes.Add("mcs_fullname", request.mcs_fullname); } if (!string.IsNullOrEmpty(request.mcs_mobilephone)) { Entity.Attributes.Add("mcs_mobilephone", request.mcs_mobilephone); } if (!string.IsNullOrEmpty(request.mcs_results)) { Entity.Attributes.Add("mcs_results", request.mcs_results); } if (request.mcs_visittime.HasValue) { Entity.Attributes.Add("mcs_visittime", request.mcs_visittime.Value); } if (!string.IsNullOrEmpty(request.mcs_logcallid)) { await _crmService.Update(Entity, userInfo?.systemuserid); } else { guid = await _crmService.Create(Entity, userInfo?.systemuserid); } validateResult.Result = true; validateResult.Description = "操作成功"; } catch (Exception ex) { validateResult.Result = false; validateResult.Description = "操作失败,原因:" + ex.Message; throw ex; } return(validateResult); }
private void ImportRecord(DynamicEntity entity) { string statecode = ""; int statuscode = -1; if (entity.Properties.Contains("statecode")) { statecode = entity["statecode"].ToString(); entity.Properties.Remove("statecode"); } if (entity.Properties.Contains("statuscode")) { statuscode = ((Status)entity["statuscode"]).Value; entity.Properties.Remove("statuscode"); } string primaryAttribute = MetadataUtility.RetrievePrimaryAttribute(_metadataService, entity.Name); string primaryAttributeValue = entity.Properties.Contains(primaryAttribute) ? entity[primaryAttribute].ToString() : ""; Guid id = entity.Properties.OfType <KeyProperty>().First().Value.Value; Guid potentialNewId = Guid.Empty; int matchingRecordCount = GetMatchingRecordCount(entity.Name, id, primaryAttributeValue, ref potentialNewId); switch (matchingRecordCount) { case 0: _crmService.Create(entity); ReportDetail(String.Format("Created {0} with id of {1}.", entity.Name, id)); break; case 1: if (potentialNewId != Guid.Empty) { id = potentialNewId; entity.Properties.OfType <KeyProperty>().First().Value.Value = potentialNewId; } _crmService.Update(entity); ReportDetail(String.Format("Updated {0} with id of {1}.", entity.Name, id)); break; default: ReportError(String.Format("Cannot import {0} with id of {1} because it matches more than one record in the target system based on attribute {2}.", entity.Name, id, primaryAttribute)); break; } if (matchingRecordCount < 2 && !String.IsNullOrEmpty(statecode)) { DynamicEntityUtility.SetStateDynamicEntity(_crmService, entity.Name, id, statecode, statuscode); ReportDetail(String.Format("Set state on {0} with id of {1}.", entity.Name, id)); } _currentRecordCount++; _entityRecordCounts[entity.Name]++; int percent = (int)Math.Round(100.0 * _currentRecordCount / _totalRecordCount); percent = percent > 100 ? 100 : percent; OnImportProgressChanged(new ProgressChangedEventArgs(percent, null)); }
/// <summary> /// 创建试乘试驾预约 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > CreateTestDrive(TestDriveViewModel request) { var validateResult = new ValidateResult <CrmEntity>(); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); try { Guid mcs_driverecordid = string.IsNullOrEmpty(request.mcs_driverecordid) ? Guid.NewGuid() : Guid.Parse(request.mcs_driverecordid); CrmExecuteEntity Entity = new CrmExecuteEntity("mcs_driverecord", mcs_driverecordid); if (!string.IsNullOrEmpty(request.mcs_fullname)) { Entity.Attributes.Add("mcs_fullname", request.mcs_fullname); } if (!string.IsNullOrEmpty(request.mcs_mobilephone)) { Entity.Attributes.Add("mcs_mobilephone", request.mcs_mobilephone); } if (!string.IsNullOrEmpty(request.mcs_carmodel)) { Entity.Attributes.Add("mcs_carmodel", new CrmEntityReference("mcs_carmodel", Guid.Parse(request.mcs_carmodel))); } if (!string.IsNullOrEmpty(request.mcs_businesstype)) { Entity.Attributes.Add("mcs_businesstype", request.mcs_businesstype); } if (!string.IsNullOrEmpty(request.mcs_dealerid)) { Entity.Attributes.Add("mcs_dealerid", new CrmEntityReference("mcs_dealer", Guid.Parse(request.mcs_dealerid))); } if (request.mcs_ordertime.HasValue) { Entity.Attributes.Add("mcs_ordertime", request.mcs_ordertime.Value); } if (!string.IsNullOrEmpty(request.mcs_testdrivetime)) { Entity.Attributes.Add("mcs_testdrivetime", new CrmEntityReference("mcs_reservationconfiguration", Guid.Parse(request.mcs_testdrivetime))); } if (!string.IsNullOrEmpty(request.UserId)) { Entity.Attributes.Add("mcs_userid", request.UserId); } if (!string.IsNullOrEmpty(request.mcs_driverecordid)) { await _crmService.Update(Entity, userInfo?.systemuserid); } else { mcs_driverecordid = await _crmService.Create(Entity, userInfo?.systemuserid); //预约成功后 进行留资 if (mcs_driverecordid != null) { CreateLead(request, userInfo?.systemuserid); } } validateResult.Result = true; validateResult.Description = "操作成功"; } catch (Exception ex) { validateResult.Result = false; validateResult.Description = "操作失败,原因:" + ex.Message; throw ex; } return(validateResult); }
//public static void CreateLead(CrmService service, LeadInfo leadDetails, Guid leadID, DynamicEntity crmLeadInfo) //{ // string firstName = string.Empty; // string lastName = string.Empty; // try // { // var lead = new lead(); // foreach (Property p in crmLeadInfo.Properties) // { // if (p.Name == "firstname") // { // firstName = CrmHelper.GetSourceValue(p.GetType().Name, p); // } // if (p.Name == "lastname") // { // lastName = CrmHelper.GetSourceValue(p.GetType().Name, p); // } // } // if (leadDetails.LeadOriginatorName == string.Concat(firstName, " ", lastName)) // { // //lead.ms_bdm= matched CRM user // lead.ms_staffreferrer = null; // lead.ms_referralname = null; // } // else // { // lead.ms_bdm = null; // lead.ms_staffreferrer = null; // lead.ms_referralname = leadDetails.LeadOriginatorName; // } // var crmBrand = new Picklist(); // if (leadDetails.Brand.ToLower() == "maxxia") // { // crmBrand.Value = 0; // } // else { crmBrand.Value = 1; } // lead.ms_brand = crmBrand; // //var crmProductType = new Picklist(); // //crmProductType.Value = Convert.ToInt32("Fully Maintained Novated Lease"); // //lead.ms_producttype = crmProductType; // //var crmOwnLead = new Picklist(); // //crmOwnLead.Value = Convert.ToInt32("No"); // //lead.ms_willyouownthelead = crmOwnLead; // //var crmRating = new Picklist(); // //if (string.IsNullOrEmpty(leadDetails.LeadRating)) // //{ // // crmRating.Value = Convert.ToInt32("Warm"); // //} // //else // //{ // // crmRating.Value = Convert.ToInt32(leadDetails.LeadRating); // //} // //lead.leadqualitycode = crmRating; // //var crmLeadSource = new Picklist(); // //crmLeadSource.Value = Convert.ToInt32(leadDetails.LeadSource); // //lead.leadsourcecode = crmLeadSource; // //var crmEnquirySource = new Picklist(); // //crmEnquirySource.Value = Convert.ToInt32(leadDetails.ActivityType); // //lead.ms_enquirysource = crmEnquirySource; // //var crmCampaignSource = new Picklist(); // //if (string.IsNullOrEmpty(leadDetails.CampaignSource )) // //{ // // crmCampaignSource.Value = Convert.ToInt32("None"); // //} // //else // //{ // // crmCampaignSource.Value = Convert.ToInt32(leadDetails.CampaignSource); // //} // //lead.ms_campaignsource = crmCampaignSource; // //if (!string.IsNullOrEmpty(leadDetails.VehicleType)) // //{ // // var crmVehicleType = new Picklist(); // // if (leadDetails.VehicleType == "New Car") // // { // // crmVehicleType.Value = Convert.ToInt32("New"); // // } // // else if(leadDetails.VehicleType == "Used Car") // // { // // crmVehicleType.Value = Convert.ToInt32("Used(Dealer)"); // // } // // else if(leadDetails.VehicleType == "Refinance Existing") // // { // // crmVehicleType.Value = Convert.ToInt32("Sales & Leaseback"); // // } // // lead.ms_vehicletype = crmVehicleType; // //} // //if (!string.IsNullOrEmpty(leadDetails.EmployerCode)) // //{ // //var emp = new account { accountnumber = leadDetails.EmployerCode }; // // var crmEmployer = new Lookup(); // // if (emp.accountid != null) // // { // // //crmEmployer.Value = emp; // // } // // else // // { // // emp = new account { name = leadDetails.EmployerName }; // // if (emp.accountid != null) // // { // // // crmEmployer.Value = emp; // // } // // else // // { // // // crmEmployer.Value = TestEmployer; // // //lead.TemPMessage; // // } // // } // // lead.ms_employer = crmEmployer; // // lead.ms_salarypackager = emp.ms_salarypackager1; // //} // //var crmState = new Picklist(); // //crmState.Value = Convert.ToInt32(leadDetails.State); // //lead.ms_homeaddressstate = crmState; // lead.firstname = leadDetails.Firstname; // lead.lastname = leadDetails.Surname; // lead.emailaddress2 = leadDetails.Email; // lead.mobilephone = leadDetails.MobilePhone; // //var crmPrefferedPhone = new Picklist(); // //if (leadDetails.MobilePreferredContact) // //{ // // crmPrefferedPhone.Value = Convert.ToInt32("Mobile"); // //} // //else // //{ // // crmPrefferedPhone.Value = Convert.ToInt32("Work"); // //} // //lead.ms_preferredphone = crmPrefferedPhone; // if (!string.IsNullOrEmpty(leadDetails.OtherPhone)) lead.telephone1 = leadDetails.OtherPhone; // lead.ms_preferredcontacttime = leadDetails.PreferredCallBackTime; // var crmAnnualGS = new CrmDecimal(); // if (leadDetails.AnnualGrossSalary.ToString() != "") // { // crmAnnualGS.Value = leadDetails.AnnualGrossSalary; // var crmRefferalSplit = new CrmDecimal(); // if (leadDetails.AnnualGrossSalary < 110000) // { // crmRefferalSplit.Value = (decimal)999.00; // } // else // { // //crmRefferalSplit.Value = null; // } // lead.ms_referralsplit = crmRefferalSplit; // } // else // { // crmAnnualGS.Value = 0; // } // lead.ms_annualgrosssalary = crmAnnualGS; // //lead.siteid // lead.ms_salesmessages = "Year: " + leadDetails.VehicleYear + "/ Make: " + leadDetails.VehicleMake + "/ Model: " + leadDetails.VehicleType + "\r\n" + "Lease Term: " + leadDetails.LeaseTerm + "\r\n * **\r\n" + leadDetails.OtherInformation; // //var emp = new account { ownerid = new Owner { Value = "" }; }; // //lead.ownerid= // var oppKey = new WebReferences.CrmSdk.Key { Value = leadID }; // lead.leadid = oppKey; // service.Update(lead); // } // catch (Exception ex) // { // throw ex; // } //} public static void ReactivateLead(CrmService service, MetadataService metaDataService, LeadInfo leadDetails, Guid leadID, DynamicEntity crmLeadInfo) { string firstName = string.Empty; string lastName = string.Empty; try { var lead = new lead(); foreach (Property p in crmLeadInfo.Properties) { if (p.Name == "firstname") { firstName = CrmHelper.GetSourceValue(p.GetType().Name, p); } if (p.Name == "lastname") { lastName = CrmHelper.GetSourceValue(p.GetType().Name, p); } } if (leadDetails.LeadOriginatorName == string.Concat(firstName, " ", lastName)) { //lead.ms_bdm= matched CRM user lead.ms_staffreferrer = null; lead.ms_referralname = null; } else { lead.ms_bdm = null; lead.ms_staffreferrer = null; lead.ms_referralname = leadDetails.LeadOriginatorName; } //var crmBrand = new Picklist(); //if (leadDetails.Brand.ToLower() == DALConstants.BrandM) //{ // crmBrand.Value = Convert.ToInt32(DALConstants.Brand.Maxxia) ; //} //else { crmBrand.Value = Convert.ToInt32(DALConstants.Brand.Remserv); } //lead.ms_brand = crmBrand; //var crmProductType = new Picklist //{ // name = "ms_producttype", // Value = CrmHelper.GetPickListCode(metaDataService, "ms_producttype", "ms_producttype", DALConstants.ProductTypeFMNL) //}; //lead.ms_producttype = crmProductType; //var crmOwnLead = new Picklist(); //crmOwnLead.Value = Convert.ToInt32(DALConstants.OwnTheLead.No); //lead.ms_willyouownthelead = crmOwnLead; //var crmRating = new Picklist(); //if (string.IsNullOrEmpty(leadDetails.LeadRating)) //{ // crmRating.Value = Convert.ToInt32("Warm"); //} //else //{ // crmRating.Value = Convert.ToInt32(leadDetails.LeadRating); //} //lead.leadqualitycode = crmRating; //var crmLeadSource = new Picklist //{ // name = "ms_leadsourcename", // Value = CrmHelper.GetPickListCode(metaDataService, "ms_leadsource", "ms_leadsourcename", leadDetails.LeadSource) //}; //lead.leadsourcecode = crmLeadSource; //leadsourceid required //var crmEnquirySource = new Picklist //{ // name = "ms_enquirysourcename", // Value = CrmHelper.GetPickListCode(metaDataService, "ms_enquirysource", "ms_enquirysourcename", leadDetails.ActivityType ) //}; //lead.ms_enquirysource = crmEnquirySource; //string csName = string.Empty; //if (string.IsNullOrEmpty(leadDetails.CampaignSource)) //{ // csName = "None"; //} //else //{ // csName = leadDetails.CampaignSource; //} //var crmCampaignSource = new Picklist //{ // name = "ms_campaignsourcename", // Value = CrmHelper.GetPickListCode(metaDataService, "ms_campaignsource", "ms_campaignsourcename", csName) //}; //lead.ms_campaignsource = crmCampaignSource; //string vehicleType = string.Empty; //if (!string.IsNullOrEmpty(leadDetails.VehicleType)) //{ // if (leadDetails.VehicleType == "New Car") // { // vehicleType="New"; // } // else if (leadDetails.VehicleType == "Used Car") // { // vehicleType="Used(Dealer)"; // } // else if (leadDetails.VehicleType == "Refinance Existing") // { // vehicleType="Sales & Leaseback"; // } // var crmVehicleType = new Picklist() // { // name = "ms_vehicletype1", // Value = CrmHelper.GetPickListCode(metaDataService, "ms_vehicletype", "ms_vehicletype1", vehicleType) // }; // lead.ms_vehicletype = crmVehicleType; //} //if (!string.IsNullOrEmpty(leadDetails.EmployerCode)) //{ //var emp = new account { accountnumber = leadDetails.EmployerCode }; // var crmEmployer = new Lookup(); // if (emp.accountid != null) // { // //crmEmployer.Value = emp; // } // else // { // emp = new account { name = leadDetails.EmployerName }; // if (emp.accountid != null) // { // // crmEmployer.Value = emp; // } // else // { // // crmEmployer.Value = TestEmployer; // //lead.TemPMessage; // } // } // lead.ms_employer = crmEmployer; // lead.ms_salarypackager = emp.ms_salarypackager1; //} //var crmState = new Picklist(); //crmState.Value = Convert.ToInt32(leadDetails.State); //lead.ms_homeaddressstate = crmState; lead.firstname = leadDetails.Firstname; lead.lastname = leadDetails.Surname; lead.emailaddress2 = leadDetails.Email; lead.mobilephone = leadDetails.MobilePhone; //var crmPrefferedPhone = new Picklist(); //if (leadDetails.MobilePreferredContact) //{ // crmPrefferedPhone.Value = Convert.ToInt32("Mobile"); //} //else //{ // crmPrefferedPhone.Value = Convert.ToInt32("Work"); //} //lead.ms_preferredphone = crmPrefferedPhone; if (!string.IsNullOrEmpty(leadDetails.OtherPhone)) { lead.telephone1 = leadDetails.OtherPhone; } lead.ms_preferredcontacttime = leadDetails.PreferredCallBackTime; var crmAnnualGS = new CrmDecimal(); if (leadDetails.AnnualGrossSalary.ToString() != "") { crmAnnualGS.Value = leadDetails.AnnualGrossSalary; var crmRefferalSplit = new CrmDecimal(); if (leadDetails.AnnualGrossSalary < 110000) { crmRefferalSplit.Value = (decimal)999.00; } else { //crmRefferalSplit.Value = null; } lead.ms_referralsplit = crmRefferalSplit; } else { crmAnnualGS.Value = 0; } lead.ms_annualgrosssalary = crmAnnualGS; //lead.siteid lead.ms_salesmessages = "Year: " + leadDetails.VehicleYear + "/ Make: " + leadDetails.VehicleMake + "/ Model: " + leadDetails.VehicleType + "\r\n" + "Lease Term: " + leadDetails.LeaseTerm + "\r\n * **\r\n" + leadDetails.OtherInformation; //var emp = new account { ownerid = new Owner { Value = "" }; }; //lead.ownerid= var oppKey = new WebReferences.CrmSdk.Key { Value = leadID }; lead.leadid = oppKey; service.Update(lead); } catch (Exception ex) { throw ex; } }
public String CreateConfig(Guid new_config_allid, Config config) { Guid configid = new_config_allid; try { DynamicEntity conf = new DynamicEntity("new_reestr"); conf.Name = "new_reestr"; CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); if (new_config_allid == new Guid("{00000000-0000-0000-0000-000000000000}")) { configid = crmService.Create(conf); } // Создаем экземпляр динамческого объекта и указываем его имя DynamicEntity myDEUpdate = new DynamicEntity(); myDEUpdate.Name = "new_config_allid"; // Создаем KeyProperty для хранения GUID’а обновляемой записи KeyProperty myConfigGuid = new KeyProperty(); myConfigGuid.Name = "new_config_allid"; // Указываем GUID обновляемой записи Key myConfigKey = new Key(); myConfigKey.Value = configid; myConfigGuid.Value = myConfigKey; myDEUpdate.Properties.Add(myConfigGuid); //if (conf.new_count != 0) // myDEUpdate.Properties.Add(new CrmNumberProperty("new_count", new CrmNumber(conf.new_count))); ////Кем выдан //if (conf.new_giveoutby != null) // myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby)); ////День рождения //if (contact.birthdate != null) // myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); crmService.Update(myDEUpdate); //поиск контакта для переназначения ответственного, если таковой меняется Owner ownerID = new Owner(); if (new_config_allid != new Guid("{00000000-0000-0000-0000-000000000000}")) { try { string ln = ""; //фамилия BusinessEntityCollection fcontact = searchContact(new_config_allid.ToString()); foreach (DynamicEntity cont1 in fcontact.BusinessEntities) { ln = cont1["lastname"].ToString(); if (cont1.Properties.Contains("ownerid")) { ownerID = (Owner)cont1["ownerid"]; } } logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}"); } catch (Exception ex) { logger.Error($"Ошибка: {ex.ToString()}"); } } return(configid.ToString()); } catch (SoapException ex) { logger.Error($"Ошибка: {ex.Detail.InnerText}"); return(ex.Detail.InnerText); } }
/// <summary> /// 勘测单新增或编辑 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > AddOrEditSurveyorder(SurveyorderMetadataModel request) { var validateResult = new ValidateResult <CrmEntity>(); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); try { Guid guid = string.IsNullOrEmpty(request.mcs_surveyorderid) ? Guid.NewGuid() : Guid.Parse(request.mcs_surveyorderid); CrmExecuteEntity Entity = new CrmExecuteEntity("mcs_surveyorder", guid); if (!string.IsNullOrEmpty(request.mcs_surveyordertype.ToString())) { int surveyordertype = Convert.ToInt32(request.mcs_surveyordertype); Entity.Attributes.Add("mcs_surveyordertype", surveyordertype); } if (!string.IsNullOrEmpty(request.mcs_accountid)) { Entity.Attributes.Add("mcs_accountid", new CrmEntityReference("account", Guid.Parse(request.mcs_accountid))); } if (!string.IsNullOrEmpty(request.mcs_username)) { Entity.Attributes.Add("mcs_username", request.mcs_username); } if (!string.IsNullOrEmpty(request.mcs_userphone)) { Entity.Attributes.Add("mcs_userphone", request.mcs_userphone); } if (!string.IsNullOrEmpty(request.mcs_idcard)) { Entity.Attributes.Add("mcs_idcard", request.mcs_idcard); } if (!string.IsNullOrEmpty(request.mcs_email)) { Entity.Attributes.Add("mcs_email", request.mcs_email); } if (!string.IsNullOrEmpty(request.mcs_carmodelid)) { Entity.Attributes.Add("mcs_carmodelid", new CrmEntityReference("mcs_carmodel", Guid.Parse(request.mcs_carmodelid))); } if (!string.IsNullOrEmpty(request.mcs_dealer)) { Entity.Attributes.Add("mcs_dealer", new CrmEntityReference("mcs_dealer", Guid.Parse(request.mcs_dealer))); } if (!string.IsNullOrEmpty(request.mcs_salesconsultant)) { Entity.Attributes.Add("mcs_salesconsultant", new CrmEntityReference("systemuser", Guid.Parse(request.mcs_salesconsultant))); } if (!string.IsNullOrEmpty(request.mcs_contactname)) { Entity.Attributes.Add("mcs_contactname", request.mcs_contactname); } if (!string.IsNullOrEmpty(request.mcs_contactphone)) { Entity.Attributes.Add("mcs_contactphone", request.mcs_contactphone); } if (!string.IsNullOrEmpty(request.mcs_contactemail)) { Entity.Attributes.Add("mcs_contactemail", request.mcs_contactemail); } if (!string.IsNullOrEmpty(request.mcs_province)) { Entity.Attributes.Add("mcs_province", new CrmEntityReference("mcs_sysarea", Guid.Parse(request.mcs_province))); } if (!string.IsNullOrEmpty(request.mcs_city)) { Entity.Attributes.Add("mcs_city", new CrmEntityReference("mcs_sysarea", Guid.Parse(request.mcs_city))); } if (!string.IsNullOrEmpty(request.mcs_area)) { Entity.Attributes.Add("mcs_area", new CrmEntityReference("mcs_sysarea", Guid.Parse(request.mcs_area))); } if (!string.IsNullOrEmpty(request.mcs_installationaddress)) { Entity.Attributes.Add("mcs_installationaddress", request.mcs_installationaddress); } if (!string.IsNullOrEmpty(request.mcs_detailaddress)) { Entity.Attributes.Add("mcs_detailaddress", request.mcs_detailaddress); } if (!string.IsNullOrEmpty(request.mcs_chargingpilemodel)) { Entity.Attributes.Add("mcs_chargingpilemodel", new CrmEntityReference("mcs_mc_chargingpilemodel", Guid.Parse(request.mcs_chargingpilemodel))); } if (!string.IsNullOrEmpty(request.mcs_communityname)) { Entity.Attributes.Add("mcs_communityname", request.mcs_communityname); } if (!string.IsNullOrEmpty(request.mcs_residentialnature.ToString())) { int residentialnature = Convert.ToInt32(request.mcs_residentialnature); Entity.Attributes.Add("mcs_residentialnature", residentialnature); } if (!string.IsNullOrEmpty(request.mcs_price)) { Entity.Attributes.Add("mcs_price", Convert.ToDecimal(request.mcs_price)); } if (!string.IsNullOrEmpty(request.mcs_parkingspace.ToString())) { int parkingspace = Convert.ToInt32(request.mcs_parkingspace); Entity.Attributes.Add("mcs_parkingspace", parkingspace); } if (!string.IsNullOrEmpty(request.mcs_residentialtype.ToString())) { int residentialtype = Convert.ToInt32(request.mcs_residentialtype); Entity.Attributes.Add("mcs_residentialtype", residentialtype); } if (!string.IsNullOrEmpty(request.mcs_remark)) { Entity.Attributes.Add("mcs_remark", request.mcs_remark); } if (!string.IsNullOrEmpty(request.mcs_surveyorderid)) { await _crmService.Update(Entity, userInfo?.systemuserid); } else { guid = await _crmService.Create(Entity, userInfo?.systemuserid); } validateResult.Result = true; validateResult.Description = "操作成功"; } catch (Exception ex) { validateResult.Result = false; validateResult.Description = "操作失败,原因:" + ex.Message; throw ex; } return(validateResult); }
/// <summary> /// 创建或编辑实体 /// </summary> /// <param name="crmEntity"></param> /// <returns></returns> public async Task <Guid> AddOrEditEntity(AccountRequest request) { Guid guid = Guid.Empty; try { guid = string.IsNullOrEmpty(request.Id) ? Guid.NewGuid() : Guid.Parse(request.Id); CrmExecuteEntity createorUpdateEntity = new CrmExecuteEntity(EntityName, guid); if (!string.IsNullOrEmpty(request.name)) { createorUpdateEntity.Attributes.Add("name", request.name); } if (!string.IsNullOrEmpty(request.mcs_onlyleadid)) { createorUpdateEntity.Attributes.Add("mcs_onlyleadid", new CrmEntityReference("mcs_onlylead", Guid.Parse(request.mcs_onlyleadid))); } if (!string.IsNullOrEmpty(request.mcs_vehcolorid)) { createorUpdateEntity.Attributes.Add("mcs_vehcolorid", new CrmEntityReference("mcs_vehiclecolor", Guid.Parse(request.mcs_vehcolorid))); } if (!string.IsNullOrEmpty(request.mcs_vehtypeid)) { createorUpdateEntity.Attributes.Add("mcs_vehtypeid", new CrmEntityReference("mcs_vehicletype", Guid.Parse(request.mcs_vehtypeid))); } if (!string.IsNullOrEmpty(request.mcs_carattention)) { createorUpdateEntity.Attributes.Add("mcs_carattention", request.mcs_carattention); } if (!string.IsNullOrEmpty(request.mcs_competingtype)) { createorUpdateEntity.Attributes.Add("mcs_competingtype", request.mcs_competingtype); } if (!string.IsNullOrEmpty(request.mcs_introducecarowner)) { createorUpdateEntity.Attributes.Add("mcs_introducecarowner", request.mcs_introducecarowner); } if (!string.IsNullOrEmpty(request.mcs_mobilephone)) { createorUpdateEntity.Attributes.Add("mcs_mobilephone", request.mcs_mobilephone); } if (!string.IsNullOrEmpty(request.mcs_estimatedtransactiondate)) { createorUpdateEntity.Attributes.Add("mcs_estimatedtransactiondate", DateTime.Parse(request.mcs_estimatedtransactiondate)); } if (request.mcs_carereason.HasValue) { createorUpdateEntity.Attributes.Add("mcs_carereason", request.mcs_carereason.Value); } if (request.mcs_gender.HasValue) { createorUpdateEntity.Attributes.Add("mcs_gender", request.mcs_gender.Value); } if (request.mcs_generation.HasValue) { createorUpdateEntity.Attributes.Add("mcs_generation", request.mcs_generation.Value); } if (request.mcs_idtype.HasValue) { createorUpdateEntity.Attributes.Add("mcs_idtype", request.mcs_idtype.Value); } if (request.mcs_level.HasValue) { createorUpdateEntity.Attributes.Add("mcs_level", request.mcs_level.Value); } if (request.mcs_purchasepurpose.HasValue) { createorUpdateEntity.Attributes.Add("mcs_purchasepurpose", request.mcs_purchasepurpose.Value); } if (request.mcs_purchaseway.HasValue) { createorUpdateEntity.Attributes.Add("mcs_purchaseway", request.mcs_purchaseway.Value); } if (request.mcs_vehicleusers.HasValue) { createorUpdateEntity.Attributes.Add("mcs_vehicleusers", request.mcs_vehicleusers.Value); } if (request.mcs_familymembernum.HasValue) { createorUpdateEntity.Attributes.Add("mcs_familymembernum", request.mcs_familymembernum.Value); } if (!string.IsNullOrEmpty(request.description)) { createorUpdateEntity.Attributes.Add("description", request.description); } if (request.mcs_customerstatus.HasValue) { createorUpdateEntity.Attributes.Add("mcs_customerstatus", request.mcs_customerstatus.Value); } //if (request.ownerid.HasValue) //{ // createorUpdateEntity.Attributes.Add("ownerid", new CrmEntityReference("systemuser", request.ownerid.Value)); //} var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); if (userInfo != null && userInfo.systemuserid.HasValue) { createorUpdateEntity.Attributes.Add("ownerid", new CrmEntityReference("systemuser", userInfo.systemuserid.Value)); } if (!string.IsNullOrEmpty(request.Id)) { await _crmService.Update(createorUpdateEntity); } else { guid = await _crmService.Create(createorUpdateEntity); } } catch (Exception ex) { throw ex; } return(guid); }
public String CreateContact(Guid contact_ID, Contact contact) { Guid contactid = contact_ID; try { contact cont = new contact(); CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); if (contact_ID == new Guid("{00000000-0000-0000-0000-000000000000}")) { contactid = crmService.Create(cont); } // Создаем экземпляр динамческого объекта и указываем его имя DynamicEntity myDEUpdate = new DynamicEntity(); myDEUpdate.Name = "contact"; // Создаем KeyProperty для хранения GUID’а обновляемой записи KeyProperty myContactGuid = new KeyProperty(); myContactGuid.Name = "contactid"; // Указываем GUID обновляемой записи Key myContactKey = new Key(); myContactKey.Value = contactid; myContactGuid.Value = myContactKey; myDEUpdate.Properties.Add(myContactGuid); if (contact.address1_city != null) { myDEUpdate.Properties.Add(new StringProperty("address1_city", contact.address1_city)); } if (contact.address1_country != null) { myDEUpdate.Properties.Add(new StringProperty("address1_country", contact.address1_country)); } if (contact.address1_line1 != null) { myDEUpdate.Properties.Add(new StringProperty("address1_line1", contact.address1_line1)); } if (contact.address1_name != null) { myDEUpdate.Properties.Add(new StringProperty("address1_name", contact.address1_name)); } if (contact.address1_postalcode != null) { myDEUpdate.Properties.Add(new StringProperty("address1_postalcode", contact.address1_postalcode)); } if (contact.emailaddress1 != null) { myDEUpdate.Properties.Add(new StringProperty("emailaddress1", contact.emailaddress1)); } if (contact.firstname != null) { myDEUpdate.Properties.Add(new StringProperty("firstname", contact.firstname)); } if (contact.lastname != null) { myDEUpdate.Properties.Add(new StringProperty("lastname", contact.lastname)); } if (contact.middlename != null) { myDEUpdate.Properties.Add(new StringProperty("middlename", contact.middlename)); } if (contact.mobilephone != null) { myDEUpdate.Properties.Add(new StringProperty("mobilephone", contact.mobilephone)); } if (contact.salutation != null) { myDEUpdate.Properties.Add(new StringProperty("salutation", contact.salutation)); } //Кем выдан if (contact.new_giveoutby != null) { myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby)); } //Номер if (contact.new_nomer != null) { myDEUpdate.Properties.Add(new StringProperty("new_nomer", contact.new_nomer)); } //Серия if (contact.new_seria != null) { myDEUpdate.Properties.Add(new StringProperty("new_seria", contact.new_seria)); } //Пол if (contact.gendercode != 0) { myDEUpdate.Properties.Add(new PicklistProperty("gendercode", new Picklist(contact.gendercode))); } //Гражданство if (contact.new_nationality != 0) { myDEUpdate.Properties.Add(new PicklistProperty("new_nationality", new Picklist(contact.new_nationality))); } //Тип ФЛ if (contact.new_type != 0) { myDEUpdate.Properties.Add(new PicklistProperty("new_type", new Picklist(contact.new_type))); } //Семейное положение if (contact.familystatuscode != 0) { myDEUpdate.Properties.Add(new PicklistProperty("familystatuscode", new Picklist(contact.familystatuscode))); } //День рождения if (contact.birthdate != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } //Посетил открытый урок if (contact.new_openles != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_openles", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_openles, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } //Дата выдачи if (contact.new_dategiveout != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_dategiveout", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_dategiveout, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } crmService.Update(myDEUpdate); //поиск контакта для переназначения ответственного, если таковой меняется Owner ownerID = new Owner(); if (contact_ID != new Guid("{00000000-0000-0000-0000-000000000000}")) { try { string ln = ""; //фамилия BusinessEntityCollection fcontact = searchContact(contact_ID.ToString()); foreach (DynamicEntity cont1 in fcontact.BusinessEntities) { ln = cont1["lastname"].ToString(); if (cont1.Properties.Contains("ownerid")) { ownerID = (Owner)cont1["ownerid"]; } } logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}"); } catch (Exception ex) { logger.Error($"Ошибка: {ex.ToString()}"); } } if (contact.ownerid != new Guid("{00000000-0000-0000-0000-000000000000}")) { if (ownerID.Value != contact.ownerid) { TargetOwnedContact target = new TargetOwnedContact(); SecurityPrincipal assignee = new SecurityPrincipal(); assignee.Type = SecurityPrincipalType.User; assignee.PrincipalId = contact.ownerid; target.EntityId = contactid; AssignRequest assign = new AssignRequest(); assign.Assignee = assignee; assign.Target = target; AssignResponse res = (AssignResponse)crmService.Execute(assign); } } return(contactid.ToString()); } catch (SoapException ex) { logger.Error($"Ошибка: {ex.Detail.InnerText}"); return(ex.Detail.InnerText); } }
/// <summary> /// 试乘试驾新增修改 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > AddOrEdit(DriveRecordAddOrEditRequest request) { var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); if (userInfo != null && !string.IsNullOrWhiteSpace(userInfo.mcs_dealerid)) { request.driveRecord.mcs_dealerid = Guid.Parse(userInfo.mcs_dealerid); } if (userInfo != null && userInfo.systemuserid != null) { request.driveRecord.mcs_consultantid = userInfo.systemuserid; } var validateResult = new ValidateResult <CrmEntity>(); var reusetCrmEntity = new CrmEntity("mcs_driverecord", new Guid()); //新增预约单 if (request.driveRecord.mcs_driverecordid == null) { var createEntity = new CrmExecuteEntity("mcs_driverecord", Guid.NewGuid()); //预约状态 创建默认是已提交 createEntity.Attributes.Add("mcs_drivestatus", 10); BasicAssignment(createEntity, request); await _crmService.Create(createEntity, userInfo?.systemuserid); reusetCrmEntity.Id = createEntity.Id; } //编辑预约单 if (request.driveRecord.mcs_driverecordid != null) { var updateEntity = new CrmExecuteEntity("mcs_driverecord", (Guid)request.driveRecord.mcs_driverecordid); //预约状态 if (request.driveRecord.mcs_drivestatus != null) { updateEntity.Attributes.Add("mcs_drivestatus", request.driveRecord.mcs_drivestatus); #region 判断如果试驾结束,为用户推送试驾反馈站内信 if (request.driveRecord.mcs_drivestatus.Value == 15) { //获取试驾结束站内信发送配置json var fetchString = _driveRecordRepository.GetConfigFetchXml(DCEM_APP_DriveOverMsgJson); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_cepconfig", FetchXml = fetchString //ProxyUserId = userInfo?.systemuserid }; fetchRequest.Headers.Add(dicHeadKey, dicHead[dicHeadKey]); var fetchResponse = await _crmService.Execute(fetchRequest); var fetchResponseResult = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; if (fetchResponseResult.Value.Results.Count > 0) { //获取试驾明细 var detail = GetDetail((Guid)request.driveRecord.mcs_driverecordid); if (detail != null && detail.Result.Detail.Attributes.ContainsKey("mcs_userid")) { //用户获取 fetchString = _driveRecordRepository.GetUser(detail.Result.Detail.Attributes["mcs_userid"].ToString()); fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_user", FetchXml = fetchString //ProxyUserId = userInfo?.systemuserid }; fetchRequest.Headers.Add(dicHeadKey, dicHead[dicHeadKey]); fetchResponse = await _crmService.Execute(fetchRequest); var responseUser = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; if (responseUser.Value.Results.Count > 0)//判断试驾用户信息是否存在 { var obj = JsonConvert.DeserializeObject <DriveRecordEndSendMsg>(fetchResponseResult.Value.Results[0].Attributes["mcs_val"].ToString()); var createUsermsgEntity = new CrmExecuteEntity("mcs_user_msg", Guid.NewGuid()); createUsermsgEntity.Attributes.Add("mcs_name", obj.mcs_name); createUsermsgEntity.Attributes.Add("mcs_content", obj.mcs_content); createUsermsgEntity.Attributes.Add("mcs_type", 2); createUsermsgEntity.Attributes.Add("mcs_readstatus", 0); var mcs_url = string.Format(obj.mcs_url, responseUser.Value.Results[0].Attributes["mcs_code"], detail.Result.Detail.Attributes["mcs_name"]); createUsermsgEntity.Attributes.Add("mcs_url", mcs_url); var UserEntityEF = new CrmEntityReference("mcs_user", responseUser.Value.Results[0].Id); createUsermsgEntity.Attributes.Add("mcs_user", UserEntityEF); await _crmService.Create(createUsermsgEntity); } } } } #endregion } BasicAssignment(updateEntity, request); await _crmService.Update(updateEntity, userInfo?.systemuserid); reusetCrmEntity.Id = (Guid)request.driveRecord.mcs_driverecordid; } validateResult.Data = reusetCrmEntity; validateResult.Result = true; validateResult.Description = "操作成功"; return(validateResult); }