using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceModel; using System.Xml; using System.Xml.Linq; using BeWo.Data; using BeWo.Data.Access; using BeWo.Data.Entities; using BeWo.Service.Core; using BeWo.Service.DCEntityMapper; using BeWo.Service.Plugins; using BeWo.Service.ServiceContracts; using BeWo.View.Navigation.Filter; using BS.Shared; using BS.Shared.Core; using BS.Shared.DataContracts; using BS.Shared.DataContracts.Compact; using BS.Shared.Extensions; using DevExpress.Utils; using DevExpress.XtraScheduler; using static System.String; using Resource = BeWo.Data.Entities.Resource; using Utils = BeWo.Service.Core.Utils; using SUtils = BS.Shared.Core.Utils; namespace BeWo.Service.ServiceImplementations { [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)] public class ResourceServiceImp : IResourceService { public void DeactivateResource(long pOid, long pVersion) { try { ServiceLogic.SetActivationType(new Dictionary { { pOid, pVersion } }, ActivationTypeId.Deleted); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeactivateResources(Dictionary pOid2Version) { try { ServiceLogic.SetActivationType(pOid2Version, ActivationTypeId.Deleted); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteBooking(long pOid, long pVersion) { try { this.DeleteBookings(new Dictionary { { pOid, pVersion } }); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteBookings(Dictionary pOid2Version) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pOid2Version.Select(e => e.Key)); lOriginals.DoForEach(or => MapperFactory.BookingSequenceDC_ResourceBookingSequence.ConcurrencyCheck(pOid2Version[or.Oid.Value], or)); DAOFactory.GenericDAO.Delete(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteResource(long pOid, long pVersion) { try { this.DeleteResources(new Dictionary { { pOid, pVersion } }); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteResources(Dictionary pOid2Version) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pOid2Version.Select(e => e.Key)); lOriginals.DoForEach(or => MapperFactory.ResourceDC_Resource.ConcurrencyCheck(pOid2Version[or.Oid.Value], or)); DAOFactory.GenericDAO.Delete(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } //private static bool inProgress = false; public List GetAllBookings(DateTime pStartSpan, DateTime pEndSpan) { try { var t = DAOFactory.SearchDAO.FindBookings(pStartSpan, pEndSpan); //### Kalender //if (!inProgress && MultitenancyOperationContextExt.Current != null && pStartSpan.Month == 4 && pStartSpan.Day == 8 && pStartSpan.Year == 2025) //{ // var tenant = MultitenancyOperationContextExt.Current.Tenant; // if (tenant == "5653806613") // { // inProgress = true; // ConvertResourceBookingsToResourceAppointments(); // } //} return MapperFactory.BookingSequenceDC_ResourceBookingSequence.MapToNewDCs(t); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllBookingsByResource(long pResourceOid, DateTime pStartSpan, DateTime pEndSpan) { try { var t = DAOFactory.SearchDAO.FindBookings(pResourceOid, pStartSpan, pEndSpan); return MapperFactory.BookingSequenceDC_ResourceBookingSequence.MapToNewDCs(t); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllResources() { try { return MapperFactory.ResourceDC_Resource.MapToNewDCs(DAOFactory.GenericDAO.GetAllActive()); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List InsertNewBookings(List pBookings) { try { var lEntities = MapperFactory.BookingSequenceDC_ResourceBookingSequence.MapToNewEntities(pBookings); DAOFactory.GenericDAO.Insert(lEntities); return lEntities.Select(e => e.Oid.Value).ToList(); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List InsertNewBookingSequenceDCs(IEnumerable pBookings) { try { var lEntities = MapperFactory.BookingSequenceDC_ResourceBookingSequence.MapToNewEntities(pBookings); DAOFactory.GenericDAO.Insert(lEntities); return MapperFactory.BookingSequenceDC_ResourceBookingSequence.MapToNewDCs(lEntities); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List InsertNewResources(List pResources) { try { List lResources = MapperFactory.ResourceDC_Resource.MapToNewEntities(pResources); DAOFactory.GenericDAO.Insert(lResources); return lResources.Select(r => r.Oid.Value).ToList(); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateBookings(List pBookings) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pBookings.Select(b => b.SequenceOid.Value)); MapperFactory.BookingSequenceDC_ResourceBookingSequence.MergeWithEntitys(pBookings, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); return lOriginals.Select(b => b.Oid.Value).ToList(); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateBookingSequenceDCs(List pBookings) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pBookings.Select(b => b.SequenceOid.Value)); MapperFactory.BookingSequenceDC_ResourceBookingSequence.MergeWithEntitys(pBookings, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); return MapperFactory.BookingSequenceDC_ResourceBookingSequence.MapToNewDCs(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateResourceDCs(List pResource) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pResource.Select(b => b.ResourceOid.Value)); MapperFactory.ResourceDC_Resource.MergeWithEntitys(pResource, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); return MapperFactory.ResourceDC_Resource.MapToNewDCs(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateResources(List pResource) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pResource.Select(b => b.ResourceOid.Value)); MapperFactory.ResourceDC_Resource.MergeWithEntitys(pResource, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); return lOriginals.Select(b => b.Oid.Value).ToList(); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateResourceAppointments(List pResourceAppointments) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pResourceAppointments.Select(b => b.ResourceAppointmentOid.Value)); MapperFactory.ResourceAppointmentDC_ResourceAppointment.MergeWithEntitys(pResourceAppointments, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); return MapperFactory.ResourceAppointmentDC_ResourceAppointment.MapToNewDCs(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List InsertNewResourceAppointments(IEnumerable pResourceAppointments) { try { var lResources = MapperFactory.ResourceAppointmentDC_ResourceAppointment.MapToNewEntities(pResourceAppointments); DAOFactory.GenericDAO.Insert(lResources); return MapperFactory.ResourceAppointmentDC_ResourceAppointment.MapToNewDCs(lResources); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteResourceAppointments(Dictionary pOid2Version) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pOid2Version.Select(e => e.Key)); lOriginals.DoForEach(or => MapperFactory.ResourceAppointmentDC_ResourceAppointment.ConcurrencyCheck(pOid2Version[or.Oid.Value], or)); DAOFactory.GenericDAO.Delete(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } /// /// Konvertiert ResourceBookings in Termine. Dabei werden nur Buchungen aus der Datenbank geladen, deren Oid noch nicht mit einem NewSchedulerAppointment-Objekt verknpüpft ist. /// public void ConvertResourceBookingsToResourceAppointments() { try { return; //const string selectQuery = "SELECT Oid, ResourceBookingSequenceOid FROM resourcebooking WHERE startdatetime >= '2020-02-01' AND IsActive = 1 AND IsDeleted = 0"; //const string selectQuery = "SELECT Oid, ResourceBookingSequenceOid FROM resourcebooking WHERE startdatetime >= '2022-12-01' AND IsActive = 1 AND IsDeleted = 0"; const string selectQuery = "SELECT Oid, ResourceBookingSequenceOid FROM resourcebooking WHERE IsActive = 1 AND IsDeleted = 0 AND Oid NOT IN (SELECT FormerBookingSequenceOid FROM newschedulerappointment WHERE FormerBookingSequenceOid IS NOT NULL)"; var dataSet = DAOFactory.AdoDAO.ExecuteQuery(selectQuery); var dataReader = dataSet.CreateDataReader(); var resourceBookingSequence2ResourceBookings = new Dictionary>(); var newSchedulerAppointments = new List(); var sequence2booking = new Dictionary>(); var allResourceBookings = DAOFactory.GenericDAO.GetAllActive(); while(dataReader.Read()) { resourceBookingSequence2ResourceBookings.AddOrUpdateValueInDictionary((long) dataReader.GetValue(0), new List {(long) dataReader.GetValue(1)}); } if(allResourceBookings.Count == 0) { return; } allResourceBookings = allResourceBookings.OrderBy(o => o.Oid).ToList(); foreach(var resourceBooking in allResourceBookings) { if(resourceBooking.Oid is null) { continue; } if(resourceBookingSequence2ResourceBookings.ContainsKey(resourceBooking.Oid.Value)) { if(!sequence2booking.ContainsKey(resourceBooking.Sequence)) { sequence2booking.Add(resourceBooking.Sequence, new List {resourceBooking}); } else { sequence2booking[resourceBooking.Sequence].Add(resourceBooking); } } } foreach(var kvp in sequence2booking) { var sequence = kvp.Key; var frequencyType = sequence.FrequencyType; foreach(var booking in kvp.Value) { var originator = DAOFactory.SearchDAO.FindEmployeeByFullname(booking.InsUser) ?? booking.Employee; if(booking.Sequence.FrequencyType.Equals(ResourceBookingFrequencyType.MonthlyOnLastDay)) { var singleBookings = ConvertType6ResourceAppointment(booking); newSchedulerAppointments.AddRange(singleBookings); continue; } // Nur, wenn der Originator ein anderer ist als der verknüpfte Mitarbeiter. var employeeList = new List(); if(!(booking.Employee is null) && !booking.Employee.Equals(originator)) { employeeList.Add(new Employee2SchedulerAppointmentDC { Employee = MapperFactory.CompactEmployeeDC_Employee.MapToNewDC(booking.Employee), ParticipationAnswer = ParticipationAnswer.Zusage, IsPC_CheckedTs = null, IsPChanged = false }); } var resourceList = new List{ MapperFactory.ResourceDC_Resource.MapToNewDC(booking.Sequence.Resource) }; var newSchedulerAppointment = new SchedulerAppointmentDC { ActivationType = ActivationTypeId.Active, AllDay = booking.Start.Equals(booking.End), CustomerList = new List(), Description = booking.Notice, EmployeeList = employeeList, EndDate = booking.End, StartDate = booking.Start, IsPrivate = false, ResourceList = resourceList, Subject = booking.Notice, Originator = MapperFactory.CompactEmployeeDC_Employee.MapToNewDC(originator), Type = 0, FormerBookingSequenceOid = booking.Sequence.Oid, ServiceRecordList = new List(), SupportConceptList = new List() }; if(kvp.Value.Count > 1 && booking.SequencePosition > 0) { newSchedulerAppointment.Type = booking.IsDeleted ? 4 : 3; } else if(frequencyType != ResourceBookingFrequencyType.Once) { newSchedulerAppointment.Type = 1; } if(!booking.Sequence.FrequencyType.Equals(ResourceBookingFrequencyType.Once)) { newSchedulerAppointment.RecurrenceInfo = CreateRecurrenceInfo(booking).ToXml(); } if(newSchedulerAppointments.FirstOrDefault(f => f.FormerBookingSequenceOid.Equals(sequence.Oid)) != null) { var recurrenceInfo = newSchedulerAppointments.First(f => f.FormerBookingSequenceOid.Equals(sequence.Oid) && f.RecurrenceInfo != null).RecurrenceInfo; using(var reader = XmlReader.Create(new StringReader(recurrenceInfo))) { reader.ReadToFollowing("RecurrenceInfo"); reader.MoveToAttribute("Id"); var id = reader.Value; var doc = XDocument.Load(new StringReader(newSchedulerAppointment.RecurrenceInfo)); var xElement = doc.Element("RecurrenceInfo"); if(xElement != null) { xElement.RemoveAttributes(); xElement.Add(new XAttribute("Id", id)); xElement.Add(new XAttribute("Index", booking.SequencePosition)); } newSchedulerAppointment.RecurrenceInfo = doc.ToString(); } } newSchedulerAppointments.Add(newSchedulerAppointment); } } InsertSchedulerAppointments(newSchedulerAppointments); } catch(Exception ex) { throw Utils.CreateBeWoFaultException(ex); } } private static RecurrenceInfo CreateRecurrenceInfo(ResourceBooking booking) { var sequence = booking.Sequence; var recInfo = new RecurrenceInfo {Range = RecurrenceRange.EndByDate}; DateTime? datum = null; // Rekonstruktion der gelöschten Zeiten (der neue Termin wird sonst nicht als gelöscht angezeigt) if(booking.Start is null) { var firstBooking = DAOFactory.SearchDAO.GetFirstResourceBookingFromSequence(sequence.Oid.Value); var sequenceStartDate = firstBooking.Start.Value; // Täglich if(sequence.FrequencyType.Equals(ResourceBookingFrequencyType.Daily)) { datum = sequenceStartDate.AddDays(sequence.RepeatInterval * booking.SequencePosition); } // Wöchentlich if(sequence.FrequencyType.Equals(ResourceBookingFrequencyType.Weekly)) { datum = sequenceStartDate.AddDays(sequenceStartDate.Day + 7 * sequence.RepeatInterval * booking.SequencePosition); } // Monatlich if(sequence.FrequencyType.Equals(ResourceBookingFrequencyType.Monthly)) { datum = sequenceStartDate.AddMonths(sequence.RepeatInterval*booking.SequencePosition); } // X. Wochentag des Monats if(sequence.FrequencyType.Equals(ResourceBookingFrequencyType.MonthlyOnFirstDay)) { datum = sequenceStartDate.AddMonthsDayDependent(sequence.RepeatInterval*booking.SequencePosition, true); } booking.Start = datum; if(datum.HasValue && firstBooking.End.HasValue) { booking.End = booking.Start.Value.AddMinutes((firstBooking.End.Value - firstBooking.Start.Value).TotalMinutes); } } if(booking.Start != null) { recInfo.Start = booking.Start.Value; } if(sequence.SequenceEnd != null) { recInfo.End = sequence.SequenceEnd.Value; } if(sequence.RepeatInterval > 1) { recInfo.Periodicity = sequence.RepeatInterval; } switch(booking.Sequence.FrequencyType) { case ResourceBookingFrequencyType.Daily: recInfo.OccurrenceCount = ((recInfo.End - recInfo.Start).Days + 1) / booking.Sequence.RepeatInterval; recInfo.Type = RecurrenceType.Daily; break; case ResourceBookingFrequencyType.Weekly: recInfo.OccurrenceCount = ((recInfo.End - recInfo.Start).Days / 7 + 1) / booking.Sequence.RepeatInterval; recInfo.Type = RecurrenceType.Weekly; recInfo.WeekDays = GetWeekDay(recInfo.Start.DayOfWeek.ToString()); break; case ResourceBookingFrequencyType.Monthly: recInfo.Type = RecurrenceType.Monthly; recInfo.OccurrenceCount = ((recInfo.End - recInfo.Start).Days / 30 + 1) / booking.Sequence.RepeatInterval; recInfo.WeekDays = GetWeekDay(recInfo.Start.DayOfWeek.ToString()); recInfo.DayNumber = recInfo.Start.Day; recInfo.WeekOfMonth = WeekOfMonth.None; break; case ResourceBookingFrequencyType.MonthlyOnFirstDay: recInfo.Type = RecurrenceType.Monthly; recInfo.OccurrenceCount = ((recInfo.End - recInfo.Start).Days / 30 + 1) / booking.Sequence.RepeatInterval; recInfo.WeekDays = GetWeekDay(recInfo.Start.DayOfWeek.ToString()); recInfo.WeekOfMonth = recInfo.Start.GetWeekOfMonth(DayOfWeek.Sunday); break; } return recInfo; } private static IEnumerable ConvertType6ResourceAppointment(ResourceBooking booking) { var sequence = booking.Sequence; if (sequence.Oid == null) return null; var firstBooking = DAOFactory.SearchDAO.GetFirstResourceBookingFromSequence(sequence.Oid.Value); if (firstBooking.Start == null || firstBooking.End == null || sequence.SequenceEnd == null) return null; // X. Letzten Wochentag im Monat berechnen für den gesamten Zeitraum (Typ 3 und 4 beachten, oder nicht?) var duration = (firstBooking.End.Value - firstBooking.Start.Value).TotalMinutes; var newDates = new List{firstBooking.Start.Value}; newDates.AddRange(CalculateLastXInMonthDates(DAOFactory.SearchDAO.GetExcludedBookingSequencePositions(sequence.Oid.Value), firstBooking.Start.Value, sequence)); var employee = MapperFactory.CompactEmployeeDC_Employee.MapToNewDC(booking.Employee); var employeeList = new List(); if (booking.Employee != null) employeeList.Add(new Employee2SchedulerAppointmentDC { Employee = employee, ParticipationAnswer = ParticipationAnswer.Zusage, IsPC_CheckedTs = null, IsPChanged = false }); var resourceList = new List { MapperFactory.ResourceDC_Resource.MapToNewDC(booking.Sequence.Resource) }; return newDates.Select(date => new SchedulerAppointmentDC { AllDay = false, CustomerList = new List(), Description = firstBooking.Notice, EmployeeList = employeeList, EndDate = date.AddMinutes(duration), FormerBookingSequenceOid = firstBooking.Sequence.Oid, IsPrivate = false, Originator = employee, ResourceList = resourceList, StartDate = date, Subject = firstBooking.Notice, Type = 0 }).ToList(); } private static IEnumerable CalculateLastXInMonthDates(ICollection excludedBookingSequencePositions, DateTime pSequenceStart, ResourceBookingSequence pSequence) { // bearbeitete und gelöschte Termine nicht beachten var result = new List(); var lCurrentPosition = 0; var lCurrentSequencePosition = 1; var lCurrentStart = pSequenceStart.AddMonthsDayDependent(1, false); while (lCurrentStart <= pSequence.SequenceEnd) { lCurrentPosition++; if (lCurrentPosition % pSequence.RepeatInterval == 0 && !excludedBookingSequencePositions.Contains(lCurrentSequencePosition)) { result.Add(lCurrentStart); lCurrentSequencePosition++; } lCurrentStart = lCurrentStart.AddMonthsDayDependent(1, false); } return result; } private static WeekDays GetWeekDay(string name) { switch (name) { case "Sunday": return WeekDays.Sunday; case "Monday": return WeekDays.Monday; case "Tuesday": return WeekDays.Thursday; case "Wednesday": return WeekDays.Wednesday; case "Thursday": return WeekDays.Thursday; case "Friday": return WeekDays.Friday; case "Saturday": return WeekDays.Saturday; default: return WeekDays.Sunday; } } public List GetAllResourceAppointments() { try { var lResources = DAOFactory.GenericDAO.GetAll(); return MapperFactory.ResourceAppointmentDC_ResourceAppointment.MapToNewDCs(lResources); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllSchedulerAppointments() { try { var lSchedulerAppointments = DAOFactory.GenericDAO.GetAll(); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(lSchedulerAppointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllActiveSchedulerAppointments() { try { var lSchedulerAppointments = DAOFactory.GenericDAO.GetAllActive(); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(lSchedulerAppointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteSchedulerAppointments(Dictionary pOid2Version) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pOid2Version.Select(n => n.Key)); lOriginals.DoForEach(on => MapperFactory.SchedulerAppointmentDCSchedulerAppointment.ConcurrencyCheck(pOid2Version[on.Oid.Value], on)); DAOFactory.GenericDAO.Delete(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List InsertSchedulerAppointments(IList pSchedulerAppointments) { try { foreach(var item in pSchedulerAppointments) { try { item.EmployeeList?.ForEach(each => { each.Employee2SchedulerAppointmentOid = null; each.Employee2SchedulerAppointmentVersion = null; each.SchedulerAppointmentOid = null; each.IsPChanged = false; each.IsPC_CheckedTs = null; }); var lRelations = MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewEntities(item.EmployeeList); DAOFactory.GenericDAO.Insert(lRelations); var neu = MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewDCs(lRelations); item.EmployeeList = neu; } catch (Exception exception) { throw Utils.CreateBeWoFaultException(exception); } } var lAppointments = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewEntities(pSchedulerAppointments); DAOFactory.GenericDAO.Insert(lAppointments); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(lAppointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateSchedulerAppointments(List pSchedulerAppointments) { try { if (pSchedulerAppointments.Any(p => p.SchedulerAppointmentOid == null)) { return new List(); } var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pSchedulerAppointments.Select(b => b.SchedulerAppointmentOid.Value)); var allegleich = true; // Termine mit Oid, die also nicht neu sind, und die in den Originalen mit RecurrenceInfo enthalten sind. Was, wenn die RecurrenceInfo auf null gesetzt wurde? var test = pSchedulerAppointments.Where(w => w.SchedulerAppointmentOid.HasValue && lOriginals.Any(a => a.Oid.HasValue && a.Oid.Value == w.SchedulerAppointmentOid.Value && a.RecurrenceInfo != null && w.RecurrenceInfo == null)).ToList(); // Wenn das Objekt aus der Datenbank vom Typ 1 ist und der Termin, der geupdated werden soll, vom Typ 0 ist, dann wurde der Serientermin in einen normalen geändert. // lOriginals und pSchedulerappointments haben dann nur einen Eintrag var originalsCount = lOriginals.Count(); var schedulerAppointmentsCount = pSchedulerAppointments.Count(); var shouldUpdateExceptions = true; SchedulerAppointment rootAppointmentToDelete = null; if(originalsCount == 1 && schedulerAppointmentsCount == 1) { var originalAppointment = lOriginals.First(); var updatedAppointment = pSchedulerAppointments.First(); if(originalAppointment.RecurrenceInfo != null && updatedAppointment.RecurrenceInfo == null && originalAppointment.Type == 1 && updatedAppointment.Type == 0) { shouldUpdateExceptions = false; var guid = originalAppointment.GetRecurrenceId(); if(guid != null && DAOFactory.SearchDAO.FindIndexZeroChangedOccurrence(guid) != null) { rootAppointmentToDelete = DAOFactory.SearchDAO.FindRootAppointmentByRecurrenceId(guid.ToString()); } } } if(test.Count > 0 && shouldUpdateExceptions) { var originalAppointments = lOriginals.Where(w => w.Oid.HasValue && test.Select(s => s.SchedulerAppointmentOid.Value).Contains(w.Oid.Value)).ToList(); foreach(var modifiedException in test) { var original = originalAppointments.FirstOrDefault(f => f.Oid.Value == modifiedException.SchedulerAppointmentOid.Value); if(original == null) { continue; } if(modifiedException.Type != 4) { modifiedException.Type = original.Type; } modifiedException.RecurrenceInfo = original.RecurrenceInfo; } } // Die geänderten Anwesenheiten updaten und die entfernten löschen foreach (var item in pSchedulerAppointments) { allegleich = false; var lNewRelations = MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewEntities(item.EmployeeList.Where(e2a => e2a.Employee2SchedulerAppointmentOid == null)); var lOldRelations = MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewDCs(DAOFactory.GenericDAO.LoadByIDs(item.EmployeeList.Where(w => w.Employee2SchedulerAppointmentOid != null).ToList().Select(s => s.Employee2SchedulerAppointmentOid.Value))); var geaenderte = new List(); foreach (var i in lOldRelations) { geaenderte.AddRange(item.EmployeeList.Where(o => o.Employee2SchedulerAppointmentOid == i.Employee2SchedulerAppointmentOid && (o.Employee2SchedulerAppointmentVersion != i.Employee2SchedulerAppointmentVersion || o.ParticipationAnswer != i.ParticipationAnswer || o.IsPChanged != i.IsPChanged) && !geaenderte.Contains(o))); } geaenderte = UpdateEmployee2SchedulerAppointments(geaenderte); var geloeschte = DAOFactory.SearchDAO.GetRemovedEmp2AppObjectsBySchAppOid(item.SchedulerAppointmentOid.Value).Where(g => !item.EmployeeList.Select(s => s.Employee2SchedulerAppointmentOid).Contains(g.Oid)); DAOFactory.GenericDAO.Delete(geloeschte); DAOFactory.GenericDAO.Insert(lNewRelations); var neu = MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewDCs(lNewRelations); var alt = item.EmployeeList.Where(e2a => e2a.Employee2SchedulerAppointmentOid != null && !geaenderte.Contains(e2a)).ToList(); alt.AddRange(neu); alt.AddRange(geaenderte); item.EmployeeList = alt; } if (allegleich) { return pSchedulerAppointments; } MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MergeWithEntitys(pSchedulerAppointments, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); // Default-Root-Termin löschen, falls eine Ausnahme an der Stelle sein sollte. if(rootAppointmentToDelete != null) { DAOFactory.GenericDAO.Delete(rootAppointmentToDelete); } rootAppointmentToDelete = null; return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetResourceAppointmentsById(IEnumerable pOids) { try { var lAppointments = DAOFactory.GenericDAO.LoadByIDs(pOids); return MapperFactory.ResourceAppointmentDC_ResourceAppointment.MapToNewDCs(lAppointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List LoadPossibleDuplicates(string pRecurrenceInfo) { try { var possibleDuplicates = DAOFactory.SearchDAO.GetResourceAppointmentExceptionsWithIndexAndId(pRecurrenceInfo); return MapperFactory.ResourceAppointmentDC_ResourceAppointment.MapToNewDCs(possibleDuplicates); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetSchedulerAppointmentsById(IEnumerable pOids) { try { var lSchedulerAppointments = DAOFactory.GenericDAO.LoadByIDs(pOids); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(lSchedulerAppointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public SchedulerAppointmentDC GetSchedulerAppointmentByid(long oid) { try { var lSchedulerAppointments = DAOFactory.GenericDAO.GetByID(oid); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDC(lSchedulerAppointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeactivateSchedulerAppointments(Dictionary pOid2Version) { try { foreach (var kvp in pOid2Version) { ServiceLogic.SetActivationType(new Dictionary { { kvp.Key, kvp.Value } }, ActivationTypeId.Deleted); } } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List DeactivateSchedulerAppointmentsForSync(Dictionary pOid2Version) { try { /* * Type: * 0: Normal * 1: Pattern * 2: Occurence * 3: ChangedOccurence * 4: DeletedOccurence */ var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pOid2Version.Keys); if(lOriginals.Count > 0 && lOriginals.Any(a => a.Type == 3 && a.Oid.HasValue && pOid2Version.Keys.Contains(a.Oid.Value))) { // Bearbeitete Serientermine werden auf "gelöscht" gesetzt var originalsToUpdate = lOriginals.Where(w => w.Type == 3 && w.Oid.HasValue && pOid2Version.Keys.Contains(w.Oid.Value)).ToList(); foreach(var original in originalsToUpdate) { original.Type = 4; } DAOFactory.GenericDAO.Update(originalsToUpdate); var updatedAppointments = DAOFactory.GenericDAO.LoadByIDs(originalsToUpdate.Select(s => s.Oid.Value)); foreach(var appointment in updatedAppointments) { // Die auf "gelöscht" gesetzten, bearbeiteten Serientermine werden aus dem Dictionary entfernt if(appointment.Oid.HasValue && appointment.Version.HasValue && pOid2Version.ContainsKey(appointment.Oid.Value)) { pOid2Version.Remove(appointment.Oid.Value); } } } // Geänderte Serientermine werden anhand der RecurrenceId aus der Datenbank geladen und der Typ auf "gelöscht" gesetzt //CB: Nur von Type = 1 also Root prüfen foreach (var org in lOriginals) { if (org.Type == 1) { List appointments = new List(); appointments.Add(org); var recurrenceIds = Utils.ExtractRecurrenceIdFromRecurrenceString(appointments); if (recurrenceIds.Count > 0) { var exceptionsToDelete = DAOFactory.SearchDAO.FindAppointmentsByRecurrenceId(recurrenceIds); exceptionsToDelete.DoForEach(exception => { if (exception.Oid != null && exception.Version != null) { pOid2Version.AddIfNotIn(new KeyValuePair(exception.Oid.Value, exception.Version.Value)); } }); } } } foreach (var kvp in pOid2Version) { ServiceLogic.SetActivationType(new Dictionary { { kvp.Key, kvp.Value } }, ActivationTypeId.Deleted); } return GetSchedulerAppointmentsById(pOid2Version.Keys); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public Dictionary> GetAllCategories2ResourcesInDictionary() { try { var lOriginals = DAOFactory.GenericDAO.GetAllActive(); lOriginals = lOriginals.Where(resource => { return resource.ValueList.All(valueListEntry2Object => valueListEntry2Object.Entry.IsActive.Equals(ActivationTypeId.Active)); }).ToList(); var ressourcen = MapperFactory.ResourceDC_Resource.MapToNewDCs(lOriginals); return ressourcen.Select(res => res.ResourceCategory) .Distinct() .OrderBy(cat => cat.TypeDescription) .Select( cat => new { Key = cat, Value = ressourcen.Where(res => res.ResourceCategory.Equals(cat)).OrderBy(res => res.Name).ToList() }).ToDictionary(a => a.Key, a => a.Value); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllOpenAppointmentsForEmployee(long pEmployeeOid) { try { var offeneTermine = DAOFactory.SearchDAO.GetAllOpenAppointmentsForEmployee(pEmployeeOid); offeneTermine.AddRange(DAOFactory.SearchDAO.GetAllParticipationNotificationsForEmployee(pEmployeeOid)); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(offeneTermine); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List InsertEmployee2SchedulerAppointments(IEnumerable pEmployee2SchedulerAppointments) { try { var lRelations = MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewEntities(pEmployee2SchedulerAppointments); DAOFactory.GenericDAO.Insert(lRelations); return MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewDCs(lRelations); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List UpdateEmployee2SchedulerAppointments(List pEmployee2SchedulerAppointments) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pEmployee2SchedulerAppointments.Select(b => b.Employee2SchedulerAppointmentOid.Value)); foreach (var item in pEmployee2SchedulerAppointments) item.IsPChanged = item.ParticipationAnswer != lOriginals.Find(f => f.Oid == item.Employee2SchedulerAppointmentOid).ParticipationAnswer; MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MergeWithEntitys(pEmployee2SchedulerAppointments, lOriginals); DAOFactory.GenericDAO.Update(lOriginals); return MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.MapToNewDCs(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteEmployee2SchedulerAppointments(Dictionary pOid2Version) { try { var lOriginals = DAOFactory.GenericDAO.LoadByIDs(pOid2Version.Select(e => e.Key)); lOriginals.DoForEach(or => MapperFactory.Employee2SchedulerAppointmentDC_Employee2SchedulerAppointment.ConcurrencyCheck(pOid2Version[or.Oid.Value], or)); DAOFactory.GenericDAO.Delete(lOriginals); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllActiveAndNotDeclinedForEmployeeAppointments(long pEmployeeOid) { try { var blubb = DAOFactory.SearchDAO.GetAllActiveAndNotDeclinedForEmployeeAppointments(pEmployeeOid); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(blubb); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public bool OverlappingAppointmentsExist(DateTime start, DateTime end, List employees, List customers, List resources, long originator, long? appointmentOid, string recurrenceId = "", int ocurrenceIndex = 0) { try { return DAOFactory.SearchDAO.OverlappingAppointmentsExist(start, end, employees, customers, resources, originator, appointmentOid, recurrenceId, ocurrenceIndex); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllActiveAppointmentsForEmployeeInInterval(DateTime start, DateTime end, long pEmployeeOid) { return GetAllActiveAppointmentsForEmployeeInInterval2(start, end, pEmployeeOid, false); } // TODO: veraltet public List GetAllActiveAppointmentsForEmployeeInInterval2(DateTime pStart, DateTime pEnd, long pEmployeeOid, bool pHasRightToSeeAllEmployeeAppointments) { try { var apps = pHasRightToSeeAllEmployeeAppointments ? DAOFactory.SearchDAO.GetAllActiveAppointmentsInInterval(pStart, pEnd) : DAOFactory.SearchDAO.GetAllActiveAppointmentsForEmployeeInInterval(pStart, pEnd, pEmployeeOid); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(apps).OrderBy(a => a.StartDate).ToList(); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllActiveAbsenceTimesInInterval(DateTime pStart, DateTime pEnd, long pEmployeeOid, bool pHasRightToSeeAllEmployeeAppointments) { try { var absenceTimes = DAOFactory.SearchDAO.GetAllAbsenceTimesInIntervalByEmployee(pStart, pEnd, pEmployeeOid, pHasRightToSeeAllEmployeeAppointments); var dcList = MapperFactory.AbsenceTimeDC_AbsenceTime.MapToNewDCs(absenceTimes); foreach (var at in dcList) { if (at.End.HasValue) { at.End = at.End.Value.Date.AddDays(1).AddTicks(-1); } } return dcList.OrderBy(a => a.Start).ToList(); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List LoadFilteredAppointmentsMitAufgaben(bool pHasRightToSeeAllEmployeeAppointments, long pEmployeeOid, DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomer, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments, bool pShowTasks) { try { long? ownerOid = null; //Keine Auswahl getroffen: Nur meine Termine anzeigen if((pSelectedEmployees?.Count == 0) && (pSelectedCustomer?.Count == 0) && (pSelectedResources?.Count == 0)) { ownerOid = pEmployeeOid; } //Benutzer hat sich selber selektiert if(pSelectedEmployees?.Exists(e => e == pEmployeeOid) ?? false) { ownerOid = pEmployeeOid; } //Man hat nur Customer und/oder Ressourcen ausgewählt, dann dürfen die eigenen nicht angezeigt werden if((pSelectedEmployees?.Count == 0) && (pSelectedCustomer?.Count > 0 || pSelectedResources?.Count > 0)) { ownerOid = null; } //Wenn man kein Recht hat alle zu sehen, muss immer auf Owner gefiltert werden, außer es sind Ressourcen vorhanden. Dann wird anonymisiert. if(!pHasRightToSeeAllEmployeeAppointments && pSelectedResources?.Count == 0) { ownerOid = pEmployeeOid; } if(!(!pHasRightToSeeAllEmployeeAppointments && pSelectedEmployees != null && pSelectedEmployees.Count == 1 && pSelectedEmployees.Contains(pEmployeeOid))) { //Rausnehmen, sonst werden Termine nicht gezeigt, bei denen man Owner ist und kein Employee ausgewählt wurde. //Wird nicht rausgenommen, wenn man die Termine anderer Mitarbeiter nicht sehen darf und "nur meine Termine" ausgewählt hat. //Sonst werden die Filter mit and und nicht mit or verknüpft. pSelectedEmployees?.Remove(pEmployeeOid); } if(pPrivateAppointmentsOnly && (pSelectedEmployees?.Count == 0) && (pSelectedCustomer?.Count == 0) && (pSelectedResources?.Count == 0) && !(pSelectedEmployees?.Count == 0) && (pSelectedCustomer?.Count > 0 || pSelectedResources?.Count > 0)) { ownerOid = pEmployeeOid; } var appointments = DAOFactory.SearchDAO.LoadFilteredAppointmentsForEmployee(pHasRightToSeeAllEmployeeAppointments, ownerOid, pIntervalStart, pIntervalEnd, pSelectedEmployees, pSelectedCustomer, pSelectedResources, pEmployeesOnly, pCustomersOnly, pResourcesOnly, pPrivateAppointmentsOnly, pOnlyMyAppointments, false).ToList(); var serientermine = appointments.Where(app => app.RecurrenceInfo != null && app.Type == 1).ToList(); var all = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(appointments).OrderBy(a => a.StartDate).ToList(); var filteredEmployeeOids = new List(); if(ownerOid.HasValue) { filteredEmployeeOids.Add(ownerOid.Value); } if(pSelectedEmployees != null) { foreach(var empOid in pSelectedEmployees) { filteredEmployeeOids.Add(empOid); } } var result = FilterAppointments(all, pEmployeeOid, filteredEmployeeOids, pSelectedCustomer, pSelectedResources, pCustomersOnly, pResourcesOnly, pShowTasks); //Check fehlerhafte RecurrenceInfos foreach(var app in result) { if(!IsNullOrEmpty(app.RecurrenceInfo)) { if(app.RecurrenceInfo.Contains("WeekDays=\"0\"")) { app.RecurrenceInfo = app.RecurrenceInfo.Replace("WeekDays=\"0\"", "WeekDays=\"2\""); } } } var test = result.Count; // Ausnahmen immer laden. Entsprechen die Ausnahmen nicht den Filterkriterien, werden sie als gelöscht markiert, um nicht auf dem Client angezeigt zu werden. var ausnahmen = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(DAOFactory.SearchDAO.FindAppointmentsByRecurrenecInfo(result.Where(w => w.Type == 1).Select(s => s.RecurrenceInfo).ToList(), true)); var demFilterEntsprechendeTermine = FilterAppointments(ausnahmen, pEmployeeOid, filteredEmployeeOids, pSelectedCustomer, pSelectedResources, pCustomersOnly, pResourcesOnly, pShowTasks); foreach(var appointment in ausnahmen.Where(w => !demFilterEntsprechendeTermine.Contains(w))) { var kosmetisch = new SchedulerAppointmentDC { SchedulerAppointmentOid = appointment.SchedulerAppointmentOid * -1, NewSchedulerAppointmentVersion = 1, Type = 4, RecurrenceInfo = appointment.RecurrenceInfo, EmployeeList = appointment.EmployeeList, CustomerList = appointment.CustomerList, ResourceList = appointment.ResourceList, Originator = appointment.Originator }; result.Add(kosmetisch); } UserDC user; if(LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) { user = MapperFactory.UserDC_User.MapToNewDC(LoggedInUserOperationContextExt.Current.User); } else { user = MapperFactory.UserDC_User.MapToNewDC(SessionFacade.LoggedInUser); } var appointmentsToCheckForAnonymization = new List(); var relatedCustomerOids = DAOFactory.SearchDAO.FindTeamRelatedCustomerOids(user.Employee.EmployeeOid); if(!(user is null)) { // Bei ausgewählten Ressourcen oder auch "Nur Ressourcen" werden auch Termine mit den ausgewählten Ressourcen geladen und anonymisiert angezeigt, die der angemeldete Mitarbeiter nicht sehen darf. // ToDo: Hat man das Rechte "Alles Ansehen", wird nicht anonymisiert, da CheckSchedulerRights true zurückgibt! //var hasRightToSeeAll = user.HasRight(UserRightType.ViewAll); appointmentsToCheckForAnonymization = pSelectedResources.Any() || pResourcesOnly ? result.Where(w => w.ResourceList.Any() && false == SUtils.CheckSchedulerRights(w, SchedulerRightsCheckType.View, user, relatedCustomerOids, true)).ToList() : new List(); if(pSelectedResources?.Any() ?? false) { AnonymizeAppointments(result.Where(appointment => appointment.ResourceList.Any()).ToList()); } // Es wird nach zugewiesenen Rechten gefiltert und ob die Termine bereits in der Liste mit den anonymisierten Terminen sind. //result = result.Where(w => (!w.ResourceList.Any() || SUtils.CheckSchedulerRights(w, SchedulerRightsCheckType.View, user, relatedCustomerOids, true)) && !appointmentsToCheckForAnonymization.Any(a => a.SchedulerAppointmentOid == w.SchedulerAppointmentOid)).ToList(); //result.AddRange(appointmentsToCheckForAnonymization); } // Aufgaben laden ConvertOldTasks(pEmployeeOid); var taskAppointmentDCs = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(DAOFactory.SearchDAO.LoadTaskAppointmentsForEmployee(pEmployeeOid, true)); result.AddRangeIfElementsNotIn(taskAppointmentDCs); //DebugUtils.WriteToLogFile($"{DateTime.Now:dd.MM.yyyy HH:mm:ss:fff}: {result.Count} Termine und {result.Count(w => w.IsTask)} Aufgaben aus der Datenbank geladen. {appointmentsToCheckForAnonymization.Count} davon anonymisiert."); Debug.WriteLine($"+++>{DateTime.Now:dd.MM.yyyy HH:mm:ss:fff}: {result.Count} Termine und {result.Count(w => w.IsTask)} Aufgaben aus der Datenbank geladen. {appointmentsToCheckForAnonymization.Count} davon anonymisiert."); // ToDo: durch jeden Termin gehen und prüfen, ob Klienten oder Mitarbeiter anonymisiert und auf read-only gesetzt werden müssen? var appointmentsToBeAnonymized = result.Where(a => !SUtils.CheckSchedulerRights(a, SchedulerRightsCheckType.View, user, relatedCustomerOids, true)).ToList(); var rest = result.Except(appointmentsToBeAnonymized); return result; } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } /// /// Anonymisiert eventuell zu anonymisierende Termine bzw. die Mitarbeiter und Klienten /// /// public static void AnonymizeAppointments(List appointments) { var anonymisiert = "Anonymisiert"; var user = LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null ? LoggedInUserOperationContextExt.Current.User : SessionFacade.LoggedInUser; if(user?.Employee?.Oid is null) { return; } // ToDo: Kalenderrechte miteinbeziehen! var hasRightToViewEmployeeAppointments = user.CheckForRight(UserRightType.KalenderMitarbeitertermineAnsehen); var hasRightToViewCustomerAppointments = user.CheckForRight(UserRightType.KalenderKliententermineAlleAnsehen); var hasRightToViewOwnTeamMembers = user.CheckForRight(UserRightType.Employee_AllowViewOwnTeam); var hasRightToViewEmployees = user.CheckForRight(UserRightType.EmployeeView_View); var visibleCustomers = DAOFactory.SearchDAO.FindAllCustomersForEmployee(user.Employee.Oid.Value, CustomerFilterEnum.All); var visibleEmployees = DAOFactory.SearchDAO.FindAllEmployeesForEmployee(user.Employee.Oid.Value); var isUserInEmployees = visibleEmployees.Contains(user.Employee); if(!hasRightToViewCustomerAppointments) { visibleCustomers.Clear(); } // Mitarbeiter ist Originator und in Liste -> die Mitarbeiter anonymisieren, die nicht in visibleEmployees sind // Mitarbeiter ist Originator -> -> die Mitarbeiter anonymisieren, die nicht in visibleEmployees sind if(!hasRightToViewEmployeeAppointments) { //visibleEmployees = new List {user.Employee}; } // ToDo: Nicht anonymisieren, wenn der Benutzer/Mitarbeiter das Recht hat, Termine anderer Mitarbeiter anzusehen foreach(var appointment in appointments) { var isOriginator = appointment.Originator.EmployeeOid.Equals(user.Employee.Oid.Value); var isAllowedToSeeOriginator = visibleEmployees.Any(employee => appointment.Originator.EmployeeOid.Equals(employee.Oid)); var isInEmployeeList = appointment.EmployeeList.Any(e2a => e2a.Employee.EmployeeOid.Equals(user.Employee.Oid.Value)); // Betreff und Ort werden anonymisiert, wenn der angemeldete Benutzer nicht Ersteller ist und nicht in der Mitarbeiterliste ist und er den Ersteller nicht ansehen darf. if(!isOriginator && !isInEmployeeList && !hasRightToViewEmployeeAppointments) { appointment.Subject = anonymisiert; appointment.Location = anonymisiert; appointment.CanBeEdited = false; } if(!isOriginator && !hasRightToViewEmployeeAppointments) { appointment.Originator.FirstName = anonymisiert; appointment.Originator.LastName = anonymisiert; appointment.CanBeEdited = false; } // Klienten anonymisieren appointment.CustomerList.DoForEach(customer => { if(!hasRightToViewCustomerAppointments) { customer.FirstName = anonymisiert; customer.LastName = anonymisiert; customer.CustomerAlias = anonymisiert; appointment.CanBeEdited = false; } }); // Mitarbeiter anonymisieren appointment.EmployeeList.DoForEach(employee2Appointment => { if(!hasRightToViewEmployeeAppointments) { employee2Appointment.Employee.FirstName = anonymisiert; employee2Appointment.Employee.LastName = anonymisiert; employee2Appointment.Employee.PersonnelNumber = null; appointment.CanBeEdited = false; } }); } } private static List AnonymizeCustomerList(List customers, UserDC user) { var result = new List(); if(user.HasRight(UserRightType.CustomerView_View)) { return customers; } var employee = DAOFactory.GenericDAO.LoadByID(user.Employee.EmployeeOid); if(user.HasRight(UserRightType.Customer_ViewMyCustomers)) { foreach(var c in customers) { var linkedCustomer = employee.Employee2CustomerList.FirstOrDefault(employee2Customer => employee2Customer.CustomerOid.HasValue && employee2Customer.CustomerOid.Value.Equals(c.CustomerOid))?.Customer; var cus = !(linkedCustomer is null) ? c : AnonymizeCustomer(c); result.AddIfNotIn(cus); } } if(user.HasRight(UserRightType.Customer_ViewMyTeams)) { var teams = DAOFactory.SearchDAO.FindAllActiveTeamsOfEmployee(user.Employee.EmployeeOid); teams.DoForEach(team => { if(team.Oid is null) { return; } var customerOfTeam = DAOFactory.SearchDAO.FindCustomerOfTeam(team.Oid.Value); customers.DoForEach(c => { if(customerOfTeam.Any(a => a.Oid.HasValue && a.Oid.Value.Equals(c.CustomerOid))) { result.AddIfNotIn(c); } }); }); } return result; } private static CompactCustomerDC AnonymizeCustomer(CompactCustomerDC customer) { return new CompactCustomerDC { ActivationType = customer.ActivationType, CurrentEmployeeRole = customer.CurrentEmployeeRole, CustomerOid = customer.CustomerOid, CustomerVersion = customer.CustomerVersion, FamilyDataOid = customer.FamilyDataOid, FamilyDataVersion = customer.FamilyDataVersion, FirstName = "Anonymisiert", IsRelatedToEmployee = customer.IsRelatedToEmployee, IsRelatedToTeam = customer.IsRelatedToTeam, LastName = "Anonymisiert", PersonOid = customer.PersonOid, RelatedTeamOids = customer.RelatedTeamOids, RelatedTeams = customer.RelatedTeams, Vormund = "Anonymisiert" }; } private static List AnonymizeAppointmentEmployeeList(List employee2SchedulerAppointment, UserDC user) { var result = new List(); if(user.HasRight(UserRightType.EmployeeView_View)) { return employee2SchedulerAppointment; } if(user.HasRight(UserRightType.Employee_AllowViewOwnTeam)) { var teams = MapperFactory.TeamDC_Team.MapToNewDCs(DAOFactory.SearchDAO.FindAllActiveTeamsOfEmployee(user.Employee.EmployeeOid)); var teamMembers = new List(); teams.DoForEach(t => t.Member.DoForEach(e => teamMembers.AddIfNotIn(e))); foreach(var e2a in employee2SchedulerAppointment) { result.AddIfNotIn(teamMembers.Contains(e2a.Employee) ? e2a : AnonymizeEmployee2SchedulerAppointment(e2a)); } return result; } employee2SchedulerAppointment.DoForEach(e2a => { if(e2a.Employee?.Equals(user.Employee) ?? false) { result.AddIfNotIn(e2a); } else { result.AddIfNotIn(AnonymizeEmployee2SchedulerAppointment(e2a)); } }); return result; } private static Employee2SchedulerAppointmentDC AnonymizeEmployee2SchedulerAppointment(Employee2SchedulerAppointmentDC employee2SchedulerAppointment) { var employee = employee2SchedulerAppointment.Employee; employee = new CompactEmployeeDC { FirstName = "Anonymisiert", LastName = "Anonymisiert", Version = employee.Version, EmployeeColor = employee.EmployeeColor, EmployeeOid = employee.EmployeeOid, EmployeeVersion = employee.Version, ActivationType = employee.ActivationType, PersonOid = employee.PersonOid, IsTeamLeader = employee.IsTeamLeader, LeadingTeamOids = employee.LeadingTeamOids, TeamOids = employee.TeamOids, RelatedTeams = employee.RelatedTeams, AllTeamMemberOids = employee.AllTeamMemberOids, PersonnelNumber = employee.PersonnelNumber, RelatedCustomerOIDList = employee.RelatedCustomerOIDList, ValueListEntries = employee.ValueListEntries, Details2 = employee.Details2, Details3 = employee.Details3 }; return new Employee2SchedulerAppointmentDC { Employee = employee, SchedulerAppointmentOid = employee2SchedulerAppointment.SchedulerAppointmentOid, Employee2SchedulerAppointmentOid = employee2SchedulerAppointment.Employee2SchedulerAppointmentOid, Employee2SchedulerAppointmentVersion = employee2SchedulerAppointment.Employee2SchedulerAppointmentVersion, IsPC_CheckedTs = employee2SchedulerAppointment.IsPC_CheckedTs, IsPChanged = employee2SchedulerAppointment.IsPChanged, ParticipationAnswer = employee2SchedulerAppointment.ParticipationAnswer }; } private void ConvertOldTasks(long pEmployeeOid) { var oldTasks = DAOFactory.SearchDAO.LoadTasksForConversion(pEmployeeOid); var taskAppointments = new List(); foreach (var task in oldTasks) { var taskAsAppointment = new SchedulerAppointment { SupportConceptList = new List { task.SupportConcept }, EmployeeList = new List(), FormerTaskOid = task.Oid, Subject = task.Title, CompletedNotice = task.CompletedNotice, TaskDescription = task.Description, IsActive = task.IsActive, IsTask = true, DueDate = task.DueDate, CompletedDate = task.CompletedDate, StartDate = task.CompletedDate.HasValue ? task.DueDate?.GetShortDateTime() : task.InsTs?.GetShortDateTime(), EndDate = task.DueDate?.GetShortDateTime().AddDays(1) ?? DateTime.MaxValue.Date }; foreach (var employee in task.EmployeeList) { var rel = new Employee2SchedulerAppointment { Employee = DAOFactory.GenericDAO.LoadByID(employee.Oid.Value), ParticipationAnswer = ParticipationAnswer.Offen }; taskAsAppointment.EmployeeList.AddIfNotIn(rel); } taskAppointments.Add(taskAsAppointment); } if (taskAppointments.Count > 0) { InsertSchedulerAppointments( MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(taskAppointments)); } } public List LoadFilteredAppointments(bool pHasRightToSeeAllEmployeeAppointments, long pEmployeeOid, DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomer, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments) { try { long? ownerOid = null; //Keine Auswahl getroffen: Nur meine Termine anzeigen if ((pSelectedEmployees == null || pSelectedEmployees.Count == 0) && (pSelectedCustomer == null || pSelectedCustomer.Count == 0) && (pSelectedResources == null || pSelectedResources.Count == 0)) { ownerOid = pEmployeeOid; } //Benutzer hat sich selber selektiert if (pSelectedEmployees != null && pSelectedEmployees.Exists(e => e == pEmployeeOid)) { ownerOid = pEmployeeOid; } //Man hat nur Customer und/oder Ressourcen ausgewählt, dann dürfen die eigenen nicht angezeigt werden if ((pSelectedEmployees == null || pSelectedEmployees.Count == 0) && (pSelectedCustomer != null && pSelectedCustomer.Count > 0 || pSelectedResources != null && pSelectedResources.Count > 0)) { ownerOid = null; } //Wenn man kein Recht hat alle zu sehen, muss immer auf Owner gefiltert werden if (!pHasRightToSeeAllEmployeeAppointments) { ownerOid = pEmployeeOid; } if(!(!pHasRightToSeeAllEmployeeAppointments && pSelectedEmployees != null && pSelectedEmployees.Count == 1 && pSelectedEmployees.Contains(pEmployeeOid))) { //Rausnehmen, sonst werden Termine nicht gezeigt, bei denen man Owner ist und kein Employee ausgewählt wurde. //Wird nicht rausgenommen, wenn man die Termine anderer Mitarbeiter nicht sehen darf und "nur meine Termine" ausgewählt hat. //Sonst werden die Filter mit and und nicht mit or verknüpft. pSelectedEmployees?.Remove(pEmployeeOid); } if(pPrivateAppointmentsOnly && (pSelectedEmployees == null || pSelectedEmployees.Count == 0) && (pSelectedCustomer == null || pSelectedCustomer.Count == 0) && (pSelectedResources == null || pSelectedResources.Count == 0) && !(pSelectedEmployees == null || pSelectedEmployees.Count == 0) && (pSelectedCustomer != null && pSelectedCustomer.Count > 0 || pSelectedResources != null && pSelectedResources.Count > 0)) { ownerOid = pEmployeeOid; } var appointments = DAOFactory.SearchDAO.LoadFilteredAppointmentsForEmployee(pHasRightToSeeAllEmployeeAppointments, ownerOid, pIntervalStart, pIntervalEnd, pSelectedEmployees, pSelectedCustomer, pSelectedResources, pEmployeesOnly, pCustomersOnly, pResourcesOnly, pPrivateAppointmentsOnly, pOnlyMyAppointments, false).ToList(); var all = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(appointments).OrderBy(a => a.StartDate).ToList(); var filteredEmployeeOids = new List(); if (ownerOid.HasValue) { filteredEmployeeOids.Add(ownerOid.Value); } if (pSelectedEmployees != null) { foreach (var empOid in pSelectedEmployees) { filteredEmployeeOids.Add(empOid); } } var result = FilterAppointments(all, pEmployeeOid, filteredEmployeeOids, pSelectedCustomer, pSelectedResources, pCustomersOnly, pResourcesOnly); //Check fehlerhafte RecurrenceInfos foreach (var app in result) { if (!IsNullOrEmpty(app.RecurrenceInfo)) { if (app.RecurrenceInfo.Contains("WeekDays=\"0\"")) { app.RecurrenceInfo = app.RecurrenceInfo.Replace("WeekDays=\"0\"", "WeekDays=\"2\""); } } } // Ausnahmen immer laden. Entsprechen die Ausnahmen nicht den Filterkriterien, werden sie als gelöscht markiert, um nicht auf dem Client angezeigt zu werden. var ausnahmen = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(DAOFactory.SearchDAO.FindAppointmentsByRecurrenecInfo(result.Where(w => w.Type == 1).Select(s => s.RecurrenceInfo).ToList(), true)); var demFilterEntsprechendeTermine = FilterAppointments(ausnahmen, pEmployeeOid, filteredEmployeeOids, pSelectedCustomer, pSelectedResources, pCustomersOnly, pResourcesOnly); foreach(var appointment in ausnahmen.Where(w => !demFilterEntsprechendeTermine.Contains(w))) { var kosmetisch = new SchedulerAppointmentDC { SchedulerAppointmentOid = appointment.SchedulerAppointmentOid * -1, NewSchedulerAppointmentVersion = 1, Type = 4, RecurrenceInfo = appointment.RecurrenceInfo, EmployeeList = appointment.EmployeeList, CustomerList = appointment.CustomerList, ResourceList = appointment.ResourceList, Originator = appointment.Originator }; result.Add(kosmetisch); } return result; } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } private static List FilterAppointments(IEnumerable pAppointments, long pEmployeeOid, ICollection pFilteredEmployeeOids, ICollection pSelectedCustomers, ICollection pSelectedResources, bool pCustomersOnly, bool pResourcesOnly, bool pShowTasks = false) { var result = new List(); foreach(var app in pAppointments) { var add = true; if(app.ResourceList.Any(a => pSelectedResources?.Any(r => r == a.ResourceOid) ?? false)) { result.AddIfNotIn(app); continue; } if(app.Originator != null && app.Originator.EmployeeOid == pEmployeeOid) { if(app.EmployeeList != null && app.EmployeeList.Count > 0) { add = false; foreach(var emp in app.EmployeeList) { if(pFilteredEmployeeOids.Contains(emp.Employee.EmployeeOid)) { add = true; } } } } // ToDo: Nicht herausnehmen, wenn Ressource in SelectedResources vorhanden ist. //Prüfe Klientenfilter if(!add) { if(app.CustomerList != null && app.CustomerList.Count > 0) { if(pCustomersOnly) { add = true; } else if(pSelectedCustomers != null && pSelectedCustomers.Count > 0) { foreach(var cust in app.CustomerList) { if(pSelectedCustomers.Contains(cust.CustomerOid)) { add = true; } } } } } //Prüfe Ressourcenfilter if(!add) { if(app.ResourceList != null && app.ResourceList.Count > 0) { if(pResourcesOnly) { add = true; } else if(pSelectedResources != null && pSelectedResources.Count > 0) { foreach(var res in app.ResourceList) { if(pSelectedResources.Contains(res.ResourceOid.Value)) { add = true; } } } } } if (app.IsTask && !pShowTasks) { add = false; } if(add) { result.Add(app); } } return result; } public List GetAllTasksForEmployee(long pEmployeeOid) { try { ConvertOldTasks(pEmployeeOid); var taskAppointmentDCs = DAOFactory.SearchDAO.LoadTaskAppointmentsForEmployee(pEmployeeOid, true); var monday = DateTime.Today.FirstDateOfWeek(DateTime.Today.GetIso8601WeekOfYear()); var appointments = DAOFactory.SearchDAO.LoadFilteredAppointmentsForEmployee(false, pEmployeeOid, monday, monday.AddDays(14), new List(), new List(), new List(), false, false, false, false, true, false); taskAppointmentDCs.AddRangeIfElementsNotIn(appointments); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(taskAppointmentDCs); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetSchedulerAppointmentTasksForEmployeeBySupportConecpt(long pEmployeeOid, long pSupportConceptOid) { try { List oids = new List(); oids.Add(pSupportConceptOid); var taskAppointments = DAOFactory.SearchDAO.GetTasksAndAppointmentsBySupportConceptOids(oids); //Alle Tasks des SupportConcept zurückgeben und nicht nur die, des angemeldeten Users .GetTasksForEmployeeBySupportConcept(pEmployeeOid, pSupportConceptOid); var dataContracts = MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(taskAppointments); return dataContracts; } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } // ToDo: Anonymisieren? public List LoadTasksAndAppointmentsForEmployee(long pEmployeeOid, DateTime pInvertalStart, int pBufferSize, long? pEmployeeAppointmentsOid) { try { ConvertOldTasks(pEmployeeOid); var taskAppointmentDCs = DAOFactory.SearchDAO.LoadTaskAppointmentsForEmployee(pEmployeeOid, false); foreach(var task in taskAppointmentDCs) { if(task.DueDate.HasValue) { task.StartDate = task.DueDate; task.EndDate = task.DueDate; } if(task.SupportConceptList != null && task.SupportConceptList.Count > 0) { task.Subject = $"{task.SupportConceptList[0].Customer.Person.LastNameFirstName}: {task.Subject}"; } } var bufferdIntervalStart = pInvertalStart.AddDays(-1 * pBufferSize); var weekOfYear = bufferdIntervalStart.GetIso8601WeekOfYear(); var monday = bufferdIntervalStart.FirstDateOfWeek(weekOfYear); if(!pEmployeeAppointmentsOid.HasValue) { pEmployeeAppointmentsOid = pEmployeeOid; } var appointments = DAOFactory.SearchDAO.LoadFilteredAppointmentsForEmployee(false, pEmployeeAppointmentsOid.Value, monday, monday.AddDays(3 * pBufferSize), new List(), new List(), new List(), false, false, false, false, true, false).ToList(); UserDC user; if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) { user = MapperFactory.UserDC_User.MapToNewDC(LoggedInUserOperationContextExt.Current.User); } else { user = MapperFactory.UserDC_User.MapToNewDC(SessionFacade.LoggedInUser); } var loggedInEmployee = DAOFactory.GenericDAO.LoadByID(pEmployeeOid); // Ist der Originator in der Mitarbeiterliste, soll der Termin angezeigt werden if(!user.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen)) { var appointments2Remove = appointments.Where(appointment => appointment.EmployeeList.Count > 0 && appointment.EmployeeList.All(a => !a.Employee.Equals(loggedInEmployee))).ToList(); appointments = appointments.Except(appointments2Remove).ToList(); } // TODO: Testen! if(!user.HasRight(UserRightType.KalenderKliententermineAlleAnsehen)) { var ownCustomers = loggedInEmployee.Employee2CustomerList.Select(s => s.Customer).ToList(); var appointmentsWithOtherCustomers = appointments.Where(w => w.CustomerList.Any(a => !ownCustomers.Contains(a))).ToList(); appointments = appointments.Except(appointmentsWithOtherCustomers).ToList(); } if(!user.HasRight(UserRightType.KalenderRessourcentermineAnsehen)) { var appsToRemove = appointments.Where(appointment => appointment.ResourceList.Any()).ToList(); appointments = appointments.Except(appsToRemove).ToList(); } var nullerIndex = new List(); var recurringAppointments = appointments.Where(app => app.RecurrenceInfo != null); recurringAppointments.DoForEach(app => { var index = Utils.ExtractIndexFromRecurrenceInfo(app.RecurrenceInfo); if(index == 0) { nullerIndex.Add(app); } }); nullerIndex.DoForEach(app => { var id = Utils.ExtractIdFromRecurrenceInfo(app.RecurrenceInfo); if(app.Type == (int) AppointmentType.ChangedOccurrence) { var toRemove = appointments.Find(f => f.RecurrenceInfo != null && f.RecurrenceInfo.Contains(id) && !f.RecurrenceInfo.Contains("Index") && f.Type == (int) AppointmentType.Pattern); appointments.Remove(toRemove); } }); taskAppointmentDCs.AddRangeIfElementsNotIn(appointments); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(taskAppointmentDCs); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void InsertTestAppointments(long pEmployeeOid) { try { CreateTestAppointmentsForEmployee(pEmployeeOid); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } private static void CreateTestAppointmentsForEmployee(long pEmployeeOid) { #if DEBUG var employee = DAOFactory.GenericDAO.LoadByID(pEmployeeOid); var employeesWithoutEmployee = DAOFactory.GenericDAO.GetAllActive().Where(emp => !emp.Equals(employee)).ToList(); var customers = DAOFactory.GenericDAO.GetAllActive(); var ownCustomers = employee.Employee2CustomerList.Select(e2c => e2c.Customer).ToList(); var resources = DAOFactory.GenericDAO.GetAllActive(); var secondEmployee = employeesWithoutEmployee.FirstOrDefault() ?? employee; var fiveOfSecondEmployeesCustomers = secondEmployee.Employee2CustomerList.Select(e2c => e2c.Customer).TakeWhile((t, j) => j != 5).ToList(); var fiveOfMyOwnCustomers = ownCustomers.TakeWhile((t, i) => i != 5).ToList(); var fiveCustomers = customers.TakeWhile((t, i) => i != 5).ToList(); var fiveResources = resources.TakeWhile((t, i) => i != 3).ToList(); var employeeListIncludingLoggedInEmployee1 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee1.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee2 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee2.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee3 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee3.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee4 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee4.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee5 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee5.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee6 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee6.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee7 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee7.Add(new Employee2SchedulerAppointment(employee)); var employeeListIncludingLoggedInEmployee8 = employeesWithoutEmployee.TakeWhile((t, i) => i != 4).Select(t => new Employee2SchedulerAppointment(t)).ToList(); employeeListIncludingLoggedInEmployee8.Add(new Employee2SchedulerAppointment(employee)); var monday = DateTime.Today.FirstDateOfWeek(DateTime.Today.GetIso8601WeekOfYear()); var tuesday = monday.AddDays(1); var wednesday = monday.AddDays(2); var thursday = monday.AddDays(3); var friday = monday.AddDays(4); var saturday = monday.AddDays(5); var sunday = monday.AddDays(6); //Originator ist angemeldeten Mitarbeiter GenerateAppointments(monday, false, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null); //Termin von anderem Mitarbeiter GenerateAppointments(tuesday, false, secondEmployee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeeListIncludingLoggedInEmployee1, null); //Originator ist angemeldeter Mitarbeiter und in Liste GenerateAppointments(wednesday, false, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeeListIncludingLoggedInEmployee2, null); //Originator ist nicht angemeldeter Mitarbeiter und der ist auch nicht in der Liste GenerateAppointments(thursday, false, secondEmployee, fiveCustomers, fiveOfSecondEmployeesCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null); //Private Termine GenerateAppointments(friday, true, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null); GenerateAppointments(saturday, true, secondEmployee, fiveCustomers, fiveOfSecondEmployeesCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null); GenerateAppointments(sunday, true, secondEmployee, fiveCustomers, fiveOfSecondEmployeesCustomers, fiveResources, employeeListIncludingLoggedInEmployee3, null); GenerateAppointments(friday.AddHours(12), true, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeeListIncludingLoggedInEmployee4, null); //AllDay-Termine ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ var mon = monday.AddDays(7); var tue = tuesday.AddDays(7); var wed = wednesday.AddDays(7); var thu = thursday.AddDays(7); var fri = friday.AddDays(7); var sat = saturday.AddDays(7); var sun = sunday.AddDays(7); //Originator ist angemeldeten Mitarbeiter GenerateAppointments(mon, false, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null, true); //Termin von anderem Mitarbeiter GenerateAppointments(tue, false, secondEmployee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeeListIncludingLoggedInEmployee5, null, true); //Originator ist angemeldeter Mitarbeiter und in Liste GenerateAppointments(wed, false, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeeListIncludingLoggedInEmployee6, null, true); //Originator ist nicht angemeldeter Mitarbeiter und der ist auch nicht in der Liste GenerateAppointments(thu, false, secondEmployee, fiveCustomers, fiveOfSecondEmployeesCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null, true); //Private Termine GenerateAppointments(fri, true, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null, true); GenerateAppointments(sat, true, secondEmployee, fiveCustomers, fiveOfSecondEmployeesCustomers, fiveResources, employeesWithoutEmployee.TakeWhile((t, i) => i != 5).Select(t => new Employee2SchedulerAppointment(t)).ToList(), null, true); GenerateAppointments(sun, true, secondEmployee, fiveCustomers, fiveOfSecondEmployeesCustomers, fiveResources, employeeListIncludingLoggedInEmployee7, null, true); GenerateAppointments(fri.AddHours(12), true, employee, fiveCustomers, fiveOfMyOwnCustomers, fiveResources, employeeListIncludingLoggedInEmployee8, null, true); // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- var ttttttt1 = employeeListIncludingLoggedInEmployee1.Select(s => s.Oid).ToList(); var ttttttt2 = employeeListIncludingLoggedInEmployee2.Select(s => s.Oid).ToList(); var ttttttt3 = employeeListIncludingLoggedInEmployee3.Select(s => s.Oid).ToList(); var ttttttt4 = employeeListIncludingLoggedInEmployee4.Select(s => s.Oid).ToList(); var ttttttt5 = employeeListIncludingLoggedInEmployee5.Select(s => s.Oid).ToList(); var ttttttt6 = employeeListIncludingLoggedInEmployee6.Select(s => s.Oid).ToList(); var ttttttt7 = employeeListIncludingLoggedInEmployee7.Select(s => s.Oid).ToList(); var ttttttt8 = employeeListIncludingLoggedInEmployee8.Select(s => s.Oid).ToList(); var mo = mon.AddDays(7); var tu = tue.AddDays(7); // Tägliche Termine var everyThirdMondayNoEnd = GenerateTestAppointment(false, false, mo.AddHours(9), mo.AddHours(10), AppointmentType.Pattern, "Täglich, alle 3 Tage. Endlos", employee); everyThirdMondayNoEnd.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Daily, 0, 0, mo.AddHours(9), null, 1); DAOFactory.GenericDAO.Insert(everyThirdMondayNoEnd); var everyWeekdayNoEnd = GenerateTestAppointment(false, false, mo.AddHours(10), mo.AddHours(11), AppointmentType.Pattern, "Wochentäglich. Endlos", employee); everyWeekdayNoEnd.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Daily, 0, 1, mo.AddHours(10), null, 1); DAOFactory.GenericDAO.Insert(everyWeekdayNoEnd); var everyThirdMondayEndsAfter12Times = GenerateTestAppointment(false, false, mo.AddHours(11), mo.AddHours(12), AppointmentType.Pattern, "Täglich, alle 3 Tage. Endet nach 12 Terminen", employee); everyThirdMondayEndsAfter12Times.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Daily, 1, 0, mo.AddHours(11), null, 1); DAOFactory.GenericDAO.Insert(everyThirdMondayEndsAfter12Times); var everyWorkdayEndsAfter12Times = GenerateTestAppointment(false, false, mo.AddHours(12), mo.AddHours(13), AppointmentType.Pattern, "Wochentäglich. Endet nach 12 Terminen", employee); everyWorkdayEndsAfter12Times.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Daily, 1, 1, mo.AddHours(12), null, 1); DAOFactory.GenericDAO.Insert(everyWorkdayEndsAfter12Times); var everyWorkdayEndsOnSpecificDate = GenerateTestAppointment(false, false, mo.AddHours(13), mo.AddHours(14), AppointmentType.Pattern, $"Wochentäglich. Endet am {mo.AddHours(13).AddDays(11):dd.MM.yyyy}", employee); everyWorkdayEndsOnSpecificDate.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Daily, 2, 1, mo.AddHours(13), everyWorkdayEndsOnSpecificDate.StartDate.Value.AddDays(11), 0); DAOFactory.GenericDAO.Insert(everyWorkdayEndsOnSpecificDate); var everyThreeDaysEndsOnSpecificDate = GenerateTestAppointment(false, false, mo.AddHours(15), mo.AddHours(16), AppointmentType.Pattern, "Jeden dritten Tag. Endet 11 Tage nach Beginn", employee); everyThreeDaysEndsOnSpecificDate.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Daily, 2, 0, mo.AddHours(15), mo.AddHours(15).AddDays(11), 0); DAOFactory.GenericDAO.Insert(everyThreeDaysEndsOnSpecificDate); // Wöchentliche Termine var everyThirdWeekMondayAndTuesday = GenerateTestAppointment(false, false, mo.AddHours(16), mo.AddHours(17), AppointmentType.Pattern, "Jede dritte Woche Montags und Dienstags. Endlos", employee); everyThirdWeekMondayAndTuesday.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Weekly, 0, 0, mo.AddHours(16), null, 1); DAOFactory.GenericDAO.Insert(everyThirdWeekMondayAndTuesday); var everySecondWeekMondaysAndTuesdays = GenerateTestAppointment(false, false, mo.AddHours(18), mo.AddHours(19), AppointmentType.Pattern, "Jede zweite Woche am Montag und Dienstag. Endet nach 17 Terminen", employee); everySecondWeekMondaysAndTuesdays.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Weekly, 0, 1, mo.AddHours(18), null, 17); DAOFactory.GenericDAO.Insert(everySecondWeekMondaysAndTuesdays); var everyWeekMondaysAndTuesdays = GenerateTestAppointment(false, false, mo.AddHours(19), mo.AddHours(20), AppointmentType.Pattern, $"Jede Woche am Montag und Dienstag. Endet am {mo.AddHours(19).AddDays(20):dd.MM.yyyy}", employee); everyWeekMondaysAndTuesdays.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Weekly, 1, 1, mo.AddHours(19), mo.AddHours(19).AddDays(20), 1); DAOFactory.GenericDAO.Insert(everyWeekMondaysAndTuesdays); // Monatliche Termine var m1 = GenerateTestAppointment(false, false, tu.AddHours(8), tu.AddHours(9), AppointmentType.Pattern, $"Am {tu.FirstDateOfWeek(tu.GetIso8601WeekOfYear())} jedes 2. Monats. Endlos", employee); m1.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Monthly, 0, 0, tu.AddHours(8), null, 1); DAOFactory.GenericDAO.Insert(m1); var m2 = GenerateTestAppointment(false, false, tu.AddHours(9), tu.AddHours(10), AppointmentType.Pattern, "Jeden dritten Mittwoch jedes 2. Monats. Endlos", employee); m2.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Monthly, 0, 1, tu.AddHours(9), null, 1); DAOFactory.GenericDAO.Insert(m2); var m3 = GenerateTestAppointment(false, false, tu.AddHours(10), tu.AddHours(11), AppointmentType.Pattern, "Jeden 3. jedes 3. Monats. Endet nach 3 Terminen", employee); m3.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Monthly, 1, 0, tu.AddHours(10), null, 3); DAOFactory.GenericDAO.Insert(m3); var m4 = GenerateTestAppointment(false, false, tu.AddHours(11), tu.AddHours(12), AppointmentType.Pattern, "Jeden 3. Montag jedes 3. Monats. Endet nach 3 Terminen", employee); m4.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Monthly, 1, 1, tu.AddHours(11), null, 3); DAOFactory.GenericDAO.Insert(m4); var m5 = GenerateTestAppointment(false, false, tu.AddHours(12), tu.AddHours(13), AppointmentType.Pattern, $"Am 17. jedes 3. Monats. Endet am {tu.AddMonths(6):dd.MM.yyyy}", employee); m5.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Monthly, 2, 0, tu.AddHours(12), tu.AddHours(12).AddMonths(6), 1); DAOFactory.GenericDAO.Insert(m5); var m6 = GenerateTestAppointment(false, false, tu.AddHours(13), tu.AddHours(14), AppointmentType.Pattern, $"Jeden 3. Montag jedes Monats. Endet am {tu.AddMonths(4):dd.MM.yyyy}", employee); m6.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Monthly, 2, 1, tu.AddHours(13), tu.AddHours(13).AddMonths(4), 1); DAOFactory.GenericDAO.Insert(m6); // Jährliche Termine var y1 = GenerateTestAppointment(false, false, tu.AddHours(14), tu.AddHours(16), AppointmentType.Pattern, $"Jährlich am {tu:dd.MM.}. Endlos", employee); y1.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Yearly, 0, 0, tu.AddHours(14), null, 1); DAOFactory.GenericDAO.Insert(y1); var y2 = GenerateTestAppointment(false, false, tu.AddHours(16), tu.AddHours(17), AppointmentType.Pattern, $"Jährlich am 3. Montag im {tu:MMMM}. Endlos", employee); y2.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Yearly, 0, 1, tu.AddHours(16), null, 1); DAOFactory.GenericDAO.Insert(y2); var y3 = GenerateTestAppointment(false, false, tu.AddHours(17), tu.AddHours(18), AppointmentType.Pattern, $"Jährlich jeden {tu.Day}. im {mo.Month:MMMM}. Endet nach 3 Terminen", employee); y3.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Yearly, 1, 0, tu.AddHours(17), null, 3); DAOFactory.GenericDAO.Insert(y3); var y4 = GenerateTestAppointment(false, false, tu.AddHours(18), tu.AddHours(19), AppointmentType.Pattern, $"Jährlich jeden 3. Montag im {mo.Month:MMMM}. Endet nach 3 Terminen", employee); y4.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Yearly, 1, 1, tu.AddHours(18), null, 3); DAOFactory.GenericDAO.Insert(y4); var y5 = GenerateTestAppointment(false, false, tu.AddHours(19), tu.AddHours(20), AppointmentType.Pattern, $"Jährlich am x. [Monat]. Endet am xx.xx.xxxx (1 Jahr später)", employee); y5.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Yearly, 2, 0, tu.AddHours(19), tu.AddHours(19).AddYears(1), 3); DAOFactory.GenericDAO.Insert(y5); var y6 = GenerateTestAppointment(false, false, tu.AddHours(20), tu.AddHours(21), AppointmentType.Pattern, $"Jährlich jeden 3. Mittwoch im {tu:MMMM}. Endet am {tu.AddHours(20).AddYears(1):dd.MM.yyyy}", employee); y6.RecurrenceInfo = GenerateRecurrenceInfo(RecurrenceType.Yearly, 2, 1, tu.AddHours(20), tu.AddHours(20).AddYears(1), 3); DAOFactory.GenericDAO.Insert(y6); // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #endif } private static string CreateRandomLocationName() { var random = new Random(Convert.ToInt32(DateTime.Now.Ticks.ToString().Substring(0, 9))).Next(); var location = ""; if(random % 2 == 0) { location = "Duisburg"; } else if(random % 3 == 0) { location = "Düsseldorf"; } else if (random % 5 == 0) { location = "Köln"; } return location; } private static void GenerateAppointments(DateTime pFirstDate, bool pIsPrivate, Employee pEmployee, IList pCustomerList, IList pOwnCustomers, IList pResourceList, IList pEmployees, string pRecurrenceInfo, bool pIsAllDay = false) { const int startHours = 6; for(var i = 0; i < 12; i++) { var appointment = GenerateTestAppointment( pIsPrivate, new List(), new List(), new List(), pIsAllDay, pIsAllDay ? pFirstDate.GetShortDateTime() : pFirstDate.AddHours(startHours + i), pIsAllDay ? pFirstDate.GetShortDateTime().AddDays(1) : pFirstDate.AddHours(startHours + i + 1), AppointmentType.Normal, $"Testtermin von {pEmployee.Person.FirstNameLastName}", pEmployee); switch (i) { case 1: appointment.CustomerList = pCustomerList; appointment.Subject += " mit Klienten"; break; case 2: appointment.Subject += " mit Mitarbeitern"; break; case 3: appointment.ResourceList = pResourceList; appointment.Subject += " mit Ressourcen"; break; case 4: appointment.CustomerList = pCustomerList; appointment.Subject += " mit Klienten und Mitarbeitern"; break; case 5: appointment.CustomerList = pCustomerList; appointment.ResourceList = pResourceList; appointment.Subject += " mit Klienten und Ressourcen"; break; case 6: appointment.CustomerList = pCustomerList; appointment.ResourceList = pResourceList; appointment.Subject += " mit Klienten, Mitarbeitern und Ressourcen"; break; case 7: appointment.ResourceList = pResourceList; appointment.Subject += " mit Mitarbeitern und Ressourcen"; break; case 8: appointment.CustomerList = pOwnCustomers; appointment.Subject += " mit eigenen Klienten"; break; case 9: appointment.CustomerList = pOwnCustomers; appointment.Subject += " mit eigenen Klienten und Mitarbeitern"; break; case 10: appointment.CustomerList = pOwnCustomers; appointment.ResourceList = pResourceList; appointment.Subject += " mit eigenen Klienten und Ressourcen"; break; case 11: appointment.CustomerList = pOwnCustomers; appointment.ResourceList = pResourceList; appointment.Subject += " mit eigenen Klienten, Mitarbeitern und Ressourcen"; break; } appointment.Subject = (pIsPrivate ? "Privat: " : "") + appointment.Subject; if (pEmployees != null) { DAOFactory.GenericDAO.Insert(pEmployees); pEmployees = DAOFactory.GenericDAO.LoadByIDs(pEmployees.Where(w => w.Oid.HasValue).Select(s => s.Oid.Value)); appointment.EmployeeList = pEmployees; } DAOFactory.GenericDAO.Insert(appointment); if(pEmployees != null) { foreach(var abc in appointment.EmployeeList) { abc.SchedulerAppointmentOid = appointment.Oid; } DAOFactory.GenericDAO.Update(appointment.EmployeeList); } } } private static string GenerateRecurrenceInfo(RecurrenceType pType, int pRecurrenceMode, int pRecurrenceOption, DateTime pStartDate, DateTime? pRecurrenceEndDate, int pOccurrenceCount) { // pRecurrenceOption ist z.B. bei täglich "Alle x Tage" oder "Jeden Arbeitstag" var monday = pStartDate.FirstDateOfWeek(pStartDate.GetIso8601WeekOfYear()); // XML für die RecurrenceInfo bauen var ri = new RecurrenceInfo { Start = pStartDate, Type = pType }; switch(pRecurrenceMode) { case 0: // Ohne Enddatum ri.Range = RecurrenceRange.NoEndDate; ri.Periodicity = 3; switch (pType) { case RecurrenceType.Daily: ri.Start = monday; if(pRecurrenceOption == 1) // Jeden Arbeitstag { ri.WeekDays = WeekDays.WorkDays; } break; case RecurrenceType.Weekly: ri.WeekDays = WeekDays.Monday | WeekDays.Tuesday; break; case RecurrenceType.Monthly: ri.WeekDays = ri.Start.GetSchedulerWeekDays(); ri.Periodicity = 2; ri.WeekOfMonth = pRecurrenceOption == 0 ? 0 : WeekOfMonth.Third; if(pRecurrenceOption == 1) // Am x. Wochentag jedes y. { var date = DateTimeUtils.GetNthDayOfWeekInMonth(ri.Start, 3, DayOfWeek.Monday); ri.Start = date; ri.WeekDays = date.GetSchedulerWeekDays(); } else // Am x. jedes y. Monats { ri.DayNumber = monday.Day; } break; case RecurrenceType.Yearly: if(pRecurrenceOption == 0) { ri.DayNumber = monday.Day; } ri.Periodicity = 1; ri.WeekOfMonth = pRecurrenceOption == 0 ? 0 : WeekOfMonth.Third; ri.WeekDays = monday.GetSchedulerWeekDays(); ri.Month = monday.Month; break; } break; case 1: // Endet nach y Terminen ri.Range = RecurrenceRange.OccurrenceCount; var day = pStartDate; switch (pType) { case RecurrenceType.Daily: if(pRecurrenceOption == 1) // Jeden Arbeitstag endet nach y Terminen { ri.WeekDays = WeekDays.WorkDays; var counter1 = 0; do { if(day.DayOfWeek != DayOfWeek.Saturday && day.DayOfWeek != DayOfWeek.Sunday) { counter1++; } day = day.AddDays(1); } while(counter1 < pOccurrenceCount - 1); } else { ri.Periodicity = 3; ri.OccurrenceCount = pOccurrenceCount; for (var i = 0; i < pOccurrenceCount - 1; i++) { day = day.AddDays(ri.Periodicity); } } ri.End = day; break; case RecurrenceType.Weekly: // Jeden Montag und Dienstag alle 2 Wochen ri.WeekDays = WeekDays.Monday | WeekDays.Tuesday; ri.OccurrenceCount = pOccurrenceCount; ri.Periodicity = 2; var weekDays = SUtils.GetWeekDaysFromNumber((int) ri.WeekDays); var counter = 1; var position = weekDays.IndexOf(day.DayOfWeek); do { for(var i = position; i < weekDays.Count; i++) { day = SUtils.GetNextDateTime(day, weekDays.ElementAt(i), ri.Periodicity, RecurrenceType.Weekly); counter++; } position = (weekDays.Count - 1) % (position == 0 ? position + 1 : position); } while(counter < pOccurrenceCount); ri.End = day; break; case RecurrenceType.Monthly: ri.WeekDays = pStartDate.GetSchedulerWeekDays(); ri.WeekOfMonth = pRecurrenceOption == 0 ? 0 : pStartDate.GetWeekOfMonthForRecurrenceInfo(); if (pRecurrenceOption == 0) // Am 3. jedes 3. Monats. Endet nach 3 Terminen { ri.DayNumber = pStartDate.Day; ri.Periodicity = 3; ri.OccurrenceCount = pOccurrenceCount; } else // Jeden 3. Montag jedes 3. Monats. Endet nach 3 Terminen { ri.End = pStartDate.AddMonths(3 * pOccurrenceCount); } break; case RecurrenceType.Yearly: ri.Month = pStartDate.Month; ri.WeekDays = pStartDate.GetSchedulerWeekDays(); ri.OccurrenceCount = pOccurrenceCount; if (pRecurrenceOption == 0) // Am x. des Monats { ri.DayNumber = pStartDate.Day; } else // Jeden 3. Montag im Juni { ri.WeekOfMonth = pStartDate.GetWeekOfMonthForRecurrenceInfo(); } break; } break; case 2: // Endet am xx.xx.xxxx if(!pRecurrenceEndDate.HasValue) { return null; } ri.Range = RecurrenceRange.EndByDate; ri.End = pRecurrenceEndDate.Value; switch (pType) { // Start, End case RecurrenceType.Daily: if(pRecurrenceOption == 0) // Alle x Tage. Endet am xx.xx.xxxx { day = ri.Start; while(day < ri.End && ri.OccurrenceCount < 3) { day = day.AddDays(3); ri.OccurrenceCount++; } } else // Jeden Arbeitstag. Endet am xx.xx.xxxx { ri.WeekDays = WeekDays.WorkDays; ri.OccurrenceCount = (ri.End - ri.Start).Days + 1 - DateTimeUtils.GetNumberOfWeekEndDaysInBetween(ri.Start, ri.End); } break; case RecurrenceType.Weekly: ri.WeekDays = WeekDays.Monday | WeekDays.Wednesday | WeekDays.Friday; var weekDays = SUtils.GetWeekDaysFromNumber((int)ri.WeekDays); day = ri.Start; var position = weekDays.IndexOf(day.DayOfWeek) + (weekDays.Count > 1 ? 1 : 0); do { for (var i = position; i < weekDays.Count; i++) { day = SUtils.GetNextDateTime(day, weekDays.ElementAt(i), 1, RecurrenceType.Weekly).Date; ri.OccurrenceCount++; } position = (weekDays.Count - 1) % (position == 0 ? position + 1 : position); } while (day < ri.End.Date); break; case RecurrenceType.Monthly: ri.WeekOfMonth = pRecurrenceOption == 0 ? 0 : pStartDate.GetWeekOfMonthForRecurrenceInfo(); if (pRecurrenceOption == 0) // Am 17. jedes 3. Monats. Endet am xx.xx.xxxx (17. diesen Monats + 6 Monate) { ri.End = new DateTime(ri.Start.AddMonths(7).Year, ri.Start.AddMonths(7).Month, 1, ri.Start.Hour, ri.Start.Minute, ri.Start.Second); ri.DayNumber = 17; ri.Periodicity = 3; ri.WeekDays = new DateTime(ri.Start.Year, ri.Start.Month, 17).GetSchedulerWeekDays(); ri.OccurrenceCount = 3; } else // Am x. [Wochentag] jedes y. Monats. Endet am xx.xx.xxxx { // 5 mal var abc = DateTimeUtils.GetNthDayOfWeekInMonth(ri.Start.AddMonths(4), 3, DayOfWeek.Wednesday); ri.End = abc < pRecurrenceEndDate.Value ? pRecurrenceEndDate.Value : abc; ri.WeekOfMonth = WeekOfMonth.Third; ri.OccurrenceCount = 5; ri.WeekDays = WeekDays.Monday; } break; case RecurrenceType.Yearly: ri.WeekOfMonth = pRecurrenceOption == 0 ? 0 : pStartDate.GetWeekOfMonthForRecurrenceInfo(); if (pRecurrenceOption == 0) // Am x. [Monat]. Endet am xx.xx.xxxx (1 Jahr später) { ri.End = ri.Start.AddYears(1); ri.DayNumber = ri.Start.Day; ri.WeekDays = ri.Start.GetSchedulerWeekDays(); ri.Month = ri.Start.Month; ri.OccurrenceCount = ri.Start.AddYears(1).Year - ri.Start.Year + 1; } else // Jeden 3. Mittwoch im [Aktueller Monat]. Endet am xx.xx.xxxx (1 Jahr vom Startdatum entfernt) { var wednesday = ri.Start.FirstDateOfWeek(ri.Start.GetIso8601WeekOfYear()).AddDays(2); ri.WeekDays = WeekDays.Wednesday; ri.Start = DateTimeUtils.GetNthDayOfWeekInMonth(wednesday, 3, wednesday.DayOfWeek); ri.DayNumber = ri.Start.Day; ri.Month = ri.Start.Month; ri.End = DateTimeUtils.GetNthDayOfWeekInMonth(ri.Start.AddYears(1), 3, ri.Start.DayOfWeek); ri.OccurrenceCount = ri.End.Year - ri.Start.Year + 1; } break; } break; } return ri.ToXml(); } private static SchedulerAppointment GenerateTestAppointment(bool pIsPrivate, bool pIsAllDay, DateTime pStart, DateTime pEnd, AppointmentType pType, string pSubject, Employee pOriginator) { return GenerateTestAppointment(pIsPrivate, new List(), new List(), new List(), pIsAllDay, pStart, pEnd, pType, pSubject, pOriginator); } private static SchedulerAppointment GenerateTestAppointment(bool pIsPrivate, IList pCustomerList, IList pResourceList, IList pEmployeeList, bool pIsAllDay, DateTime pStart, DateTime pEnd, AppointmentType pType, string pSubject, Employee pOriginator) { var appointment = new SchedulerAppointment { AllDay = pIsAllDay, CustomerList = pCustomerList, EmployeeList = pEmployeeList, ResourceList = pResourceList, StartDate = pStart, EndDate = pEnd, Type = (int) pType, Location = CreateRandomLocationName(), IsPrivate = pIsPrivate, Subject = pSubject, Originator = pOriginator, Notice = SUtils.TestAppointmentNotice }; return appointment; } public void DeleteTestAppointments() { try { var testAppointments = DAOFactory.SearchDAO.GetTestAppointments(); DAOFactory.GenericDAO.Delete(testAppointments); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List CheckResourceAvailability(DateTime start, DateTime end, List resourceOids, long? selectedAppointmentOid) { try { var s = PluginLoader.FindClass(); return s.CheckResourceAvailability(start, end, resourceOids, selectedAppointmentOid); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public SchedulerAppointmentDC FindRootAppointmentByRecurrenceId(string recurrenceId) { var rootAppointment = DAOFactory.SearchDAO.FindRootAppointmentByRecurrenceId(recurrenceId); return rootAppointment == null ? null : MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDC(rootAppointment); } public string ValidateSchedulerAppointment(DateTime start, DateTime end, IEnumerable employees, IEnumerable customers, List resources, long originator, long? appointmentOid, Guid? recurrenceId, int occurrenceIndex = 0, bool shouldSkipResourceAvailability = false) { try { var s = PluginLoader.FindClass(); return s.ValidateSchedulerAppointment(start, end, employees, customers, resources, originator, appointmentOid, recurrenceId, occurrenceIndex); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public void DeleteMobileTestAppointments() { var appointments2Delete = DAOFactory.SearchDAO.GetAllMobileTestAppointments(); DAOFactory.GenericDAO.Delete(appointments2Delete); } public List LoadFilteredAllActiveAppointments(long employeeOid, DateTime start, DateTime end, List customerOids) { try { var entities = DAOFactory.SearchDAO.LoadFilteredAllActiveAppointments(employeeOid, start, end, customerOids); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(entities); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List LoadOccurrencesByRecurrenceId(string recurrenceId) { try { var appointments = DAOFactory.SearchDAO.LoadOccurrencesByRecurrenceId(recurrenceId); return MapperFactory.SchedulerAppointmentDCSchedulerAppointment.MapToNewDCs(appointments); } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public Dictionary> FindAppointmentsInRange(int duration, DateTime startDate, DateTime endDate, List resourceOids, List customerOids, List employeeOids, long loggedInEmployeeOid, int intervalBuffer = 30, bool skipWeekends = true) { try { var intervals = DAOFactory.SearchDAO.FindAppointmentsInRange(duration, startDate, endDate, resourceOids, customerOids, employeeOids, loggedInEmployeeOid, intervalBuffer, skipWeekends); return intervals; } catch (Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllActiveCustomersAbsenceTimesInInterval(DateTime start, DateTime end, long employeeOid, List selectedCustomerOids) { try { // Klienten nach Rechten des Mitarbeiters filtern var customers = DAOFactory.SearchDAO.GetActiveCustomersForEmployee(employeeOid, CustomerFilterEnum.All, true); var customerOids = customers.Where(customer => customer.Oid.HasValue).Select(customer => customer.Oid.Value).ToList(); customerOids = customerOids.Where(oid => selectedCustomerOids.Contains(oid)).ToList(); var absenceTimes = DAOFactory.SearchDAO.GetAllAbsenceTimesInIntervalForCustomers(start, end, customerOids); var dcList = MapperFactory.AbsenceTimeDC_AbsenceTime.MapToNewDCs(absenceTimes); // Wozu ist das gut? Es verfälscht die Abwesenheiten //foreach(var at in dcList) //{ // if(at.End.HasValue) // { // at.End = at.End.Value.Date.AddDays(1).AddTicks(-1); // } //} return dcList.OrderBy(a => a.Start).ToList(); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } public List GetAllActiveEmployeeAbsenceTimesInInterval(DateTime start, DateTime end, long employeeOid, List selectedEmployeeOids) { try { var employees = DAOFactory.SearchDAO.GetAllActiveEmployeesForEmployee(employeeOid); var employeeOids = employees.Where(employee => employee.Oid.HasValue).Select(employee => employee.Oid.Value).ToList(); employeeOids = employeeOids.Where(selectedEmployeeOids.Contains).ToList(); var absenceTimes = DAOFactory.SearchDAO.GetAllEmployeeAbsenceTimesInIntervalForEmployee(start, end, employeeOids); var dcList = MapperFactory.AbsenceTimeDC_AbsenceTime.MapToNewDCs(absenceTimes); //foreach(var at in dcList) //{ // // Das betrifft doch nur ganztägige Abwesenheiten // if(at.End.HasValue) // { // if(at.End.Value.Hour == 0 && at.End.Value.Minute == 0 && at.End.Value.Second == 0) // { // at.End = at.End.Value.Date.AddDays(1).AddTicks(-1); // } // } //} return dcList.OrderBy(a => a.Start).ToList(); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } public Dictionary> CheckResourceAvailabilityWithEmployeeInformation(DateTime start, DateTime end, List resourceOids, long? selectedAppointmentOid, Guid? recurrenceId, int occurrenceIndex = 0, bool shouldSkipResourceAvailability = false) { try { var s = PluginLoader.FindClass(); return s.CheckResourceAvailabilityWithBookingEmployees(start, end, resourceOids, selectedAppointmentOid, recurrenceId, occurrenceIndex, shouldSkipResourceAvailability); } catch(Exception e) { throw Utils.CreateBeWoFaultException(e); } } } }