using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Web.Mvc; using BeWo.Service.ServiceImplementations; using BeWoPlanerMobil.Models; using BeWoPlanerMobil.Service; using BeWoPlanerMobil.Util; using static BeWoPlanerMobil.Util.MobileUtils; using BS.Shared; using BS.Shared.Core; using BS.Shared.DataContracts; using BS.Shared.DataContracts.Compact; using BS.Shared.Extensions; using BS.Shared.Services; using DevExpress.XtraScheduler; using DevExpress.XtraScheduler.Compatibility; using static BS.Shared.ServiceRecordValidationResult; using ServiceRecordDC = BS.Shared.DataContracts.ServiceRecordDC; namespace BeWoPlanerMobil.Controllers { public class MainController : AbstractBaseController { private const string _LeerzeichenFuerGetMethoden = " "; private MainModel _Model; public MainModel Model { get { if(!MobileSessionFacade.IsUserLoggedIn()) { RedirectToActionPermanent("Index", "Login"); return null; } if(((MainModel) Session[MainModelSessionKey])?.Employee == null) { _Model = new MainModel { Employee = MobileSessionFacade.LoggedInEmployee }; Session[MainModelSessionKey] = _Model; } else { _Model = (MainModel)Session[MainModelSessionKey]; } return _Model; } } private const string MainModelSessionKey = "MainModel"; private Dictionary _ParentGoals; private static readonly List _Zieltypen = new List { ValueListEntryType.SupportConceptGoalCategoryType, ValueListEntryType.SupportConceptIndividualGoalCategoryType }; private static readonly List _Massnahmentypen = new List { ValueListEntryType.SupportConceptGoalType, ValueListEntryType.SupportConceptIndividualGoalType }; [Authorize] public ActionResult Main() { try { ViewData["ValidationError"] = string.Empty; if(!MobileSessionFacade.IsUserLoggedIn() || Request.Browser.Browser.Equals("InternetExplorer")) { return RedirectToActionPermanent("Index", "Login"); } Model.ShowExpiredSupportConcepts = GetUserSettingValue("ShowExpiredSupportConcepts") == "1"; Model.ShowOnlyOwnSupportConcepts = GetUserSettingValue("ShowOnlyMySupportConcepts") == "1"; var unter = GetSettingValue("ShowSignature"); Model.ShowSignature = unter == "1"; #if DEBUG Model.ShowSignature = true; #endif Model.GroupsOfPeople = EmployeeService.GetAllGroups(GetUser().Employee.EmployeeOid); Model.SelectedGoals = null; Model.ShowDistanceField = "1" == GetSettingValue("ShowDistanceFields"); Model.Dokutypes = ValueListService.GetAllValueListEntrysByType(ValueListEntryType.DocumentType); if (Model.Dokutypes != null) { Model.Dokutypes = Model.Dokutypes.OrderBy(s => s.ValueListEntryOid).ToArray(); } if(MainModel.AllEmployees == null) { MainModel.AllEmployees = EmployeeService.GetAllActiveEmployeesCompact().OrderBy(e => e.LastName).ToList(); } var myRelatedCustomers = Model.Employee == null ? new List() : Model.Employee.RelatedCustomers; if (MobileSessionFacade.CheckForUserRight(UserRightType.CustomerView_View)) { Model.Customers = CustomerService.GetAllActiveCompactCustomers().OrderBy(k => k.LastName).ToList(); } else if(MobileSessionFacade.CheckForUserRight(UserRightType.Customer_ViewMyCustomers)) { Model.Customers = CustomerService.GetCompactCustomersById(myRelatedCustomers.Select(c => c.Customer.CustomerOid).ToList()).OrderBy(k => k.LastName).ToList(); } else { Model.Customers = new List(); } if(MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreationForOtherEmployees)) { Model.Employees = EmployeeService.GetAllActiveEmployeesCompact(); } else if(MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreationForOtherTeamMember) && Model.Employee?.EmployeeOid != null) { Model.Employees = EmployeeService.GetAllTeamMember(MobileSessionFacade.LoggedInCompactEmployee); } else { Model.Employees = new List { MobileSessionFacade.LoggedInCompactEmployee }; } if(Model.ShowOnlyOwnSupportConcepts == false && MobileSessionFacade.CheckForUserRight(UserRightType.SupportConcept_ViewAllSupportConcepts)) { Model.SupportConcepts = CustomerService.GetAllActiveSupportConcepts(); } else { Model.SupportConcepts = CustomerService.GetAllActiveSupportConceptsByCustomers(myRelatedCustomers.Select(c => c.Customer.CustomerOid)); } if(!Model.ShowExpiredSupportConcepts) { Model.SupportConcepts = Model.SupportConcepts.Where(w => { var endDate = MainModel.GetEndDateOfSupportConcept(w); return endDate == null || endDate.Value >= DateTime.Now; }).ToList(); } if(Model.ServiceCategories == null) { Model.ServiceCategories = new List(); } if(Model.SelectedConceptCostBearerRelations == null) { Model.SelectedConceptCostBearerRelations = new List(); } if (Model.CostBearer2SupportConceptOid != null) { LoadRecordsToModel(); } if (Model.SelectedEmployee == null) { Model.SelectedEmployee = MobileSessionFacade.LoggedInCompactEmployee; } var IsServiceRecordNoticeMandatorySetting = GetSettingValue("IsServiceRecordNoticeMandatory"); if (IsServiceRecordNoticeMandatorySetting != null && IsServiceRecordNoticeMandatorySetting == "0") { Model.IsServiceRecordNoticeMandatory = false; } else { Model.IsServiceRecordNoticeMandatory = true; } if(Model.SelectedSupportConceptListObject == null) { Model.SelectedSupportConceptListObject = Model.SupportConceptListObjects.First(); } } catch (Exception e) { log.Error(e.Message, e); } return View(Model); } [HttpPost] [Authorize] public ActionResult SetShowOnlyOwnSupportConcepts(FormCollection collection) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } var newValue = "true,false" == collection["ShowOnlyOwnSupportConcepts"]; Model.ShowOnlyOwnSupportConcepts = newValue; return UpdateSettings("ShowOnlyMySupportConcepts", newValue ? "1" : "0"); ; } [HttpPost] [Authorize] public ActionResult SetShowExpiredSupportConcepts(FormCollection pCollection) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } var newValue = "true,false" == pCollection["ShowExpiredSupportConcepts"]; Model.ShowExpiredSupportConcepts = newValue; return UpdateSettings("ShowExpiredSupportConcepts", newValue ? "1" : "0"); } [Authorize] public ActionResult UpdateSettings(string pKey, string pValue) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } var userSettings = GetUser().Settings; UserSettingsUtils.SetSettingValue(SettingsType.ApplicationSettings, pKey, pValue, userSettings); UserService.UpdateUserSettings(GetUser().UserOid.Value, userSettings); return RedirectToAction("Main"); } [HttpPost] public new ActionResult Logout() { return base.Logout(); } [Authorize] public string LoadGoals(long pCostbearer2SupportConceptOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return " "; } var sc = Model.SupportConcepts.FirstOrDefault(f => f.CostBearerRelations.Any(cbr => cbr.CostBearer2SupportConceptOid.HasValue && cbr.CostBearer2SupportConceptOid.Value.Equals(pCostbearer2SupportConceptOid))); if (sc == null) { return " "; } Model.SelectedSupportConcept = sc; var selectedGoals = sc.Goals; var missingParents = selectedGoals.Where(w => w.ParentOid != null && false == selectedGoals.Any(a => a.ValueListEntryOid.Equals(w.ParentOid))).Select(s => s.ParentOid).ToList(); _ParentGoals = new Dictionary(); foreach (var oid in missingParents) { LoadMissingParents(oid.Value); } var goalTree = BuildGoalTree(selectedGoals.Union(_ParentGoals.Values).ToList()); return SerializeObject(goalTree); } private static List BuildGoalTree(List goals) { var ziele = goals.Where(w => _Zieltypen.Contains(w.Type)).OrderBy(s => s.TypeDescription).ToList(); var massnahmen = goals.Where(w => _Massnahmentypen.Contains(w.Type)).OrderBy(s => s.TypeDescription).ToList(); var goalTree = new List(); var goalTreeDic = new Dictionary(); foreach(var ziel in ziele) { var treeItem = new GoalTreeItem {Children = new List(), Header = ziel.TypeDescription, ParentOid = ziel.ParentOid, ValueListEntryOid = ziel.ValueListEntryOid}; goalTreeDic.Add(ziel.ValueListEntryOid.Value, treeItem); if(ziel.ParentOid == null) { goalTree.Add(treeItem); } } foreach(var zielMitEltern in goalTreeDic.Values.Where(w => w.ParentOid != null)) { goalTreeDic[zielMitEltern.ParentOid.Value].Children.Add(zielMitEltern); } foreach(var ziel in massnahmen) { var kind = new GoalTreeItem {Children = new List(), Header = ziel.TypeDescription, IsLeaf = true, ValueListEntryOid = ziel.ValueListEntryOid}; if(ziel.ParentOid != null && goalTreeDic.ContainsKey(ziel.ParentOid.Value)) { kind.ParentOid = goalTreeDic[ziel.ParentOid.Value].ParentOid; goalTreeDic[ziel.ParentOid.Value].Children.Add(kind); } } foreach(var item in goalTreeDic.Values) { if(item.Children.Count == 0) { item.IsLeaf = true; } } return goalTree; } private void LoadMissingParents(long pParentOid) { while(true) { var parentDC = ValueListService.GetValueListEntryByOid(pParentOid); if(!_ParentGoals.ContainsKey(parentDC.ValueListEntryOid.Value)) { _ParentGoals.Add(parentDC.ValueListEntryOid.Value, parentDC); if(parentDC.ParentOid != null) { pParentOid = parentDC.ParentOid.Value; continue; } } break; } } [Authorize] public string LoadBWPSettings() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var m = OperationsService.GetMandator(); var time = MobileUtils.GetSettingValue(m.Settings, "TimeUntilUILock"); return SerializeObject(time); } [Authorize] public string CheckEndDate() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var m = OperationsService.GetMandator(); var endtime = MobileUtils.GetSettingValue(m.Settings, "IsEndDateVisible"); return SerializeObject(endtime); } [Authorize] public string CheckOnlyYearMonth() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var m = OperationsService.GetMandator(); var yearMonth = MobileUtils.GetSettingValue(m.Settings, "IsOnlyYearMonthVisible"); return SerializeObject(yearMonth); } [Authorize] public string CheckIsZeiterfassDateNormal() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var m = OperationsService.GetMandator(); var normal = MobileUtils.GetSettingValue(m.Settings, "IsZeiterfassDateNormal"); return SerializeObject(normal); } [Authorize] public string CheckIsZeiterfassungInStdMin() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var m = OperationsService.GetMandator(); var zeiterInStdMin = MobileUtils.GetSettingValue(m.Settings, "IsZeiterfassungInStdMin"); return SerializeObject(zeiterInStdMin); } [Authorize] public string CheckDokuReiter() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } return SerializeObject(Model.Dokutypes); } private static string GetUserSettingValue(string key) { var user = MobileSessionFacade.LoggedInUser; var settings = user?.SettingList.FirstOrDefault(f => f.Type.Equals(SettingsType.ApplicationSettings)); return settings != null ? MobileUtils.GetSettingValue(settings.Value, key) : null; } private string GetSettingValue(string key) { var man = OperationsService.GetMandator(); return MobileUtils.GetSettingValue(man.Settings, key); } [Authorize] public string LoadAppointments(string newtoday) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var date = DateTime.ParseExact(newtoday, "dd.MM.yyyy", null); var appointments = KalenderService.LoadFilteredAppointments(true, Model.Employee.EmployeeOid.Value, date.Date, date.Date.AddDays(1), new List(), new List(), new List(), false, false, false, false, true).ToList(); var holySweetFlyingFuck = appointments.Where(w => w.StartDate.HasValue && w.EndDate.HasValue && ((date.InBetween(w.StartDate.Value, w.EndDate.Value, false) || date.CompareShortDates(w.StartDate.Value)) && w.RecurrenceInfo == null || w.RecurrenceInfo != null && (w.Type == 3 || w.Type == 4) && (date.InBetween(w.StartDate.Value, w.EndDate.Value, false) || date.CompareShortDates(w.StartDate.Value)))).ToList(); var deletedOccurrences = holySweetFlyingFuck.Where(w => w.Type == 4).Select(s => GetOccurrenceId(s.RecurrenceInfo)).ToList(); var changedOccurrences = holySweetFlyingFuck.Where(w => w.Type == 3).Select(s => GetOccurrenceId(s.RecurrenceInfo)).ToList(); holySweetFlyingFuck = holySweetFlyingFuck.Where(w => w.Type != 4).ToList(); foreach (var appointment in appointments) { if (appointment.RecurrenceInfo != null && appointment.Type == 1) { var recurrenceInfo = new RecurrenceInfo(); recurrenceInfo.FromXml(appointment.RecurrenceInfo); var occurrenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); pattern.RecurrenceInfo.FromXml(appointment.RecurrenceInfo); pattern.Start = pattern.RecurrenceInfo.Start; pattern.End = pattern.RecurrenceInfo.End; var patternId = pattern.RecurrenceInfo.Id.ToString(); var interval = new TimeInterval(date, date.AddDays(1)); var occurrences = occurrenceCalculator.CalcOccurrences(interval, pattern); if (occurrences.Count > 0) { foreach (var termin in occurrences.GetAppointments(interval)) { var index = termin.RecurrenceIndex; var duration = (appointment.EndDate.Value - appointment.StartDate.Value).TotalMinutes; if (!date.InBetween(termin.Start.GetShortDateTime(), termin.Start.AddMinutes(duration), true) || changedOccurrences.Any(a => a.PatternId.Equals(patternId) && a.Index == index) || deletedOccurrences.Any(a => a.PatternId.Equals(patternId) && a.Index == index)) { continue; } holySweetFlyingFuck.AddIfNotIn(new SchedulerAppointmentDC { AllDay = appointment.AllDay, CustomerList = appointment.CustomerList, Description = appointment.Description, EmployeeList = appointment.EmployeeList, EndDate = termin.Start.AddMinutes(duration), FormerBookingSequenceOid = appointment.FormerBookingSequenceOid, IsPrivate = appointment.IsPrivate, LabelId = appointment.LabelId, Location = appointment.Location, Originator = appointment.Originator, RecurrenceInfo = termin.RecurrenceInfo.ToXml(), ReminderInfo = appointment.ReminderInfo, ResourceList = appointment.ResourceList, StartDate = termin.Start, Subject = appointment.Subject ?? "", Type = appointment.Type }); } } } } return SerializeObject(holySweetFlyingFuck.OrderBy(x => x.StartDate.Value.Hour)); } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 510"); } } [Authorize] public string LoadStatistics(long oid) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var supportConceptStatistics = OperationsService.CreateSupportConceptStatistics(oid, DateTime.Now); return SerializeObject(supportConceptStatistics); } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 560"); } } [Authorize] public string UpdateAppointment(long oid, string betreff, string notice, string startZeit, string endZeit, string day, string endDate, string pLocation) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var date = DateTime.Parse(day); var end = DateTime.Parse(endDate); var zeit = ConvertRecordTimesWithEndDate(startZeit, endZeit, date, end, 0); var b1 = KalenderService.GetSchedulerAppointmentByid(oid); b1.EndDate = zeit[1]; b1.StartDate = zeit[0]; b1.Subject = betreff; b1.Description = notice; b1.Location = pLocation; KalenderService.UpdateSchedulerAppointments(new List{b1}); return _LeerzeichenFuerGetMethoden; } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 550: Internal Server Error"); } } [Authorize] public void InsertAppointment(string pStartDate, string pStartTime, string pEndTime, string pSubject, string pNotice, string pEndDate, string pLocation) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return; } var date = DateTime.Parse(pStartDate); var end = DateTime.Parse(pEndDate); var zeit = ConvertRecordTimesWithEndDate(pStartTime, pEndTime, date, end, 0); var newApp = new SchedulerAppointmentDC { EmployeeList = new List(), CustomerList = new List(), ResourceList = new List(), SupportConceptList = new List(), EndDate = zeit[1], StartDate = zeit[0], Subject = pSubject, Description = pNotice, Originator = MobileSessionFacade.LoggedInCompactEmployee, Location = pLocation }; //var newE2S = new Employee2SchedulerAppointmentDC //{ // Employee = MobileSessionFacade.LoggedInCompactEmployee //}; //newApp.EmployeeList.Add(newE2S); var list = new List {newApp}; KalenderService.InsertSchedulerAppointments(list); } catch (Exception e) { log.Error(e.Message, e); SerializeObject("Fehler 520"); } } [Authorize] public string LoadBeWoTasks(string newtoday) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var date = DateTime.ParseExact(newtoday, "dd.MM.yyyy", null); var tasks = AnalysisService.GetTasksForEmployeeByDate(Model.Employee.EmployeeOid.Value, date); return SerializeObject(tasks); } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 530"); } } [Authorize] public string SaveUnterschrift(string blob, string zeitstempel, long? ServiceRecord) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var date = DateTime.Parse(zeitstempel); OperationsService.InsertSignature(new SignatureDC { DataBild = blob, Zeitstempel = date, ServiceRecordOid = ServiceRecord }); return _LeerzeichenFuerGetMethoden; } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 540"); } } [Authorize] public string SetSaveSignature(bool save) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.SaveSignature = save; return _LeerzeichenFuerGetMethoden; } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 777: Fail Error Compilation"); } } [Authorize] public string LoadServiceCategories(long pServiceCategoryOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } try { var scm = Model?.ServiceCategories.FirstOrDefault(s => s.ServiceCategoryOid.Value == pServiceCategoryOid); return SerializeObject(scm != null ? scm.ServiceDescriptions : new List()); } catch(Exception exception) { Debug.WriteLine(exception); throw; } } [Authorize] public string LoadTextbausteineForServiceCategory(long pServiceCategoryOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } try { if (!MobileSessionFacade.CheckForUserRight(UserRightType.TextbausteineNurEigeneAnsehen) && !MobileSessionFacade.CheckForUserRight(UserRightType.TextbausteineAlleAnsehen)) { return _LeerzeichenFuerGetMethoden; } var textbausteine = OperationsService.GetAllTextModules(); foreach (var tm in textbausteine) { if (tm.Text == null) { tm.Text = ""; } } if(!MobileSessionFacade.CheckForUserRight(UserRightType.TextbausteineAlleAnsehen)) { textbausteine = textbausteine.Where(w => w.Employee.EmployeeOid == Model.Employee.EmployeeOid).ToList(); } Model.Textbausteine = textbausteine.Where(w => w.ServiceCategory == null || w.ServiceCategory.ServiceCategoryOid == pServiceCategoryOid).ToList(); Model.Textbausteine.AddRangeIfElementsNotIn(Utils.GetParentTextModules(Model.Textbausteine)); var displayItems = Model.Textbausteine.Select(s => new TextbausteinDisplayItem(s.TextModuleOid.Value, s.Name, s.Parent?.TextModuleOid, s.IsParent, s.Text)).ToList(); foreach(var item in displayItems) { if(item.ParentOid != null) { var parent = displayItems.FirstOrDefault(f => f.Oid == item.ParentOid); parent?.Children.AddIfNotIn(item); } } displayItems = displayItems.Where(w => w.ParentOid == null).ToList(); return SerializeObject(displayItems); } catch(Exception exception) { Debug.WriteLine(exception); throw; } } [Authorize] public string LoadCompleteTextbausteinByOid(long pTextbausteinOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var abc = Model.Textbausteine.FirstOrDefault(f => f.TextModuleOid.HasValue && f.TextModuleOid.Value == pTextbausteinOid); return abc?.Text; } public string ErrorZeiterfassungAnzeigen(int errorwert) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.ErrorWert = errorwert; return _LeerzeichenFuerGetMethoden; } catch (Exception e) { log.Error(e.Message, e); return SerializeObject("Fehler 777: Fail Error Compilation"); } } [HttpPost] [Authorize] public ActionResult CreateServiceRecord(FormCollection collection) { try { if(Model == null) { return RedirectToActionPermanent("Index", "Login"); } string doku1; if(Model.Dokutypes != null && Model.Dokutypes.Length > 1) { doku1 = collection["Dokumentation"]; } else { doku1 = collection["Dokumentation6"]; } log.Info($"CreateServiceRecord: datum:{collection["Datum"]}; start:{collection["Start"]}; ende:{collection["Ende"]}; dauer:{collection["Dauer"]}; doku:{doku1}; aktion:{collection["versteckt"]}"); if(string.IsNullOrEmpty(collection["Datum"])) { return View("Main", Model); } var distanz = collection["Distanz"]; var distanceInMeters = 0; if(!string.IsNullOrEmpty(distanz)) { if(int.TryParse(distanz, out var parsedDistance)) { distanceInMeters = parsedDistance; } } var submitBtnVal = collection["versteckt"]; var selectedCostbearerSCRelOid = Model.CostBearer2SupportConceptOid < 1 ? null : Model.CostBearer2SupportConceptOid; var datum = Convert.ToDateTime(collection["Datum"]); var enddatum = datum; var start = collection["Start"]; var ende = collection["Ende"]; var dauer = 0; if(datum > enddatum) { enddatum = datum; } if(!string.IsNullOrEmpty(collection["Dauer"])) { int.TryParse(collection["Dauer"], out dauer); } var doku2 = collection["Dokumentation2"]; var doku3 = collection["Dokumentation3"]; var doku4 = collection["Dokumentation4"]; var doku5 = collection["Dokumentation5"]; var zeitenFeld = new DateTime[2]; if(start == string.Empty && ende == string.Empty) { zeitenFeld[0] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1); if(enddatum == datum) { zeitenFeld[1] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1).AddMinutes(dauer); } else { zeitenFeld[1] = new DateTime(enddatum.Year, enddatum.Month, enddatum.Day, 0, 0, 1).AddMinutes(dauer); } } else { zeitenFeld = enddatum == datum ? ConvertRecordTimes(start, ende, datum, dauer) : ConvertRecordTimesWithEndDate(start, ende, datum, enddatum, dauer); } if(dauer == 0 || zeitenFeld[1] != zeitenFeld[0]) { dauer = (int) (zeitenFeld[1] - zeitenFeld[0]).TotalMinutes; } if(submitBtnVal.Equals("Speichern")) { var selectedRecordOid = Model.SelectedServiceRecordOid ?? Model.SelectedServiceRecord.ServiceRecordOid; Model.NewServiceRecord = OperationsService.GetServiceRecordById(selectedRecordOid.Value); } if(Model.NewServiceRecord == null) { return RedirectToActionPermanent("Main"); } Model.NewServiceRecord.IP = Request.UserHostAddress; Model.NewServiceRecord.Goals = Model.SelectedGoals; Model.NewServiceRecord.Start = zeitenFeld[0]; Model.NewServiceRecord.End = zeitenFeld[1]; Model.NewServiceRecord.DistanceInMeter = distanceInMeters; if(Model.Employee.EmployeeOid != null) { if(!submitBtnVal.Equals("Speichern")) { Model.NewServiceRecord.Employee = Model.SelectedEmployee ?? MobileSessionFacade.LoggedInCompactEmployee; } else { if (Model.SelectedEmployee != null) { Model.NewServiceRecord.Employee = Model.SelectedEmployee; } } var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(selectedCostbearerSCRelOid))); if(sc != null) { if(sc.SupportConceptOid != null) { Model.NewServiceRecord.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid); } Model.NewServiceRecord.Customer = sc.Customer; var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(selectedCostbearerSCRelOid)); Model.NewServiceRecord.CostBearer = cb2ScRel.CostBearer; var intervall = Model.NewServiceRecord.CostBearer.ActualMinuteIntervall; if(intervall > 0) { Model.NewServiceRecord.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - dauer % intervall) : dauer; } else { Model.NewServiceRecord.RoundedDuration = dauer; } Model.NewServiceRecord.CostBearer2SupportConceptOid = selectedCostbearerSCRelOid; } else { Model.NewServiceRecord.RoundedDuration = dauer; } } Model.NewServiceRecord.DurationInStunden = ZeiterfassungsDauer.Minuten; Model.NewServiceRecord.ServiceRecordFormat = ServiceRecordFormate.OriginaleZeiterfassung; Model.NewServiceRecord.Notice = string.IsNullOrEmpty(doku1) ? null : doku1; Model.NewServiceRecord.Notice2 = string.IsNullOrEmpty(doku2) ? null : doku2; Model.NewServiceRecord.Notice3 = string.IsNullOrEmpty(doku3) ? null : doku3; Model.NewServiceRecord.Notice4 = string.IsNullOrEmpty(doku4) ? null : doku4; Model.NewServiceRecord.Notice5 = string.IsNullOrEmpty(doku5) ? null : doku5; var serviceDescOid = 0L; if (Model.SelectedServiceDescriptionOid.HasValue) { serviceDescOid = Model.SelectedServiceDescriptionOid.Value; } else if (!string.IsNullOrEmpty(collection["ServiceDescription"])) { serviceDescOid = Convert.ToInt64(collection["ServiceDescription"]); } if (serviceDescOid > 0) { Model.NewServiceRecord.ServiceDescription = OperationsService.GetServiceDescription(serviceDescOid); } if (Model.NewServiceRecord.RoundedDuration == 0) { Model.NewServiceRecord.RoundedDuration = dauer; } Model.NewServiceRecord.IP = Request.UserHostAddress; Model.NewServiceRecord.InsertedOn = DateTime.Now; Model.NewServiceRecord.InsUser = $"{MobileSessionFacade.LoggedInEmployee.FirstName} {MobileSessionFacade.LoggedInEmployee.LastName}"; Model.NewServiceRecord.IsCreatedInMobileClient = true; if(Model.IsInGroupBookingMode && Model.SelectedSupportConcepts.Count > 1) { return submitBtnVal.Equals("Anlegen") ? SaveGroupBooking() : UpdateGroupBooking(); } if(submitBtnVal.Equals("Anlegen")) { var oidList = OperationsService.InsertNewServiceRecords(new List { Model.NewServiceRecord }); Model.ServiceRecordOid = oidList[0]; } else { OperationsService.UpdateServiceRecords(new List { Model.NewServiceRecord }); } Model.NewServiceRecord = new ServiceRecordDC(); if(selectedCostbearerSCRelOid.HasValue) { Model.ServiceRecords = OperationsService.FindServiceRecordsForLastDays(selectedCostbearerSCRelOid, Model.Zeitraum, Model.Employee.EmployeeOid).ToList(); } } catch (Exception e) { log.Error(e.Message, e); } Model.SaveSignature = Model.ShowSignature && Model.SelectedSupportConcept != null; return RedirectToActionPermanent("Main"); } private ActionResult SaveGroupBooking() { var employeeCount = Model.SelectedEmployees.Count; var personCount = Model.SelectedSupportConcepts.Count; var cb2SCOids = (from scDc in Model.SelectedSupportConcepts where scDc.CostBearerRelations != null && scDc.CostBearerRelations.Count > 0 let costBearer2SupportConceptOid = scDc.CostBearerRelations[0].CostBearer2SupportConceptOid where costBearer2SupportConceptOid != null select costBearer2SupportConceptOid.Value).ToList(); var list = CalculateGroupBookingDuration(employeeCount, personCount, cb2SCOids); var newDCList = new List(); foreach(var dc in list) { foreach(var emp in Model.SelectedEmployees) { var newDC = CloneServiceRecordForGroupBooking(dc); newDC.Employee = emp; newDC.InsertedOn = DateTime.Now; newDCList.Add(newDC); } } if(newDCList.Count > 0) { if(newDCList.Count == 1) { OperationsService.InsertNewServiceRecords(newDCList); } else { var groupDC = new ServiceRecordGroupDC { EmployeeCount = employeeCount, CustomerCount = personCount, StartDate = Model.NewServiceRecord.Start, EndDate = Model.NewServiceRecord.End, Notice = Model.NewServiceRecord.Notice, Notice2 = Model.NewServiceRecord.Notice2, Notice3 = Model.NewServiceRecord.Notice3, Notice4 = Model.NewServiceRecord.Notice4, Notice5 = Model.NewServiceRecord.Notice5, ServiceRecordList = newDCList }; if(Model.NewServiceRecord.GroupRoundedDuration != null) { groupDC.RoundedDuration = Model.NewServiceRecord.GroupRoundedDuration.Value; } OperationsService.InsertNewServiceRecordGroup(groupDC); } } Model.SelectedSupportConcepts.Clear(); Model.SelectedConceptCostBearerRelations.Clear(); Model.SelectedCostbearerRelOids.Clear(); Model.SelectedGroupOfPeopleOids.Clear(); Model.SelectedEmployees = new List{ MobileSessionFacade.LoggedInCompactEmployee }; return RedirectToActionPermanent("Main"); } private ActionResult UpdateGroupBooking() { var dc = Model.SelectedServiceRecord; var group = OperationsService.GetServiceRecordGroup(dc.GroupOid.Value); UpdateServiceRecordGroup(group); var employeeCount = Model.SelectedEmployees.Count; var customerCount = Model.SelectedSupportConcepts.Count; group.EmployeeCount = employeeCount; group.CustomerCount = customerCount; var roundDuration = true; var minuteInterval = 0; CompactOrganisationDC org = null; var cb2scOids = new List(); foreach(var scdc in Model.SelectedSupportConcepts) { if(scdc.CostBearerRelations.Count > 0) { cb2scOids.Add(scdc.CostBearerRelations.ElementAt(0).CostBearer2SupportConceptOid.Value); if(org == null) { org = scdc.CostBearerRelations.ElementAt(0).CostBearer; if(org != null) { minuteInterval = org.ActualMinuteIntervall; } } else { if(scdc.CostBearerRelations.ElementAt(0).CostBearer == null || !org.Equals(scdc.CostBearerRelations.ElementAt(0).CostBearer)) { roundDuration = false; } } } } var duration = (decimal) (Model.NewServiceRecord.End.Value - Model.NewServiceRecord.Start.Value).TotalMinutes; var lRoundedDuration = duration; decimal groupDuration; decimal roundedDuration; var gd = OperationsService.CalculateGroupDuration2(customerCount, employeeCount, duration, cb2scOids.ToArray()); if(gd != null) { groupDuration = gd.TotalDuration; roundedDuration = gd.SingleDuration; } else { if(minuteInterval > 0 && roundDuration) { lRoundedDuration = duration % minuteInterval != 0 ? duration + (minuteInterval - duration % minuteInterval) : duration; } groupDuration = lRoundedDuration; roundedDuration = Math.Round(groupDuration / Model.SelectedSupportConcepts.Count, 0 , MidpointRounding.AwayFromZero); } Model.NewServiceRecord.RoundedDuration = roundedDuration; Model.NewServiceRecord.GroupRoundedDuration = groupDuration; group.Notice = Model.NewServiceRecord.Notice; group.Notice2 = Model.NewServiceRecord.Notice2; group.Notice3 = Model.NewServiceRecord.Notice3; group.Notice4 = Model.NewServiceRecord.Notice4; group.Notice5 = Model.NewServiceRecord.Notice5; group.RoundedDuration = groupDuration; group.StartDate = Model.NewServiceRecord.Start; group.EndDate = Model.NewServiceRecord.End; foreach(var item in group.ServiceRecordList) { item.Notice = Model.NewServiceRecord.Notice; item.Notice2 = Model.NewServiceRecord.Notice2; item.Notice3 = Model.NewServiceRecord.Notice3; item.Notice4 = Model.NewServiceRecord.Notice4; item.Notice5 = Model.NewServiceRecord.Notice5; item.End = Model.NewServiceRecord.End; item.Start = Model.NewServiceRecord.Start; item.RoundedDuration = roundedDuration; item.DistanceInMeter = Model.NewServiceRecord.DistanceInMeter; item.ServiceDescription = Model.NewServiceRecord.ServiceDescription; item.ServiceRecordFormat = Model.NewServiceRecord.ServiceRecordFormat; item.DurationInStunden = Model.NewServiceRecord.DurationInStunden; item.ServiceDescription = item.ServiceDescription ?? Model.NewServiceRecord.ServiceDescription; item.GroupEmployeeCount = group.EmployeeCount; item.GroupPersonCount = group.CustomerCount; item.GroupOid = Model.NewServiceRecord.GroupOid; item.GroupRoundedDuration = groupDuration; if(item.CostBearer != null && item.CostBearer.CostBearerOid == null && item.SupportConcept != null && item.SupportConcept.CostBearerList.Count > 0) { item.CostBearer.CostBearerOid = item.SupportConcept.CostBearerList[0].CostBearerOid; } } if(Model.NewServiceRecord.GroupOid.HasValue) { OperationsService.UpdateServiceRecordGroup(group); } Model.NewServiceRecord = null; Model.SelectedServiceRecord = null; Model.SelectedSupportConcepts = new List(); Model.SelectedEmployees = new List(); ResetGroupBookingMode(false); Model.IsInEditingMode = false; return RedirectToActionPermanent("Main"); } private IEnumerable CalculateGroupBookingDuration(int pEmployeeCount, int pCustomerCount, ICollection cb2ScOids) { var compactSupportConcepts = CustomerServiceImp.GetCompactSupportConcepts((from sc in Model.SelectedSupportConcepts where sc.SupportConceptOid != null select sc.SupportConceptOid.Value).ToList(), GetUser().Employee.EmployeeOid); var nodes = (from supportConcept in Model.SelectedSupportConcepts let cb = supportConcept.CostBearerRelations.FirstOrDefault(f => cb2ScOids.Contains(f.CostBearer2SupportConceptOid.Value)) let sc = compactSupportConcepts.FirstOrDefault(f => f.SupportConceptOid == supportConcept.SupportConceptOid) where cb != null && sc != null select SupportConceptService.CreateFlatSupportConceptItem(sc, CustomerService.LoadOrganisationCompact(cb.CostBearer.OrganisationOid))).ToList(); var list = new List(); foreach(var node in nodes) { var sc = CloneServiceRecordForGroupBooking(Model.NewServiceRecord); if(Model.NewServiceRecord.RoundedDuration == 0) { if(Model.NewServiceRecord.Start.HasValue && Model.NewServiceRecord.End.HasValue) { var minutes = Model.NewServiceRecord.End.Value.Subtract(Model.NewServiceRecord.Start.Value).TotalMinutes; Model.NewServiceRecord.RoundedDuration = (decimal)minutes; } } sc.GroupRoundedDuration = Model.NewServiceRecord.RoundedDuration; sc.CostBearer2SupportConceptOid = node.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid; sc.SupportConcept = node.SupportConceptTreeNodeDC.SupportConcept; sc.CostBearer = node.SupportConceptTreeNodeDC.CostBearer; sc.Customer = node.SupportConceptTreeNodeDC.Customer; sc.GroupEmployeeCount = pEmployeeCount; sc.GroupPersonCount = pCustomerCount; list.Add(sc); } var roundDuration = false; var minuteInterval = 0; string calcdId = null; var lastMinuteInterval = -1; if(Model.SelectedServiceDescriptionOid.HasValue && IsBillable(Model.SelectedServiceDescriptionOid.Value, Model.GetServiceDesctiptions())) { roundDuration = true; foreach(var org in from dc in Model.SelectedSupportConcepts where dc.CostBearerRelations.Count > 0 select dc.CostBearerRelations.First().CostBearer) { if(org != null) { minuteInterval = org.ActualMinuteIntervall; if(lastMinuteInterval == -1) { lastMinuteInterval = minuteInterval; calcdId = org.CostBearerID; } else if(lastMinuteInterval != minuteInterval) { roundDuration = false; } } else if(minuteInterval >= 0) { roundDuration = false; } else { minuteInterval = 0; } } } var duration = Model.NewServiceRecord.RoundedDuration; var totalDuration = duration; var groupDuration = OperationsService.CalculateGroupDuration2(pCustomerCount, pEmployeeCount, Model.NewServiceRecord.RoundedDuration, nodes.Select(s => s.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid.Value).ToArray()); if(groupDuration != null) { Model.NewServiceRecord.GroupRoundedDuration = groupDuration.TotalDuration; Model.NewServiceRecord.RoundedDuration = groupDuration.SingleDuration; } else { if(minuteInterval > 0 && roundDuration) { var calc = Calculations.GetInstance(calcdId); totalDuration = calc.GetRoundedDuration(minuteInterval, duration); } Model.NewServiceRecord.RoundedDuration = Math.Round(totalDuration / pCustomerCount, 0, MidpointRounding.AwayFromZero); Model.NewServiceRecord.GroupRoundedDuration = totalDuration; } return list; } private void UpdateServiceRecordGroup(ServiceRecordGroupDC pGroupDC) { var newCount = 0; foreach(var serviceRecord in pGroupDC.ServiceRecordList) { if(!serviceRecord.ServiceRecordOid.HasValue) { newCount++; } } if(newCount == pGroupDC.ServiceRecordList.Count) { return; } var dcsToChange = new List(); var oldSCs = new Dictionary(); var oldEmps = new Dictionary(); var newKeys = new Dictionary(); foreach(var sc in Model.SelectedSupportConcepts) { foreach(var emp in Model.SelectedEmployees) { var key = emp.EmployeeOid + "_" + sc.SupportConceptOid; if(sc.CostBearerRelations != null && sc.CostBearerRelations.Count > 0) { var costBearer2SupportConceptOid = sc.CostBearerRelations.ElementAt(0).CostBearer2SupportConceptOid; if(costBearer2SupportConceptOid != null) { key += "_" + costBearer2SupportConceptOid.Value; } newKeys.Add(key, key); } } } foreach(var item in pGroupDC.ServiceRecordList) { var key = item.Employee.EmployeeOid + "_" + item.SupportConcept.SupportConceptOid; if(item.CostBearer2SupportConceptOid.HasValue) { key += "_" + item.CostBearer2SupportConceptOid.Value; } if(newKeys.ContainsKey(key)) { newKeys.Remove(key); } else { dcsToChange.Add(item); } if(!oldEmps.ContainsKey(item.Employee.EmployeeOid)) { oldEmps.Add(item.Employee.EmployeeOid, item.Employee); } if(!oldSCs.ContainsKey(item.SupportConcept.SupportConceptOid)) { oldSCs.Add(item.SupportConcept.SupportConceptOid, item.SupportConcept); } } if(newKeys.Count != 0 || dcsToChange.Count != 0) { if(newKeys.Count > 0) { foreach(var sc in Model.SelectedSupportConcepts) { foreach(var emp in Model.SelectedEmployees) { var key = emp.EmployeeOid + "_" + sc.SupportConceptOid; if(sc.CostBearerRelations != null && sc.CostBearerRelations.Count > 0) { key += "_" + sc.CostBearerRelations.ElementAt(0).CostBearer2SupportConceptOid; } if(!newKeys.ContainsKey(key)) { continue; } ServiceRecordDC newServiceRecord; if(dcsToChange.Count > 0) { newServiceRecord = dcsToChange[0]; dcsToChange.Remove(newServiceRecord); } else { newServiceRecord = CloneServiceRecordForGroupBooking(Model.NewServiceRecord); pGroupDC.ServiceRecordList.Add(newServiceRecord); } newServiceRecord.Employee = emp; newServiceRecord.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, null); newServiceRecord.CostBearer = sc.CostBearerRelations.ElementAt(0).CostBearer; newServiceRecord.Customer = sc.Customer; newServiceRecord.CostBearer2SupportConceptOid = sc.CostBearerRelations.ElementAt(0).CostBearer2SupportConceptOid; } } } foreach(var item in dcsToChange) { pGroupDC.ServiceRecordList.Remove(item); } } } [Authorize] public ActionResult SaveZeiterfassungAfterCrash(string pDatum, string pStartDate, string pEndDate, string pDuration, string pNotice, string pServiceDescription, string pNotice2, string pNotice3, string pNotice4, string pNotice5, string pEndDate2) { try { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } log.Info($"saveZeiterfassungAfterCrash: datum:{pDatum};start:{pStartDate};ende:{pEndDate};dauer:{pDuration};doku:{pNotice};doku2:{pNotice2};doku3:{pNotice3};doku4:{pNotice4};doku5:{pNotice5};pEndDate2:{pEndDate2}"); if (string.IsNullOrEmpty(pDatum)) { return View("Main", Model); } var selectedCostbearerSCRelOid = Model.CostBearer2SupportConceptOid < 1 ? null : Model.CostBearer2SupportConceptOid; var datum = Convert.ToDateTime(pDatum); var start = pStartDate; var ende = pEndDate; var dauer = 0; var enddatum = pEndDate2 != "" ? Convert.ToDateTime(pEndDate2) : datum; if (datum > enddatum) { enddatum = datum; } if (!string.IsNullOrEmpty(pDuration)) { int.TryParse(pDuration, out dauer); } var doku = pNotice; var doku2 = pNotice2; var doku3 = pNotice3; var doku4 = pNotice4; var doku5 = pNotice5; var zeitenFeld = new DateTime[2]; if (start == string.Empty && ende == string.Empty) { zeitenFeld[0] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1); if (enddatum == datum) { zeitenFeld[1] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1).AddMinutes(dauer); } else { zeitenFeld[1] = new DateTime(enddatum.Year, enddatum.Month, enddatum.Day, 0, 0, 1).AddMinutes(dauer); } } else { zeitenFeld = enddatum == datum ? ConvertRecordTimes(start, ende, datum, dauer) : ConvertRecordTimesWithEndDate(start, ende, datum, enddatum, dauer); } if (dauer == 0 || zeitenFeld[1] != zeitenFeld[0]) { dauer = (int)(zeitenFeld[1] - zeitenFeld[0]).TotalMinutes; } if (Model.NewServiceRecord == null) { return RedirectToActionPermanent("Main"); } Model.NewServiceRecord.Goals = Model.SelectedGoals; Model.NewServiceRecord.Start = zeitenFeld[0]; Model.NewServiceRecord.End = zeitenFeld[1]; if (Model.Employee.EmployeeOid != null) { Model.NewServiceRecord.Employee = Model.SelectedEmployee ?? MobileSessionFacade.LoggedInCompactEmployee; var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(selectedCostbearerSCRelOid))); if (sc != null) { if (sc.SupportConceptOid != null) { Model.NewServiceRecord.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid); } Model.NewServiceRecord.Customer = sc.Customer; var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(selectedCostbearerSCRelOid)); Model.NewServiceRecord.CostBearer = cb2ScRel.CostBearer; var intervall = Model.NewServiceRecord.CostBearer.ActualMinuteIntervall; if (intervall > 0) { Model.NewServiceRecord.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - dauer % intervall) : dauer; } else { Model.NewServiceRecord.RoundedDuration = dauer; } Model.NewServiceRecord.CostBearer2SupportConceptOid = selectedCostbearerSCRelOid; } else { Model.NewServiceRecord.RoundedDuration = dauer; } } Model.NewServiceRecord.Notice = doku; if (doku2 != "") { Model.NewServiceRecord.Notice2 = doku2; } if (doku3 != "") { Model.NewServiceRecord.Notice3 = doku3; } if (doku4 != "") { Model.NewServiceRecord.Notice4 = doku4; } if (doku5 != "") { Model.NewServiceRecord.Notice5 = doku5; } var serviceDescOid = 0L; if (Model.SelectedServiceDescriptionOid.HasValue) { serviceDescOid = Model.SelectedServiceDescriptionOid.Value; } else if (!string.IsNullOrEmpty(pServiceDescription)) { serviceDescOid = Convert.ToInt64(pServiceDescription); } if (serviceDescOid > 0) { Model.NewServiceRecord.ServiceDescription = OperationsService.GetServiceDescription(serviceDescOid); } Model.NewServiceRecord.IP = Request.UserHostAddress; Model.NewServiceRecord.InsertedOn = DateTime.Now; Model.NewServiceRecord.InsUser = $"{MobileSessionFacade.LoggedInEmployee.FirstName} {MobileSessionFacade.LoggedInEmployee.LastName}"; Model.NewServiceRecord.IsCreatedInMobileClient = true; OperationsService.InsertNewServiceRecords(new List { Model.NewServiceRecord }); Model.NewServiceRecord = new ServiceRecordDC(); if (selectedCostbearerSCRelOid.HasValue) { Model.ServiceRecords = OperationsService.FindServiceRecordsForLastDays(selectedCostbearerSCRelOid, Model.Zeitraum, Model.Employee.EmployeeOid).ToList(); } } catch (Exception e) { log.Error(e.Message, e); Model.ErrorWert = 2; //log.Error(e.Message, e); } return RedirectToActionPermanent("Main"); } [HttpPost] [Authorize] public ActionResult SelectSupportConcept(FormCollection formCollection) { if(Model == null) { return RedirectToActionPermanent("Index", "Login"); } long? cb2scOid = Convert.ToInt64(formCollection["CostBearer2SupportConceptOid"]); Model.CostBearer2SupportConceptOid = cb2scOid; Model.SelectedSupportConcept = Model.SupportConcepts.FirstOrDefault( f => f.CostBearerRelations.Any( a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(Model.CostBearer2SupportConceptOid))); if(Model.SelectedSupportConcept != null) { Model.SelectedSupportConceptListObject = Model.SupportConceptListObjects.First(f => long.Parse(f.CostBearer2SupportConceptOid) == cb2scOid); var details = OperationsService.GetSupportConceptTreeNodeDetailInfo(Model.SelectedSupportConcept.Customer.CustomerOid, Model.SelectedSupportConcept.SupportConceptOid, Model.CostBearer2SupportConceptOid); Model.ServiceCategories = details.ServiceAccountings.Count > 0 ? CreateServiceCategoryModels(details.ServiceAccountings.Select(sa => sa.ServiceDescription).ToList()) : CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions()); Model.ServiceCategories = Model.ServiceCategories.Where(c => !c.OhneHilfeplan.HasValue || c.OhneHilfeplan.Value == AccountingvisibilityType.Beides || c.OhneHilfeplan.Value == AccountingvisibilityType.NurKlientenbezogen).ToList(); } else if(cb2scOid == -2) { Model.SelectedSupportConceptListObject = Model.SupportConceptListObjects.First(f => f.CostBearer2SupportConceptOid.Equals(cb2scOid.ToString())); Model.ServiceCategories = CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions()); Model.ServiceCategories = Model.ServiceCategories.Where(c => !c.OhneHilfeplan.HasValue || c.OhneHilfeplan.Value == AccountingvisibilityType.Beides || c.OhneHilfeplan.Value == AccountingvisibilityType.NichtKlientenbezogen).ToList(); } else if(cb2scOid == -1) { Model.SelectedSupportConceptListObject = Model.SupportConceptListObjects.First(f => f.CostBearer2SupportConceptOid.Equals(cb2scOid.ToString())); Model.ServiceCategories.Clear(); } Model.Zeitraum = 7; LoadRecordsToModel(); return RedirectToActionPermanent("Main"); } [HttpPost] [Authorize] public ActionResult DeleteServiceRecord(FormCollection formCollection) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } Model.ServiceRecordOidToDelete = long.Parse(formCollection["serviceRecordOidHolder"]); if (Model.ServiceRecordOidToDelete != null && Model.ServiceRecordOidToDelete > 0 && MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.ServiceRecordView_Delete)))) { var serviceRecordDC = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid != null && f.ServiceRecordOid.Value.Equals(Model.ServiceRecordOidToDelete)); var version = serviceRecordDC?.ServiceRecordVersion; if (version != null) { OperationsService.DeleteServiceRecord(Model.ServiceRecordOidToDelete.Value, version.Value); Model.ServiceRecords = Model.ServiceRecords.Where(sr => sr.ServiceRecordOid != null && !sr.ServiceRecordOid.Value.Equals(serviceRecordDC.ServiceRecordOid)).ToList(); } } ResetGroupBookingMode(false); return RedirectToActionPermanent("Main"); } public string SetRecordOidToDelete(long serviceRecordOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.ServiceRecordOidToDelete = serviceRecordOid; return _LeerzeichenFuerGetMethoden; } public string UpdateGoals(string pGoalOids) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var sc = Model.SelectedSupportConcept; if (sc == null) { return _LeerzeichenFuerGetMethoden; } var splitOids = pGoalOids.Split(';'); var selectedGoalOids = splitOids.Select(long.Parse).ToList(); var goals = sc.Goals.Where(w => w.ValueListEntryOid.HasValue && selectedGoalOids.Contains(w.ValueListEntryOid.Value)).ToList(); Model.SelectedGoals = goals; return _LeerzeichenFuerGetMethoden; } public string SetServiceDescription(long pServiceDescriptionOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.SelectedServiceDescriptionOid = pServiceDescriptionOid; return _LeerzeichenFuerGetMethoden; } [HttpPost] [Authorize] public ActionResult LoadServiceRecords(FormCollection formCollection) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } var zeitraum = int.Parse(formCollection["Records"]); if (zeitraum < 0) { zeitraum = 7; } Model.Zeitraum = zeitraum; LoadRecordsToModel(); return RedirectToActionPermanent("Main"); } private void LoadRecordsToModel() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return; } if (Model.Zeitraum < 0 || Model.CostBearer2SupportConceptOid.HasValue && Model.CostBearer2SupportConceptOid.Value == -1) { Model.ServiceRecords = new List(); return; } var records = OperationsService.FindServiceRecordsForLastDays(Model.CostBearer2SupportConceptOid < 1 ? null : Model.CostBearer2SupportConceptOid, Model.Zeitraum, Model.Employee.EmployeeOid); var recordsOhneDuplikate = new List(); foreach(var r in records.Where(r => !recordsOhneDuplikate.Any(a => a.GroupOid.HasValue && a.GroupOid.Value.Equals(r.GroupOid)))) { recordsOhneDuplikate.Add(r); } Model.ServiceRecords = recordsOhneDuplikate; } public string SetSelectedServiceRecord(long? recordOid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.SelectedServiceRecordOid = recordOid; if (recordOid == null) { Model.SelectedGoals = new List(); } else { var serviceRecordDC = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid.HasValue && f.ServiceRecordOid.Value.Equals(Model.SelectedServiceRecordOid)); if (serviceRecordDC != null) { Model.SelectedServiceRecord = serviceRecordDC; Model.SelectedGoals = serviceRecordDC.Goals; } } return _LeerzeichenFuerGetMethoden; } [HttpPost] [Authorize] public ActionResult SetSelectedGroupServiceRecord(FormCollection pFormCollection) { if(Model == null) { return RedirectToActionPermanent("Index", "Login"); } long.TryParse(pFormCollection["hiddenElement"], out var recordOid); Model.SelectedServiceRecordOid = recordOid; Model.IsInGroupBookingMode = true; Model.IsInEditingMode = true; var serviceRecord = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid == recordOid); var supportConcepts = new List(); var employees = new List(); Model.SelectedServiceRecord = serviceRecord; Model.SelectedSupportConcepts.Clear(); Model.SelectedEmployees.Clear(); Model.SelectedCostbearerRelOids.Clear(); Model.SelectedConceptCostBearerRelations.Clear(); var relationOids = new List(); if (serviceRecord?.GroupOid != null) { var serviceRecordGroup = OperationsService.GetServiceRecordGroup(serviceRecord.GroupOid.Value); if(serviceRecordGroup != null) { employees.AddRangeIfElementsNotIn(serviceRecordGroup.ServiceRecordList.Select(s => s.Employee)); relationOids = serviceRecordGroup.ServiceRecordList.Select(s => s.CostBearer2SupportConceptOid.Value).ToList(); var costBearerRelations = CustomerService.GetSupportConceptCostBearerRelationsById(relationOids); Model.SelectedConceptCostBearerRelations.AddRangeIfElementsNotIn(costBearerRelations); foreach(var rel in costBearerRelations) { var sc = CustomerService.LoadSupportConcept(rel.SupportConcept.SupportConceptOid); var oid = sc.SupportConceptOid; if(!supportConcepts.Any(a => a.SupportConceptOid.Equals(oid))) { supportConcepts.Add(sc); } } } } Model.SelectedCostbearerRelOids.AddRangeIfElementsNotIn(relationOids); Model.SelectedSupportConcepts = supportConcepts; Model.SelectedEmployees = employees; Model.ServiceCategories = CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions()); return RedirectToActionPermanent("Main"); } public string GetSelectedRecordInformation() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var result = _LeerzeichenFuerGetMethoden; if (Model.SelectedServiceRecordOid.HasValue) { result = SerializeObject(Model.ServiceRecords.First(f => f.ServiceRecordOid == Model.SelectedServiceRecordOid)); } return result; } public string GetSelectedRecordInformationWithOid(long oid) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } LoadRecordsToModel(); return SerializeObject(Model.ServiceRecords.First(f => f.ServiceRecordOid == oid)); } [Authorize] public string CheckRights(string von, string bis, bool inEditMode, string dateString, string startString, string endString) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } log.Info($"CheckRights: von:{von};bis:{bis};inEditMode:{inEditMode};dateString:{dateString};startString:{startString};endString:{endString}"); var startHoursDt = ConvertTimeStringToDateTime(startString); var endHoursDt = ConvertTimeStringToDateTime(endString); if (!DateTime.TryParse(dateString, out var date)) { date = DateTime.Now.Date; } var startDt = date.AddHours(startHoursDt.Hour).AddMinutes(startHoursDt.Minute); var endDt = date.AddHours(endHoursDt.Hour).AddMinutes(endHoursDt.Minute); if (startDt > endDt) { return "StartGreaterEnd"; } var dauer = (int)(endDt - startDt).TotalMinutes; if (dauer == 0) { startDt = startDt.AddSeconds(1); endDt = endDt.AddSeconds(1); } var checkSR = new ServiceRecordDC(); if (inEditMode) { checkSR = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid.HasValue && f.ServiceRecordOid.Value.Equals(Model.SelectedServiceRecordOid)); } if (checkSR == null) { checkSR = new ServiceRecordDC(); } checkSR.Goals = Model.SelectedGoals; checkSR.Start = startDt; checkSR.End = endDt; checkSR.IP = Request.UserHostAddress; checkSR.ServiceDescription = OperationsService.GetServiceDescription(Model.SelectedServiceDescriptionOid.Value); checkSR.Employee = Model.SelectedEmployee ?? MobileSessionFacade.LoggedInCompactEmployee; if (Model.SelectedEmployee != null && !Model.IsInGroupBookingMode) { var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(Model.CostBearer2SupportConceptOid))); if (sc != null) { if (sc.SupportConceptOid != null) { checkSR.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid); } checkSR.Customer = sc.Customer; var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(Model.CostBearer2SupportConceptOid)); checkSR.CostBearer = cb2ScRel.CostBearer; var intervall = checkSR.CostBearer.ActualMinuteIntervall; if (intervall > 0) { checkSR.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - dauer % intervall) : dauer; } checkSR.CostBearer2SupportConceptOid = Model.CostBearer2SupportConceptOid; } } var mandator = OperationsService.GetMandator(); var settings = mandator.Settings ?? string.Empty; var splitSettings = settings.Split(';'); var maxDaysEditSRsAllowedSetting = splitSettings.ToList().FirstOrDefault(f => f.Contains("MaxDaysEditServiceRecordsAllowed")); var maxDaysEditSRsAllowed = maxDaysEditSRsAllowedSetting != null ? int.Parse(maxDaysEditSRsAllowedSetting.Split('=')[1]) : 0; var limitFuerZeiterfassungSetting = splitSettings.ToList().FirstOrDefault(f => f.Contains("AnzTageZeiterfassErfolgt")); var limitFuerZeiterfassung = limitFuerZeiterfassungSetting != null ? int.Parse(limitFuerZeiterfassungSetting.Split('=')[1]) : 0; if (MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowEditAfterMaxDaysInNextMonth)) { maxDaysEditSRsAllowed = -1; } SupportConceptStatisticsDC stats = null; if (Model.CostBearer2SupportConceptOid != null && Model.CostBearer2SupportConceptOid > 0) { stats = OperationsService.CreateSupportConceptStatistics(Model.CostBearer2SupportConceptOid.Value, DateTime.Now); } var employees = new List {checkSR.Employee.EmployeeOid}; var validationResults = new List(); checkSR.ServiceRecordFormat = ServiceRecordFormate.OriginaleZeiterfassung; checkSR.DurationInStunden = ZeiterfassungsDauer.Minuten; string dateRangeString = null; if(Model.IsInGroupBookingMode) { if (checkSR.GroupOid.HasValue) { var serviceRecordGroup = OperationsService.GetServiceRecordGroup(checkSR.GroupOid.Value); serviceRecordGroup.ServiceRecordList.DoForEach(sr => employees.AddIfNotIn(sr.Employee.EmployeeOid)); } else { Model.SelectedEmployees.DoForEach(e => employees.AddIfNotIn(e.EmployeeOid)); } var cb2scOids = (from scDc in Model.SelectedSupportConcepts where scDc.CostBearerRelations != null && scDc.CostBearerRelations.Count > 0 select scDc.CostBearerRelations[0].CostBearer2SupportConceptOid.Value).ToList(); var relations = CustomerService.GetSupportConceptCostBearerRelationsById(cb2scOids); foreach (var rel in relations) { var sr = CloneServiceRecordForGroupBooking(checkSR); sr.SupportConcept = rel.SupportConcept; sr.CostBearer = rel.CostBearer; sr.CostBearer2SupportConceptOid = rel.CostBearer2SupportConceptOid; var result = OperationsService.ValidateServiceRecord(sr, null, maxDaysEditSRsAllowed, employees, cb2scOids); dateRangeString = rel.DateRangeString; validationResults.Add(new ServiceRecord2Validation(sr, result, dateRangeString)); } } else { if (Model.SelectedSupportConcept != null) { var node = CreateFlatSupportConceptItem(CustomerService.LoadCompactSupportConceptDC(Model.SelectedSupportConcept.SupportConceptOid.Value, Model.SelectedEmployee.EmployeeOid), null); dateRangeString = node?.SupportConceptTreeNodeDC != null ? node.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.DateRangeString : ""; } var result = OperationsService.ValidateServiceRecordEntry(checkSR, stats, maxDaysEditSRsAllowed, checkSR.GroupOid.HasValue, employees); validationResults.Add(new ServiceRecord2Validation(checkSR, result, dateRangeString ?? "")); } var allowOverlappingFLS = MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreateOverlappingFLS); var allowOverlappingFLSForEmployee = MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreateOverlappingFLSForEmployee); var allowMoreFLSThanApproved = MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreateMoreFLSThanApproved); var bookAfterSettlementInvoice = MobileSessionFacade.CheckForUserRight(UserRightType.BookServiceRecordAfterSettlementInvoice); var newResult = new ValidationResult(); var exitLoop = false; foreach (var sr2v in validationResults) { if(exitLoop) { break; } foreach (var vr in sr2v.ValidationResults) { if (exitLoop) { break; } switch(vr.ResultType) { case ServiceRecordOverlapping: newResult.Message += "An dem gewählten Datum '" + von + "' existiert bereits ein Eintrag (" + vr.Message + " bei Klient/in " + vr.CustomerName + ").

"; newResult.KannTrotzdemGespeichertWerden = allowOverlappingFLS; exitLoop = !allowOverlappingFLS; break; case EmployeeOverlapping: newResult.Message += "An dem gewählten Datum " + von + " existiert bereits ein Eintrag von " + vr.EmployeeName + " (" + vr.Message + ").

"; newResult.KannTrotzdemGespeichertWerden = allowOverlappingFLSForEmployee; exitLoop = !allowOverlappingFLSForEmployee; break; case OutsideOfSupportConcept: newResult.Message += "Das gewählte Datum " + von.Substring(0, 10) + " liegt außerhalb des Zeitraumes des gewählten Hilfeplans (" + sr2v.HilfePlanZeitraum + ").

"; newResult.KannTrotzdemGespeichertWerden = false; exitLoop = true; break; case ApprovedFLSOverspending: var klient = "diesen Hilfeplan"; if (!string.IsNullOrEmpty(vr.CustomerName)) { klient = "Klient/in " + vr.CustomerName; } var msg = "Die für " + klient + " genehmigten FLS (" + vr.ApprovedHours + ") werden mit diesem Eintrag überschritten. (" + vr.HoursNew + ")."; newResult.Message += msg + "

"; newResult.KannTrotzdemGespeichertWerden = allowMoreFLSThanApproved; exitLoop = !allowMoreFLSThanApproved; break; case OutOfEditLimit: newResult.Message += "Sie können keine neuen Leistungen für den " + von + " dokumentieren, da bereits der " + maxDaysEditSRsAllowed + ". des nachfolgenden Monats überschritten ist.

"; exitLoop = true; newResult.KannTrotzdemGespeichertWerden = false; break; case Error: newResult.Message += "Beim Speichern ist ein Fehler aufgetreten.

"; exitLoop = true; newResult.KannTrotzdemGespeichertWerden = false; break; case SettlementInvoiceAlreadyExisting: var klient2 = "diesen Hilfeplan"; if(!string.IsNullOrEmpty(vr.CustomerName)) { klient2 = "Klient/in " + vr.CustomerName; } newResult.KannTrotzdemGespeichertWerden = bookAfterSettlementInvoice; exitLoop = !bookAfterSettlementInvoice; if (bookAfterSettlementInvoice) { newResult.Message += "Es existiert bereits eine Spitzabrechnung für " + klient2 + ". Um diesen Eintrag zu berücksichtigen, muss eventuell eine neue Spitzabrechnung erstellt werden.

"; } else { newResult.Message += "Sie können den Eintrag nicht bearbeiten, da bereits eine Spitzabrechnung für " + klient2 + "

"; } break; case FristAbgelaufen: var intervall = "einem Tag"; if (limitFuerZeiterfassung != 1) { intervall = "" + limitFuerZeiterfassung + " Tagen"; } newResult.Message += "Sie können keine neuen Leistungen für den " + von + " dokumentieren, da die Zeiterfassung innerhalb von " + intervall + " erfolgen muss.

"; exitLoop = true; newResult.KannTrotzdemGespeichertWerden = false; break; case Custom: newResult.Message += vr.Message + "

"; exitLoop = true; newResult.KannTrotzdemGespeichertWerden = false; break; } } } if (!string.IsNullOrEmpty(newResult.Message)) { newResult.Message += newResult.KannTrotzdemGespeichertWerden ? "
Möchten Sie trotzdem speichern?

" : "
Speichern nicht möglich.

"; } Model.NewServiceRecord = new ServiceRecordDC(); return SerializeObject(newResult); } public bool CheckRightsAfterCrash(string von, string bis, bool inEditMode, string dateString, string startString, string endString, long costbearerOId, string leistung) { if (Model == null) { return false; } log.Info($"CheckRightsAfterCrash: von:{von};bis:{bis};inEditMode:{inEditMode};dateString:{dateString};startString:{startString};endString:{endString}"); var date = DateTime.Now.Date; var startHoursDt = ConvertTimeStringToDateTime(startString); var endHoursDt = ConvertTimeStringToDateTime(endString); if (!DateTime.TryParse(dateString, out date)) { date = DateTime.Now.Date; } var startDt = date.AddHours(startHoursDt.Hour).AddMinutes(startHoursDt.Minute); var endDt = date.AddHours(endHoursDt.Hour).AddMinutes(endHoursDt.Minute); if (startDt > endDt) { Model.ErrorWert = 5; return false; } var dauer = (int)(endDt - startDt).TotalMinutes; if (dauer == 0) { startDt = startDt.AddSeconds(1); endDt = endDt.AddSeconds(1); } var checkSR = new ServiceRecordDC { Goals = Model.SelectedGoals, Start = startDt, End = endDt }; if (Model.Employee.EmployeeOid != null) { checkSR.Employee = MobileSessionFacade.LoggedInCompactEmployee; _Model.CostBearer2SupportConceptOid = costbearerOId; var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(Model.CostBearer2SupportConceptOid))); if (sc != null) { if (sc.SupportConceptOid != null) { checkSR.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid); } checkSR.Customer = sc.Customer; var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(Model.CostBearer2SupportConceptOid)); checkSR.CostBearer = cb2ScRel.CostBearer; var intervall = checkSR.CostBearer.ActualMinuteIntervall; if (intervall > 0) { checkSR.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - (dauer % intervall)) : dauer; } checkSR.CostBearer2SupportConceptOid = Model.CostBearer2SupportConceptOid; } } checkSR.IP = Request.UserHostAddress; checkSR.InsertedOn = DateTime.Now; checkSR.InsUser = $"{MobileSessionFacade.LoggedInEmployee.FirstName} {MobileSessionFacade.LoggedInEmployee.LastName}"; if (leistung != null || leistung == "") { Model.SelectedServiceDescriptionOid = Convert.ToInt64(leistung); } else { Model.SelectedServiceDescriptionOid = 6; } checkSR.ServiceDescription = OperationsService.GetServiceDescription(Model.SelectedServiceDescriptionOid.Value); var man = OperationsService.GetMandator(); var s = man.Settings ?? string.Empty; var einzeln = s.Split(';'); var g = einzeln.ToList().FirstOrDefault(f => f.Contains("MaxDaysEditServiceRecordsAllowed")); var t = g != null ? int.Parse(g.Split('=')[1]) : 0; SupportConceptStatisticsDC stats = null; if (Model.CostBearer2SupportConceptOid != null && Model.CostBearer2SupportConceptOid > 0) { stats = OperationsService.CreateSupportConceptStatistics(Model.CostBearer2SupportConceptOid.Value, DateTime.Now); } var result = OperationsService.ValidateServiceRecordEntry(checkSR, stats, t, false, new List { checkSR.Employee.EmployeeOid }); if (result.Count != 0) { if (result[0].EndDate.Day <= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month <= date.Month || result[0].EndDate.Day >= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month <= date.Month || result[0].EndDate.Day <= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month >= date.Month || result[0].EndDate.Day >= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month >= date.Month) { Model.ErrorWert = 4; return false; } Model.ErrorWert = 3; return false; } Model.ErrorWert = 1; return true; } public string SetViewMode() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.SelectedCustomer = null; Model.SelectedCustomerOid = null; return _LeerzeichenFuerGetMethoden; } public string GetSelectedSupportConceptCustomer() { return Model.SelectedSupportConcept == null ? "NoSupportConceptSelected" : SerializeObject(Model.SelectedSupportConcept.Customer.CustomerOid); } public string GetSelectedCustomer(long customerOid) { if (Model == null) { return "SessionTimeout"; } Model.SelectedCustomer = CustomerService.LoadCustomer(customerOid); Model.SelectedCustomerOid = customerOid; return SerializeObject(GetJSONCustomer(Model.SelectedCustomer)); } public string SetServiceRecordEmployee(long employeeOid) { try { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.SelectedEmployee = MainModel.AllEmployees.First(f => f.EmployeeOid.Equals(employeeOid)); return _LeerzeichenFuerGetMethoden; } catch (Exception e) { log.Info("Error in SetServiceRecordEmployee:"); log.Error(e.Message, e); if (MainModel.AllEmployees == null) { log.Info("Weitere Infos: AllEmployees = null!"); } else { log.Info($"Weitere Infos: AllEmployees enthält {MainModel.AllEmployees.Count} Elemente: "); StringBuilder sb = new StringBuilder(); foreach (var ce in MainModel.AllEmployees) { if (sb.Length > 0) { sb.Append(","); } sb.Append(ce.EmployeeOid); } log.Info(sb.ToString()); } throw e; } } public string CheckToken(string token) { if(token != null && token.Equals("abcd")) { return SerializeObject("localhost;demo"); } return _LeerzeichenFuerGetMethoden; } // Gruppenbuchungen [HttpPost] [Authorize] public ActionResult SetGroupBookingMode(FormCollection pFormCollection) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } var isInGroupBookingMode = "true,false" == pFormCollection["IsInGroupBookingMode"]; ResetGroupBookingMode(isInGroupBookingMode); return RedirectToAction("Main"); } private void ResetGroupBookingMode(bool pIsInGroupBookingMode) { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return; } Model.IsInGroupBookingMode = pIsInGroupBookingMode; if (pIsInGroupBookingMode) { Model.SelectedSupportConcept = null; Model.SelectedEmployee = null; Model.ServiceCategories = CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions()); Model.SelectedEmployees.Add(MobileSessionFacade.LoggedInCompactEmployee); } else { Model.ServiceCategories.Clear(); Model.SelectedCostbearerRelOids.Clear(); Model.SelectedEmployees.Clear(); Model.SelectedSupportConcepts.Clear(); Model.SelectedConceptCostBearerRelations.Clear(); Model.SelectedEmployee = MobileSessionFacade.LoggedInCompactEmployee; if (Model.SelectedSupportConcept != null) { var details = OperationsService.GetSupportConceptTreeNodeDetailInfo(Model.SelectedSupportConcept.Customer.CustomerOid, Model.SelectedSupportConcept.SupportConceptOid, Model.CostBearer2SupportConceptOid); Model.ServiceCategories = details.ServiceAccountings.Count > 0 ? CreateServiceCategoryModels(details.ServiceAccountings.Select(sa => sa.ServiceDescription).ToList()) : CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions()); Model.ServiceCategories = Model.ServiceCategories.Where(c => !c.OhneHilfeplan.HasValue || c.OhneHilfeplan.Value == AccountingvisibilityType.Beides || c.OhneHilfeplan.Value == AccountingvisibilityType.NurKlientenbezogen).ToList(); } else if (Model.CostBearer2SupportConceptOid == -2) { Model.ServiceCategories = CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions()); Model.ServiceCategories = Model.ServiceCategories.Where(c => !c.OhneHilfeplan.HasValue || c.OhneHilfeplan.Value == AccountingvisibilityType.Beides || c.OhneHilfeplan.Value == AccountingvisibilityType.NichtKlientenbezogen).ToList(); } } } [HttpPost] [Authorize] public ActionResult ResetEditingMode(FormCollection pFormCollection) { if (Model == null) { return RedirectToActionPermanent("Index", "Login"); } Model.NewServiceRecord = new ServiceRecordDC(); Model.SelectedServiceRecord = null; Model.SelectedSupportConcepts.Clear(); Model.SelectedEmployees.Clear(); Model.IsInGroupBookingMode = false; Model.IsInEditingMode = false; return RedirectToActionPermanent("Main"); } public string LoadCategoryAndDescription() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } if (Model.SelectedServiceRecord == null) { return _LeerzeichenFuerGetMethoden; } var serviceDescriptionOid = Model.SelectedServiceRecord.ServiceDescription.ServiceDescriptionOid.ToString(); var serviceCategoryOid = Model.SelectedServiceRecord.ServiceDescription.Category.ServiceCategoryOid.ToString(); return $"{serviceDescriptionOid}/{serviceCategoryOid}"; } [Authorize] public string ResetGroupBookingModeViaGET() { if (Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } Model.IsInGroupBookingMode = false; Model.SelectedCostbearerRelOids.Clear(); Model.SelectedEmployees.Clear(); Model.SelectedSupportConcepts.Clear(); Model.SelectedConceptCostBearerRelations.Clear(); return MainModel.IsEmployeeSelectionVisible.ToString(); } [Authorize] public string AddSupportConceptCostBearerRelationsToGroupBooking(string pRelOids, string pGroupOids) { if(Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } var rawRelOids = string.IsNullOrEmpty(pRelOids) ? new string[0] : pRelOids.Split(','); var rawGroupOids = string.IsNullOrEmpty(pGroupOids) ? new string[0] : pGroupOids.Split(','); var relOids = new List(); var groups = new List(); rawRelOids.DoForEach(s => relOids.AddIfNotIn(long.Parse(s))); Model.SelectedGroupOfPeopleOids.Clear(); rawGroupOids.DoForEach(s => { var group = Model.GroupsOfPeople.FirstOrDefault(f => f.GroupOfPeopleOid.HasValue && f.GroupOfPeopleOid.Value.Equals(long.Parse(s))); if(group == null) { return; } groups.AddIfNotIn(group); group.SupportConceptList.DoForEach(f => relOids.AddRangeIfElementsNotIn(f.CostBearerRelOids)); }); Model.SelectedSupportConcepts.Clear(); Model.SelectedCostbearerRelOids.Clear(); Model.SelectedCostbearerRelOids.AddRangeIfElementsNotIn(relOids); var selectedSupportConcepts = Model.SupportConcepts.Where(w => w != null && w.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && relOids.Contains(a.CostBearer2SupportConceptOid.Value))).ToList(); var groupCostBearerRelations = CustomerService.GetSupportConceptCostBearerRelationsById(relOids); Model.SelectedConceptCostBearerRelations.Clear(); Model.SelectedConceptCostBearerRelations.AddRangeIfElementsNotIn(groupCostBearerRelations); Model.SelectedSupportConcepts.AddRangeIfElementsNotIn(selectedSupportConcepts); foreach (var gruppe in groups.Where(g => g.GroupOfPeopleOid.HasValue)) { var groupRelOids = new List(); gruppe.SupportConceptList.ForEach(f => groupRelOids.AddRange(f.CostBearerRelOids)); if (!gruppe.GroupOfPeopleOid.HasValue) { continue; } var groupOid = gruppe.GroupOfPeopleOid.Value; if (relOids.ContainsItems(groupRelOids)) { Model.SelectedGroupOfPeopleOids.AddIfNotIn(groupOid); } else if (Model.SelectedGroupOfPeopleOids.Contains(groupOid)) { Model.SelectedGroupOfPeopleOids.Remove(groupOid); } } return SerializeObject(Model.SelectedRelations.ToArray()); } [Authorize] public string RemoveSupportConceptCostBearerRelationFromGroupBooking(string pRelOid) { if(Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } long.TryParse(pRelOid, out var supportConceptCostBearerRelationOid); var supportConcept = Model.SelectedSupportConcepts.FirstOrDefault(f => f.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid == supportConceptCostBearerRelationOid)); var relation = Model.SelectedConceptCostBearerRelations.FirstOrDefault(f => f.CostBearer2SupportConceptOid == supportConceptCostBearerRelationOid); Model.SelectedSupportConcepts.Remove(supportConcept); Model.SelectedConceptCostBearerRelations.Remove(relation); return _LeerzeichenFuerGetMethoden; } [Authorize] public string AddEmployeesToGroupBooking(string pEmployeeOids) { if(Model == null) { RedirectToActionPermanent("Index", "Login"); return _LeerzeichenFuerGetMethoden; } if(string.IsNullOrEmpty(pEmployeeOids)) { Model.SelectedEmployees.Clear(); return _LeerzeichenFuerGetMethoden; } var rawEmployeeOids = pEmployeeOids.Split(','); var oids = new List(); rawEmployeeOids.DoForEach(s => oids.AddIfNotIn(long.Parse(s))); var employees = Model.Employees.Where(w => oids.Contains(w.EmployeeOid)); Model.SelectedEmployees.Clear(); Model.SelectedEmployees.AddRangeIfElementsNotIn(employees); return _LeerzeichenFuerGetMethoden; } [HttpPost] [Authorize] public ActionResult LoadSignatureImage(FormCollection pFormCollection) { if(Model == null) { return RedirectToActionPermanent("Index", "Login"); } var isParsingSuccessful = long.TryParse(pFormCollection["signatureOidHolder"], out var signatureOid); if(isParsingSuccessful) { Model.SignatureImage = OperationsService.GetSignature(signatureOid).DataBild; } return RedirectToActionPermanent("Main"); } [Authorize] public string ResetSignatureImage() { if(Model == null) { return _LeerzeichenFuerGetMethoden; } Model.SignatureImage = null; return _LeerzeichenFuerGetMethoden; } } }