using System; using System.Collections.Generic; using System.Linq; using BeWo.Data; using BeWo.Data.Access; using BeWo.Data.Entities; using BeWo.Data.Utils; using BeWo.Service.DCEntityMapper; using BS.Shared; using BS.Shared.Core; using BS.Shared.DataContracts; using BS.Shared.DataContracts.Compact; using BS.Shared.Extensions; namespace BeWo.Service.Plugins { public class OperationService : AbstractIDSpecificDefaultClass { protected String ReturnMessage { get; set; } protected virtual bool CreateServiceRecordsIfAnyExistInDateRange { get { return false; } } public virtual String CreateDefaultCustomerServiceRecords(DateTime start, DateTime end, IList cb2scOids) { var vs = PluginLoader.FindClass(); ReturnMessage = ""; DateTimeSpan span = new DateTimeSpan(); span.StartDateTime = start; span.EndDateTime = end.AddDays(1).AddTicks(-1); var c2sList = DAOFactory.GenericDAO.LoadByIDs(cb2scOids); foreach (var c2s in c2sList) { var srList = DAOFactory.SearchDAO.FindServiceRecordsInSpan(c2s.Oid.Value, span).ToList(); if (srList.Count == 0 || CreateServiceRecordsIfAnyExistInDateRange) { var newSrList = ErstelleStundenplanEintraege(span.StartDateTime.Date, span.EndDate.Date, c2s, vs, srList); DAOFactory.GenericDAO.Insert(newSrList); OperationService.MakeServiceRecordHistoryEntry(newSrList, newSrList.Select(sr => sr.Oid.Value).ToList(), StatementType.Insert); if (ReturnMessage.Length > 0) { ReturnMessage += "\n"; } ReturnMessage += String.Format("Es wurden {0} Einträge erstellt.", newSrList.Count); } else { if (srList.Count > 1) { ReturnMessage = String.Format("In dem ausgewählten Zeitraum sind bereits {0} Einträge vorhanden, daher können keine weiteren Einträge automatisch erstellt werden.", srList.Count); } else { ReturnMessage = String.Format("In dem ausgewählten Zeitraum ist bereits ein Eintrag vorhanden, daher können keine weiteren Einträge automatisch erstellt werden."); } } } return ReturnMessage; } public virtual List ErstelleStundenplanEintraege(DateTime start, DateTime ende, CostBearer2SupportConcept c2s, VacationService vs, List existingList) { var customer = c2s.SupportConcept.Customer; List serviceRecords = new List(); var defaultSd = GetDefaultServiceDescription(c2s); if (defaultSd == null) { ReturnMessage = "Es konnte keine passende Leistung ermittelt werden."; return serviceRecords; } while (start <= ende) { //var ferien = vs.GetFerien(start, "nrw"); var stundenplan = GetStundenplan(customer, start, start); var ft = vs.GetFeiertag(start); //if (ferien == null && ft == null) if (ft == null && !HatAbwesenheit(start, customer)) { var newServiceRecords = CreateServiceRecords(stundenplan, start, c2s, defaultSd, existingList); serviceRecords.AddRange(newServiceRecords); } start = start.AddDays(1); } return serviceRecords; } private bool HatAbwesenheit(DateTime start, Customer customer) { foreach (var at in customer.AbsenceTimes) { if (at.Start <= start && (!at.End.HasValue || at.End >= start)) { return true; } } return false; } protected virtual IList CreateServiceRecords(Arbeitszeit arbeitszeit, DateTime datum, CostBearer2SupportConcept c2s, ServiceDescription defaultSd, List existingList) { var records = new List(); if (arbeitszeit != null && arbeitszeit.ArbeitszeitEintraege != null) { foreach (var ae in arbeitszeit.ArbeitszeitEintraege) { if (IsSameWeekday(ae, datum.DayOfWeek)) { if (existingList == null || existingList.Count(s => s.Start.Value.Date == datum.Date) == 0) { var sr = CreateServiceRecord(ae, datum, c2s, defaultSd); records.Add(sr); } } } } return records; } public virtual ServiceRecord CreateServiceRecord(ArbeitszeitEintrag ae, DateTime datum, CostBearer2SupportConcept c2s, ServiceDescription defaultSd) { ServiceRecord sr = new ServiceRecord(); sr.Start = GetDateTime(ae.UhrzeitVon, datum); sr.End = GetDateTime(ae.UhrzeitBis, datum); sr.RoundedDuration = (decimal)sr.End.Value.Subtract(sr.Start.Value).TotalMinutes; if (ae.Employee != null) { sr.Employee = ae.Employee; } else { sr.Employee = GetHauptbetreuung(c2s.SupportConcept.Customer, datum); } if (sr.Employee == null) { sr.Employee = LoggedInUserOperationContextExt.Current.User.Employee; } sr.Customer = c2s.SupportConcept.Customer; sr.SupportConcept = c2s.SupportConcept; sr.CostBearer2SupportConcept = c2s; sr.ServiceDescription = defaultSd; sr.ServiceRecordType = ServiceRecordTypeId.DefaultActivity; sr.DistanceInMeter = 0; sr.DurationInStunden = ZeiterfassungsDauer.Minuten; sr.ServiceRecordFormat = ServiceRecordFormate.OriginaleZeiterfassung; sr.Relevance = 0; return sr; } public virtual Employee GetHauptbetreuung(Customer customer, DateTime date) { return customer.Employee2CustomerList.FirstOrDefault(e2c => e2c.IsActive == ActivationTypeId.Active && (!e2c.StartDate.HasValue || e2c.StartDate.Value.Date <= date) && (!e2c.EndDate.HasValue || e2c.EndDate.Value.Date >= date) && e2c.ValueList.Any(b => b.Entry.Type.Equals(ValueListEntryType.StaffRoleType) && b.Entry.SystemEntryID.HasValue && b.Entry.SystemEntryID.Value == SystemEntryID.EmployeeRoleMainAttendant))?.Employee; } public virtual ServiceDescription GetDefaultServiceDescription(CostBearer2SupportConcept c2s) { foreach (var ap in c2s.ApprovalPeriodList) { if (ap.ServiceCategory != null) { var desc = DAOFactory.SearchDAO.FindServiceDescriptionForCategory(ap.ServiceCategory.Oid.Value); var sd = desc.OrderBy(a => a.Position).FirstOrDefault(); if (sd != null) { return sd; } } } return GetDefaultServiceDescription(); } public virtual CheckObjectDeletionResultDC CheckObjectDeletionAllowed(long objectoid, TableID tableId) { var result = new CheckObjectDeletionResultDC(); if (tableId == TableID.ServiceCategory) { result.DeletionAllowed = true; var count = DAOFactory.SearchDAO.GetServiceRecordCountForServiceCategory(objectoid); if (count > 0) { if (count == 1) { result.Message = String.Format("Es existiert ein Eintrag für die gewählte Kategorie. Vorhandene Einträge werden nicht verändert. Möchten Sie die Kategorie wirklich löschen?", count); } else { result.Message = String.Format("Es existieren {0} Einträge für die gewählte Kategorie. Vorhandene Einträge werden nicht verändert. Möchten Sie die Kategorie wirklich löschen?", count); } } } else if (tableId == TableID.ServiceDescription) { result.DeletionAllowed = true; var count = DAOFactory.SearchDAO.GetServiceRecordCountForServiceDescription(objectoid); if (count > 0) { if (count == 1) { result.Message = String.Format("Es existiert ein Eintrag für die gewählte Leistung. Vorhandene Einträge werden nicht verändert. Möchten Sie die Leistung wirklich löschen?", count); } else { result.Message = String.Format("Es existieren {0} Einträge für die gewählte Leistung. Vorhandene Einträge werden nicht verändert. Möchten Sie die Leistung wirklich löschen?", count); } } } return result; } public virtual ServiceDescription GetDefaultServiceDescription() { return null; } private Arbeitszeit GetStundenplan(Customer customer, DateTime start, DateTime ende) { if (customer == null) { return null; } var stundenplan = SucheStundenplan(customer.Arbeitszeiten, start, ende); return stundenplan; } private static Arbeitszeit SucheStundenplan(IList arbeitszeiten, DateTime start, DateTime ende) { if (arbeitszeiten != null && arbeitszeiten.Count > 0) { foreach (var az in arbeitszeiten) { if ((!az.GueltigVon.HasValue || az.GueltigVon <= ende) && (!az.GueltigBis.HasValue || az.GueltigBis >= start)) { return az; } } } return null; } public static bool IsSameWeekday(ArbeitszeitEintrag ae, DayOfWeek day) { if (day == DayOfWeek.Monday && ae.Tag == AppointmentDayOfWeek.Montag) { return true; } if (day == DayOfWeek.Tuesday && ae.Tag == AppointmentDayOfWeek.Dienstag) { return true; } if (day == DayOfWeek.Wednesday && ae.Tag == AppointmentDayOfWeek.Mittwoch) { return true; } if (day == DayOfWeek.Thursday && ae.Tag == AppointmentDayOfWeek.Donnerstag) { return true; } if (day == DayOfWeek.Friday && ae.Tag == AppointmentDayOfWeek.Freitag) { return true; } if (day == DayOfWeek.Saturday && ae.Tag == AppointmentDayOfWeek.Samstag) { return true; } return false; } public static DateTime? GetDateTime(String timeAsString, DateTime date) { String dateStr = String.Format("{0:dd.MM.yyyy} {1}", date, timeAsString); DateTime dateOut; if (DateTime.TryParse(dateStr, out dateOut)) { return dateOut; } return null; } public virtual IList GetTextModulesForSelectedSupportConcept(bool pShouldShowAllTextModules, long pEmployeeOid, bool pHasRightToSeeAllTextModules, bool pIsInAdministrationView, long? cb2scOid) { var list = GetTextModules(pShouldShowAllTextModules, pEmployeeOid, pHasRightToSeeAllTextModules, pIsInAdministrationView); //if (cb2scOid.HasValue) //{ // var cb2Sc = DAOFactory.GenericDAO.LoadByID(cb2scOid.Value); // var vlist = new List // { // ValueListEntryType.SupportConceptGoalCategoryType, // ValueListEntryType.SupportConceptGoalType, // ValueListEntryType.SupportConceptIndividualGoalType, // ValueListEntryType.SupportConceptIndividualGoalCategoryType // }; // var goals = cb2Sc.SupportConcept.ValueList.Where(v => vlist.Contains(v.Entry.Type)).Select(v => v.Entry).ToList(); // if (goals.Count > 0) // { // foreach (var tb in list) // { // if (tb.Parent != null) // { // tb.Parent.Name = String.Format(" {0}", tb.Parent.Name); // } // } // var allMainGoals = DAOFactory.SearchDAO.FindValueListEntries(new List() { ValueListEntryType.SupportConceptGoalCategoryType, ValueListEntryType.SupportConceptGoalType }); // Dictionary dict = new Dictionary(); // foreach (var item in allMainGoals) // { // dict.Add(item.Oid.Value, item); // } // foreach (var item in goals) // { // if (!dict.ContainsKey(item.Oid.Value)) // { // dict.Add(item.Oid.Value, item); // } // } // var zielKategorie = new TextModuleDC(); // zielKategorie.Name = "Ziele"; // zielKategorie.TextModuleOid = 1000000; // zielKategorie.IsParent = true; // list.Add(zielKategorie); // var entryOid2TextbausteinDict = new Dictionary(); // long oid = 1000001; // foreach (var item in goals) // { // var path = new List(); // path.Add(item); // var parentpath = GetAllParentGoalCategoies(dict, item); // path.AddRange(parentpath); // //Der Pfad enthält den Gesamten Pfad vom Kind zum Obersten Vater Knoten und muss rückwärts durchlaufen werden // for (int i = path.Count - 1; i >= 0; i--) // { // var ziel = path[i]; // if (!entryOid2TextbausteinDict.ContainsKey(ziel.Oid.Value)) // { // TextModuleDC tm = new TextModuleDC(); // tm.Text = ziel.Value; // tm.Name = ziel.Value; // tm.TextModuleOid = oid++; // if (ziel.ParentOid.HasValue && entryOid2TextbausteinDict.ContainsKey(ziel.ParentOid.Value)) // { // var parent = entryOid2TextbausteinDict[ziel.ParentOid.Value]; // parent.IsParent = true; // tm.Parent = parent; // } // else // { // //an die oberste Kategorie hängen // tm.Parent = zielKategorie; // } // entryOid2TextbausteinDict.Add(ziel.Oid.Value, tm); // list.Add(tm); // } // } // } // } //} return list; } private static List GetAllParentGoalCategoies(Dictionary goalCategoryDict, ValueListEntry goal) { var path = new List(); if (goal.ParentOid.HasValue && goalCategoryDict.ContainsKey(goal.ParentOid.Value)) { var parentCat = goalCategoryDict[goal.ParentOid.Value]; while (parentCat != null) { path.Add(parentCat); if (parentCat.ParentOid.HasValue && goalCategoryDict.ContainsKey(parentCat.ParentOid.Value)) { parentCat = goalCategoryDict[parentCat.ParentOid.Value]; } else { parentCat = null; } } } return path; } public virtual IList GetTextModules(bool pShouldShowAllTextModules, long pEmployeeOid, bool pHasRightToSeeAllTextModules, bool pIsInAdministrationView) { var textmodules = DAOFactory.SearchDAO.GetActiveTextModules(pShouldShowAllTextModules, pHasRightToSeeAllTextModules, pIsInAdministrationView, pEmployeeOid); var abc = textmodules.FirstOrDefault(f => f.Oid == 41); var isActive = abc?.IsActive; var list = MapperFactory.TextModuleDC_TextModule.CreateDcList(textmodules); var abcDC = list.FirstOrDefault(f => f.TextModuleOid == 41); var activationType = abcDC?.ActivationType; return list.OrderBy(t => t.Name).ToList(); } // ToDo: Unterschriftenbemerkung hier einbauen public static void MakeServiceRecordHistoryEntry(List lOriginals, IEnumerable serviceRecordOidList, StatementType statementType) { var serviceRecordHistoryEntries = new List(); if (statementType.Equals(StatementType.Insert) && serviceRecordOidList != null) { var iterator = 0; foreach (var history in lOriginals.Select(serviceRecordOriginal => new ServiceRecordHistory { TimeStamp = DateTime.Now, ChangeType = statementType, CostBearer2SupportConcept = serviceRecordOriginal.CostBearer2SupportConcept, CostBearer2SupportConceptOid = serviceRecordOriginal.CostBearer2SupportConceptOid, Customer = serviceRecordOriginal.Customer, CustomerOid = serviceRecordOriginal.CustomerOid, Employee = serviceRecordOriginal.Employee, EmployeeOid = serviceRecordOriginal.EmployeeOid, End = serviceRecordOriginal.End, Group = serviceRecordOriginal.Group, GroupEmployeeCount = serviceRecordOriginal.GroupEmployeeCount, GroupOid = serviceRecordOriginal.GroupOid, GroupPersonCount = serviceRecordOriginal.GroupPersonCount, GroupRoundedDuration = serviceRecordOriginal.GroupRoundedDuration, IP = serviceRecordOriginal.IP, IsActive = serviceRecordOriginal.IsActive, Notice = serviceRecordOriginal.Notice, ServiceRecordOid = serviceRecordOidList.ElementAt(iterator), RoundedDuration = serviceRecordOriginal.RoundedDuration, ServiceDescription = serviceRecordOriginal.ServiceDescription, ServiceRecordType = serviceRecordOriginal.ServiceRecordType, ServiceRecordInsTs = serviceRecordOriginal.InsTs, ServiceRecordVersion = serviceRecordOriginal.Version ?? 0, ServiceRecordInsUser = serviceRecordOriginal.InsUser, ServiceRecordUdpUser = serviceRecordOriginal.UdpUser, Start = serviceRecordOriginal.Start, SupportConcept = serviceRecordOriginal.SupportConcept, SystemEntryID = serviceRecordOriginal.SystemEntryID, DistanceInMeter = serviceRecordOriginal.DistanceInMeter, IsCreatedInMobileClient = serviceRecordOriginal.IsCreatedInMobileClient })) { iterator++; serviceRecordHistoryEntries.Add(history); } } else { foreach (var original in lOriginals) { SignatureStateInfoFromServiceRecordHistoryEntry previousRecordHistorySignatureInfo = null; if (original.Oid.HasValue) { previousRecordHistorySignatureInfo = DAOFactory.SearchDAO.FindMostRecentSignatureStatusInfoByServiceRecordOid(original.Oid.Value); } serviceRecordHistoryEntries.AddIfNotIn(new ServiceRecordHistory { TimeStamp = DateTime.Now, ChangeType = statementType, CostBearer2SupportConcept = original.CostBearer2SupportConcept, CostBearer2SupportConceptOid = original.CostBearer2SupportConceptOid, Customer = original.Customer, CustomerOid = original.CustomerOid, Employee = original.Employee, EmployeeOid = original.EmployeeOid, End = original.End, Group = original.Group, GroupEmployeeCount = original.GroupEmployeeCount, GroupOid = original.GroupOid, GroupPersonCount = original.GroupPersonCount, GroupRoundedDuration = original.GroupRoundedDuration, IP = original.IP, IsActive = original.IsActive, Notice = original.Notice, ServiceRecordOid = original.Oid, RoundedDuration = original.RoundedDuration, ServiceDescription = original.ServiceDescription, ServiceRecordType = original.ServiceRecordType, ServiceRecordInsTs = original.InsTs, ServiceRecordVersion = original.Version ?? 0, ServiceRecordInsUser = original.InsUser, ServiceRecordUdpUser = original.UdpUser, Start = original.Start, SupportConcept = original.SupportConcept, SystemEntryID = original.SystemEntryID, DistanceInMeter = original.DistanceInMeter, IsCreatedInMobileClient = original.IsCreatedInMobileClient, ServiceRecordSignatureStateType = previousRecordHistorySignatureInfo?.ServiceRecordSignatureStateType ?? SignatureStateType.None, CustomerConfirmationReceiptSignatureStateType = previousRecordHistorySignatureInfo?.CustomerConfirmationReceiptSignatureStateType ?? SignatureStateType.None, EmployeeConfirmationReceiptSignatureStateType = previousRecordHistorySignatureInfo?.EmployeeConfirmationReceiptSignatureStateType ?? SignatureStateType.None, CustomerConfirmationReceiptSignatureOid = previousRecordHistorySignatureInfo?.CustomerConfirmationReceiptSignatureOid, EmployeeConfirmationReceiptSignatureOid = previousRecordHistorySignatureInfo?.EmployeeConfirmationReceiptSignatureOid }); } } DAOFactory.GenericDAO.Insert(serviceRecordHistoryEntries); } } }