Calendar.xaml.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Media;
  10. using System.Windows.Threading;
  11. using Comal.Classes;
  12. using InABox.Clients;
  13. using InABox.Configuration;
  14. using InABox.Core;
  15. using InABox.DynamicGrid;
  16. using InABox.WPF;
  17. using Org.BouncyCastle.Asn1.X509.Qualified;
  18. using PRS.Shared;
  19. using Syncfusion.SfSkinManager;
  20. using Syncfusion.UI.Xaml.Scheduler;
  21. using Selection = InABox.Core.Selection;
  22. using SelectionChangedEventArgs = System.Windows.Controls.SelectionChangedEventArgs;
  23. namespace PRSDesktop
  24. {
  25. public class SfScheduler2 : SfScheduler
  26. {
  27. public static readonly DependencyProperty HeaderVisibilityProperty =
  28. DependencyProperty.Register(
  29. nameof(HeaderVisibility),
  30. typeof(Visibility),
  31. typeof(SfScheduler2),
  32. new UIPropertyMetadata(Visibility.Collapsed)
  33. );
  34. public Visibility HeaderVisibility
  35. {
  36. get => (Visibility)GetValue(HeaderVisibilityProperty);
  37. set
  38. {
  39. SetValue(HeaderVisibilityProperty,value);
  40. SetHeaderVisibility();
  41. }
  42. }
  43. private void SetHeaderVisibility()
  44. {
  45. if (GetTemplateChild("PART_ScheduleHeaderControl") is SchedulerHeaderControl cell)
  46. cell.Visibility = HeaderVisibility;
  47. }
  48. public override void OnApplyTemplate()
  49. {
  50. base.OnApplyTemplate();
  51. SetHeaderVisibility();
  52. }
  53. }
  54. public partial class Calendar
  55. {
  56. private enum Suppress
  57. {
  58. Selector, // Prevent the Selector from Being Changed
  59. Calendar, // Prevent the Calendar from Being Reconfigured
  60. Events, // Prevent the Selectors from Responding to Events
  61. Refresh, // Stop the Data from Being refreshed
  62. Settings // Dont allow settings to be updated
  63. }
  64. private EventSuppressor suppressor = null;
  65. public void DisableUpdate()
  66. {
  67. if (suppressor == null)
  68. suppressor = new EventSuppressor(Suppress.Refresh, Suppress.Settings);
  69. }
  70. public void EnableUpdate()
  71. {
  72. if (suppressor != null)
  73. {
  74. suppressor.Dispose();
  75. suppressor = null;
  76. }
  77. }
  78. private void DoSetValue<T>(DependencyProperty property, T value, Action? updateselector, Action? updateinterface)
  79. {
  80. SetValue(property, value);
  81. if (!EventSuppressor.IsSet(Suppress.Selector) && (updateselector != null))
  82. using (new EventSuppressor(Suppress.Events))
  83. updateselector();
  84. if (!EventSuppressor.IsSet(Suppress.Calendar) && (updateinterface != null))
  85. updateinterface();
  86. if (!EventSuppressor.IsSet(Suppress.Refresh))
  87. Refresh();
  88. if (!EventSuppressor.IsSet(Suppress.Settings))
  89. {
  90. Properties.SettingsVisible = SettingsVisible;
  91. Properties.Date = SelectedDate;
  92. Properties.StartHour = (int)Bookings.DaysViewSettings.StartHour;
  93. Properties.EndHour = (int)Bookings.DaysViewSettings.EndHour;
  94. Properties.CalendarView = CalendarView;
  95. Properties.EmployeeSelector = EmployeeSettings;
  96. Properties.EmployeeSelection = EmployeeSelection;
  97. Properties.TimeInterval = TimeInterval;
  98. Properties.AssignmentType = AssignmentType;
  99. Properties.BackgroundType = BackgroundType;
  100. Properties.Zoom = Zoom;
  101. SaveSettings?.Invoke(this, Properties);
  102. }
  103. }
  104. #region HeaderVisibility Dependency Property
  105. public static readonly DependencyProperty HeaderVisibilityProperty =
  106. DependencyProperty.Register(
  107. nameof(HeaderVisibility),
  108. typeof(Visibility),
  109. typeof(Calendar),
  110. new UIPropertyMetadata(Visibility.Collapsed)
  111. );
  112. public Visibility HeaderVisibility
  113. {
  114. get => (Visibility)GetValue(HeaderVisibilityProperty);
  115. set
  116. {
  117. SetValue(HeaderVisibilityProperty,value);
  118. Bookings.HeaderVisibility = value;
  119. }
  120. }
  121. #endregion
  122. #region SettingsVisible Dependency Property
  123. public static readonly DependencyProperty SettingsVisibleProperty =
  124. DependencyProperty.Register(
  125. nameof(SettingsVisible),
  126. typeof(CalendarSettingsVisibility),
  127. typeof(Calendar),
  128. new UIPropertyMetadata(CalendarSettingsVisibility.Disabled)
  129. );
  130. public CalendarSettingsVisibility SettingsVisible
  131. {
  132. get => (CalendarSettingsVisibility)GetValue(SettingsVisibleProperty);
  133. set => SetSettingsVisibility(value);
  134. }
  135. private void SetSettingsVisibility(CalendarSettingsVisibility value)
  136. {
  137. DoSetValue(
  138. SettingsVisibleProperty,
  139. value,
  140. () => { },
  141. () =>
  142. {
  143. _splitPanel.View = value == CalendarSettingsVisibility.Visible
  144. ? DynamicSplitPanelView.Combined
  145. : DynamicSplitPanelView.Master;
  146. _splitPanel.AllowableViews = value == CalendarSettingsVisibility.Disabled
  147. ? DynamicSplitPanelView.Master
  148. : DynamicSplitPanelView.Master | DynamicSplitPanelView.Combined;
  149. ResizeColumns(this.ActualWidth);
  150. }
  151. );
  152. }
  153. #endregion
  154. #region CalendarView Dependency Property
  155. public static readonly DependencyProperty CalendarViewProperty =
  156. DependencyProperty.Register(
  157. nameof(CalendarView),
  158. typeof(CalendarViewType),
  159. typeof(Calendar),
  160. new UIPropertyMetadata(CalendarViewType.Day)
  161. );
  162. public CalendarViewType CalendarView
  163. {
  164. get => (CalendarViewType)GetValue(CalendarViewProperty);
  165. set => SetCalendarView(value);
  166. }
  167. private void SetCalendarView(CalendarViewType value)
  168. {
  169. DoSetValue(
  170. CalendarViewProperty,
  171. value,
  172. () => CalendarViewSelector.SelectedIndex = (int)value,
  173. () =>
  174. {
  175. Bookings.ViewType = value switch
  176. {
  177. CalendarViewType.Day => SchedulerViewType.Day,
  178. CalendarViewType.WorkWeek => SchedulerViewType.WorkWeek,
  179. CalendarViewType.Week => SchedulerViewType.Week,
  180. _ => SchedulerViewType.Day
  181. };
  182. ResizeColumns(this.ActualWidth);
  183. }
  184. );
  185. }
  186. private void CalendarViewSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
  187. {
  188. if (EventSuppressor.IsSet(Suppress.Events))
  189. return;
  190. using (new EventSuppressor(Suppress.Selector))
  191. SetCalendarView((CalendarViewType)CalendarViewSelector.SelectedIndex);
  192. }
  193. #endregion
  194. #region EmployeeSelector Dependency Property
  195. public static readonly DependencyProperty EmployeeSelectionProperty =
  196. DependencyProperty.Register(
  197. nameof(EmployeeSelection),
  198. typeof(EmployeeSelectorData),
  199. typeof(Calendar),
  200. new UIPropertyMetadata(new EmployeeSelectorData())
  201. );
  202. public EmployeeSelectorData EmployeeSelection
  203. {
  204. get => (EmployeeSelectorData)GetValue(EmployeeSelectionProperty);
  205. set => SetEmployeeSelection(value);
  206. }
  207. private void SetEmployeeSelection(EmployeeSelectorData value)
  208. {
  209. DoSetValue(
  210. EmployeeSelectionProperty,
  211. value,
  212. () => EmployeeSelector.Selection = value,
  213. () =>
  214. {
  215. _employees = EmployeeSelector.GetEmployeeData((row, rosters) => new EmployeeResourceModel(row, rosters));
  216. ReloadColumns();
  217. }
  218. );
  219. }
  220. private void EmployeeSelector_OnSelectionChanged(object sender, EmployeeSelectorSelectionChangedArgs args)
  221. {
  222. if (EventSuppressor.IsSet(Suppress.Events))
  223. return;
  224. using (new EventSuppressor(Suppress.Selector))
  225. SetEmployeeSelection(args.Selection);
  226. }
  227. #endregion
  228. #region EmployeeSettings Dependency Property
  229. public static readonly DependencyProperty EmployeeSettingsProperty =
  230. DependencyProperty.Register(
  231. nameof(EmployeeSettings),
  232. typeof(EmployeeSelectorSettings),
  233. typeof(Calendar),
  234. new UIPropertyMetadata(new EmployeeSelectorSettings())
  235. );
  236. public EmployeeSelectorSettings EmployeeSettings
  237. {
  238. get => (EmployeeSelectorSettings)GetValue(EmployeeSettingsProperty);
  239. set => SetEmployeeSettings(value);
  240. }
  241. private void SetEmployeeSettings(EmployeeSelectorSettings value)
  242. {
  243. DoSetValue(
  244. EmployeeSettingsProperty,
  245. value,
  246. () => EmployeeSelector.Settings = value,
  247. () =>
  248. {
  249. // Nothing to do here
  250. }
  251. );
  252. }
  253. private void EmployeeSelector_OnSettingsChanged(object sender, EmployeeSelectorSettingsChangedArgs args)
  254. {
  255. if (EventSuppressor.IsSet(Suppress.Events))
  256. return;
  257. using (new EventSuppressor(Suppress.Selector))
  258. SetEmployeeSettings(args.Settings);
  259. }
  260. #endregion
  261. #region TimeInterval DependencyProperty
  262. public static readonly DependencyProperty TimeIntervalProperty =
  263. DependencyProperty.Register(
  264. "TimeInterval",
  265. typeof(CalendarTimeInterval),
  266. typeof(Calendar),
  267. new PropertyMetadata(CalendarTimeInterval.FifteenMinutes)
  268. );
  269. public CalendarTimeInterval TimeInterval
  270. {
  271. get => (CalendarTimeInterval)GetValue(TimeIntervalProperty);
  272. set => SetTimeInterval(value);
  273. }
  274. private void SetTimeInterval(CalendarTimeInterval value)
  275. {
  276. DoSetValue(
  277. TimeIntervalProperty,
  278. value,
  279. () => IntervalSelector.SelectedIndex = (int)value,
  280. () =>
  281. {
  282. Bookings.DaysViewSettings.TimeInterval = TimeIntervalToTimeSpan(value);
  283. UpdateZoom();
  284. });
  285. }
  286. private void IntervalSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  287. {
  288. if (EventSuppressor.IsSet(Suppress.Events))
  289. return;
  290. using (new EventSuppressor(Suppress.Selector))
  291. SetTimeInterval((CalendarTimeInterval)IntervalSelector.SelectedIndex);
  292. }
  293. public TimeSpan TimeIntervalToTimeSpan(CalendarTimeInterval interval)
  294. {
  295. return interval switch
  296. {
  297. CalendarTimeInterval.FiveMinutes => new TimeSpan(0, 5, 0),
  298. CalendarTimeInterval.SixMinutes => new TimeSpan(0, 6, 0),
  299. CalendarTimeInterval.TenMinutes => new TimeSpan(0, 10, 0),
  300. CalendarTimeInterval.FifteenMinutes => new TimeSpan(0, 15, 0),
  301. CalendarTimeInterval.TwentyMinutes => new TimeSpan(0, 20, 0),
  302. CalendarTimeInterval.ThirtyMinutes => new TimeSpan(0, 30, 0),
  303. _ => new TimeSpan(1, 0, 0)
  304. };
  305. }
  306. public int BlocksPerHour(CalendarTimeInterval interval)
  307. {
  308. return interval switch
  309. {
  310. CalendarTimeInterval.FiveMinutes => 12,
  311. CalendarTimeInterval.SixMinutes => 10,
  312. CalendarTimeInterval.TenMinutes => 6,
  313. CalendarTimeInterval.FifteenMinutes => 4,
  314. CalendarTimeInterval.TwentyMinutes => 3,
  315. CalendarTimeInterval.ThirtyMinutes => 2,
  316. _ => 1
  317. };
  318. }
  319. private TimeSpan AdjustStartTime(TimeSpan time)
  320. {
  321. long blocksize = TimeIntervalToTimeSpan(TimeInterval).Ticks;
  322. //long blocksperday = TimeSpan.FromDays(1).Ticks / ;
  323. long blocknumber = time.Ticks / blocksize;
  324. long blockstart = blocknumber * blocksize;
  325. return TimeSpan.FromTicks(blockstart);
  326. }
  327. #endregion
  328. #region SelectedDate Dependency Property
  329. public static readonly DependencyProperty SelectedDateProperty =
  330. DependencyProperty.Register(
  331. nameof(SelectedDate),
  332. typeof(DateTime),
  333. typeof(Calendar),
  334. new UIPropertyMetadata(DateTime.Today)
  335. );
  336. public DateTime SelectedDate
  337. {
  338. get => (DateTime)GetValue(SelectedDateProperty);
  339. set => SetSelectedDate(value);
  340. }
  341. private void SetSelectedDate(DateTime value)
  342. {
  343. DoSetValue(
  344. SelectedDateProperty,
  345. value,
  346. () => { /* DateSelector.Date = value; */ },
  347. () => {
  348. Bookings.DisplayDate = value;
  349. Bookings.SelectedDate = value;
  350. });
  351. }
  352. // private void DateSelector_DateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  353. // {
  354. // if (EventSuppressor.IsSet(Suppress.Events))
  355. // return;
  356. // using (new EventSuppressor(Suppress.Selector))
  357. // SetSelectedDate(DateSelector.Date);
  358. // }
  359. public DateTime StartDate => (Properties?.CalendarView ?? CalendarViewType.Day) == CalendarViewType.Day
  360. ? SelectedDate
  361. : SelectedDate.StartOfWeek(DayOfWeek.Monday);
  362. public DateTime EndDate => Properties.CalendarView == CalendarViewType.Day
  363. ? StartDate.AddDays(1)
  364. : Properties.CalendarView == CalendarViewType.WorkWeek
  365. ? StartDate.AddDays(5)
  366. : StartDate.AddDays(7);
  367. #endregion
  368. #region StartHour Dependency Properties
  369. public static readonly DependencyProperty StartHourProperty =
  370. DependencyProperty.Register(
  371. nameof(StartHour),
  372. typeof(int),
  373. typeof(Calendar),
  374. new UIPropertyMetadata(6)
  375. );
  376. public int StartHour
  377. {
  378. get => (int)GetValue(StartHourProperty);
  379. set => SetStartHour(value);
  380. }
  381. private void SetStartHour(int value)
  382. {
  383. value = Math.Min(EndHour-1,Math.Max(0, value));
  384. DoSetValue(
  385. StartHourProperty,
  386. value,
  387. () => StartTimeSelector.Text = FormatHour(value),
  388. () =>
  389. {
  390. Bookings.DaysViewSettings.StartHour = value;
  391. UpdateZoom();
  392. });
  393. }
  394. private void StartTimeSelector_Down_Click(object sender, RoutedEventArgs e)
  395. {
  396. if (EventSuppressor.IsSet(Suppress.Events))
  397. return;
  398. SetStartHour(StartHour - 1);
  399. }
  400. private void StartTimeSelector_Up_Click(object sender, RoutedEventArgs e)
  401. {
  402. if (EventSuppressor.IsSet(Suppress.Events))
  403. return;
  404. SetStartHour(StartHour + 1);
  405. }
  406. #endregion
  407. #region End Hour Property
  408. public static readonly DependencyProperty EndHourProperty =
  409. DependencyProperty.Register(
  410. nameof(EndHour),
  411. typeof(int),
  412. typeof(Calendar),
  413. new UIPropertyMetadata(18)
  414. );
  415. public int EndHour
  416. {
  417. get => (int)GetValue(EndHourProperty);
  418. set => SetEndHour(value);
  419. }
  420. private void SetEndHour(int value)
  421. {
  422. value = Math.Max(StartHour + 1, Math.Min(24, value));
  423. DoSetValue(
  424. EndHourProperty,
  425. value,
  426. () => FinishTimeSelector.Text = FormatHour(value),
  427. () =>
  428. {
  429. Bookings.DaysViewSettings.EndHour = value;
  430. UpdateZoom();
  431. });
  432. }
  433. private void FinishTimeSelector_Down_Click(object sender, RoutedEventArgs e)
  434. {
  435. if (EventSuppressor.IsSet(Suppress.Events))
  436. return;
  437. SetEndHour(EndHour - 1);
  438. }
  439. private void FinishTimeSelector_Up_Click(object sender, RoutedEventArgs e)
  440. {
  441. if (EventSuppressor.IsSet(Suppress.Events))
  442. return;
  443. SetEndHour(EndHour + 1);
  444. }
  445. private string FormatHour(int hour)
  446. {
  447. return hour <= 0 || hour >= 24
  448. ? "Midnight"
  449. : hour < 12
  450. ? string.Format("{0}:00 AM", hour)
  451. : hour > 12
  452. ? string.Format("{0}:00 PM", hour)
  453. : "12:00 NN";
  454. }
  455. #endregion
  456. #region AssignmentType Dependency Property
  457. public static readonly DependencyProperty AssignmentTypeProperty =
  458. DependencyProperty.Register(
  459. nameof(AssignmentType),
  460. typeof(CalendarAssignmentType),
  461. typeof(Calendar),
  462. new UIPropertyMetadata(CalendarAssignmentType.Booked)
  463. );
  464. public CalendarAssignmentType AssignmentType
  465. {
  466. get => (CalendarAssignmentType)GetValue(AssignmentTypeProperty);
  467. set => SetAssignmentType(value);
  468. }
  469. private void SetAssignmentType(CalendarAssignmentType value)
  470. {
  471. DoSetValue(
  472. AssignmentTypeProperty,
  473. value,
  474. () => AssignmentTypeSelector.SelectedIndex = (int)value,
  475. null
  476. );
  477. }
  478. private void AssignmentTypeSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  479. {
  480. if (EventSuppressor.IsSet(Suppress.Events))
  481. return;
  482. using (new EventSuppressor(Suppress.Selector))
  483. SetAssignmentType((CalendarAssignmentType)AssignmentTypeSelector.SelectedIndex);
  484. }
  485. #endregion
  486. #region BackgroundType Dependency Property
  487. public static readonly DependencyProperty BackgroundTypeProperty =
  488. DependencyProperty.Register(
  489. nameof(BackgroundType),
  490. typeof(CalendarBackgroundType),
  491. typeof(Calendar),
  492. new UIPropertyMetadata(CalendarBackgroundType.Roster)
  493. );
  494. public CalendarBackgroundType BackgroundType
  495. {
  496. get => (CalendarBackgroundType)GetValue(BackgroundTypeProperty);
  497. set => SetBackgroundType(value);
  498. }
  499. private void SetBackgroundType(CalendarBackgroundType type)
  500. {
  501. DoSetValue(
  502. BackgroundTypeProperty,
  503. type,
  504. () => BackgroundTypeSelector.SelectedIndex = (int)type,
  505. null
  506. );
  507. }
  508. private void BackgroundTypeSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  509. {
  510. if (EventSuppressor.IsSet(Suppress.Events))
  511. return;
  512. using (new EventSuppressor(Suppress.Selector))
  513. SetBackgroundType((CalendarBackgroundType)BackgroundTypeSelector.SelectedIndex);
  514. }
  515. #endregion
  516. #region Zoom Dependency Properties
  517. public static readonly DependencyProperty ZoomProperty =
  518. DependencyProperty.Register(
  519. nameof(Zoom),
  520. typeof(double),
  521. typeof(Calendar),
  522. new UIPropertyMetadata((double)100F)
  523. );
  524. public double Zoom
  525. {
  526. get => (double)GetValue(ZoomProperty);
  527. set => SetZoom(value);
  528. }
  529. private void SetZoom(double value)
  530. {
  531. DoSetValue(
  532. ZoomProperty,
  533. value,
  534. () => ZoomSelector.Text = $"{value:F0}%",
  535. () => UpdateZoom()
  536. );
  537. }
  538. private void UpdateZoom()
  539. {
  540. if (double.IsNaN(this.ActualHeight) || (this.ActualHeight == 0.0F))
  541. return;
  542. var blocksize = (this.ActualHeight - (Bookings.DaysViewSettings.ViewHeaderHeight + Bookings.DaysViewSettings.ResourceHeaderSize + 2.0F)) / ((EndHour - StartHour) * this.BlocksPerHour(TimeInterval));
  543. Bookings.DaysViewSettings.TimeIntervalSize = (double)Zoom * blocksize / 100.0F;
  544. }
  545. private void ZoomSelector_Down_Click(object sender, RoutedEventArgs e)
  546. {
  547. if (EventSuppressor.IsSet(Suppress.Events))
  548. return;
  549. ZoomOut();
  550. }
  551. private void ZoomSelector_Up_Click(object sender, RoutedEventArgs e)
  552. {
  553. if (EventSuppressor.IsSet(Suppress.Events))
  554. return;
  555. ZoomIn();
  556. }
  557. public void ZoomIn() => SetZoom(Zoom * 1.125F);
  558. public void ZoomOut() => SetZoom(Zoom / 1.125F);
  559. public void ResetZoom() => SetZoom(100.0F);
  560. #endregion
  561. #region Event Handlers
  562. public event LoadSettings<CalendarSettings> LoadSettings;
  563. public event SaveSettings<CalendarSettings> SaveSettings;
  564. public CalendarConfigurationEvent ConfigurationChanged;
  565. public event CalendarDataEvent CustomiseContextMenu;
  566. public event CalendarDataEvent SelectionChanged;
  567. public event CalendarDataEvent ItemCreated;
  568. public event CalendarDataEvent ItemChanged;
  569. public event CalendarHandledEvent ItemEditing;
  570. #endregion
  571. public void SelectEmployee(Guid employeeid) => EmployeeSelector.SelectEmployee(employeeid);
  572. // Populated as requiew when EmployeeSelector.SelectionChanged is triggered
  573. private EmployeeResourceModel[] _employees = new EmployeeResourceModel[] { };
  574. // Populated once at startup
  575. private StandardLeaveModel[] _standardleaves = new StandardLeaveModel[] { };
  576. private LeaveRequestModel[] _leaverequests = new LeaveRequestModel[] { };
  577. // Populated on each Refresh
  578. private TimeSheetModel[] _timesheets = new TimeSheetModel[] { };
  579. // Populated on each Refresh
  580. private List<AssignmentModel> _assignments = new List<AssignmentModel>();
  581. private bool bColumnsLoaded;
  582. private AssignmentGrid ag;
  583. private DynamicDataGrid<Meeting> mg;
  584. public bool IsReady { get; set; }
  585. public CalendarSettings Properties { get; set; }
  586. //public SfScheduler2? Bookings => this.FindName("_bookings") as SfScheduler2;
  587. public Calendar()
  588. {
  589. using (EventSuppressor.All<Suppress>())
  590. {
  591. InitializeComponent();
  592. SetValue(StartHourProperty, 0);
  593. SetValue(EndHourProperty, 24);
  594. SfSkinManager.SetTheme(Bookings, new Theme() { ThemeName = "Office2019White", ScrollBarMode = ScrollBarMode.Compact });
  595. }
  596. }
  597. public virtual void Setup()
  598. {
  599. using (new EventSuppressor(Suppress.Settings, Suppress.Refresh, Suppress.Events))
  600. {
  601. Properties = LoadSettings?.Invoke(this) ?? new CalendarSettings();
  602. SetCalendarView(Properties.CalendarView);
  603. SetSettingsVisibility(Properties.SettingsVisible);
  604. SetSelectedDate(Properties.Date);
  605. SetStartHour(Properties.StartHour);
  606. SetEndHour(Properties.EndHour);
  607. SetTimeInterval(Properties.TimeInterval);
  608. SetAssignmentType(Properties.AssignmentType);
  609. SetBackgroundType(Properties.BackgroundType);
  610. SetCalendarView(Properties.CalendarView);
  611. SetZoom(Properties.Zoom);
  612. EmployeeSelector.Setup();
  613. SetEmployeeSettings(Properties.EmployeeSelector);
  614. SetEmployeeSelection(Properties.EmployeeSelection);
  615. _employees = EmployeeSelector.GetEmployeeData((row, rosters) => new EmployeeResourceModel(row, rosters));
  616. MultiQuery query = new MultiQuery();
  617. query.Add(
  618. new Filter<LeaveRequest>(x=>x.Status).IsNotEqualTo(LeaveRequestStatus.Rejected),
  619. LeaveRequestModel.Columns
  620. );
  621. query.Add(
  622. null,
  623. StandardLeaveModel.Columns
  624. );
  625. query.Query();
  626. _standardleaves = query.Get<StandardLeave>().Rows.Select(row => new StandardLeaveModel(row)).ToArray();
  627. _leaverequests = query.Get<LeaveRequest>().Rows.Select(row => new LeaveRequestModel(row)).ToArray();
  628. var widthtimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
  629. widthtimer.Tick += (o, e) =>
  630. {
  631. if (Bookings.ActualWidth > 0.0F)
  632. {
  633. widthtimer.IsEnabled = false;
  634. ReloadColumns();
  635. }
  636. };
  637. widthtimer.IsEnabled = true;
  638. }
  639. }
  640. public virtual void Shutdown(CancelEventArgs? cancel)
  641. {
  642. }
  643. public virtual void Refresh()
  644. {
  645. if (EventSuppressor.IsSet(Suppress.Refresh))
  646. return;
  647. using (new WaitCursor())
  648. {
  649. if (!bColumnsLoaded)
  650. ReloadColumns();
  651. MultiQuery query = new MultiQuery();
  652. var empids = _employees.Select(x => x.ID).ToArray();
  653. if (BackgroundType != CalendarBackgroundType.Roster)
  654. {
  655. query.Add<TimeSheet>(
  656. new Filter<TimeSheet>(x => x.EmployeeLink.ID).InList(empids)
  657. .And(x => x.Date).IsGreaterThanOrEqualTo(StartDate)
  658. .And(x => x.Date).IsLessThanOrEqualTo(EndDate)
  659. .And(x=>x.LeaveRequestLink.ID).IsEqualTo(Guid.Empty)
  660. .And(x=>x.StandardLeaveLink.ID).IsEqualTo(Guid.Empty),
  661. TimeSheetModel.Columns
  662. );
  663. }
  664. query.Add<Assignment>(
  665. new Filter<Assignment>(x => x.EmployeeLink.ID).InList(empids)
  666. .And(x => x.Date).IsGreaterThanOrEqualTo(StartDate)
  667. .And(x => x.Date).IsLessThanOrEqualTo(EndDate),
  668. AssignmentModel.Columns,
  669. new SortOrder<Assignment>(x => x.EmployeeLink.ID).ThenBy(x => x.Date).ThenBy(x => x.Booked.Duration, SortDirection.Descending)
  670. );
  671. query.Query();
  672. _timesheets = (BackgroundType == CalendarBackgroundType.Roster)
  673. ? new TimeSheetModel[] { }
  674. : query.Get<TimeSheet>().Rows.Select(r => new TimeSheetModel(r)).ToArray();
  675. _assignments = query.Get<Assignment>().Rows.Select(r => new AssignmentModel(r)).ToList();
  676. LoadBackground();
  677. var appointments = new CalendarAppointments();
  678. LoadStandardLeaves(appointments);
  679. LoadLeaveRequests(appointments);
  680. LoadAssignments(appointments);
  681. try
  682. {
  683. Bookings.DisplayDate = Bookings.SelectedDate.HasValue ? Bookings.SelectedDate.Value : StartDate;
  684. Bookings.ItemsSource = appointments;
  685. }
  686. catch (Exception e)
  687. {
  688. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  689. }
  690. }
  691. }
  692. public EmployeeRosterItem GetRoster(Guid employeeid, DateTime date)
  693. {
  694. var employee = _employees.FirstOrDefault(x => x.ID == employeeid);
  695. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.Start, date);
  696. return roster;
  697. }
  698. public bool GetActiveWindow(Guid employeeid, DateTime date, ref TimeSpan start, ref TimeSpan finish)
  699. {
  700. bool result = false;
  701. foreach (var assignment in _assignments.Where(a => (a.EmployeeID == employeeid) && (a.Date) == date))
  702. {
  703. result = true;
  704. var curstart = AssignmentType switch
  705. {
  706. CalendarAssignmentType.Booked => assignment.BookedStart,
  707. CalendarAssignmentType.Actual => assignment.ActualStart,
  708. _ => Assignment.EffectiveTime(assignment.ActualStart, assignment.BookedStart)
  709. };
  710. var curfinish = AssignmentType switch
  711. {
  712. CalendarAssignmentType.Booked => assignment.BookedFinish,
  713. CalendarAssignmentType.Actual => assignment.ActualFinish,
  714. _ => Assignment.EffectiveTime(
  715. assignment.ActualFinish,
  716. Assignment.EffectiveTime(assignment.ActualStart, assignment.BookedStart)
  717. .Add(assignment.BookedDuration)
  718. )
  719. };
  720. start = start > curstart ? curstart : start;
  721. finish = finish < curfinish ? curfinish : finish;
  722. }
  723. if ((BackgroundType == CalendarBackgroundType.Roster) ||
  724. ((BackgroundType == CalendarBackgroundType.Automatic) && (date >= DateTime.Today)))
  725. {
  726. var employee = _employees.FirstOrDefault(x => x.ID == employeeid);
  727. if (employee != null)
  728. {
  729. var roster = RosterUtils.GetRoster(employee.Roster, employee.Start, date);
  730. if (roster != null)
  731. {
  732. var blocks = roster.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue);
  733. foreach (var block in blocks)
  734. {
  735. start = start > block.Start ? block.Start : start;
  736. finish = finish < block.Finish ? block.Finish : finish;
  737. }
  738. }
  739. }
  740. }
  741. else
  742. {
  743. foreach (var timesheet in _timesheets.Where(t => (t.EmployeeID == employeeid) && (t.Date == date)))
  744. {
  745. result = true;
  746. var curstart = !timesheet.Approved.IsEmpty()
  747. ? timesheet.ApprovedStart
  748. : timesheet.Start;
  749. var curfinish = !timesheet.Approved.IsEmpty()
  750. ? timesheet.ApprovedFinish
  751. : timesheet.Finish;
  752. start = start > curstart ? curstart : start;
  753. finish = finish < curfinish ? curfinish : finish;
  754. }
  755. }
  756. return result;
  757. }
  758. public CoreRow[] GetAssignments(Guid employeeid, DateTime date)
  759. {
  760. return _assignments.Where(a => (a.Row != null) && (a.EmployeeID == employeeid) && (a.Date == date)).Select(x => x.Row!).ToArray();
  761. }
  762. public void UpdateAssignment(Assignment assignment)
  763. {
  764. void UpdateCalendar<TEntity, TModel>(
  765. TEntity entity,
  766. List<TModel> collection,
  767. Action<TModel> refresh
  768. ) where TEntity : Entity where TModel : class, IModel
  769. {
  770. if (Bookings.ItemsSource is CalendarAppointments appointments)
  771. {
  772. var appointment = appointments.FirstOrDefault(x => (Guid)x.Id == entity.ID) as ScheduleAppointment;
  773. if (appointment != null)
  774. {
  775. appointments.Remove(appointment);
  776. var calappt = appointment as ICalendarAppointment<TModel>;
  777. if (calappt != null)
  778. collection.Remove(calappt.Model);
  779. }
  780. var table = new CoreTable();
  781. table.LoadColumns(typeof(TEntity));
  782. var row = table.NewRow();
  783. table.LoadRow(row, entity);
  784. var model = (Activator.CreateInstance(typeof(TModel),row) as TModel)!;
  785. collection.Add(model);
  786. refresh(model);
  787. }
  788. }
  789. if (Bookings.ItemsSource is CalendarAppointments appointments)
  790. UpdateCalendar(assignment, _assignments, (model) => LoadAssignment(model,appointments));
  791. }
  792. private void LoadBackground()
  793. {
  794. var regions = new ObservableCollection<SpecialTimeRegion>();
  795. foreach (var resource in Bookings.ResourceCollection)
  796. {
  797. var sEmpID = (((SchedulerResource)resource).Id as string) ?? "";
  798. var empid = Guid.Parse(sEmpID);
  799. var employee = _employees.FirstOrDefault(x => x.ID == empid);
  800. for (var date = StartDate; date < EndDate; date = date.AddDays(1))
  801. {
  802. if ((BackgroundType == CalendarBackgroundType.Roster) ||
  803. ((BackgroundType == CalendarBackgroundType.Automatic) && (date >= DateTime.Today)))
  804. {
  805. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.Start, date);
  806. if (roster != null)
  807. {
  808. var blocks = roster.GetBlocks(date, TimeSpan.FromSeconds(0), TimeSpan.FromDays(1));
  809. foreach (var block in blocks)
  810. {
  811. regions.Add(
  812. new SpecialTimeRegion
  813. {
  814. StartTime = date.Add(block.Start),
  815. EndTime = date.Add(block.Finish.Subtract(TimeSpan.FromSeconds(1))),
  816. ResourceIdCollection = new ObservableCollection<object> { ((SchedulerResource)resource).Id },
  817. Background = new SolidColorBrush(Colors.Yellow) {Opacity = 0.3},
  818. Foreground = new SolidColorBrush(Colors.Black),
  819. Text = ""
  820. }
  821. );
  822. }
  823. }
  824. }
  825. else
  826. {
  827. foreach (var timesheet in _timesheets.Where(t => (t.EmployeeID == empid) && (t.Date == date)))
  828. {
  829. var start = !timesheet.Approved.IsEmpty()
  830. ? timesheet.ApprovedStart
  831. : timesheet.Start;
  832. var finish = !timesheet.Approved.IsEmpty()
  833. ? timesheet.ApprovedFinish
  834. : timesheet.Finish;
  835. regions.Add(
  836. new SpecialTimeRegion
  837. {
  838. StartTime = date.Add(start),
  839. EndTime = date.Add(finish),
  840. ResourceIdCollection = new ObservableCollection<object> { ((SchedulerResource)resource).Id },
  841. Background = new SolidColorBrush(!timesheet.Approved.IsEmpty() ? Colors.LightGreen : Colors.LightSalmon) { Opacity = 0.4 },
  842. Foreground = new SolidColorBrush(Colors.Transparent),
  843. Text = "",
  844. CanMergeAdjacentRegions = false
  845. }
  846. );
  847. }
  848. }
  849. }
  850. }
  851. Bookings.DaysViewSettings.SpecialTimeRegions = regions;
  852. }
  853. private void LoadStandardLeaves(CalendarAppointments appointments)
  854. {
  855. for (var date = StartDate; date < EndDate; date = date.AddDays(1))
  856. {
  857. var leaves = _standardleaves.Where(x =>
  858. (x.From <= date)
  859. && (x.To.Add(x.ToTime) > date)
  860. ).ToArray();
  861. foreach (var leave in leaves)
  862. {
  863. foreach (var resource in Bookings.ResourceCollection)
  864. {
  865. var sEmpID = ((SchedulerResource)resource).Id as string;
  866. var empid = Guid.Parse(sEmpID);
  867. var employee = _employees.FirstOrDefault(x => x.ID == empid);
  868. var start = (date.Date == leave.From.Date) ? leave.FromTime : TimeSpan.FromSeconds(0);
  869. var finish = (date.Date == leave.To.Date) ? leave.ToTime : TimeSpan.FromDays(1).Subtract(TimeSpan.FromSeconds(1));
  870. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.Start, date);
  871. if (roster != null)
  872. {
  873. var blocks = roster.GetBlocks(date, start, finish);
  874. foreach (var block in blocks)
  875. {
  876. var appt = new StandardLeaveAppointment(leave, _ => empid, x => x.Color, block);
  877. appointments.Add(appt);
  878. }
  879. }
  880. }
  881. }
  882. }
  883. }
  884. private void LoadLeaveRequests(CalendarAppointments appointments)
  885. {
  886. for (var date = StartDate; date < EndDate; date = date.AddDays(1))
  887. {
  888. var ids = Bookings.ResourceCollection
  889. .Cast<SchedulerResource>()
  890. .Where(x=>!String.IsNullOrWhiteSpace(x.Id as String))
  891. .Select(x => Guid.Parse(x.Id.ToString() ?? ""));
  892. var leaves = _leaverequests.Where(x =>
  893. (x.From <= date)
  894. && (x.To.Add(x.ToTime) > date)
  895. && ids.Contains(x.EmployeeID)
  896. ).ToArray();
  897. foreach (var leave in leaves)
  898. {
  899. var employee = _employees.FirstOrDefault(x => x.ID == leave.EmployeeID);
  900. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.Start, date);
  901. if (roster != null)
  902. {
  903. var start = (date.Date == leave.From.Date) ? leave.FromTime : TimeSpan.FromSeconds(0);
  904. var finish = (date.Date == leave.To.Date) ? leave.ToTime : TimeSpan.FromDays(1).Subtract(TimeSpan.FromSeconds(1));
  905. var blocks = roster.GetBlocks(date, start, finish);
  906. foreach (var block in blocks)
  907. {
  908. var appt = new LeaveRequestAppointment(leave, x=>x.EmployeeID, x => x.Color, block);
  909. appointments.Add(appt);
  910. }
  911. }
  912. }
  913. }
  914. }
  915. private void LoadAssignment(AssignmentModel assignment, CalendarAppointments appointments)
  916. {
  917. var model = new AssignmentAppointment(assignment, x => x.EmployeeID, x => x.Color, AssignmentType);
  918. appointments.Add(model);
  919. }
  920. private void LoadAssignments(CalendarAppointments appointments)
  921. {
  922. foreach (var assignment in _assignments)
  923. LoadAssignment(assignment, appointments);
  924. }
  925. public DataModel DataModel(Selection selection)
  926. {
  927. var ids = _assignments.Select(x => x.ID).ToArray();
  928. return new AutoDataModel<Assignment>(new Filter<Assignment>(x => x.ID).InList(ids));
  929. }
  930. // private void ResizeIntervals(double height)
  931. // {
  932. // if (Bookings.FindVisualChildren<ScrollPanel>().Any())
  933. // {
  934. //
  935. // if (height > 95 && Bookings.DaysViewSettings.EndHour - Bookings.DaysViewSettings.StartHour > 0)
  936. // {
  937. // double scrollheight = _employees.Length * 75 > Bookings.ActualWidth ? 15.0F : 0.0F;
  938. // var header = _employees.Length > 1 ? 93.0F + scrollheight : 50.0F;
  939. // Bookings.DaysViewSettings.TimeIntervalSize =
  940. // (height - header) / ((Bookings.DaysViewSettings.EndHour - Bookings.DaysViewSettings.StartHour) * 2.0F);
  941. // }
  942. // }
  943. //
  944. // // var scrollers = Bookings.FindVisualChildren<ScrollViewer>().Where(x => string.Equals(x.Name, "PART_TimeSlotScrollViewer")).ToArray();
  945. // // foreach (var scroll in scrollers)
  946. // // scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
  947. //
  948. // }
  949. private void Schedule_SizeChanged(object sender, SizeChangedEventArgs e)
  950. {
  951. //ResizeIntervals(e.NewSize.Height);
  952. ResizeColumns(e.NewSize.Width);
  953. }
  954. private void ResizeColumns(double width)
  955. {
  956. if (double.IsNaN(width) || !Bookings.FindVisualChildren<ScrollPanel>().Any())
  957. return;
  958. var maxcount = (int)width / 75;
  959. Bookings.DaysViewSettings.VisibleResourceCount = Math.Min(maxcount,
  960. _employees.Length * (Bookings.ViewType == SchedulerViewType.Day ? 1 : Bookings.ViewType == SchedulerViewType.WorkWeek ? 5 : 7));
  961. if (Bookings.ResourceCollection is ObservableCollection<SchedulerResource> resources)
  962. {
  963. var colwidth = GetResourceColumnWidth();
  964. foreach (var emp in _employees)
  965. {
  966. var resource = resources.FirstOrDefault(x => String.Equals(x.Id?.ToString(), emp.ID.ToString()));
  967. if (resource != null)
  968. {
  969. var comps = emp.Name.Split(' ');
  970. var display = emp.Name;
  971. if (colwidth < 75)
  972. display = string.Format("{0}{1}", comps[0].Length > 0 ? comps[0][..1] : "",
  973. comps.Length > 1 ? comps.Skip(1).First()[..1].ToUpper() : "");
  974. else if (colwidth < 150)
  975. display = string.Format("{0} {1}", comps.First(),
  976. comps.Length > 1 ? comps.Skip(1).First()[..1].ToUpper() : "");
  977. resource.Name = display;
  978. }
  979. }
  980. }
  981. }
  982. private T CheckGrid<T>(ref T grid) where T : new()
  983. {
  984. if (grid == null)
  985. grid = new T();
  986. return grid;
  987. }
  988. private void ReloadColumns()
  989. {
  990. ResizeColumns(Bookings.ActualWidth);
  991. var colwidth = GetResourceColumnWidth();
  992. var resources = new List<SchedulerResource>();
  993. foreach (var emp in _employees)
  994. {
  995. var comps = emp.Name.Split(' ');
  996. var display = emp.Name;
  997. if (colwidth < 75)
  998. display = CoreUtils.Codify(emp.Name);
  999. else if (colwidth < 150)
  1000. display = string.Format("{0} {1}", comps.Length > 0 ? comps.First() : "", comps.Length > 1 ? comps.Skip(1).First().Substring(0, 1).ToUpper() : "");
  1001. resources.Add(new SchedulerResource { Name = display, Id = emp.ID.ToString() });
  1002. }
  1003. var sorted = new ObservableCollection<SchedulerResource>();
  1004. foreach (var resource in resources.OrderBy(x => x.Name))
  1005. sorted.Add(resource);
  1006. try
  1007. {
  1008. Bookings.DaysViewSettings.ResourceHeaderSize = sorted.Count <= 1 ? 0 : 45;
  1009. }
  1010. catch (Exception e)
  1011. {
  1012. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1013. }
  1014. //ResizeIntervals(Bookings.ActualHeight);
  1015. try
  1016. {
  1017. Bookings.ResourceCollection = sorted;
  1018. }
  1019. catch (Exception e)
  1020. {
  1021. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1022. }
  1023. bColumnsLoaded = true;
  1024. }
  1025. // private SchedulerResource GetCurrentResource()
  1026. // {
  1027. // var p = Mouse.GetPosition(Bookings);
  1028. // var panels = Bookings.FindVisualChildren<ScrollViewer>().FirstOrDefault(x => string.Equals(x.Name, "PART_ViewHeaderScrollViewer"));
  1029. // var resource = (int)((p.X + panels.HorizontalOffset - (Bookings.DaysViewSettings.TimeRulerSize + 20F)) / GetResourceColumnWidth());
  1030. // return (Bookings.ResourceCollection as Collection<SchedulerResource>)[resource];
  1031. // }
  1032. //
  1033. // private DateTime GetCurrentTime()
  1034. // {
  1035. // var p = Mouse.GetPosition(Bookings);
  1036. // var hours = (p.Y - (_employees.Length > 1 ? 95.0F : 50.0F)) / (Bookings.DaysViewSettings.TimeIntervalSize * 2F) +
  1037. // Bookings.DaysViewSettings.StartHour;
  1038. // var result = Bookings.SelectedDate.Value + TimeSpan.FromHours(hours);
  1039. // return result;
  1040. // }
  1041. private double GetResourceColumnWidth()
  1042. {
  1043. var colcount = Math.Max(1, _employees.Length);
  1044. colcount = colcount * (Bookings.ViewType == SchedulerViewType.Day ? 1 : Bookings.ViewType == SchedulerViewType.Day ? 5 : 7);
  1045. var colwidth = Bookings.ActualWidth / colcount;
  1046. var minwidth = (Bookings.ActualWidth - (Bookings.DaysViewSettings.TimeRulerSize + 20F)) / Bookings.DaysViewSettings.VisibleResourceCount;
  1047. return Math.Max(minwidth, colwidth);
  1048. }
  1049. private void Schedule_AppointmentEditorOpening(object sender, AppointmentEditorOpeningEventArgs e)
  1050. {
  1051. e.Cancel = true;
  1052. }
  1053. private Dictionary<CalendarMenuName, MenuItem> _menuitems = new Dictionary<CalendarMenuName, MenuItem>();
  1054. public MenuItem? FindMenu(CalendarMenuName name)
  1055. {
  1056. _menuitems.TryGetValue(name, out MenuItem result);
  1057. return result;
  1058. }
  1059. MenuItem CreateMenu<T>(ItemsControl menu, CalendarMenuName name, string header, Action<T?>? action = null, T? data = null) where T : class
  1060. {
  1061. var item = new MenuItem();
  1062. item.Name = name.ToString();
  1063. item.Header = header;
  1064. if (action != null)
  1065. item.Click += (o,args) => action(data);
  1066. item.IsEnabled = data != null;
  1067. menu.Items.Add(item);
  1068. _menuitems[name] = item;
  1069. return item;
  1070. }
  1071. private void Bookings_OnSchedulerContextMenuOpening(object? sender, SchedulerContextMenuOpeningEventArgs e)
  1072. {
  1073. e.ContextMenu.Items.Clear();
  1074. if ((e.MenuType == SchedulerContextMenuType.Appointment) && (e.MenuInfo.Appointment is AssignmentAppointment appointment))
  1075. {
  1076. if (appointment.Model.MeetingID != Guid.Empty)
  1077. CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Edit Meeting", EditMeeting, appointment.Model);
  1078. else
  1079. {
  1080. CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Edit Assignment", EditAssignment, appointment.Model);
  1081. e.ContextMenu.Items.Add(new Separator());
  1082. CreateMenu(e.ContextMenu, CalendarMenuName.Copy, "Copy Assignment", CopyAssignment, appointment.Model);
  1083. e.ContextMenu.Items.Add(new Separator());
  1084. CreateMenu(e.ContextMenu, CalendarMenuName.Fill, "Fill Available Time", FillAssignment, appointment.Model);
  1085. }
  1086. e.ContextMenu.Items.Add(new Separator());
  1087. CreateDigitalFormsMenu(e.ContextMenu, appointment);
  1088. if (appointment.Model.MeetingID != Guid.Empty)
  1089. CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Delete Meeting", DeleteMeeting, appointment.Model);
  1090. else
  1091. CreateMenu(e.ContextMenu, CalendarMenuName.Delete, "Delete Assignment", DeleteAssignment, appointment.Model);
  1092. e.ContextMenu.Items.Add(new Separator());
  1093. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomIn, "Zoom In", (data) => ZoomIn(), null);
  1094. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomOut, "Zoom Out", (data) => ZoomOut(), null);
  1095. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ResetZoom, "Reset Zoom", (data) => ResetZoom(), null);
  1096. CustomiseContextMenu?.Invoke(e.ContextMenu, new CalendarDataEventArgs<object>((e.MenuInfo.Appointment as ICalendarAppointment)?.Model));
  1097. }
  1098. else if (e.MenuType == SchedulerContextMenuType.TimeSlotCell)
  1099. {
  1100. if (Guid.TryParse(e.MenuInfo.Resource.Id?.ToString(), out Guid employeeid))
  1101. {
  1102. var slot = new CalendarTimeSlot(employeeid, e.MenuInfo.DateTime.Value);
  1103. var createmenu = new MenuItem() { Header = "Create.." };
  1104. CreateMenu(createmenu, CalendarMenuName.CreateNew, "New Assignment", (data) => CreateAssignment(slot), slot);
  1105. CreateMenu(createmenu, CalendarMenuName.CreateNew, "New Meeting", (data) => CreateMeeting(slot), slot);
  1106. e.ContextMenu.Items.Add(createmenu);
  1107. if (_copiedmodel != null)
  1108. {
  1109. e.ContextMenu.Items.Add(new Separator());
  1110. CreateMenu(e.ContextMenu, CalendarMenuName.Paste, "Paste Assignment", (data) => PasteAssignment(slot), slot);
  1111. }
  1112. e.ContextMenu.Items.Add(new Separator());
  1113. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomIn, "Zoom In", (data) => ZoomIn(), slot);
  1114. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomOut, "Zoom Out", (data) => ZoomOut(), slot);
  1115. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ResetZoom, "Reset Zoom", (data) => ResetZoom(), slot);
  1116. CustomiseContextMenu?.Invoke(e.ContextMenu, new CalendarDataEventArgs<CalendarTimeSlot>(slot));
  1117. }
  1118. }
  1119. }
  1120. private static void CreateDigitalFormsMenu(ContextMenu menu, AssignmentAppointment appointment)
  1121. {
  1122. var digitalForms = new MenuItem { Header = "Digital Forms" };
  1123. DynamicGridUtils.PopulateFormMenu<AssignmentForm, Assignment, AssignmentLink>(
  1124. digitalForms,
  1125. appointment.Model.ID,
  1126. () => new Client<Assignment>().Load(new Filter<Assignment>(x => x.ID).IsEqualTo(appointment.Model.ID)).First(),
  1127. false);
  1128. menu.Items.Add(digitalForms);
  1129. menu.Items.Add(new Separator());
  1130. }
  1131. public void CreateMeeting(CalendarTimeSlot slot)
  1132. {
  1133. if (slot == null)
  1134. {
  1135. MessageBox.Show("Please select an employee first!");
  1136. return;
  1137. }
  1138. var meeting = new Meeting();
  1139. meeting.Date = slot.Time.Date;
  1140. meeting.Time.Start = AdjustStartTime(slot.Time.TimeOfDay);
  1141. meeting.Time.Duration = TimeIntervalToTimeSpan(TimeInterval);
  1142. meeting.Time.Finish = meeting.Time.Start + meeting.Time.Duration;
  1143. ItemCreated?.Invoke(this, new CalendarDataEventArgs<Meeting>(meeting));
  1144. var args = new CalendarHandledEventArgs<Meeting>(meeting);
  1145. ItemEditing?.Invoke(this, args);
  1146. if (args.Status == CalendarHandledStatus.Cancel)
  1147. return;
  1148. if (args.Status == CalendarHandledStatus.Handled)
  1149. {
  1150. Refresh();
  1151. return;
  1152. }
  1153. CheckGrid(ref mg);
  1154. var items = new[] { meeting };
  1155. bool bOK = mg.EditItems(
  1156. items,
  1157. (type) =>
  1158. {
  1159. if (type == typeof(Assignment))
  1160. return LoadMeetingEmployees(meeting, slot.EmployeeID);
  1161. else if (type == typeof(MeetingItem))
  1162. return LoadMeetingItems();
  1163. return null;
  1164. },
  1165. true
  1166. );
  1167. if (bOK)
  1168. Refresh();
  1169. }
  1170. private CoreTable LoadMeetingEmployees(Meeting meeting, Guid employeeid)
  1171. {
  1172. var result = new CoreTable();
  1173. result.LoadColumns(typeof(Assignment));
  1174. var assignment = new Assignment();
  1175. assignment.EmployeeLink.ID = employeeid;
  1176. var emp = new Client<Employee>().Load(new Filter<Employee>(x => x.ID).IsEqualTo(employeeid)).FirstOrDefault();
  1177. if (emp != null)
  1178. assignment.EmployeeLink.Synchronise(emp);
  1179. result.LoadRows(new[] { assignment });
  1180. return result;
  1181. }
  1182. private CoreTable LoadMeetingItems()
  1183. {
  1184. var result = new CoreTable();
  1185. result.LoadColumns(typeof(MeetingItem));
  1186. return result;
  1187. }
  1188. private void EditMeeting(AssignmentModel model)
  1189. {
  1190. if (model == null)
  1191. {
  1192. MessageBox.Show("Please select an entry first!");
  1193. return;
  1194. }
  1195. CheckGrid(ref mg);
  1196. var meeting = new Client<Meeting>().Query(
  1197. new Filter<Meeting>(x => x.ID).IsEqualTo(model.MeetingID),
  1198. mg.LoadEditorColumns()
  1199. ).Rows.FirstOrDefault()?.ToObject<Meeting>();
  1200. if ((meeting != null) && (mg.EditItems(new[] { meeting })))
  1201. {
  1202. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Meeting>(meeting));
  1203. Refresh();
  1204. }
  1205. }
  1206. private void DeleteMeeting(AssignmentModel model)
  1207. {
  1208. if (model == null)
  1209. {
  1210. MessageBox.Show("Please select an entry first!");
  1211. return;
  1212. }
  1213. if (MessageBox.Show("Are you sure you wish to delete this meeting?", "Confirm Delete", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1214. return;
  1215. var meeting = new Meeting { ID = model.MeetingID };
  1216. new Client<Meeting>().Delete(meeting, "Meeting Deleted from Scheduler");
  1217. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Meeting>(meeting));
  1218. Refresh();
  1219. SelectionChanged?.Invoke(this, new CalendarDataEventArgs<Meeting>(null));
  1220. }
  1221. public Assignment CreateAssignment(CalendarTimeSlot slot)
  1222. {
  1223. if (slot == null)
  1224. {
  1225. MessageBox.Show("Please select an employee first!");
  1226. return null;
  1227. }
  1228. var ass = new Assignment();
  1229. ass.Date = slot.Time.Date;
  1230. ass.Booked.Start = AdjustStartTime(slot.Time.TimeOfDay);
  1231. ass.Booked.Duration = TimeIntervalToTimeSpan(TimeInterval);
  1232. ass.Booked.Finish = ass.Booked.Start + ass.Booked.Duration;
  1233. if ((AssignmentType == CalendarAssignmentType.Actual) || ((AssignmentType == CalendarAssignmentType.Automatic) && (ass.Date <= DateTime.Today)))
  1234. {
  1235. ass.Actual.Start = ass.Booked.Start;
  1236. ass.Actual.Duration = ass.Booked.Duration;
  1237. ass.Actual.Finish = ass.Actual.Start + ass.Actual.Duration;
  1238. }
  1239. ass.EmployeeLink.ID = slot.EmployeeID;
  1240. ItemCreated?.Invoke(this, new CalendarDataEventArgs<Assignment>(ass));
  1241. var args = new CalendarHandledEventArgs<Assignment>(ass);
  1242. ItemEditing?.Invoke(this, args);
  1243. if (args.Status == CalendarHandledStatus.Cancel)
  1244. return null;
  1245. if ((args.Status == CalendarHandledStatus.Handled) || CheckGrid(ref ag).EditItems(new[] { ass }))
  1246. {
  1247. UpdateAssignment(ass);
  1248. _copiedmodel = null;
  1249. }
  1250. return ass;
  1251. }
  1252. private void FillAssignment(AssignmentModel model)
  1253. {
  1254. MessageBox.Show("Not Yet Implemented");
  1255. }
  1256. private void EditAssignment(AssignmentModel model)
  1257. {
  1258. if (model == null)
  1259. {
  1260. MessageBox.Show("Please select an entry first!");
  1261. return;
  1262. }
  1263. var grid = CheckGrid(ref ag);
  1264. var ass = new Client<Assignment>().Query(new Filter<Assignment>(x => x.ID).IsEqualTo(model.ID), grid.LoadEditorColumns())
  1265. .ToObjects<Assignment>().FirstOrDefault();
  1266. if (grid.EditItems(new[] { ass }))
  1267. {
  1268. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(ass));
  1269. Refresh();
  1270. }
  1271. }
  1272. private void DeleteAssignment(AssignmentModel model)
  1273. {
  1274. if (model == null)
  1275. {
  1276. MessageBox.Show("Please select an entry first!");
  1277. return;
  1278. }
  1279. if (MessageBox.Show("Are you sure you wish to delete this assignment?", "Confirm Delete", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1280. return;
  1281. var ass = new Assignment { ID = model.ID };
  1282. new Client<Assignment>().Delete(ass, "Assignment Deleted from Scheduler");
  1283. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(ass));
  1284. Refresh();
  1285. SelectionChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(null));
  1286. }
  1287. private AssignmentModel _copiedmodel;
  1288. private void CopyAssignment(AssignmentModel model)
  1289. {
  1290. if (model == null)
  1291. {
  1292. MessageBox.Show("Please select an entry first!");
  1293. return;
  1294. }
  1295. _copiedmodel = model;
  1296. }
  1297. private Assignment PasteAssignment(CalendarTimeSlot slot)
  1298. {
  1299. if (slot == null)
  1300. {
  1301. MessageBox.Show("Please select an employee first!");
  1302. return null;
  1303. }
  1304. var ass = _assignments.FirstOrDefault(a => a.ID == _copiedmodel.ID)?.Row?.ToObject<Assignment>();
  1305. if (ass == null)
  1306. {
  1307. MessageBox.Show("Cannot find copied entry!");
  1308. return null;
  1309. }
  1310. ass.Date = SelectedDate.Date;
  1311. ass.ID = Guid.Empty;
  1312. ass.Number = 0;
  1313. ass.CommitChanges();
  1314. ass.Booked.Start = AdjustStartTime(slot.Time.TimeOfDay);
  1315. ass.Booked.Duration = TimeIntervalToTimeSpan(TimeInterval);
  1316. ass.Booked.Finish = ass.Booked.Start + ass.Booked.Duration;
  1317. if ((AssignmentType == CalendarAssignmentType.Actual) || ((AssignmentType == CalendarAssignmentType.Automatic) && (ass.Date <= DateTime.Today)))
  1318. {
  1319. ass.Actual.Start = ass.Booked.Start;
  1320. ass.Actual.Duration = ass.Booked.Duration;
  1321. ass.Actual.Finish = ass.Actual.Start + ass.Actual.Duration;
  1322. }
  1323. ass.EmployeeLink.ID = slot.EmployeeID;
  1324. new Client<Assignment>().Save(ass, "");
  1325. UpdateAssignment(ass);
  1326. _copiedmodel = null;
  1327. return ass;
  1328. }
  1329. private void Bookings_OnAppointmentTapped(object? sender, AppointmentTappedArgs e)
  1330. {
  1331. //if (e.Appointment is AssignmentModel model)
  1332. if (e.Appointment is AssignmentAppointment appointment)
  1333. {
  1334. ICalendarDataEventArgs args = new CalendarDataEventArgs<Assignment>(
  1335. appointment.Model.Row?.ToObject<Assignment>()
  1336. );
  1337. SelectionChanged?.Invoke(this, args);
  1338. }
  1339. else
  1340. SelectionChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(null));
  1341. }
  1342. private void Calendar_OnSizeChanged(object sender, SizeChangedEventArgs e)
  1343. {
  1344. if (double.IsNaN(this.ActualHeight) || (this.ActualHeight == 0))
  1345. return;
  1346. UpdateZoom();
  1347. }
  1348. private void _settingsButton_OnClick(object sender, RoutedEventArgs e)
  1349. {
  1350. _splitPanel.View = DynamicSplitPanelView.Master;
  1351. }
  1352. private void _splitPanel_OnOnChanged(object sender, DynamicSplitPanelSettings e)
  1353. {
  1354. if (EventSuppressor.IsSet(Suppress.Events))
  1355. return;
  1356. if (e.View == DynamicSplitPanelView.Combined && SettingsVisible != CalendarSettingsVisibility.Visible)
  1357. SetSettingsVisibility(CalendarSettingsVisibility.Visible);
  1358. else if (e.View == DynamicSplitPanelView.Master && SettingsVisible == CalendarSettingsVisibility.Visible)
  1359. SetSettingsVisibility(CalendarSettingsVisibility.Hidden);
  1360. }
  1361. }
  1362. }