/// <summary> /// Сохраняет карточку физ лица. /// </summary> /// <param name="control">The control.</param> /// <param name="model">The model.</param> /// <returns></returns> public ActionResult Save(string control, PersonModel model) { PersonModelValidator validator = new PersonModelValidator(model.EditCard || !model.Card.PersonID.HasValue || model.Card.PersonID.Value == 0); ValidationResult validationResults = validator.Validate(model); if (!validationResults.IsValid) { validationResults.AddToModelState(ModelState, null); } ModelState["Model.PersonTypes.PersonThemeID"].Errors.Clear(); if (!ModelState.IsValid) { return(JavaScriptAlert( Kesco.Persons.Web.Localization.Resources.Validation_ErrorDlg_Title, Kesco.Persons.Web.Localization.Resources.Validation_Person_ErrorDlg_Message + "<br clear='all'/><ul>" + String.Join("\n", GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e)) ) + "</ul>")); } // если указан идентификатор лица, то операция - создать/редактировать карточку // иначе вернуть карточку bool saveEmplsAndThemes = (model.Card.PersonID == null || model.Card.PersonID.Value == 0); try { // Транслитерация if (!StringExtensions.HasOnlyLatinChars(model.Card.LastNameLat)) { model.Card.LastNameLat = Repository.Persons.TraslitSentence(StringExtensions.Coalesco(model.Card.LastNameLat, model.Card.LastNameRus)); } if (!StringExtensions.HasOnlyLatinChars(model.Card.FirstNameLat)) { model.Card.FirstNameLat = Repository.Persons.TraslitSentence(StringExtensions.Coalesco(model.Card.FirstNameLat, model.Card.FirstNameRus)); } if (!StringExtensions.HasOnlyLatinChars(model.Card.MiddleNameLat)) { model.Card.MiddleNameLat = Repository.Persons.TraslitSentence(StringExtensions.Coalesco(model.Card.MiddleNameLat, model.Card.MiddleNameRus)); } List <FormatRegistration> FormatRegistrations = Repository.FormatRegistrations.GetAllFormats(); if (!FormatRegistrations.Exists(f => f.ID == model.Card.TerritoryID)) { model.Card.INN = model.Card.OKPO = ""; } var card = new IndividualCardForSave { Check = model.Confirmed || ( model.EditCard ? (model.Card.ID.HasValue && model.Card.ID.Value != 0) : (model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0) ), NewID = 0, WhatDo = model.EditCard ? ((model.Card.ID.HasValue && model.Card.ID.Value != 0) ? SaveAction.едактироватьКарточку : SaveAction.СоздатьКарточку) : ((model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0) ? SaveAction.едактироватьЛицо : SaveAction.СоздатьЛицо), ДатаРождения = model.Card.Birthday, От = model.Card.From ?? new DateTime(1980, 1, 1), До = (model.Card.To ?? new DateTime(2049, 12, 31)).AddDays(1), ИмяЛат = model.Card.FirstNameLat ?? String.Empty, ИмяРус = model.Card.FirstNameRus ?? String.Empty, ИНН = model.Card.INN ?? String.Empty, Кличка = model.Card.Nickname ?? String.Empty, КодБизнесПроекта = model.Card.BusinessProjectID, КодКарточки = model.Card.ID ?? 0, КодЛица = model.Card.PersonID ?? 0, КодОргПравФормы = model.Card.IncorporationFormID, КодТерритории = model.Card.TerritoryID, ОГРН = model.Card.OGRN ?? String.Empty, ОКПО = model.Card.OKPO ?? String.Empty, ОтчествоЛат = model.Card.MiddleNameLat ?? String.Empty, ОтчествоРус = model.Card.MiddleNameRus ?? String.Empty, Пол = model.Card.Sex ?? 'М', Примечание = model.Card.Comment ?? String.Empty, Проверено = model.Card.Verified, ФамилияЛат = model.Card.LastNameLat ?? String.Empty, ФамилияРус = model.Card.LastNameRus ?? String.Empty, ОКОНХ = String.Empty, ОКВЭД = String.Empty, КПП = String.Empty, КодЖД = String.Empty, АдресЮридический = model.Card.AddressLegal ?? String.Empty, АдресЮридическийЛат = model.Card.AddressLegalLat ?? String.Empty, }; if (model.Card.IncorporationFormID.HasValue) { card.ОКОНХ = model.Card.OKONH ?? String.Empty; card.ОКВЭД = model.Card.OKVED ?? String.Empty; card.КПП = model.Card.KPP ?? String.Empty; card.КодЖД = model.Card.RwID ?? String.Empty; } // если редактируем реквизиты, // то всегда обновляем лицо if (model.EditCard) { SaveAction action = card.WhatDo; card.WhatDo = SaveAction.едактироватьЛицо; Repository.Persons.TryToSaveIndividual(card); card.WhatDo = action; } model.Card.PersonID = Repository.Persons.TryToSaveIndividual(card); } catch (SavePersonException ex) { string script2 = String.Format(@"(function() {{ var duplicates = {3}; var callbackUrl = encodeURIComponent('{0}'); var url = '{1}&callbackUrl={{0}}'; url = $.validator.format(url, callbackUrl); openPopupWindow(url, {{ type: 'POST', Duplicates: duplicates }}, function (result) {{ ViewModel.Model.Confirmed(false); if ($.isArray(result)) {{ var person = result[0]; if (person.value == {2}) {{ // если value == PersonID, создаём/сохраняем лицо ViewModel.Model.Confirmed(true); ViewModel.save(); }} else {{ // иначе закрываем и открываем похожее лицо closeDialogAndReturnValue(JSON.stringify(result)); }} }} }}, 'wnd_Duplicates', 670, 400); }})()" , Url.FullPathAction("DialogResult", "Default"), Url.Action("Index", "NaturalDuplicates", new { id = model.Card.PersonID ?? 0, t = 1 }), model.Card.PersonID ?? 0, Kesco.Web.Mvc.Json.Serialize( ex.Issues .GroupBy(issue => issue.PersonID) .Select(gr => new { PersonID = gr.Key, Nickname = gr.First().Nickname, Issues = gr.Select(i => new { Field = i.Field, Granted = i.Granted, R = i.R, Value = i.Value }).ToList() }) , true ) ); return(JavaScript(script2)); } // Создание связи между лицом-работником и работадателем if (model.EmployerId.HasValue && model.Card.PersonID.HasValue) { try { PersonLinkAccessor.PersonLinkForSave sqlParams = new PersonLinkAccessor.PersonLinkForSave(); sqlParams.WhatDo = 0; sqlParams.КодЛицаРодителя = model.EmployerId.Value; sqlParams.КодЛицаПотомка = model.Card.PersonID.Value; sqlParams.КодТипаСвязиЛиц = 1; sqlParams.Параметр = 0; Repository.Links.MergePersonLink(sqlParams); } catch (Exception ex) { Logger.WriteEx(new DetailedException("Ошибка создания связи между лицом-работником и работадателем", ex)); } } string errMsg = String.Empty; if (saveEmplsAndThemes) { try { var responsibleEmployeesIDs = model.ResponsibleEmployees.Select(employee => Convert.ToInt32(employee.ID)).ToList(); Repository.Persons.MergeResponsibleEmployees(model.Card.PersonID.Value, String.Join(",", responsibleEmployeesIDs)); //Repository.Persons.AssignResponsibleEmployee( // model.Card.PersonID.Value, // UserContext.EmployeeInfo.ID // ); } catch (Exception ex) { errMsg = String.Format( Resources.Resources.Persons_Natural_SaveErrorWhileSavingResps, ex.Message ); Logger.WriteEx(new DetailedException(errMsg, ex)); } try { Repository.Persons.SavePersonTypes( model.Card.PersonID.Value, String.Join(",", model.PersonTypes.PersonTypeIDs) ); } catch (Exception ex2) { var errMsg2 = String.Format( Resources.Resources.Persons_Natural_SaveErrorWhileSavingPersonTypes, ex2.Message ); Logger.WriteEx(new DetailedException(errMsg2, ex2)); if (errMsg != String.Empty) { errMsg += "\n\n"; } errMsg += errMsg2; } } var parametrs = Kesco.Web.Mvc.Json.Serialize(new { value = model.Card.PersonID, label = model.Card.Nickname }, true); string sectionID = HttpContext.Request["sectionId"] ?? HttpUtility.ParseQueryString(HttpContext.Request.UrlReferrer.ToString()).Get("sectionId"); if (sectionID != null) { var values = JsonConvert.DeserializeObject <JObject>(parametrs); values.Add("sectionId", sectionID); parametrs = Kesco.Web.Mvc.Json.Serialize(values, true); } string script = String.Format(@" (function() {{ var result = {0}; var errMsg = {1}; if (errMsg) {{ alert(errMsg); }} returnResult(result); }})();" , parametrs, Kesco.Web.Mvc.Json.Serialize(errMsg) ); return(JavaScript(script)); }
public ActionResult Save(string control, PersonModel model) { PersonModelValidator validator = new PersonModelValidator(model.Card.PersonID == null || model.Card.PersonID.Value == 0); ValidationResult validationResults = validator.Validate(model); if (!validationResults.IsValid) { validationResults.AddToModelState(ModelState, null); } ModelState["Model.PersonTypes.PersonThemeID"].Errors.Clear(); if (!ModelState.IsValid) { return(JavaScriptAlert( Kesco.Persons.Web.Localization.Resources.Validation_ErrorDlg_Title, Kesco.Persons.Web.Localization.Resources.Validation_Person_ErrorDlg_Message + "<br clear='all'/><ul>" + String.Join("\n", GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e)) ) + "</ul>")); } List <FormatRegistration> FormatRegistrations = Repository.FormatRegistrations.GetAllFormats(); if (!FormatRegistrations.Exists(f => f.ID == model.Card.TerritoryID)) { model.Card.INN = model.Card.OKPO = ""; } // если указан идентификатор лица, то операция - редактировать карточку // иначе вернуть карточку bool saveEmplsAndThemes = (model.Card.PersonID == null || model.Card.PersonID.Value == 0); try { model.Card.PersonID = Repository.Persons.TryToSaveJuridical(new JuridicalCardForSave { NewID = 0, WhatDo = (model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0) ? SaveAction.едактироватьЛицо : SaveAction.СоздатьЛицо, Check = model.Confirmed || (model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0), КодЛица = model.Card.PersonID ?? 0, КодКарточки = model.Card.ID ?? 0, Кличка = model.Card.Nickname ?? String.Empty, КодБизнесПроекта = model.Card.BusinessProjectID, КодТерритории = model.Card.TerritoryID, ГосОрганизация = model.Card.IsStateOrganization ? 1 : 0, БИК = model.Card.BIK ?? String.Empty, ИНН = model.Card.INN ?? String.Empty, ОГРН = model.Card.OGRN ?? String.Empty, ОКПО = model.Card.OKPO ?? String.Empty, КорСчет = model.Card.LoroConto ?? String.Empty, БИКРКЦ = model.Card.BIKRKC ?? String.Empty, SWIFT = model.Card.SWIFT ?? String.Empty, Примечание = model.Card.Comment ?? String.Empty, Проверено = model.Card.Verified, От = model.Card.Requisites.From ?? new DateTime(1980, 1, 1), До = (model.Card.Requisites.To ?? new DateTime(2049, 12, 31)).AddDays(1), КодОргПравФормы = model.Card.Requisites.IncorporationFormID, КраткоеНазваниеЛат = model.Card.Requisites.ShortNameLat ?? String.Empty, КраткоеНазваниеРус = model.Card.Requisites.ShortNameRus ?? String.Empty, КраткоеНазваниеРусРП = model.Card.Requisites.ShortNameRusGenitive ?? String.Empty, ПолноеНазвание = model.Card.Requisites.FullName ?? String.Empty, ОКОНХ = model.Card.Requisites.OKONH ?? String.Empty, ОКВЭД = model.Card.Requisites.OKVED ?? String.Empty, КПП = model.Card.Requisites.KPP ?? String.Empty, КодЖД = model.Card.Requisites.RwID ?? String.Empty, АдресЮридический = model.Card.Requisites.AddressLegal ?? String.Empty, АдресЮридическийЛат = model.Card.Requisites.AddressLegalLat ?? String.Empty }); } catch (System.Data.SqlClient.SqlException ex) { } catch (SavePersonException ex) { string script2 = String.Format(@"(function() {{ var duplicates = {3}; var callbackUrl = encodeURIComponent('{0}'); var url = '{1}&callbackUrl={{0}}'; url = $.validator.format(url, callbackUrl); openPopupWindow(url, {{ type: 'POST', Duplicates: duplicates }}, function (result) {{ ViewModel.Model.Confirmed(false); if ($.isArray(result)) {{ var person = result[0]; if (person.value == {2}) {{ // если value == PersonID, создаём/сохраняем лицо ViewModel.Model.Confirmed(true); ViewModel.save(); }} else {{ // иначе закрываем и открываем похожее лицо closeDialogAndReturnValue(JSON.stringify(result)); }} }} }}, 'wnd_Duplicates', 670, 400); }})()" , Url.FullPathAction("DialogResult", "Default"), Url.Action("Index", "NaturalDuplicates", new { id = model.Card.PersonID ?? 0, t = 1 }), model.Card.PersonID ?? 0, Kesco.Web.Mvc.Json.Serialize( ex.Issues .GroupBy(issue => issue.PersonID) .Select(gr => new { PersonID = gr.Key, Nickname = gr.First().Nickname, Issues = gr.Select(i => new { Field = i.Field, Granted = i.Granted, R = i.R, Value = i.Value }).ToList() }) , true ) ); return(JavaScript(script2)); } string errMsg = String.Empty; if (saveEmplsAndThemes) { try { var responsibleEmployeesIDs = model.ResponsibleEmployees.Select(employee => Convert.ToInt32(employee.ID)).ToList(); Repository.Persons.MergeResponsibleEmployees(model.Card.PersonID.Value, String.Join(",", responsibleEmployeesIDs)); //Repository.Persons.AssignResponsibleEmployee( // model.Card.PersonID.Value, // UserContext.EmployeeInfo.ID // ); } catch (Exception ex) { errMsg = String.Format( Resources.Resources.Persons_Natural_SaveErrorWhileSavingResps, ex.Message ); Logger.WriteEx(new DetailedException(errMsg, ex)); } try { Repository.Persons.SavePersonTypes( model.Card.PersonID.Value, String.Join(",", model.PersonTypes.PersonTypeIDs) ); } catch (Exception ex2) { var errMsg2 = String.Format( Resources.Resources.Persons_Natural_SaveErrorWhileSavingPersonTypes, ex2.Message ); Logger.WriteEx(new DetailedException(errMsg2, ex2)); if (errMsg != String.Empty) { errMsg += "\n\n"; } errMsg += errMsg2; } } string sectionID = HttpContext.Request["sectionId"] ?? HttpUtility.ParseQueryString(HttpContext.Request.UrlReferrer.ToString()).Get("sectionId"); string script = String.Format(@" (function() {{ var result = {0}; var errMsg = {1}; if (errMsg) {{ alert(errMsg); }} returnResult(result); }})();" , Kesco.Web.Mvc.Json.Serialize(new { value = model.Card.PersonID, label = model.Card.Nickname, sectionId = sectionID }, true), Kesco.Web.Mvc.Json.Serialize(errMsg) ); return(JavaScript(script)); }