using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Navigation; using BeWo.Annotations; using BeWo.Core; using BeWo.Core.Service; using BeWo.Scheduler.Converter; using BeWo.Scheduler.Utils; using BeWo.Scheduler.ViewModel; using BeWo.ServiceProxy; using BeWo.View; using BeWo.View.Detail; using BS.Shared; using BS.Shared.Core; using BS.Shared.DataContracts; using BS.Shared.DataContracts.Compact; using BS.Shared.Extensions; using BS.Shared.Translation; using DevExpress.Xpf.Bars; using DevExpress.Xpf.Editors; using DevExpress.Xpf.Scheduler; using DevExpress.Xpf.Scheduler.Reporting; using DevExpress.XtraScheduler; using DevExpress.XtraScheduler.Compatibility; using DevExpress.XtraScheduler.iCalendar; using DevExpress.XtraScheduler.Services; using Microsoft.Win32; using Appointment = DevExpress.XtraScheduler.Appointment; using AppointmentViewInfoCustomizingEventArgs = DevExpress.Xpf.Scheduler.AppointmentViewInfoCustomizingEventArgs; using ColorConverter = System.Windows.Media.ColorConverter; using DateTime = System.DateTime; using InplaceEditorEventArgs = DevExpress.Xpf.Scheduler.InplaceEditorEventArgs; using SchedulerControl = DevExpress.Xpf.Scheduler.SchedulerControl; namespace BeWo.Scheduler.View { public partial class NewSchedulerView : INotifyPropertyChanged { private bool _disableUpdateRequestString = false; private bool _IsEmployeeBrushVisible; public bool IsEmployeeBrushVisible { get => _IsEmployeeBrushVisible; set { _IsEmployeeBrushVisible = value; OnPropertyChanged(nameof(IsEmployeeBrushVisible)); } } private bool _IsAbsenceTimeVisible; public bool IsAbsenceTimeVisible { get => _IsAbsenceTimeVisible; set { _IsAbsenceTimeVisible = value; OnPropertyChanged(nameof(IsAbsenceTimeVisible)); } } private bool _IsTasksVisible; public bool IsTasksVisible { get => _IsTasksVisible; set { _IsTasksVisible = value; OnPropertyChanged(nameof(IsTasksVisible)); } } public bool IsInCustomerViewMode { get; set; } private SchedulerPrintingSettings _PrintingSettings = new SchedulerPrintingSettings(); public NewSchedulerViewModel ViewModel { get; set; } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] public void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool ZeigeNurMeineTermine { get => BeWoApp.AppSettings.ZeigeNurMeineTermine; set { if(BeWoApp.AppSettings.ZeigeNurMeineTermine != value) { BeWoApp.AppSettings.ZeigeNurMeineTermine = value; BeWoApp.SaveAppSettings(); OnPropertyChanged(nameof(ZeigeNurMeineTermine)); } } } private List _AllEmployees; public List AllEmployees { get => _AllEmployees ?? (_AllEmployees = new List()); set { if(!ListEquals(_AllEmployees, value)) { _AllEmployees = value; OnPropertyChanged(nameof(AllEmployees)); } } } private List _GefilterteMitarbeiter; public List GefilterteMitarbeiter { get => _GefilterteMitarbeiter ?? (_GefilterteMitarbeiter = new List(AllEmployees)); set { if(!ListEquals(_GefilterteMitarbeiter, value)) { _GefilterteMitarbeiter = value; _GefilterteMitarbeiter.Sort((x, y) => string.Compare(x.LastName + ", " + x.FirstName, y.LastName + ", " + y.FirstName, StringComparison.Ordinal)); OnPropertyChanged(nameof(GefilterteMitarbeiter)); } } } private List _GefilterteKlienten; public List GefilterteKlienten { get => _GefilterteKlienten ?? (_GefilterteKlienten = new List(AllCustomers)); set { if(!ListEquals(_GefilterteKlienten, value)) { _GefilterteKlienten = value; _GefilterteKlienten.Sort((x, y) => string.Compare(x.LastName + ", " + x.FirstName, y.LastName + ", " + y.FirstName, StringComparison.Ordinal)); OnPropertyChanged(nameof(GefilterteKlienten)); } } } private List _AllCustomers; public List AllCustomers { get => _AllCustomers ?? (_AllCustomers = new List()); set { if(!ListEquals(_AllCustomers, value)) { _AllCustomers = value; OnPropertyChanged(nameof(AllCustomers)); } } } private List _AllResources; public List AllResources { get => _AllResources ?? (_AllResources = new List()); set { if(!ListEquals(_AllResources, value)) { _AllResources = value; OnPropertyChanged(nameof(AllResources)); } } } private List _CustomerList; public List CustomerList { get => _CustomerList ?? (_CustomerList = new List()); set { if(!ListEquals(_CustomerList, value)) { _CustomerList = value; _CustomerList.Sort((x, y) => string.Compare(x.LastName + ", " + x.FirstName, y.LastName + ", " + y.FirstName, StringComparison.Ordinal)); OnPropertyChanged(nameof(CustomerList)); } } } private int _TimelineDayCount; private SchedulerViewType _CurrentViewType; private Dictionary> _Category2ResourcesDictionary; public Dictionary> Category2ResourcesDictionary { get => _Category2ResourcesDictionary ?? (_Category2ResourcesDictionary = new Dictionary>()); set { if(!CheckCats2ResourcesForEqualitiy(value)) { _Category2ResourcesDictionary = value; AllResources = new List(); value.DoForEach(d => AllResources.AddRange(d.Value)); OnPropertyChanged(nameof(Category2ResourcesDictionary)); } } } private bool CheckCats2ResourcesForEqualitiy(Dictionary> dic2) { if(_Category2ResourcesDictionary is null && dic2 != null || dic2 is null && _Category2ResourcesDictionary != null) { return false; } return _Category2ResourcesDictionary is null && dic2 is null || _Category2ResourcesDictionary != null && dic2 != null && _Category2ResourcesDictionary.Count == dic2.Count && _Category2ResourcesDictionary.Except(dic2).Any(); } private static bool ListEquals(IReadOnlyCollection list1, ICollection list2) { if(list1 is null && list2 is null) { return true; } if(list1 is null && list2 != null || list1 != null && list2 is null) { return false; } return list1.Count == list2.Count && list1.All(list2.Contains); } private List _SelectedEmployees = new List(); private List _SelectedCustomers = new List(); private List _SelectedResources = new List(); public List SelectedEmployees { get => _SelectedEmployees; set { if(!ListEquals(_SelectedEmployees, value)) { _SelectedEmployees = value; _SelectedEmployees.Sort((x, y) => string.Compare(x.LastName + ", " + x.FirstName, y.LastName + ", " + y.FirstName, StringComparison.Ordinal)); AlleMitarbeiterCB.IsChecked = ListEquals(value, AllEmployees); ZeigeNurMeineTermine = value.Count == 1 && value.Contains(BeWoApp.CompactLoggedOnEmployee); OnPropertyChanged(nameof(SelectedEmployees)); OnPropertyChanged(nameof(SelectedItems)); } } } public List SelectedCustomers { get => _SelectedCustomers; set { if(!ListEquals(_SelectedCustomers, value)) { _SelectedCustomers = value; _SelectedCustomers.Sort((x, y) => string.Compare(x.LastName + ", " + x.FirstName, y.LastName + ", " + y.FirstName, StringComparison.Ordinal)); if(NurMeineKlientenCB.IsChecked.HasValue && NurMeineKlientenCB.IsChecked.Value && value.Equals(GefilterteKlienten) || value.Equals(AllCustomers)) { AlleKlientenCB.IsChecked = true; } OnPropertyChanged(nameof(SelectedCustomers)); OnPropertyChanged(nameof(SelectedItems)); } } } public List SelectedResources { get => _SelectedResources; set { if(!ListEquals(_SelectedResources, value)) { _SelectedResources = value; AlleRessourcenCB.IsChecked = ListEquals(value, AllResources); OnPropertyChanged(nameof(SelectedResources)); OnPropertyChanged(nameof(SelectedItems)); } } } public IEnumerable SelectedItems { get { var erg = new List(); erg.AddRange(SelectedEmployees); erg.AddRange(SelectedCustomers); erg.AddRange(SelectedResources); return erg; } } public IEnumerable AllItems { get { var erg = new List(); erg.AddRange(GefilterteKlienten); erg.AddRange(AllResources); return erg; } } public static bool IgnoreChangeEvents; //private List _EmployeesTeams = new List(); private string _Requests; public string Requests { get => _Requests ?? (_Requests = "keine Benachrichtigungen"); set { _Requests = value; OnPropertyChanged(nameof(Requests)); } } public static TimeSpan FetchPadding = TimeSpan.FromDays(14); private TimeInterval _LastFetchedInterval = new TimeInterval(); public long CustomerOidToPreselect { get; set; } //private static string[] outlookCalendarPaths; //public static string[] OutlookCalendarPaths //{ // get // { // if (outlookCalendarPaths != null) // return outlookCalendarPaths; // try // { // outlookCalendarPaths = OutlookExchangeHelper.GetOutlookCalendarPaths(); // } // catch // { // outlookCalendarPaths = new string[0]; // } // return outlookCalendarPaths; // } //} // KONSTRUKTOR public NewSchedulerView(long customerOid) { // Kalenderaufruf aus dem CustomerView2 heraus CustomerOidToPreselect = customerOid; ConstructObject(); //PruefeObAbwesenheitsuebertragungErlaubt(); } public NewSchedulerView() { ConstructObject(); } private DateTime? _SelectedAppointmentStartDate; private SchedulerAppointmentDC _SelectedAppointmentFromHomePanelView; public NewSchedulerView(DateTime pIntervalStartDate, SchedulerAppointmentDC pAppointment) { _SelectedAppointmentFromHomePanelView = pAppointment; _SelectedAppointmentStartDate = pIntervalStartDate; ConstructObject(); } private static void GetCacheObjects(Action, List, Dictionary>> callback) { Cache.GetInstance().GetSchedulerObjects(callback); } private void ConstructObject() { IsEmployeeBrushVisible = true; InitializeComponent(); InitViewModel(); InitScheduler(); Scheduler.Storage.AppointmentStorage.ResourceSharing = false; DataContext = this; EditorLocalizer.Active = new GermanEditorLocalizer(); InitRights(); foreach(var item in from object item in TabControl.Items let ti = (TabItem)item where ti.Visibility.Equals(Visibility.Visible) select item) { TabControl.SelectedIndex = TabControl.Items.IndexOf(item); break; } } //private void Synchronize() //{ // var synchronizer = new OutlookExportSynchronizer(Scheduler.Storage.GetCoreStorage()); // if (OutlookCalendarPaths.Length <= 0) return; // ((ISupportCalendarFolders) synchronizer).CalendarFolderName = OutlookCalendarPaths[0]; // synchronizer.ForeignIdFieldName = "OutlookEntryId"; // synchronizer.AppointmentSynchronizing += (sender, args) => // { // }; // synchronizer.Synchronize(); //} private bool _IstErsterAufruf = true; #region InitViewModel private void InitViewModel() { ViewModel = new NewSchedulerViewModel(); ViewModel.ViewModelChanged += ViewModel_ViewModelChanged; ViewModel.ViewModelChanged += UpdateRequestStringEvent; } private void ViewModel_ViewModelChanged(object sender, EventArgs e) { this.Dispatch(() => { UpdateDataSource(e.Data); LoadSchedulerViewType(); if(_IstErsterAufruf) { if(MainControl.HatNeueTermine && _SelectedAppointmentFromHomePanelView == null) { FensterOeffnen(); } else { OpenAppointmentFromHomePanel(); } _IstErsterAufruf = false; } }); } private void InitScheduler() { if(_SelectedAppointmentFromHomePanelView != null && _SelectedAppointmentStartDate.HasValue) { var monday = _SelectedAppointmentStartDate.Value.FirstDateOfWeek(_SelectedAppointmentStartDate.Value.GetIso8601WeekOfYear()); Scheduler.Start = monday; } else { Scheduler.Start = DateTime.Today; } _TimelineDayCount = 0; Scheduler.DayView.NavigationButtonVisibility = NavigationButtonVisibility.Always; Scheduler.DayView.AppointmentDisplayOptions.ShowRecurrence = true; Scheduler.DayView.AppointmentDisplayOptions.ShowReminder = true; Scheduler.DayView.ResourcesPerPage = 1; Scheduler.WorkWeekView.ShowFullWeek = _SelectedAppointmentFromHomePanelView != null && (Scheduler.Start.DayOfWeek.Equals(DayOfWeek.Saturday) || Scheduler.Start.DayOfWeek.Equals(DayOfWeek.Sunday)); Scheduler.WorkWeekView.ShowWorkTimeOnly = false; Scheduler.WorkWeekView.NavigationButtonVisibility = NavigationButtonVisibility.Always; Scheduler.WorkWeekView.ResourcesPerPage = 1; Scheduler.WeekView.NavigationButtonVisibility = NavigationButtonVisibility.Always; Scheduler.WeekView.ResourcesPerPage = 1; Scheduler.MonthView.NavigationButtonVisibility = NavigationButtonVisibility.Always; Scheduler.MonthView.ResourcesPerPage = 1; Scheduler.TimelineView.NavigationButtonVisibility = NavigationButtonVisibility.Always; Scheduler.TimelineView.ResourcesPerPage = 1; } private void LoadSchedulerViewType() { var settings = ViewModel.GetActiveSettings(); _CurrentViewType = BeWoApp.AppSettings.SchedulerViewType; Scheduler.ActiveViewType = _CurrentViewType; Scheduler.DayView.DayCount = BeWoApp.AppSettings.SchedulerDayViewDayCount; settings.DayViewCount = BeWoApp.AppSettings.SchedulerDayViewDayCount; Scheduler.TimelineView.IntervalCount = BeWoApp.AppSettings.SchedulerTimelineViewDayCount; settings.TimelineIntervalCount = BeWoApp.AppSettings.SchedulerTimelineViewDayCount; UpdateOptionPanel(); switch(_CurrentViewType) { case SchedulerViewType.Day: DayViewOptions.Visibility = Visibility.Visible; TimelineViewOptions.Visibility = Visibility.Collapsed; break; case SchedulerViewType.Month: var interval = Scheduler.ActiveView.GetVisibleIntervals(); Scheduler.ActiveView.SetVisibleIntervals(new TimeIntervalCollection {new TimeInterval(interval.Start, new TimeSpan(35, 0, 0, 0))}); UpdateOptionPanel(); break; case SchedulerViewType.Timeline: DayViewOptions.Visibility = Visibility.Collapsed; TimelineViewOptions.Visibility = Visibility.Visible; break; } } private void SaveSchedulerViewType(SchedulerViewType schedulerViewType) { BeWoApp.AppSettings.SchedulerViewType = schedulerViewType; var settings = ViewModel.GetActiveSettings(); if(settings is null) { return; } BeWoApp.AppSettings.SchedulerTimelineViewDayCount = settings.TimelineIntervalCount; BeWoApp.SaveAppSettings(); } private void InitRights() { MitarbeiterTabItem.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen) ? Visibility.Visible : Visibility.Collapsed; RessourcenTabItem.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAnsehen) ? Visibility.Visible : Visibility.Collapsed; KlientenTabItem.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View) || BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_ViewMyTeams) || BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_ViewMyCustomers) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll) ? Visibility.Visible : Visibility.Collapsed; MitarbeiterEbenenCheckBox.Visibility = MitarbeiterTabItem.Visibility; RessourcenEbenenCheckBox.Visibility = RessourcenTabItem.Visibility; KlientenEbenenCheckBox.Visibility = KlientenTabItem.Visibility; MitarbeiterfarbenEinAusCheckBox.Visibility = MitarbeiterTabItem.Visibility; ButtonDeleteAppointments.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.Termine_IntervalDelete) ? Visibility.Visible : Visibility.Collapsed; AbwesenheitButtonItem.IsVisible = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderInAbwesenheitenUebernehmen) ? true : false; } private void UpdateDataSource(ISchedulerViewModel vm) { try { IgnoreChangeEvents = true; Scheduler.Storage.BeginUpdate(); UpdateCustomFieldMappings(vm); Scheduler.Storage.EndUpdate(); // DateTime.MaxValue wird nicht unterstützt, weil zu dem EndDate noch etwas draufaddiert wird und dann der MaxValue überschritten werden würde Scheduler.Storage.AppointmentStorage.DataSource = vm.Appointments; Scheduler.Storage.BeginUpdate(); UpdateSchedulerSettings(); foreach(var item in Scheduler.Storage.AppointmentStorage.Items) { var bapp = item.GetSourceObject(Scheduler.GetCoreStorage()) as IBeWoAppointment; if(item.IsRecurring) { var ausnahmen = item.GetExceptions(); foreach(var exc in ausnahmen) { var beWoAppointment = exc.GetSourceObject(Scheduler.GetCoreStorage()) as IBeWoAppointment; if(beWoAppointment?.CustomFields is null) { continue; } foreach(var field in beWoAppointment.CustomFields) { exc.CustomFields[field.Key] = field.Value; } } } if(bapp?.CustomFields is null) { continue; } foreach(var field in bapp.CustomFields) { item.CustomFields[field.Key] = field.Value; } } } catch(Exception e) { throw e; } finally { Scheduler.Storage.EndUpdate(); IgnoreChangeEvents = false; } } private void UpdateSchedulerSettings() { var settings = ViewModel.GetActiveSettings(); Scheduler.Start = settings.StartDate; var starttimeInterval = settings.StartDate.Date; if(_SelectedAppointmentStartDate.HasValue) { var weekOfYear = _SelectedAppointmentStartDate.Value.GetIso8601WeekOfYear(); var monday = _SelectedAppointmentStartDate.Value.FirstDateOfWeek(weekOfYear); settings.StartDate = monday; Scheduler.Start = monday; starttimeInterval = settings.StartDate; settings.ViewType = _SelectedAppointmentStartDate.Value.DayOfWeek == DayOfWeek.Saturday || _SelectedAppointmentStartDate.Value.DayOfWeek == DayOfWeek.Sunday ? AppointmentViewType.Week : AppointmentViewType.WorkWeek; _SelectedAppointmentStartDate = null; } else { settings.ViewType = ViewTypeConvert.ToAppointmentViewType(_CurrentViewType); } starttimeInterval = starttimeInterval.AddHours(Scheduler.WorkWeekView.WorkTime.Start.Hours); switch(settings.ViewType) { case AppointmentViewType.Day: Scheduler.ActiveViewType = SchedulerViewType.Day; Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0))); Scheduler.DayView.DayCount = settings.DayViewCount; break; case AppointmentViewType.Week: Scheduler.ActiveViewType = SchedulerViewType.Week; Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0))); break; case AppointmentViewType.Month: Scheduler.ActiveViewType = SchedulerViewType.Month; break; case AppointmentViewType.WorkWeek: Scheduler.ActiveViewType = SchedulerViewType.WorkWeek; Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0))); break; case AppointmentViewType.Timeline: Scheduler.ActiveViewType = SchedulerViewType.Timeline; Scheduler.TimelineView.ResourcesPerPage = settings.TimelineResourceCount; Scheduler.TimelineView.IntervalCount = settings.TimelineIntervalCount; break; } UpdateOptionPanel(); try { Scheduler.GroupType = settings.GroupByResource ? SchedulerGroupType.Resource : SchedulerGroupType.None; Scheduler.OptionsCustomization.AllowAppointmentCreate = UsedAppointmentType.Custom; Scheduler.OptionsCustomization.AllowAppointmentDrag = UsedAppointmentType.Custom; Scheduler.OptionsCustomization.AllowAppointmentDelete = UsedAppointmentType.Custom; Scheduler.OptionsCustomization.AllowAppointmentEdit = UsedAppointmentType.Custom; Scheduler.OptionsCustomization.AllowAppointmentDragBetweenResources = UsedAppointmentType.Custom; } catch(Exception) { MessageBox.Show("Ein Fehler bei der Darstellung ist aufgetreten.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } private void UpdateCustomFieldMappings(ISchedulerViewModel vm) { Scheduler.Storage.AppointmentStorage.CustomFieldMappings.Clear(); vm.AddCustomFieldsMapping(Scheduler.Storage); } #endregion public CheckBoxConverter CheckBoxConverter => Resources[nameof(CheckBoxConverter)] as CheckBoxConverter; #region Filterauswahl private void AlleMitarbeiterCB_OnClick(object sender, RoutedEventArgs e) { if(sender is CheckBox checkBox) { var isChecked = checkBox.IsChecked ?? false; SelectedEmployees = isChecked ? new List(AllEmployees) : new List(); if(SelectedEmployees.Count > 1) { ZeigeNurMeineTermine = false; } TeamMembersCheckBox.IsChecked = false; return; } var cb = (CheckBox) sender; if(!cb.IsChecked.HasValue) { return; } SelectedEmployees = cb.IsChecked.Value ? new List(AllEmployees) : new List(); if(SelectedEmployees.Count > 1) { ZeigeNurMeineTermine = false; } } private void MitarbeiterListe_OnClick(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; if(CheckBoxConverter != null && cb.DataContext is CompactEmployeeDC selectedEmployee) { CheckBoxConverter.AktuellerMitarbeiter = selectedEmployee; } } private void AlleRessourcenCB_OnClick(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; if(!cb.IsChecked.HasValue) { return; } SelectedResources = cb.IsChecked.Value ? new List(AllResources) : new List(); if(CheckBoxConverter != null && SelectedResources != null) { CheckBoxConverter.SelektierteRessourcen = SelectedResources; ReloadVM(true); } } private void RessourcenKategorieCB_OnClick(object sender, RoutedEventArgs e) { var cb = (CheckBox)sender; if (!cb.IsChecked.HasValue) { return; } var list = cb.Tag as List; if (SelectedResources == null) { SelectedResources = new List(); } foreach (var item in list) { if (cb.IsChecked.Value && !SelectedResources.Contains(item)) { SelectedResources.Add(item); } else if (!cb.IsChecked.Value && SelectedResources.Contains(item)) { SelectedResources.Remove(item); } } if (CheckBoxConverter != null) { OnPropertyChanged(nameof(SelectedResources)); OnPropertyChanged(nameof(SelectedItems)); CheckBoxConverter.SelektierteRessourcen = SelectedResources; ReloadVM(true); } } private void RessourcenTV_OnClick(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; if(CheckBoxConverter != null && cb.DataContext is ResourceDC selectedResource) { CheckBoxConverter.AktuelleRessource = selectedResource; } } private void AlleKlientennCB_OnClick(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; if(!cb.IsChecked.HasValue) return; if(NurMeineKlientenCB.IsChecked.HasValue && NurMeineKlientenCB.IsChecked.Value) { SelectedCustomers = cb.IsChecked.Value ? new List(GefilterteKlienten) : new List(); } else { SelectedCustomers = cb.IsChecked.Value ? new List(AllCustomers) : new List(); } } private void KlientenListe_OnClick(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; if(CheckBoxConverter != null && cb.DataContext is CompactCustomerDC selectedCustomer) { CheckBoxConverter.AktuellerKlient = selectedCustomer; } } private void ListItemCheckedEvent(object sender, RoutedEventArgs e) { ReloadVM(true); } private void BtnRemoveElement_Click(object sender, RoutedEventArgs e) { var selectedDC = ((Button) sender).Tag as IDataContract; switch(selectedDC) { case CompactEmployeeDC _: var employee = selectedDC as CompactEmployeeDC; SelectedEmployees.Remove(employee); OnPropertyChanged(nameof(SelectedEmployees)); if(employee != null && employee.Equals(BeWoApp.CompactLoggedOnEmployee)) { ZeigeNurMeineTermine = false; ReloadVM(true); } else if(SelectedEmployees.Count == 1 && SelectedEmployees.First().Equals(BeWoApp.CompactLoggedOnEmployee)) { ZeigeNurMeineTermine = true; } break; case CompactCustomerDC _: var customer = selectedDC as CompactCustomerDC; SelectedCustomers.Remove(customer); OnPropertyChanged(nameof(SelectedCustomers)); break; case ResourceDC _: var resource = selectedDC as ResourceDC; SelectedResources.Remove(resource); OnPropertyChanged(nameof(SelectedResources)); break; } OnPropertyChanged(nameof(SelectedItems)); } private void ButtonDayView_Click(object sender, RoutedEventArgs e) { Scheduler.ActiveViewType = SchedulerViewType.Day; _CurrentViewType = Scheduler.ActiveViewType; UpdateOptionPanel(); DayViewOptions.Visibility = Visibility.Visible; TimelineViewOptions.Visibility = Visibility.Collapsed; SaveSchedulerViewType(SchedulerViewType.Day); } private void ButtonMonthView_Click(object sender, RoutedEventArgs e) { Scheduler.ActiveViewType = SchedulerViewType.Month; _CurrentViewType = Scheduler.ActiveViewType; var interval = Scheduler.ActiveView.GetVisibleIntervals(); Scheduler.ActiveView.SetVisibleIntervals(new TimeIntervalCollection {new TimeInterval(interval.Start, new TimeSpan(35, 0, 0, 0))}); UpdateOptionPanel(); SaveSchedulerViewType(SchedulerViewType.Month); } private void ButtonWorkWeekView_Click(object sender, RoutedEventArgs e) { Scheduler.ActiveViewType = SchedulerViewType.WorkWeek; _CurrentViewType = Scheduler.ActiveViewType; UpdateOptionPanel(); SaveSchedulerViewType(SchedulerViewType.WorkWeek); } private void ButtonWeekView_Click(object sender, RoutedEventArgs e) { Scheduler.ActiveViewType = SchedulerViewType.Week; _CurrentViewType = Scheduler.ActiveViewType; UpdateOptionPanel(); SaveSchedulerViewType(SchedulerViewType.Week); } private void ButtonTimelineView_Click(object sender, RoutedEventArgs e) { Scheduler.ActiveViewType = SchedulerViewType.Timeline; _CurrentViewType = Scheduler.ActiveViewType; UpdateOptionPanel(); DayViewOptions.Visibility = Visibility.Collapsed; TimelineViewOptions.Visibility = Visibility.Visible; SaveSchedulerViewType(SchedulerViewType.Timeline); } private void SpinEditDayViewDayCount_EditValueChanged(object sender, EditValueChangedEventArgs e) { if(e.NewValue != null && int.TryParse(e.NewValue.ToString(), out var count) && count > 0) { Scheduler.DayView.DayCount = count; _TimelineDayCount = count; BeWoApp.AppSettings.SchedulerDayViewDayCount = count; } } private void SpinEditTimelineViewDayCount_EditValueChanged(object sender, EditValueChangedEventArgs e) { if(e.NewValue != null && int.TryParse(e.NewValue.ToString(), out var count) && count > 0) { Scheduler.TimelineView.IntervalCount = count; _TimelineDayCount = count; BeWoApp.AppSettings.SchedulerTimelineViewDayCount = count; } } #endregion private bool _Enabled; public bool Enabled { get => _Enabled; set { _Enabled = value; OnPropertyChanged(nameof(Enabled)); } } public void UpdateRequestString() { if (_disableUpdateRequestString) { return; } ServiceFacade.DoResourceServiceSync(r => _Liste = r.GetAllOpenAppointmentsForEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value)); var count = 0; var oidList = new List(); foreach(var termin in _Liste) { if(termin.Originator.EmployeeOid == BeWoApp.LoggedOnEmployee.EmployeeOid.Value) { foreach(var status in termin.EmployeeList.Where(w => w.Employee.EmployeeOid != BeWoApp.LoggedOnEmployee.EmployeeOid.Value)) { if(status.IsPChanged && status.ParticipationAnswer != ParticipationAnswer.Offen && status.ParticipationAnswer != ParticipationAnswer.Verstrichen && !oidList.Contains(status.Employee2SchedulerAppointmentOid.Value)) { oidList.Add(status.Employee2SchedulerAppointmentOid.Value); count++; } } } else { if(termin.EmployeeList.Any(a => a.Employee.EmployeeOid == BeWoApp.LoggedOnEmployee.EmployeeOid.Value)) { foreach(var status in termin.EmployeeList.Where(w => w.Employee.EmployeeOid == BeWoApp.LoggedOnEmployee.EmployeeOid.Value)) { if(!status.IsPChanged && status.ParticipationAnswer == ParticipationAnswer.Offen && status.ParticipationAnswer != ParticipationAnswer.Verstrichen && !oidList.Contains(status.Employee2SchedulerAppointmentOid.Value)) { oidList.Add(status.Employee2SchedulerAppointmentOid.Value); count++; } } } } } Enabled = count > 0; Requests = $"{(count == 0 ? "keine" : count.ToString())} Benachrichtigung{(count == 1 ? "" : "en")}"; } private List _Liste = new List(); private void NewSchedulerStorage_AppointmentsChanged(object sender, PersistentObjectsEventArgs e) { var appList = e.Objects.Cast().ToList(); if (IgnoreChangeEvents || IgnoreManualAppointmentCreation) { return; } if(appList.Any(f => f.CF_IsPrivate())) { ShowPrivateAppointmentsCheckBox.IsChecked = true; } var changedAppointments = appList.Where(appointment => appointment.Type != AppointmentType.DeletedOccurrence).ToList(); ViewModel.ActiveAppointmentViewModel.SaveAppointments(Scheduler, changedAppointments); ReloadVM(true); } private int _NumberOfAppointmentsToDelete; private readonly List _AppointmentsToDelete = new List(); private void NewSchedulerStorage_AppointmentDeleting(object sender, PersistentObjectCancelEventArgs e) { var appointment = (Appointment) e.Object; var items = Scheduler.Storage.AppointmentStorage.Items; if(appointment.IsRecurring) { var aptList = new List(); foreach(var item in items) { var apt = item.GetSourceObject(Scheduler.GetCoreStorage()) as SchedulerAppointmentVM; aptList.Add(apt); } var serientermine = aptList.Where(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Contains(appointment.RecurrenceInfo.Id.ToString()) && w.EventType == 1).ToList(); var root = serientermine.FirstOrDefault(); if(root?.CustomFields[nameof(CustomFieldStorage)] != null) { var customFieldStorage = (CustomFieldStorage) root.CustomFields[nameof(CustomFieldStorage)]; if(customFieldStorage.InternalInfo?.IsTimeChangedRecurringAppointment ?? false) { e.Cancel = true; return; } } } var selectedAppointmentCount = Scheduler.SelectedAppointments.Count; if(_NumberOfAppointmentsToDelete == 0) { _NumberOfAppointmentsToDelete = selectedAppointmentCount; } var sourceObj = (SchedulerAppointmentVM) appointment.GetSourceObject(Scheduler.GetCoreStorage()); if(!(sourceObj is null)) { var customerOids = new List(); ServiceFacade.DoEmployeeServiceSync(s => customerOids = s.LoadTeamsRelatedCustomerOids(BeWoApp.CompactLoggedOnEmployee.EmployeeOid)); if(!BeWoUtils.CheckSchedulerRights(appointment, sourceObj.IsNew, SchedulerRightsCheckType.Edit, customerOids, true)) { e.Cancel = true; return; } if(e.Object is Appointment app) { e.Cancel = PrepareDeletion(app); } } else { if(e.Object is Appointment app) { e.Cancel = PrepareDeletion(app); } } } private bool PrepareDeletion(Appointment appointment) { var shouldCancel = false; var msg = GetDeleteMessageForAppointment(appointment); var dataContract = appointment.GetSourceObject(Scheduler.GetCoreStorage()) is SchedulerAppointmentVM schedulerAppointmentVM ? schedulerAppointmentVM.CommitToDataContract() : CreateDummyAppointment(appointment); if(dataContract.SchedulerAppointmentOid.HasValue) { // Nur bei Normalem Typ nachfragen. Bei Serienterminen wird bereits im Fenster vorher gefragt, ob gelöscht werden soll. if (appointment.Type == AppointmentType.Normal && MessageBox.Show(msg, "BeWoPlaner", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No) { shouldCancel = true; if(_NumberOfAppointmentsToDelete > 0) { _NumberOfAppointmentsToDelete--; } _AppointmentsToDelete.Remove(dataContract); } else { _AppointmentsToDelete.AddIfNotIn(dataContract); if(_AppointmentsToDelete.Count == _NumberOfAppointmentsToDelete) { DeleteAppointments(); } } } return shouldCancel; } private long _DummyOid = -1; private SchedulerAppointmentDC CreateDummyAppointment(Appointment appointment) { var dummyAppointment = new SchedulerAppointmentDC { SchedulerAppointmentOid = _DummyOid, Subject = appointment.Subject, StartDate = appointment.Start, EndDate = appointment.End }; _DummyOid--; return dummyAppointment; } private void DeleteAppointments() { var stringBuilder = new StringBuilder(); foreach(var appointment in _AppointmentsToDelete.OrderBy(o => o.StartDate).ThenBy(o => o.EndDate)) { var oid = appointment.SchedulerAppointmentOid?.ToString() ?? "NO OID"; var start = appointment.StartDate.Value; var end = appointment.EndDate.Value; string type; switch(appointment.Type) { case 0: type = "Normal"; break; case 1: type = "Pattern"; break; case 2: type = "Occurrence"; break; case 3: type = "ChangedOccurrence"; break; case 4: type = "DeletedOccurrence"; break; default: type = "Normal"; break; } stringBuilder.AppendLine($"\tOid:\t\t{oid}\r\n\tBetreff: {appointment.Subject}\r\n\tStart:\t\t{start:dd.MM.yyyy HH:mm}\r\n\tEnde:\t\t{end:dd.MM.yyyy HH:mm}\r\n\tTyp:\t\t{type}\r\n"); } //BeWoApp.LogMessage($"DeleteAppointments aufgerufen. Es {(_AppointmentsToDelete.Count == 1 ? "wird" : "werden")} {_AppointmentsToDelete.Count} {(_AppointmentsToDelete.Count == 1 ? "Termin" : "Termine")} gelöscht\n{stringBuilder}", Colors.Red); var idList = (from item in _AppointmentsToDelete where item.SchedulerAppointmentOid.HasValue && item.SchedulerAppointmentOid.Value > 0 select item.SchedulerAppointmentOid.Value).ToList(); IgnoreChangeEvents = true; ServiceFacade.DoResourceServiceAsync(s => s.GetSchedulerAppointmentsById(idList), appointments2 => { var oids2Versions = appointments2.ToDictionary(dc => dc.SchedulerAppointmentOid.Value, dc => dc.NewSchedulerAppointmentVersion.Value); ServiceFacade.DoResourceServiceAsync(s2 => s2.DeactivateSchedulerAppointmentsForSync(oids2Versions), updatedAppointments2 => { this.Dispatch(() => { ViewModel.ActiveAppointmentViewModel.UpdateViewModel(updatedAppointments2); Scheduler.ActiveView.LayoutChanged(); UpdateRequestString(); ReloadVM(true); ResetDeletionMode(); IgnoreChangeEvents = false; }); }); }); } private static string GetDeleteMessageForAppointment(Appointment appointment) { var message = "Möchten Sie den gewählten Termin wirklich löschen?"; if(appointment != null) { var subject = appointment.Subject; var interval = GetAppointmentTimeString(appointment); message = $"Möchten Sie den gewählten Termin \"{subject}\" vom {interval} wirklich löschen?"; } return message; } public static string GetAppointmentTimeString(Appointment appointment) { var interval = string.Empty; if(appointment != null) { var start = appointment.Start; var end = appointment.End; // 1. 17. August 2021 09:00 Uhr bis 10:00 Uhr // 2. 17. August 2021 // 3. 17. August 2021 09:00 Uhr bis 19. August 2021 10 Uhr // 4. 17. August 2021 bis 19. August 2021 if(start.Date == end.Date) { interval = appointment.AllDay ? $"{start:dd. MMMM yyyy}" : $"{start:dd. MMMM yyyy HH:mm} Uhr bis {end:HH:mm} Uhr"; } else { interval = appointment.AllDay ? $"{start:dd. MMMM yyyy} bis zum {end:dd. MMMM yyyy}" : $"{start: dd. MMMM yyyy HH:mm} Uhr bis zum {end:dd. MMMM yyyy HH:mm} Uhr"; } } return interval; } private void ResetDeletionMode() { _AppointmentsToDelete.Clear(); _NumberOfAppointmentsToDelete = 0; _DummyOid = 0; } private void NewSchedulerStorage_AppointmentsInserted(object sender, PersistentObjectsEventArgs e) { if(IgnoreManualAppointmentCreation) { return; } var appList = e.Objects.Cast().ToList(); if(appList.Any(f => f.CF_IsPrivate())) { ShowPrivateAppointmentsCheckBox.IsChecked = true; } ViewModel.ActiveAppointmentViewModel.InsertAppointments(Scheduler, appList); UpdateRequestString(); ReloadVM(true); } private void Scheduler_EditAppointmentFormShowing(object sender, EditAppointmentFormEventArgs e) { var control = (SchedulerControl) sender; IgnoreChangeEvents = true; if(_IsNew) { var employees2Appointments = new ObservableCollection(SelectedEmployees.Select(item => new Employee2SchedulerAppointmentDC {Employee = item, ParticipationAnswer = ParticipationAnswer.Offen}).ToList()); e.Appointment.CF_EmployeeList(employees2Appointments); e.Appointment.CF_CustomerList(new List(SelectedCustomers)); e.Appointment.CF_ResourceList(new List(SelectedResources)); } var app = e.Appointment; if (app.AllDay) // Neue Ganztägige Termine funktionieren nicht richtig, wenn man das Ganztägig wegklickt, wird das Enddatum falsch gesetzt { if (app.CustomFields != null && app.CustomFields.Count > 0) { var cf = app.CustomFields[0] as CustomFieldStorage; if (cf != null && !cf.SchedulerAppointmentOid.HasValue) // Nur bei neuen Terminen { app.AllDay = true; //app.Start = app.Start.Date.AddHours(8); //app.End = app.Start.Date.AddHours(9); app.Start = app.Start.Date; app.End = app.Start.Date; } } } var form = ViewModel.GetEditAppointmentForm(control, e.Appointment); if(form is null) { if(_IsNew) { _IsNew = false; } IgnoreChangeEvents = false; return; } e.Form = form; e.AllowResize = false; if(_IsNew) { _IsNew = false; } IgnoreChangeEvents = false; } private void SchedulerControl_EditRecurrentAppointmentFormShowing(object sender, EditAppointmentFormEventArgs e) { } private void Scheduler_PopupMenuShowing(object sender, SchedulerMenuEventArgs e) { if(Scheduler.SelectedAppointments?.Count == 1) { var customerOids = new List(); ServiceFacade.DoEmployeeServiceSync(s => customerOids = s.LoadTeamsRelatedCustomerOids(BeWoApp.CompactLoggedOnEmployee.EmployeeOid)); bool isAllowedToEdit; var test = Scheduler.SelectedAppointments.First(); if(test.IsOccurrence) { var patternAppointment = test.RecurrencePattern; var sourceObject = patternAppointment.GetSourceObject(Scheduler.GetCoreStorage()); var viewModel = (SchedulerAppointmentVM) sourceObject; isAllowedToEdit = BeWoUtils.CheckSchedulerRights(test, viewModel.IsNew, SchedulerRightsCheckType.Edit, customerOids, true); } else { isAllowedToEdit = Scheduler.SelectedAppointments.Any(a => BeWoUtils.CheckSchedulerRights(a, ((SchedulerAppointmentVM) a.GetSourceObject(Scheduler.GetCoreStorage())).IsNew, SchedulerRightsCheckType.Edit, customerOids, true)); } if(!isAllowedToEdit) { var menuItem = e.Menu.ItemLinks.FirstOrDefault(f => f.Name.Contains("DeleteAppointment")); if(menuItem != null) { e.Menu.ItemLinks.Remove(menuItem); } } } if(!BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.Mitarbeiterstundenkonto_ViewAll)) { var verfuegbarkeitMenue = e.Menu.ItemLinks.FirstOrDefault(f => f.GetType() == typeof(BarButtonItemLink) && (((BarButtonItemLink) f).Item?.Name.Contains("MitarbeiterVerfuegbarkeitPruefenButtonItem") ?? false)); if(verfuegbarkeitMenue != null) { e.Menu.ItemLinks.Remove(verfuegbarkeitMenue); } } if(Scheduler.SelectedAppointments.Count == 0 || Scheduler.SelectedAppointments[0]?.Type != AppointmentType.ChangedOccurrence) { var restoreMenu = e.Menu.ItemLinks.FirstOrDefault(f => { var type = f.GetType(); if(type == typeof(BarButtonItemLink)) { var item = (BarButtonItemLink) f; if(item.Name.Contains("RestoreAppointmentButtonItem")) { return true; } } return false; }); if(restoreMenu != null) { e.Menu.ItemLinks.Remove(restoreMenu); } } if(!BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderInZeiterfassungUebernehmen)) { BarItemLinkBase menuItem = null; foreach(var item in e.Menu.ItemLinks) { if(item.GetType() == typeof(BarButtonItemLink)) { var barButton = (BarButtonItemLink) item; if(barButton.Name.Contains("ZeiterfassungButtonItem")) { menuItem = item; } } } if(menuItem != null) { e.Menu.ItemLinks.Remove(menuItem); } } if(Scheduler.SelectedAppointments.Count > 0) { var zusageButton = e.Menu.ItemLinks.FirstOrDefault(f => f.GetType() == typeof(BarButtonItemLink) && ((BarButtonItemLink) f).BarItemName.Equals("ZusagenButtonItem")); var mitVorbehaltButton = e.Menu.ItemLinks.FirstOrDefault(f => f.GetType() == typeof(BarButtonItemLink) && ((BarButtonItemLink) f).BarItemName.Equals("MitVorbehaltButtonItem")); var absageButton = e.Menu.ItemLinks.FirstOrDefault(f => f.GetType() == typeof(BarButtonItemLink) && ((BarButtonItemLink) f).BarItemName.Equals("AbsagenButtonItem")); var seperatorTop = e.Menu.ItemLinks.FirstOrDefault(f => f.GetType() == typeof(BarItemLinkSeparator) && ((BarItemLinkSeparator) f).BarItemName.Equals("ZusagenStackSeperatorTop")); var seperatorBottom = e.Menu.ItemLinks.FirstOrDefault(f => f.GetType() == typeof(BarItemLinkSeparator) && ((BarItemLinkSeparator) f).BarItemName.Equals("ZusagenStackSeperatorBottom")); if(!Scheduler.SelectedAppointments[0].CF_IsTask() && Scheduler.SelectedAppointments[0].CF_EmployeeList().Any(a => a.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid))) { return; } if(seperatorTop != null) { e.Menu.ItemLinks.Remove(seperatorTop); } if(seperatorBottom != null) { e.Menu.ItemLinks.Remove(seperatorBottom); } if(zusageButton != null) { e.Menu.ItemLinks.Remove(zusageButton); } if(mitVorbehaltButton != null) { e.Menu.ItemLinks.Remove(mitVorbehaltButton); } if(absageButton != null) { e.Menu.ItemLinks.Remove(absageButton); } } } private bool _IsNew; private void Scheduler_InitNewAppointment(object sender, AppointmentEventArgs e) { _IsNew = true; ViewModel.InitNewAppointment(e.Appointment); } private void Scheduler_AppointmentViewInfoCustomizing(object sender, AppointmentViewInfoCustomizingEventArgs e) { var appointment = e.ViewInfo.Appointment; var customFields = e.ViewInfo.Appointment.CustomFields; if(customFields[nameof(CustomFieldStorage)] is null) { return; } customFields.BeginUpdate(); e.ViewInfo.CustomViewInfo = customFields; customFields.EndUpdate(); } private void AllowAppointmentAenderung(object sender, AppointmentOperationEventArgs e) { var darfTerminDetailsSehen = true; var appointment = e.Appointment; if(appointment.GetCustomFieldStorage() is null) { e.Allow = false; return; } if(appointment.CF_IsAbsenceTime()) { e.Allow = false; return; } var ersteller = appointment.CF_Originator(); var mitarbeiterliste = appointment.CF_EmployeeList(); var istErsteller = ersteller?.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) ?? false; bool canBeEdited = appointment.CF_CanBeEdited(); if (!istErsteller && appointment.CF_IsPrivate() && !mitarbeiterliste.Any(a => Equals(a.Employee, BeWoApp.CompactLoggedOnEmployee)) || !canBeEdited) { darfTerminDetailsSehen = false; } e.Allow = darfTerminDetailsSehen; } private void AllowAppointmentCreateEvent(object sender, AppointmentOperationEventArgs e) { e.Allow = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderAnsehen) || BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderKliententermineAnlegen) || BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnlegen); } private void UpdateOptionPanel() { switch(ViewTypeConvert.ToAppointmentViewType(_CurrentViewType)) { case AppointmentViewType.Day: TimelineViewOptions.Visibility = Visibility.Collapsed; DayViewOptions.Visibility = Visibility.Visible; SpinEditDayViewDayCount.Value = Scheduler.DayView.DayCount; _TimelineDayCount = 0; break; case AppointmentViewType.Timeline: TimelineViewOptions.Visibility = Visibility.Visible; DayViewOptions.Visibility = Visibility.Collapsed; SpinEditTimelineViewDayCount.Value = _TimelineDayCount == 0 ? Scheduler.TimelineView.IntervalCount : _TimelineDayCount; break; default: _TimelineDayCount = 0; TimelineViewOptions.Visibility = Visibility.Collapsed; DayViewOptions.Visibility = Visibility.Collapsed; break; } Scheduler.WeekView.AppointmentDisplayOptions.AppointmentAutoHeight = true; Scheduler.MonthView.AppointmentDisplayOptions.AppointmentAutoHeight = true; Scheduler.TimelineView.AppointmentDisplayOptions.AppointmentAutoHeight = true; } private void ShowPrivateAppointmentsCheckBox_OnClick(object sender, RoutedEventArgs e) { ReloadVM(true); } private void LeftExpanderClick(object sender, RoutedEventArgs e) { if(!LeftExpanderButton.IsChecked.HasValue) { return; } AuswahlGrid.Visibility = ZeigeNurMeineTermineCheckBox.Visibility = LeftExpanderButton.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible; } private void RightExpanderClick(object sender, RoutedEventArgs e) { if(!RightExpanderButton.IsChecked.HasValue) { return; } DateNavigator.Visibility = RightExpanderButton.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible; } private void NurEigeneKlientenAnzeigen(object sender, RoutedEventArgs e) { //!BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View) && BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_ViewMyCustomers) ? AllCustomers : var relatedCustomerOids = BeWoApp.LoggedOnEmployee.RelatedCustomers.Select(s => s.Customer.CustomerOid); if(NurMeineKlientenCB.IsChecked.HasValue && NurMeineKlientenCB.IsChecked.Value) { GefilterteKlienten = AllCustomers.Where(ac => relatedCustomerOids.Contains(ac.CustomerOid)).ToList(); } else if(NurMeineKlientenCB.IsChecked.HasValue && !NurMeineKlientenCB.IsChecked.Value) { GefilterteKlienten = AllCustomers; } } private void TextBoxEmployees_OnTextChanged(object sender, TextChangedEventArgs e) { var suchtext = ((TextBox) sender).Text; GefilterteMitarbeiter = AllEmployees.Where(m => m.FirstName.ToLower().Contains(suchtext.ToLower()) || m.LastName.ToLower().Contains(suchtext.ToLower())).ToList(); } private void TextBoxCustomers_OnTextChanged(object sender, TextChangedEventArgs e) { var suchtext = ((TextBox) sender).Text; GefilterteKlienten = AllCustomers.Where(m => m.FullName.ToLower().Contains(suchtext.ToLower())).ToList(); } private void FensterOeffnen() { var neueListe = new SchedulerAppointmentListVM(_Liste, AllCustomers, AllEmployees, Category2ResourcesDictionary); var zuBestaetigen = InitAppointmentsToAnswer(neueListe); var updates = InitAppointmentStatusUpdates(neueListe); if(!zuBestaetigen.Any() && !updates.Any()) { return; } var requestAnswerView = new RequestAnswerView(zuBestaetigen, updates); requestAnswerView.Closed += RequestAnswerViewClosedEvent; requestAnswerView.ParticipationChanged += UpdateRequestStringEvent; requestAnswerView.ParticipationChanged += UpdateBeiParticipationChanged; requestAnswerView.Show(); } public static List InitAppointmentsToAnswer(SchedulerAppointmentListVM listVm) { return listVm.Appointments.Where(app => { var customFieldStorage = (CustomFieldStorage)app.CustomFields[nameof(CustomFieldStorage)]; var originator = customFieldStorage.Originator; if(customFieldStorage.EmployeeList is null || originator.EmployeeOid == BeWoApp.LoggedOnEmployee.EmployeeOid.Value) { return false; } var empList = customFieldStorage.EmployeeList; return empList.Any(a => a.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && a.ParticipationAnswer == ParticipationAnswer.Offen); }).ToList(); } public static List InitAppointmentStatusUpdates(SchedulerAppointmentListVM listVm) { return listVm.Appointments.Where(app => { var customFieldStorage = (CustomFieldStorage)app.CustomFields[nameof(CustomFieldStorage)]; if(customFieldStorage.Originator is null || customFieldStorage.EmployeeList is null) { return false; } var empList = customFieldStorage.EmployeeList; var originator = customFieldStorage.Originator; return originator.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && empList.Any(employee2AppointmentRelation => employee2AppointmentRelation.IsPChanged && employee2AppointmentRelation.ParticipationAnswer != ParticipationAnswer.Offen && employee2AppointmentRelation.ParticipationAnswer != ParticipationAnswer.Verstrichen && !employee2AppointmentRelation.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid)); }).ToList(); } private void RequestAnswerViewClosedEvent(object sender, EventArgs e) { ReloadVM(true); UpdateRequestString(); } public void ShowAppointmentRequests(object sender, RequestNavigateEventArgs e) { FensterOeffnen(); } private void UpdateBeiParticipationChanged(object sender, EventArgs e) { ReloadVM(true); } private void UpdateRequestStringEvent(object sender, EventArgs e) { UpdateRequestString(); } private void AuswahlAufhebenClick(object sender, RoutedEventArgs e) { SelectedResources.Clear(); SelectedEmployees.Clear(); SelectedCustomers.Clear(); AlleMitarbeiterCB.IsChecked = false; AlleKlientenCB.IsChecked = false; AlleRessourcenCB.IsChecked = false; OnPropertyChanged(nameof(SelectedCustomers)); OnPropertyChanged(nameof(SelectedEmployees)); OnPropertyChanged(nameof(SelectedResources)); OnPropertyChanged(nameof(SelectedItems)); } private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var tabControl = (TabControl) sender; var selectedItem = (TabItem) tabControl.SelectedItem; var mitarbeiterPinsel = new LinearGradientBrush(new GradientStopCollection {new GradientStop(Color.FromRgb(69, 153, 59), 0), new GradientStop(Color.FromRgb(32, 92, 25), 1)}, new Point(0.5, 0), new Point(0.5, 1)); var klientenPinsel = new LinearGradientBrush(new GradientStopCollection {new GradientStop(Color.FromRgb(59, 119, 153), 0), new GradientStop(Color.FromRgb(25, 72, 92), 1)}, new Point(0.5, 0), new Point(0.5, 1)); var ressourcenPinsel = new LinearGradientBrush(new GradientStopCollection {new GradientStop(Color.FromRgb(4, 180, 208), 0), new GradientStop(Color.FromRgb(3, 129, 149), 1)}, new Point(0.5, 0), new Point(0.5, 1)); var h = selectedItem.Header.ToString(); if(h == Translator.Translate("Mitarbeiter")) { tabControl.Background = mitarbeiterPinsel; tabControl.BorderBrush = mitarbeiterPinsel; } else if(h == Translator.Translate("Klienten")) { tabControl.Background = klientenPinsel; tabControl.BorderBrush = klientenPinsel; } else { tabControl.Background = ressourcenPinsel; tabControl.BorderBrush = ressourcenPinsel; } } private void ReloadButton_OnClick(object sender, RoutedEventArgs e) { ReloadVM(true); } //private void ExportButton_OnClick(object sender, RoutedEventArgs e) //{ // SaveFileDialog dialog = new SaveFileDialog // { // Filter = "iCalendar files (*.ics)|*.ics", // FilterIndex = 1 // }; // if (dialog.ShowDialog() == true) // { // using (Stream stream = dialog.OpenFile()) // { // iCalendarExporter exporter = new iCalendarExporter(Scheduler.Storage.InnerStorage); // exporter.Export(stream); // } // } //} private void ZusagenButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { if(Scheduler.SelectedAppointments.Count <= 0) { return; } ZusageAendern(ParticipationAnswer.Zusage, Scheduler.SelectedAppointments[0]); } private void MitVorbehaltButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { if(Scheduler.SelectedAppointments.Count <= 0) { return; } ZusageAendern(ParticipationAnswer.Vorbehalt, Scheduler.SelectedAppointments[0]); } private void AbsagenButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { if(Scheduler.SelectedAppointments.Count <= 0) { return; } ZusageAendern(ParticipationAnswer.Absage, Scheduler.SelectedAppointments[0]); } private void ZusageAendern(ParticipationAnswer antwort, Appointment selectedAppointment) { var el = selectedAppointment.CF_EmployeeList(); var neu = new ObservableCollection(el.DoForEach(dfe => { if(!dfe.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid)) { return; } dfe.ParticipationAnswer = antwort; dfe.IsPC_CheckedTs = null; }).ToList()); selectedAppointment.CF_EmployeeList(neu); if(selectedAppointment.Type == AppointmentType.Occurrence) { var id = selectedAppointment.RecurrenceInfo.Id.ToString(); var index = selectedAppointment.RecurrenceIndex; ServiceFacade.DoResourceServiceAsync(s => s.FindRootAppointmentByRecurrenceId(id), rootAppointment => { this.Dispatch(() => { var changedOccurrence = new SchedulerAppointmentDC { ActivationType = ActivationTypeId.Active, AllDay = selectedAppointment.AllDay, CanBeEdited = rootAppointment.CanBeEdited, CompletedDate = selectedAppointment.CF_CompletedDate(), CompletedNotice = selectedAppointment.CF_CompletedNotice(), CompletedUser = selectedAppointment.CF_CompletedUser(), CustomerList = selectedAppointment.CF_CustomerList() ?? new List(), Description = selectedAppointment.Description, DueDate = selectedAppointment.CF_DueDate(), EmployeeList = selectedAppointment.CF_EmployeeList()?.ToList() ?? new List(), EndDate = selectedAppointment.End, FormerBookingSequenceOid = rootAppointment.FormerBookingSequenceOid, FormerTaskOid = rootAppointment.FormerTaskOid, HasServiceRecordEntry = selectedAppointment.CF_HasServiceRecordEntry(), IsPrivate = rootAppointment.IsPrivate, IsTask = rootAppointment.IsTask, IsTeilnahmeBestaetigung = rootAppointment.IsTeilnahmeBestaetigung, LabelKey = rootAppointment.LabelKey, Location = rootAppointment.Location, Originator = selectedAppointment.CF_Originator() ?? BeWoApp.CompactLoggedOnEmployee, RecurrenceInfo = $"", ReminderInfo = rootAppointment.ReminderInfo, ResourceList = selectedAppointment.CF_ResourceList() ?? new List(), ServiceRecordList = new List(), StartDate = selectedAppointment.Start, Status = rootAppointment.Status, Subject = selectedAppointment.Subject, SupportConceptList = new List(), TaskDescription = rootAppointment.TaskDescription, Type = (int) AppointmentType.ChangedOccurrence }; ServiceFacade.DoResourceServiceAsync(s2 => s2.InsertSchedulerAppointments(new List{changedOccurrence}), () => { this.Dispatch(() => { ReloadVM(true); }); }); }); }); } else { var appointment = (SchedulerAppointmentVM)selectedAppointment.GetSourceObject(Scheduler.GetCoreStorage()); ServiceFacade.DoResourceServiceAsync(s => s.UpdateSchedulerAppointments(new List { appointment.CommitToDataContract() }), delegate { this.Dispatch(() => { ReloadVM(true); }); }); } } private void ZeiterfassungButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { if(Scheduler.SelectedAppointments.Count <= 0) { return; } var appointment = Scheduler.SelectedAppointments.FirstOrDefault(); if(appointment is null) { return; } var employee2SchedulerAppointmentList = appointment.CF_EmployeeList(); var customerList = appointment.CF_CustomerList(); var employeeList = employee2SchedulerAppointmentList.Select(employee2SchedulerAppointment => employee2SchedulerAppointment.Employee).ToList(); String notice = appointment.Description; if (String.IsNullOrEmpty(notice)) { notice = appointment.Subject; } BeWoUtils.CreateZeiterfassung(appointment.Start, appointment.End, customerList, employeeList, notice, appointment, serviceRecords => { try { IgnoreManualAppointmentCreation = true; IgnoreChangeEvents = true; var schedulerAppointment = (SchedulerAppointmentVM) appointment.GetSourceObject(Scheduler.GetCoreStorage()); schedulerAppointment?.ServiceRecordList.AddRange(serviceRecords); var appointmentOid = schedulerAppointment?.CommitToDataContract().SchedulerAppointmentOid; if(appointmentOid.HasValue) { appointment.CF_ServiceRecordList(serviceRecords); ViewModel.ActiveAppointmentViewModel.SaveAppointments(Scheduler, new List {appointment}); ReloadVM(true); } else { // Serientermin! var recurrenceInfo = appointment.RecurrenceInfo; var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); pattern.RecurrenceInfo.FromXml(recurrenceInfo.ToXml()); var apt = appointment.RecurrencePattern.CreateException(AppointmentType.ChangedOccurrence, appointment.RecurrenceIndex); apt.Duration = appointment.Duration; apt.End = apt.Start.Add(appointment.Duration); apt.Subject = appointment.Subject; apt.Location = appointment.Location; apt.Description = appointment.Description; Scheduler.Storage.AppointmentStorage.CreateCustomFields(apt); apt.CustomFields[nameof(CustomFieldStorage)] = appointment.CustomFields[nameof(CustomFieldStorage)]; appointment.CF_ServiceRecordList(serviceRecords); ViewModel.ActiveAppointmentViewModel.InsertAppointments(Scheduler, new List {apt}); IgnoreChangeEvents = true; ReloadVM(true); } } finally { IgnoreManualAppointmentCreation = false; IgnoreChangeEvents = false; } }); } private void AbwesenheitButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { // Wenn nichts ausgewählt wurde, nichts tun if (Scheduler.SelectedAppointments.Count <= 0) { return; } var appointment = Scheduler.SelectedAppointments.FirstOrDefault(); if (appointment is null) { return; } // Listen der teilnehmenden Personen füllen var employee2SchedulerAppointmentList = appointment.CF_EmployeeList(); var customerList = appointment.CF_CustomerList(); var employeeList = employee2SchedulerAppointmentList.Select(employee2SchedulerAppointment => employee2SchedulerAppointment.Employee).ToList(); // Betreff des Termins als Notiz der einzutragenden Abwesenheit nutzen String notice = "(aus Kalender übertragen)"; if (appointment.Subject.IsNotNullOrEmpty()) { notice = appointment.Subject + " " + notice; } BeWoUtils.CreateAbsenceTime(appointment.Start, appointment.End, customerList, employeeList, notice, appointment, absenceTimes => { try { IgnoreManualAppointmentCreation = true; IgnoreChangeEvents = true; } finally { IgnoreManualAppointmentCreation = false; IgnoreChangeEvents = false; } }); } private bool IgnoreManualAppointmentCreation { get; set; } private void MeinTB_OnChecked(object sender, RoutedEventArgs e) { var toggleButton = (ToggleButton) sender; if(toggleButton?.IsChecked is null) { return; } if(!toggleButton.IsChecked.Value) { MitarbeiterSuchGrid.Visibility = Visibility.Collapsed; MitarbeiterSuchTextBox.Clear(); } else { MitarbeiterSuchGrid.Visibility = Visibility.Visible; MitarbeiterSuchTextBox.Focus(); } } private void MeinTB2_OnChecked(object sender, RoutedEventArgs e) { var toggleButton = (ToggleButton) sender; if(toggleButton?.IsChecked is null) { return; } if(!toggleButton.IsChecked.Value) { KlientenSuchGrid.Visibility = Visibility.Collapsed; KlientenSuchTextBox.Clear(); } else { KlientenSuchGrid.Visibility = Visibility.Visible; KlientenSuchTextBox.Focus(); } } private void SchedulerStorage_OnFetchAppointments(object sender, FetchAppointmentsEventArgs e) { if(_LastFetchingDateTime != null && _LastFetchingDateTime.Value < DateTime.Now.AddMilliseconds(-500d)) { return; } _LastFetchingDateTime = DateTime.Now; ReloadVM(); } private bool _ReloadingViewModel; private DateTime? _LastFetchingDateTime; public TimeInterval FetchingInterval { get; set; } private void ReloadVM(bool shouldForceReload = false) { if(_ReloadingViewModel) { return; } _ReloadingViewModel = true; if(ViewModel is null) { _ReloadingViewModel = false; return; } var range = Scheduler.ActiveView.GetVisibleIntervals(); var start = range.Start; var end = range.End; FetchingInterval = new TimeInterval(start - FetchPadding, end + FetchPadding); var selectedEmployeeOids = SelectedEmployees.Select(s => s.EmployeeOid).ToList(); var selectedCustomerOids = SelectedCustomers.Select(s => s.CustomerOid).ToList(); var selectedResourceOids = SelectedResources.Where(w => w.ResourceOid.HasValue).Select(s => s.ResourceOid.Value).ToList(); var employeesOnly = MitarbeiterEbenenCheckBox.IsChecked != null && MitarbeiterEbenenCheckBox.IsChecked.Value; var customersOnly = KlientenEbenenCheckBox.IsChecked != null && KlientenEbenenCheckBox.IsChecked.Value; var resourcesOnly = RessourcenEbenenCheckBox.IsChecked != null && RessourcenEbenenCheckBox.IsChecked.Value; var onlyPrivateAppointments = ShowPrivateAppointmentsCheckBox.IsChecked != null && ShowPrivateAppointmentsCheckBox.IsChecked.Value; var showOnlyMyAppointments = ZeigeNurMeineTermine; var showAbsenceTimes = AbwesenheitenEinAusCheckBox.IsChecked != null && AbwesenheitenEinAusCheckBox.IsChecked.Value; if(!shouldForceReload && FetchingInterval.Equals(_LastFetchedInterval)) { _ReloadingViewModel = false; return; } _LastFetchedInterval = FetchingInterval; ReloadAppointmentViewModel(start, end, selectedEmployeeOids, selectedCustomerOids, selectedResourceOids, employeesOnly, customersOnly, resourcesOnly, onlyPrivateAppointments, showOnlyMyAppointments, showAbsenceTimes); } public void ReloadAppointmentViewModel(DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomer, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments, bool pShouldShowAbsenceTimes, Action callback = null) { ResetDeletionMode(); if (!BeWoApp.LoggedOnEmployee.EmployeeOid.HasValue) { return; } var start = pIntervalStart - FetchPadding; var end = pIntervalEnd + FetchPadding; var service = Scheduler.GetService(); this.Dispatch(() => { if(service.IsDataRefreshAllowed) { GetCacheObjects((customers, employees, resources) => { ServiceFacade.DoResourceServiceAsync(s2 => s2.LoadFilteredAppointmentsMitAufgaben( BeWoApp.HasLoggedOnUserRight(new[] { UserRightType.KalenderMitarbeitertermineAnsehen }), BeWoApp.LoggedOnEmployee.EmployeeOid.Value, start, end, pSelectedEmployees, pSelectedCustomer, pSelectedResources, pEmployeesOnly, pCustomersOnly, pResourcesOnly, pPrivateAppointmentsOnly, pOnlyMyAppointments, IsTasksVisible ), appointments => { ServiceFacade.DoResourceServiceAsync(s3 => s3.GetAllActiveEmployeeAbsenceTimesInInterval(start, end, BeWoApp.LoggedOnEmployee.EmployeeOid.Value, SelectedEmployees.Select(employee => employee.EmployeeOid).ToList()), employeeAbsenceTimes => { ServiceFacade.DoResourceServiceAsync(s4 => s4.GetAllActiveCustomersAbsenceTimesInInterval(start, end, BeWoApp.LoggedOnEmployeeOid.Value, SelectedCustomers.Select(customer => customer.CustomerOid).ToList()), customerAbsenceTimes => { this.Dispatch(() => { var prefilteredAppointments = appointments.Where(w => (w.EmployeeList.Count == 0 && w.Originator.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) || w.EmployeeList.Count > 0 && w.EmployeeList.Any(a => a.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid)) || BeWoUtils.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen)) && (!w.EmployeeList.TrueForAll(e2a => e2a.ParticipationAnswer == ParticipationAnswer.Absage) || w.EmployeeList is null || w.EmployeeList.Count == 0)).ToList(); var anonymizedAppointments = appointments.Where(w => w.CanBeEdited == false && w.IsTask == false).ToList(); prefilteredAppointments.AddRangeIfElementsNotIn(anonymizedAppointments); if(!IsTasksVisible) { prefilteredAppointments = prefilteredAppointments.Where(app => !app.IsTask).ToList(); } var vm = new SchedulerAppointmentListVM(prefilteredAppointments, customers, employees, resources); if(pShouldShowAbsenceTimes) { vm.Appointments.AddRange(ViewModel.ConvertAbsenceTimesToAppointments(customerAbsenceTimes, end, employees, customers)); vm.Appointments.AddRange(ViewModel.ConvertAbsenceTimesToAppointments(employeeAbsenceTimes, end, employees, customers)); //vm.Appointments.AddRange(ViewModel.ConvertAbsenceTimesToAppointments(employeeAbsenceTimes.Where(w => { return SelectedEmployees.Count == 0 || SelectedEmployees.Any(a => a.EmployeeOid == w.EmployeeOid); }), end, e, c)); } ViewModel.ActiveAppointmentViewModel = vm; ViewModel.SchedulerSettings = ViewModel.GetActiveSettings(); ViewModel.SchedulerSettings.StartDate = pIntervalStart; GefilterteMitarbeiter = ViewModel.ActiveAppointmentViewModel.AllEmployees; AllEmployees = ViewModel.ActiveAppointmentViewModel.AllEmployees; GefilterteKlienten = ViewModel.ActiveAppointmentViewModel.AllCustomers; AllCustomers = ViewModel.ActiveAppointmentViewModel.AllCustomers; Category2ResourcesDictionary = ViewModel.ActiveAppointmentViewModel.Categories2Resources; SelectedEmployees = AllEmployees.Where(w => SelectedEmployees.Any(a => a.EmployeeOid.Equals(w.EmployeeOid))).ToList(); SelectedCustomers = AllCustomers.Where(w => SelectedCustomers.Any(a => a.CustomerOid.Equals(w.CustomerOid))).ToList(); SelectedResources = AllResources.Where(w => SelectedResources.Any(a => a.ResourceOid.Equals(w.ResourceOid))).ToList(); //var items = SelectedItems; //var testtesttest = ViewModel.ActiveAppointmentViewModel; _ReloadingViewModel = false; // TODO: Hier tritt eine Exception auf, wenn man zu schnell löscht? Scheduler.Storage.RefreshData(); Scheduler.Storage.RefreshUI(); callback?.Invoke(); }); }); }); }); }); } else { _ReloadingViewModel = false; } }); } public void OpenAppointmentFromHomePanel() { if (_SelectedAppointmentFromHomePanelView != null) { var apps = Scheduler.ActiveView.GetAppointments().ToList(); var oid = _SelectedAppointmentFromHomePanelView.SchedulerAppointmentOid; Appointment appointmentToOpen = null; if (oid != null) { appointmentToOpen = apps.FirstOrDefault(app => { var oidValue = app.CF_SchedulerAppointmentOid(); return oidValue.HasValue && oidValue.Value == oid; }); //if(appointmentToOpenFormHomePanel != null) //{ // Scheduler.ShowEditAppointmentForm(appointmentToOpenFormHomePanel); //} } else if (_SelectedAppointmentFromHomePanelView.RecurrenceId != null && _SelectedAppointmentFromHomePanelView.RecurrenceIndex > 0) { appointmentToOpen = apps.FirstOrDefault(appointment => appointment.RecurrenceInfo.Id.ToString().Equals(_SelectedAppointmentFromHomePanelView.RecurrenceId)); //if(appointmentToOpenFormHomePanel != null) //{ // Scheduler.ShowEditAppointmentForm(appointmentToOpenFormHomePanel); //} } if (appointmentToOpen != null) { Scheduler.ShowEditAppointmentForm(appointmentToOpen); } _SelectedAppointmentFromHomePanelView = null; } //while (_IsComingFromHomeDragPanel) //{ //Thread.Sleep(100); //} } private void ExportButton_OnClick(object sender, RoutedEventArgs e) { var dialog = new SaveFileDialog {Filter = "iCalendar files (*.ics)|*.ics", FilterIndex = 1}; if(dialog.ShowDialog() != true) { return; } using(var stream = dialog.OpenFile()) { ExportAppointmentsAs_iCal(stream); } } private void ExportAppointmentsAs_iCal(Stream stream) { if(stream is null) { return; } try { var productIdentifier = $"-//{BeWoApp.Mandator}//DXScheduler iCalendarExchange Example//DE"; var exporter = new iCalendarExporter(Scheduler.GetCoreStorage()) {ProductIdentifier = productIdentifier}; exporter.AppointmentExporting += OnAppointmentExporting; exporter.Export(stream); } catch(Exception e) { MessageBox.Show($"Der Kalender konnte leider nicht exportiert werden.\n{e.Message}", "Fehler beim Export", MessageBoxButton.OK, MessageBoxImage.Error); } } private void OnAppointmentExporting(object sender, AppointmentExportingEventArgs appointmentExportingEventArgs) { appointmentExportingEventArgs.Cancel = !Scheduler.ActiveView.GetAppointments().Contains(appointmentExportingEventArgs.Appointment); } //private void OnAppointmentExporting(object sender, AppointmentExportingEventArgs appointmentExportingEventArgs) //{ // var iCalArgs = (iCalendarAppointmentExportingEventArgs)appointmentExportingEventArgs; // var vEvent = iCalArgs.VEvent; // var ma = (ObservableCollection)appointmentExportingEventArgs.Appointment.CF_EmployeeList(); // var ca = (List)appointmentExportingEventArgs.Appointment.CF_CustomerList(); // var ra = (List)appointmentExportingEventArgs.Appointment.CF_ResourceList(); //} //private void SyncWithOutlook(object sender, RoutedEventArgs e) //{ // Synchronize(); //} private void PrintCalendar(object sender, RequestNavigateEventArgs e) { if(Scheduler.ActiveView.GetAppointments().Count == 0) { MessageBox.Show("Das Drucken ist nicht möglich, da im ausgewählten Intervall keine Termine vorhanden sind.", "Drucken nicht möglich", MessageBoxButton.OK, MessageBoxImage.Error); return; } var range = Scheduler.ActiveView.GetVisibleIntervals(); var datesList = new List(); if(range.GetType() == typeof(WeekIntervalCollection)) { for(var i = 0; i < range.Duration.Days; i++) { datesList.Add(range.Start.AddDays(i)); } } else { datesList.AddRange(range.Select(x => x.Start)); } var absenceTimeOids = Scheduler.ActiveView.GetAppointments().Where(w => w.CF_IsAbsenceTime() && w.CF_AbsenceTimeOid().HasValue).Select(s => s.CF_AbsenceTimeOid()).ToList(); var apps = Scheduler.ActiveView.GetAppointments().Where(w => !w.CF_IsAbsenceTime()).ToList(); var appointmentOidListe = apps.Where(w => !w.IsOccurrence && !w.IsRecurring || w.IsException).Select(app => Convert.ToInt64(((SchedulerAppointmentVM) app.GetSourceObject(Scheduler.GetCoreStorage())).Id)).Distinct().ToList(); var serienTerminOids = apps.Where(w => w.IsRecurring || w.IsOccurrence).Select(app => Convert.ToInt64(((SchedulerAppointmentVM) app.RecurrencePattern.GetSourceObject(Scheduler.GetCoreStorage())).Id)).Distinct().ToList(); var serienTermine = new List(); var recurringAppointments = new List(); var deletedOccurrences = new List(); var st = apps.Where(app => app.IsRecurring || app.IsOccurrence).ToList(); var recurrenceIds = st.Select(s => s.RecurrenceInfo.Id.ToString()).Distinct().ToList(); foreach(var app in ViewModel.ActiveAppointmentViewModel.Appointments) { if(!(app.RecurrenceInfo is null)) { var id = Utils.Utils.ExtractIdFromRecurrenceInfo(app.RecurrenceInfo); if(recurrenceIds.Contains(id) && app.EventType == (int) AppointmentType.DeletedOccurrence) { if(app is SchedulerAppointmentVM vm) { deletedOccurrences.AddIfNotIn(vm.CommitToDataContract()); } } } } //var deletedOccurrences = apps.Where(w => w.Type == AppointmentType.DeletedOccurrence).ToList(); foreach(var app in apps.Where(w => w.IsOccurrence || w.IsRecurring).Where(app => !recurringAppointments.Any(a => a.RecurrenceInfo.Id.Equals(app.RecurrenceInfo.Id)))) { recurringAppointments.Add(app); } foreach(var serienTermin in recurringAppointments) { var basistermin = (SchedulerAppointmentVM) serienTermin.RecurrencePattern.GetSourceObject(Scheduler.GetCoreStorage()); var info = serienTermin.RecurrenceInfo; var ausnahmen = apps.Where(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Id.Equals(info.Id) && w.IsException).ToList(); var calc = OccurrenceCalculator.CreateInstance(info); var ttc = new TimeInterval(range.Start, range.End + new TimeSpan(1, 0, 0)); var kollektionOhneAusnahmen = calc.CalcOccurrences(ttc, serienTermin.RecurrencePattern).Where(w => w.RecurrenceIndex != 0 && !w.IsException).ToList(); if(ausnahmen.Any(appointment => appointment.IsException && appointment.RecurrenceIndex == 0) && basistermin.DataContract.SchedulerAppointmentOid != null) { serienTerminOids.Remove(basistermin.DataContract.SchedulerAppointmentOid.Value); } var neu = new List(); foreach(var app in kollektionOhneAusnahmen.Where(w => !ausnahmen.Select(s => s.RecurrenceIndex).Contains(w.RecurrenceIndex))) { var recurrenceId = app.RecurrenceInfo.Id.ToString(); if (app.IsOccurrence && deletedOccurrences.Any(a => a.RecurrenceId == recurrenceId && a.RecurrenceIndex == app.RecurrenceIndex)) { continue; } neu.AddIfNotIn(app); } if(ausnahmen.Count > 0) { kollektionOhneAusnahmen = kollektionOhneAusnahmen.Where(w => !ausnahmen.Select(s => s.RecurrenceIndex).Contains(w.RecurrenceIndex)).ToList(); } foreach(var appointment in kollektionOhneAusnahmen) { var recurrenceId = appointment.RecurrenceInfo.Id.ToString(); var recurrenceIndex = appointment.RecurrenceIndex; if(!(appointment.IsOccurrence && deletedOccurrences.Any(a => a.RecurrenceIdReference == recurrenceId && a.RecurrenceIndexReference == recurrenceIndex))) { serienTermine.AddIfNotIn(new SchedulerAppointmentDC { AllDay = appointment.AllDay, CustomerList = basistermin.CustomerList, EmployeeList = basistermin.EmployeeList.ToList(), ResourceList = basistermin.ResourceList, StartDate = appointment.Start, EndDate = appointment.End, Description = appointment.Description, IsPrivate = basistermin.IsPrivate, Location = appointment.Location, Subject = appointment.Subject, LabelKey = (long?) appointment.LabelKey, Type = (int)appointment.Type, Originator = basistermin.Originator, RecurrenceInfo = appointment.RecurrenceInfo.ToXml(), ServiceRecordList = basistermin.ServiceRecordList, SupportConceptList = basistermin.SupportConceptList }); } } //serienTermine.AddRangeIfElementsNotIn(kollektionOhneAusnahmen.Select(z => new SchedulerAppointmentDC //{ // AllDay = z.AllDay, CustomerList = basistermin.CustomerList, EmployeeList = basistermin.EmployeeList.ToList(), ResourceList = basistermin.ResourceList, StartDate = z.Start, EndDate = z.End, Description = z.Description, IsPrivate = basistermin.IsPrivate, Location = z.Location, Subject = z.Subject, LabelId = z.LabelId, Type = (int) z.Type, Originator = basistermin.Originator, RecurrenceInfo = z.RecurrenceInfo.ToXml() //})); } appointmentOidListe.AddRange(serienTerminOids.Where(w => !appointmentOidListe.Contains(w))); var mehrTaegigeTermine = new List(); foreach (var app in apps.Where(a => !a.SameDay && !(!a.SameDay && a.AllDay && a.Duration == new TimeSpan(1, 0, 0, 0)))) { var sourceObject = app.GetSourceObject(Scheduler.GetCoreStorage()); if(sourceObject is SchedulerAppointmentVM vm) { mehrTaegigeTermine.Add(vm.CommitToDataContract()); //BeWoApp.LogMessage($"{vm.Subject}: {vm.Start:dd.MM.yyyy HH:mm} - {vm.End:dd.MM.yyyy HH:mm}; {(AppointmentType) vm.EventType}", Colors.Green); } else { var occurrenceVM = new SchedulerAppointmentVM(app); mehrTaegigeTermine.Add(occurrenceVM.CommitToDataContract()); //BeWoApp.LogMessage($"{occurrenceVM.Subject}: {occurrenceVM.Start:dd.MM.yyyy HH:mm} - {occurrenceVM.End:dd.MM.yyyy HH:mm}; {(AppointmentType)occurrenceVM.EventType}", Colors.Purple); } } appointmentOidListe.RemoveRange(mehrTaegigeTermine.Where(w => w.SchedulerAppointmentOid.HasValue).Select(s => s.SchedulerAppointmentOid.Value)); var neueTermine = SchedulerUtils.GenerateSeveralDaysAppointments(mehrTaegigeTermine); var variablenDictionary = new Dictionary { {"appointmentOidListe", appointmentOidListe}, {"datesList", datesList}, {"employeeOid", BeWoApp.LoggedOnEmployee.EmployeeOid}, {"serienTermine", serienTermine}, {"mehrtaegigeTermine", neueTermine}, {"absenceTimeOids", absenceTimeOids} }; BeWoUtils.ShowReport("Kalender", variablenDictionary, ReportEnum.KalenderMonatsReportEnum); } public void PreselectCustomer(long pCustomerOid) { if(!AllCustomers.Any(c => c.CustomerOid.Equals(pCustomerOid))) { return; } SelectedCustomers = new List {AllCustomers.Find(f => f.CustomerOid.Equals(pCustomerOid))}; OnPropertyChanged(nameof(SelectedCustomers)); OnPropertyChanged(nameof(SelectedItems)); OnPropertyChanged(nameof(GefilterteKlienten)); } private void DateNavigator_OnSelectedDatesChanged(object sender, EventArgs e) { _CurrentViewType = Scheduler.ActiveViewType; var navigator = (DevExpress.Xpf.Editors.DateNavigator.DateNavigator) sender; var selectedDates = navigator.SelectedDates; var isSelectedDateFetched = _LastFetchedInterval.ContainsEveryDateFromList(selectedDates); if(!isSelectedDateFetched && !(_LastFetchedInterval.Start.Equals(new DateTime(1, 1, 1, 0, 0, 0)) && _LastFetchedInterval.End.Equals(new DateTime(1, 1, 1, 0, 30, 0)))) { ReloadVM(); } } private void MitarbeiterVerfuegbarkeitPruefenButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { var intervall = Scheduler.ActiveView.SelectedInterval; ServiceFacade.DoEmployeeServiceAsync(s1 => s1.GetAllActiveEmployeesCompact(), dcs => ServiceFacade.DoReportServiceAsync( s2 => s2.GetMitarbeiterverfuegbarkeiten(dcs, intervall.Start, intervall.End), s3 => this.Dispatch(() => { var mviv = new MitarbeiterverfuegbarkeitsinfoView(s3, intervall.Start, intervall.End); if(mviv.CommandBindings.Count == 0) { mviv.CommandBindings.Add( new CommandBinding( ApplicationCommands.Close, (s, e2) => { if(!mviv.DoSaveCheck()) { return; } PopupContent.Visibility = Visibility.Hidden; PopupContent.Child = null; })); } PopupContent.Child = mviv; PopupContent.Height = 400; PopupContent.Width = 450; PopupContent.Visibility = Visibility.Visible; }))); } private void MitarbeiterfarbenEinAusCheckBox_OnChecked(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; IsEmployeeBrushVisible = cb.IsChecked ?? true; } private void NurMeineTermineEinAusCheckBox_OnChecked(object sender, RoutedEventArgs e) { var checkBox = (CheckBox) sender; if(CheckBoxConverter is null || BeWoApp.CompactLoggedOnEmployee is null) { return; } if(checkBox.IsChecked != null && checkBox.IsChecked.Value) { SelectedEmployees = new List {BeWoApp.CompactLoggedOnEmployee}; CheckBoxConverter.AktuellerMitarbeiter = BeWoApp.CompactLoggedOnEmployee; } else if(checkBox.IsChecked != null && !checkBox.IsChecked.Value && SelectedEmployees.Count == 1) { SelectedEmployees.Remove(BeWoApp.CompactLoggedOnEmployee); CheckBoxConverter.AktuellerMitarbeiter = null; } OnPropertyChanged(nameof(SelectedEmployees)); OnPropertyChanged(nameof(SelectedItems)); ReloadVM(true); } private void AbwesenheitenEinAusCheckBox_OnChecked(object sender, RoutedEventArgs e) { var cb = (CheckBox) sender; IsAbsenceTimeVisible = cb.IsChecked ?? true; ReloadVM(true); } public static void WriteToDebugLog(string message, bool isWithoutTimestamp = false) { #if DEBUG var callerName2 = new StackTrace().GetFrame(2).GetMethod().Name; var callerName = new StackTrace().GetFrame(1).GetMethod().Name; using(var file = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\scheduler_log.txt", true)) { var messageToWrite = isWithoutTimestamp ? message : $"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} {callerName2}->{callerName}: {message}"; file.WriteLine(messageToWrite); } Debug.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} {callerName}: {message}"); #endif } public static void WriteMethodCallToLog(long pElapsedMilliseconds) { #if DEBUG var callerName = new StackTrace().GetFrame(1).GetMethod().Name; using(var logFile = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\method_calls_log.txt", true)) { logFile.WriteLine($"{callerName} took {pElapsedMilliseconds} ms"); } #endif } private void Scheduler_OnInplaceEditorShowing(object sender, InplaceEditorEventArgs e) { if(!_IsNew) { return; } var n = new ObservableCollection(SelectedEmployees.Select(item => new Employee2SchedulerAppointmentDC {Employee = item, ParticipationAnswer = ParticipationAnswer.Offen}).ToList()); e.Appointment.CF_EmployeeList(n); e.Appointment.CF_CustomerList(new List(SelectedCustomers)); e.Appointment.CF_ResourceList(new List(SelectedResources)); _IsNew = false; } private void ButtonDeleteAppointmentsInInterval_Click(object sender, RoutedEventArgs e) { DeleteAppointmentsPopup.IsOpen = true; } private void AbortDeletingAppointments_Click(object sender, RoutedEventArgs e) { DeleteAppointmentsPopup.IsOpen = false; } private void DeleteAppointmentsForGood_Click(object sender, RoutedEventArgs e) { var employeesOnly = MitarbeiterEbenenCheckBox.IsChecked != null && MitarbeiterEbenenCheckBox.IsChecked.Value; var customersOnly = KlientenEbenenCheckBox.IsChecked != null && KlientenEbenenCheckBox.IsChecked.Value; var resourcesOnly = RessourcenEbenenCheckBox.IsChecked != null && RessourcenEbenenCheckBox.IsChecked.Value; var onlyPrivateAppointments = ShowPrivateAppointmentsCheckBox.IsChecked != null && ShowPrivateAppointmentsCheckBox.IsChecked.Value; var showOnlyMyAppointments = ZeigeNurMeineTermine; var loggedOnUserHasRightToSeeAllAppointments = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderKliententermineAlleAnsehen) || BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll); var loggedOnEmployeeOid = BeWoApp.LoggedOnEmployee.EmployeeOid.Value; var date = DeleteForGoodIntervalEndDateEdit.DateTime; var userRights = new Dictionary { { UserRightType.KalenderKliententermineAendern, BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderKliententermineAendern) }, { UserRightType.KalenderMitarbeitertermineAendern, BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAendern) }, { UserRightType.KalenderRessourcentermineAendern, BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAendern) }, { UserRightType.KalenderRessourcentermineAndererAendern, BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAndererAendern) } }; var dialog = new MessageDialog(() => { ServiceFacade.DoOperationsServiceAsync(s => s.DeleteAppointmentsInInterval( loggedOnUserHasRightToSeeAllAppointments, loggedOnEmployeeOid, date, SelectedEmployees.Select(employee => employee.EmployeeOid).ToList(), SelectedCustomers.Select(customer => customer.CustomerOid).ToList(), SelectedResources.Select(resource => resource.ResourceOid.Value).ToList(), employeesOnly, customersOnly, resourcesOnly, onlyPrivateAppointments, showOnlyMyAppointments, userRights), () => { this.Dispatch(() => { DeleteAppointmentsPopup.IsOpen = false; ReloadVM(true); }); }); }); ServiceFacade.DoOperationsServiceAsync( s => s.GetMessageFromServerForDeletingAppointments( loggedOnUserHasRightToSeeAllAppointments, loggedOnEmployeeOid, date, SelectedEmployees.Select(employee => employee.EmployeeOid).ToList(), SelectedCustomers.Select(customer => customer.CustomerOid).ToList(), SelectedResources.Select(resource => resource.ResourceOid.Value).ToList(), employeesOnly, customersOnly, resourcesOnly, onlyPrivateAppointments, showOnlyMyAppointments, userRights), xaml => { this.Dispatch(() => { dialog.SetXaml(xaml); dialog.ShowDialog(); }); }); } private void RestoreAppointmentButtonItem_OnItemClick(object sender, ItemClickEventArgs e) { var appointmentToRestore = Scheduler.SelectedAppointments[0]; var appointmentVM = (SchedulerAppointmentVM) appointmentToRestore.GetSourceObject(Scheduler.GetCoreStorage()); var appointmentDC = appointmentVM?.CommitToDataContract(); if(appointmentDC?.SchedulerAppointmentOid is null || appointmentDC.NewSchedulerAppointmentVersion is null || appointmentToRestore.Type != AppointmentType.ChangedOccurrence) { return; } ServiceFacade.DoResourceServiceAsync(s => s.GetSchedulerAppointmentByid(appointmentDC.SchedulerAppointmentOid.Value), appointment => { if(appointment.SchedulerAppointmentOid is null || appointment.NewSchedulerAppointmentVersion is null) { return; } ServiceFacade.DoResourceServiceAsync(s => s.DeleteSchedulerAppointments(new Dictionary {{appointment.SchedulerAppointmentOid.Value, appointment.NewSchedulerAppointmentVersion.Value}}), () => { this.Dispatch(() => { ReloadVM(true); }); }); }); } private void AufgabeAnlegen_OnItemClick(object sender, ItemClickEventArgs e) { // TODO: Durch eigenen Editor ersetzen, der mit dem Scheduler nichts am Hut hat! // var dueDate = Scheduler.SelectedInterval.End; //var end = dueDate.GetShortDateTime().AddDays(1); // var start = Scheduler.SelectedInterval.Start.GetShortDateTime(); // var newTask = Scheduler.Storage.CreateAppointment(AppointmentType.Normal, start, end, "Neue Aufgabe"); // newTask.AllDay = true; //var employees2Appointments = SelectedEmployees.Select(item => new Employee2SchedulerAppointmentDC { Employee = item, ParticipationAnswer = ParticipationAnswer.Offen }).ToList(); // ViewModel.InitNewTask(newTask, dueDate, employees2Appointments, SelectedCustomers, SelectedResources, new List()); // Scheduler.ShowEditAppointmentForm(newTask); } private void ShowTasksCheckBox_OnClick(object sender, RoutedEventArgs e) { var checkBox = (CheckBox) sender; IsTasksVisible = checkBox.IsChecked ?? false; ReloadVM(true); } private void Scheduler_OnAppointmentDrag(object sender, AppointmentDragEventArgs e) { var editedAppointment = e.EditedAppointment; var editedIsTask = editedAppointment.CF_IsTask(); var editedEnd = editedAppointment.End; var editedDueDate = editedAppointment.CF_DueDate(); var sourceAppointment = e.SourceAppointment; var sourceIsTask = sourceAppointment.CF_IsTask(); var sourceEnd = sourceAppointment.End; if(editedIsTask) { editedAppointment.AllDay = true; } if(editedIsTask && sourceIsTask && !Equals(editedEnd, sourceEnd) && editedDueDate.HasValue) { editedDueDate = editedEnd.MergeDatesByDate(editedDueDate.Value).AddDays(-1); editedAppointment.CF_DueDate(editedDueDate); } } private static void WriteToDebug(string pText) { Debug.WriteLine($"-----------------------> {pText}"); } private void LogStorage() { var storageAppointments = Scheduler.Storage.AppointmentStorage.Items.ToList(); var stringBuilder = new StringBuilder(); stringBuilder.Append("AppointmentStorage-Inhalt:\n"); foreach(var app in storageAppointments) { stringBuilder.Append($"{app.Subject} {app.Start:dd.MM.yyyy HH:mm}-{app.End:dd.MM.yyyy HH:mm}\n"); } WriteToDebug(stringBuilder.ToString()); } private void Scheduler_OnAppointmentDrop(object sender, AppointmentDragEventArgs e) { } private void ListView_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { var datacontext = (ListView) sender; var selected = datacontext.SelectedItem; } private void btn_showEmployeeInformation_Click(object sender, RoutedEventArgs e) { var cb = (Button)sender; var datacontext = cb.DataContext; CompactEmployeeDC emp = (CompactEmployeeDC)datacontext; var control = new InformationView(); control.SetXaml(ServiceFacade.DoOperationsServiceSync(s => s.GetXAMLInformationStringForEmployee(emp.EmployeeOid))); var beWoWindow = new BeWoWindow(); control.ButtonCloseClicked += () => beWoWindow.Close(); beWoWindow.Height = 200; beWoWindow.Width = 400; beWoWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; beWoWindow.GroupBoxContent = control; beWoWindow.Owner = BeWoApp.CurrentBeWo.MainWindow; beWoWindow.rootGroupBox.Header = "Infos zu " + emp.FirstName + " " + emp.LastName; beWoWindow.ShowDialog(); } private void btn_showCustomerInformation_Click(object sender, RoutedEventArgs e) { var cb = (Button)sender; var datacontext = cb.DataContext; CompactCustomerDC customer = (CompactCustomerDC)datacontext; var control = new InformationView(); control.SetXaml(ServiceFacade.DoOperationsServiceSync(s => s.GetXAMLInformationStringForScheduler(customer.CustomerOid))); var beWoWindow = new BeWoWindow(); control.ButtonCloseClicked += () => beWoWindow.Close(); beWoWindow.Height = 200; beWoWindow.Width = 600; beWoWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; beWoWindow.GroupBoxContent = control; beWoWindow.Owner = BeWoApp.CurrentBeWo.MainWindow; beWoWindow.rootGroupBox.Header = "Infos zu " + customer.FirstName + " " + customer.LastName; beWoWindow.ShowDialog(); } private void SpinEditTimelineViewDayCount_OnLostFocus(object sender, RoutedEventArgs e) { BeWoApp.SaveAppSettings(); } private void SpinEditDayViewDayCount_OnLostFocus(object sender, RoutedEventArgs e) { BeWoApp.SaveAppSettings(); } private void MyTeamsCheckBox_OnClick(object sender, RoutedEventArgs e) { if(sender is CheckBox checkBox) { var isChecked = checkBox.IsChecked ?? false; if(isChecked) { Cache.GetInstance().GetAllTeamMemberForEmployee(BeWoApp.CompactLoggedOnEmployee, teamMembers => { this.Dispatch(() => { SelectedEmployees = new List(AllEmployees.Where(employee => teamMembers.Contains(employee))); AlleMitarbeiterCB.IsChecked = ListEquals(AllEmployees, SelectedEmployees); OnPropertyChanged(nameof(SelectedEmployees)); OnPropertyChanged(nameof(SelectedItems)); ReloadVM(true); }); }); } else { SelectedEmployees = new List(); OnPropertyChanged(nameof(SelectedEmployees)); OnPropertyChanged(nameof(SelectedItems)); ReloadVM(true); } } } private void NewSchedulerView_OnLoaded(object sender, RoutedEventArgs e) { ReloadVM(true); } } #region Converter public static class ViewTypeConvert { public static AppointmentViewType ToAppointmentViewType(SchedulerViewType schedulerViewType) { switch(schedulerViewType) { case SchedulerViewType.Day: return AppointmentViewType.Day; case SchedulerViewType.Week: return AppointmentViewType.Week; case SchedulerViewType.Timeline: return AppointmentViewType.Timeline; case SchedulerViewType.Month: return AppointmentViewType.Month; default: return AppointmentViewType.WorkWeek; } } } public class TextFromIDataContractConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(value is ResourceDC resourceDC) { return resourceDC.Name; } if(value is Employee2SchedulerAppointmentDC dc) { return dc.Employee.SimpleDescription; } var filterableDC = value as IFilterableDC; return filterableDC?.SimpleDescription; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class GermanEditorLocalizer : EditorLocalizer { public override string Language => "Deutsch"; public override string GetLocalizedString(EditorStringId id) { return id.Equals(EditorStringId.Today) ? "Heute" : base.GetLocalizedString(id); } } public class ViewInfo2CustomFieldsConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(value is CustomFieldCollection customFields) { var customFieldStorage = (CustomFieldStorage)customFields[nameof(CustomFieldStorage)]; if(customFieldStorage != null && parameter != null && parameter.Equals("AlleRessourcen")) { return customFieldStorage.ResourceList; } } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class AppointmentToolTipConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { var customFields = (CustomFieldCollection) value; if(customFields is null) { return string.Empty; } var customFieldStorage = (CustomFieldStorage) customFields[nameof(CustomFieldStorage)]; var mitarbeiter = customFieldStorage.EmployeeList; var ressourcen = customFieldStorage.ResourceList; var klienten = customFieldStorage.CustomerList; var tooltip = string.Empty; var seperator = "; "; if(parameter is null) { return tooltip; } var auswahl = new List(); switch(parameter.ToString()) { case "Ressourcen": seperator = ", "; if(ressourcen != null) { auswahl = ressourcen.Cast().ToList(); } break; case "Mitarbeiter": if(mitarbeiter != null) { auswahl = mitarbeiter.Select(s => s.Employee).Cast().ToList(); } break; case "Klienten": if(klienten != null) { auswahl = klienten.Cast().ToList(); } break; } foreach(var item in auswahl) { var index = auswahl.IndexOf(item); if(index % 3 == 0 && index < auswahl.Count - 1 && index > 0) { tooltip += "\n"; } tooltip += item.ToString(); if(index < auswahl.Count - 1) { tooltip += seperator; } } return tooltip; } catch(Exception e) { return string.Empty; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class WidthAdditionMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var w1 = System.Convert.ToDouble(values[0]); var w2 = System.Convert.ToDouble(values[1]); return w1 + w2; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class FilterBackgroundConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var farbe = Color.FromRgb(192, 255, 208); try { if(!(values[0] is List selectedItems) || !selectedItems.Any()) { return new LinearGradientBrush(new GradientStopCollection {new GradientStop(farbe, 1)}, new Point(.5, 0), new Point(.5, 1)); } if(!(values[1] is CustomFieldCollection customViewInfo)) { return new LinearGradientBrush(new GradientStopCollection {new GradientStop(farbe, 1)}, new Point(.5, 0), new Point(.5, 1)); } var customFieldStorage = (CustomFieldStorage) customViewInfo[nameof(CustomFieldStorage)]; var isTask = customFieldStorage.IsTask; if(isTask) { farbe = Color.FromRgb(153, 59, 59); } if(customFieldStorage.IsAbsenceTime && customFieldStorage.IsCustomerAbsenceTime) { farbe = Color.FromRgb(59, 119, 153); } var appointmentCustomers = customFieldStorage.CustomerList; var appointmentResources = customFieldStorage.ResourceList; var gradientCollection = new GradientStopCollection(); var farbKollektion = new List(); if(selectedItems.Any(appointmentCustomers.Contains)) { farbKollektion.Add(Color.FromRgb(59, 119, 153)); } if(selectedItems.Any(appointmentResources.Contains)) { farbKollektion.Add(Color.FromRgb(4, 180, 208)); } switch(farbKollektion.Count) { case 1: if(BeWoApp.AppSettings.ShowMultipleResourceColors) { AddResourceColors(gradientCollection, appointmentResources, appointmentCustomers.Any()); } //else { var first = appointmentResources.FirstOrDefault(); gradientCollection.Add(first != null ? new GradientStop((Color)(ColorConverter.ConvertFromString(first.Color) ?? Color.FromRgb(4, 180, 208)), 1) : new GradientStop(farbKollektion[0], 1)); } break; case 2: // 1. Klientenfarbe gradientCollection.Add(new GradientStop(farbKollektion[0], 0.5)); // 2. Resourcenfarben if(BeWoApp.AppSettings.ShowMultipleResourceColors) { AddResourceColors(gradientCollection, appointmentResources, true); } else { var first2 = appointmentResources.FirstOrDefault(); if (first2 != null) { gradientCollection.Add(new GradientStop((Color)(ColorConverter.ConvertFromString(first2.Color) ?? Color.FromRgb(4, 180, 208)), 0.5)); } } break; default: gradientCollection.Add(new GradientStop(farbe, 1)); break; } return new LinearGradientBrush(gradientCollection, new Point(.5, 0), new Point(.5, 1)); } catch(Exception) { return new LinearGradientBrush(new GradientStopCollection {new GradientStop(farbe, 1)}, new Point(.5, 0), new Point(.5, 1)); } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } private static void AddResourceColors(GradientStopCollection gradientCollection, IReadOnlyList resourceList, bool hasCustomers) { var previousOffset = hasCustomers ? 0.5 : 0; var numberOfResources = resourceList.Count; if(numberOfResources == 0) { return; } if(numberOfResources > 4) { numberOfResources = 4; } var iterator = hasCustomers == false ? 1d / numberOfResources : previousOffset / numberOfResources; for(var i = 0; i < numberOfResources; i++) { var resource = resourceList[i]; var currentOffset = previousOffset; var nextOffset = currentOffset + iterator; if(nextOffset > 1) { nextOffset = 1; } previousOffset = nextOffset; gradientCollection.Add(new GradientStop((Color)(ColorConverter.ConvertFromString(resource.Color) ?? Color.FromRgb(4, 180, 208)), currentOffset)); gradientCollection.Add(new GradientStop((Color)(ColorConverter.ConvertFromString(resource.Color) ?? Color.FromRgb(4, 180, 208)), nextOffset)); } } } public class AppointmentBorderZusageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { var customFields = (CustomFieldCollection) value; if(customFields is null) { return new SolidColorBrush(Color.FromRgb(192, 255, 208)); } var customFieldStorage = (CustomFieldStorage) customFields[nameof(CustomFieldStorage)]; var employeeList = customFieldStorage.EmployeeList; var isTask = customFieldStorage.IsTask; return employeeList.Any(e => e.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && e.ParticipationAnswer == ParticipationAnswer.Vorbehalt) ? new SolidColorBrush(Color.FromRgb(185, 39, 217)) : isTask ? new SolidColorBrush(Color.FromRgb(153, 59, 59)) : new SolidColorBrush(Color.FromRgb(192, 255, 208)); } catch(Exception e) { Console.WriteLine(e); return new SolidColorBrush(Color.FromRgb(192, 255, 208)); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class NichtNochEinConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(!(value is Employee2SchedulerAppointmentDC employee2SchedulerAppointment)) { return null; } if(parameter != null && parameter.Equals("GibName")) { return employee2SchedulerAppointment.Employee.DetailDescription; } var color = Color.FromRgb(255, 255, 255); switch(employee2SchedulerAppointment.ParticipationAnswer) { case ParticipationAnswer.Vorbehalt: color = Color.FromRgb(185, 39, 217); break; case ParticipationAnswer.Zusage: color = Color.FromRgb(72, 212, 78); break; case ParticipationAnswer.Absage: color = Color.FromRgb(171, 0, 48); break; } return new SolidColorBrush(color); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class InformationButtonVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return BeWoApp.AppSettings.ShowInfoButtonInCalender ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion }