Calendar.xaml.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  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.AlwaysStartOnToday ? DateTime.Today : 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. AlwaysTodayBox.IsChecked = Properties.AlwaysStartOnToday;
  616. _employees = EmployeeSelector.GetEmployeeData((row, rosters) => new EmployeeResourceModel(row, rosters));
  617. MultiQuery query = new MultiQuery();
  618. query.Add(
  619. new Filter<LeaveRequest>(x=>x.Status).IsNotEqualTo(LeaveRequestStatus.Rejected),
  620. LeaveRequestModel.Columns
  621. );
  622. query.Add(
  623. null,
  624. StandardLeaveModel.Columns
  625. );
  626. query.Query();
  627. _standardleaves = query.Get<StandardLeave>().Rows.Select(row => new StandardLeaveModel(row)).ToArray();
  628. _leaverequests = query.Get<LeaveRequest>().Rows.Select(row => new LeaveRequestModel(row)).ToArray();
  629. var widthtimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
  630. widthtimer.Tick += (o, e) =>
  631. {
  632. if (Bookings.ActualWidth > 0.0F)
  633. {
  634. widthtimer.IsEnabled = false;
  635. ReloadColumns();
  636. }
  637. };
  638. widthtimer.IsEnabled = true;
  639. }
  640. }
  641. public virtual void Shutdown(CancelEventArgs? cancel)
  642. {
  643. }
  644. private bool bFirst = true;
  645. public virtual void Refresh()
  646. {
  647. RefreshData(StartDate, EndDate);
  648. }
  649. private void RefreshData(DateTime startDate, DateTime endDate)
  650. {
  651. if (EventSuppressor.IsSet(Suppress.Refresh))
  652. return;
  653. using (new WaitCursor())
  654. {
  655. if (!bColumnsLoaded)
  656. ReloadColumns();
  657. MultiQuery query = new MultiQuery();
  658. var empids = _employees.Select(x => x.ID).ToArray();
  659. if (BackgroundType != CalendarBackgroundType.Roster)
  660. {
  661. query.Add<TimeSheet>(
  662. new Filter<TimeSheet>(x => x.EmployeeLink.ID).InList(empids)
  663. .And(x => x.Date).IsGreaterThanOrEqualTo(startDate)
  664. .And(x => x.Date).IsLessThanOrEqualTo(endDate)
  665. .And(x=>x.LeaveRequestLink.ID).IsEqualTo(Guid.Empty)
  666. .And(x=>x.StandardLeaveLink.ID).IsEqualTo(Guid.Empty),
  667. TimeSheetModel.Columns
  668. );
  669. }
  670. query.Add<Assignment>(
  671. new Filter<Assignment>(x => x.EmployeeLink.ID).InList(empids)
  672. .And(x => x.Date).IsGreaterThanOrEqualTo(startDate)
  673. .And(x => x.Date).IsLessThanOrEqualTo(endDate),
  674. AssignmentModel.Columns,
  675. new SortOrder<Assignment>(x => x.EmployeeLink.ID).ThenBy(x => x.Date).ThenBy(x => x.Booked.Duration, SortDirection.Descending)
  676. );
  677. query.Query();
  678. _timesheets = (BackgroundType == CalendarBackgroundType.Roster)
  679. ? new TimeSheetModel[] { }
  680. : query.Get<TimeSheet>().Rows.Select(r => new TimeSheetModel(r)).ToArray();
  681. _assignments = query.Get<Assignment>().Rows.Select(r => new AssignmentModel(r)).ToList();
  682. LoadBackground();
  683. var appointments = new CalendarAppointments();
  684. LoadStandardLeaves(appointments);
  685. LoadLeaveRequests(appointments);
  686. LoadAssignments(appointments);
  687. try
  688. {
  689. Bookings.DisplayDate = Bookings.SelectedDate.HasValue ? Bookings.SelectedDate.Value : StartDate;
  690. Bookings.ItemsSource = appointments;
  691. }
  692. catch (Exception e)
  693. {
  694. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  695. }
  696. bFirst = false;
  697. }
  698. }
  699. public EmployeeRosterItem GetRoster(Guid employeeid, DateTime date)
  700. {
  701. var employee = _employees.FirstOrDefault(x => x.ID == employeeid);
  702. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.RosterStart, date);
  703. return roster;
  704. }
  705. public bool GetActiveWindow(Guid employeeid, DateTime date, ref TimeSpan start, ref TimeSpan finish)
  706. {
  707. bool result = false;
  708. foreach (var assignment in _assignments.Where(a => (a.EmployeeID == employeeid) && (a.Date) == date))
  709. {
  710. result = true;
  711. var curstart = AssignmentType switch
  712. {
  713. CalendarAssignmentType.Booked => assignment.BookedStart,
  714. CalendarAssignmentType.Actual => assignment.ActualStart,
  715. _ => Assignment.EffectiveTime(assignment.ActualStart, assignment.BookedStart)
  716. };
  717. var curfinish = AssignmentType switch
  718. {
  719. CalendarAssignmentType.Booked => assignment.BookedFinish,
  720. CalendarAssignmentType.Actual => assignment.ActualFinish,
  721. _ => Assignment.EffectiveTime(
  722. assignment.ActualFinish,
  723. Assignment.EffectiveTime(assignment.ActualStart, assignment.BookedStart)
  724. .Add(assignment.BookedDuration)
  725. )
  726. };
  727. start = start > curstart ? curstart : start;
  728. finish = finish < curfinish ? curfinish : finish;
  729. }
  730. if ((BackgroundType == CalendarBackgroundType.Roster) ||
  731. ((BackgroundType == CalendarBackgroundType.Automatic) && (date >= DateTime.Today)))
  732. {
  733. var employee = _employees.FirstOrDefault(x => x.ID == employeeid);
  734. if (employee != null)
  735. {
  736. var roster = RosterUtils.GetRoster(employee.Roster, employee.RosterStart, date);
  737. if (roster != null)
  738. {
  739. var blocks = roster.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue);
  740. foreach (var block in blocks)
  741. {
  742. start = start > block.Start ? block.Start : start;
  743. finish = finish < block.Finish ? block.Finish : finish;
  744. }
  745. }
  746. }
  747. }
  748. else
  749. {
  750. foreach (var timesheet in _timesheets.Where(t => (t.EmployeeID == employeeid) && (t.Date == date)))
  751. {
  752. result = true;
  753. var curstart = !timesheet.Approved.IsEmpty()
  754. ? timesheet.ApprovedStart
  755. : timesheet.Start;
  756. var curfinish = !timesheet.Approved.IsEmpty()
  757. ? timesheet.ApprovedFinish
  758. : timesheet.Finish;
  759. start = start > curstart ? curstart : start;
  760. finish = finish < curfinish ? curfinish : finish;
  761. }
  762. }
  763. return result;
  764. }
  765. public CoreRow[] GetAssignments(Guid employeeid, DateTime date)
  766. {
  767. return _assignments.Where(a => (a.Row != null) && (a.EmployeeID == employeeid) && (a.Date == date)).Select(x => x.Row!).ToArray();
  768. }
  769. public void UpdateAssignment(Assignment assignment)
  770. {
  771. void UpdateCalendar<TEntity, TModel>(
  772. TEntity entity,
  773. List<TModel> collection,
  774. Action<TModel> refresh
  775. ) where TEntity : Entity where TModel : class, IModel
  776. {
  777. if (Bookings.ItemsSource is CalendarAppointments appointments)
  778. {
  779. var appointment = appointments.FirstOrDefault(x => (Guid)x.Id == entity.ID) as ScheduleAppointment;
  780. if (appointment != null)
  781. {
  782. appointments.Remove(appointment);
  783. var calappt = appointment as ICalendarAppointment<TModel>;
  784. if (calappt != null)
  785. collection.Remove(calappt.Model);
  786. }
  787. var table = new CoreTable();
  788. table.LoadColumns(typeof(TEntity));
  789. var row = table.NewRow();
  790. table.FillRow(row, entity);
  791. var model = (Activator.CreateInstance(typeof(TModel),row) as TModel)!;
  792. collection.Add(model);
  793. refresh(model);
  794. }
  795. }
  796. if (Bookings.ItemsSource is CalendarAppointments appointments)
  797. UpdateCalendar(assignment, _assignments, (model) => LoadAssignment(model,appointments));
  798. }
  799. private void LoadBackground()
  800. {
  801. var regions = new ObservableCollection<SpecialTimeRegion>();
  802. foreach (var resource in Bookings.ResourceCollection)
  803. {
  804. var sEmpID = (((SchedulerResource)resource).Id as string) ?? "";
  805. var empid = Guid.Parse(sEmpID);
  806. var employee = _employees.FirstOrDefault(x => x.ID == empid);
  807. for (var date = StartDate; date < EndDate; date = date.AddDays(1))
  808. {
  809. if ((BackgroundType == CalendarBackgroundType.Roster) ||
  810. ((BackgroundType == CalendarBackgroundType.Automatic) && (date >= DateTime.Today)))
  811. {
  812. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.RosterStart, date);
  813. if (roster != null)
  814. {
  815. var blocks = roster.GetBlocks(date, TimeSpan.FromSeconds(0), TimeSpan.FromDays(1));
  816. foreach (var block in blocks)
  817. {
  818. regions.Add(
  819. new SpecialTimeRegion
  820. {
  821. StartTime = date.Add(block.Start),
  822. EndTime = date.Add(block.Finish.Subtract(TimeSpan.FromSeconds(1))),
  823. ResourceIdCollection = new ObservableCollection<object> { ((SchedulerResource)resource).Id },
  824. Background = new SolidColorBrush(Colors.Yellow) {Opacity = 0.3},
  825. Foreground = new SolidColorBrush(Colors.Black),
  826. Text = ""
  827. }
  828. );
  829. }
  830. }
  831. }
  832. else
  833. {
  834. foreach (var timesheet in _timesheets.Where(t => (t.EmployeeID == empid) && (t.Date == date)))
  835. {
  836. var start = !timesheet.Approved.IsEmpty()
  837. ? timesheet.ApprovedStart
  838. : timesheet.Start;
  839. var finish = !timesheet.Approved.IsEmpty()
  840. ? timesheet.ApprovedFinish
  841. : timesheet.Finish;
  842. regions.Add(
  843. new SpecialTimeRegion
  844. {
  845. StartTime = date.Add(start),
  846. EndTime = date.Add(finish),
  847. ResourceIdCollection = new ObservableCollection<object> { ((SchedulerResource)resource).Id },
  848. Background = new SolidColorBrush(!timesheet.Approved.IsEmpty() ? Colors.LightGreen : Colors.LightSalmon) { Opacity = 0.4 },
  849. Foreground = new SolidColorBrush(Colors.Transparent),
  850. Text = "",
  851. CanMergeAdjacentRegions = false
  852. }
  853. );
  854. }
  855. }
  856. }
  857. }
  858. Bookings.DaysViewSettings.SpecialTimeRegions = regions;
  859. }
  860. private void LoadStandardLeaves(CalendarAppointments appointments)
  861. {
  862. for (var date = StartDate; date < EndDate; date = date.AddDays(1))
  863. {
  864. var leaves = _standardleaves.Where(x =>
  865. (x.From <= date)
  866. && (x.To.Add(x.ToTime) > date)
  867. ).ToArray();
  868. foreach (var leave in leaves)
  869. {
  870. foreach (var resource in Bookings.ResourceCollection)
  871. {
  872. var sEmpID = ((SchedulerResource)resource).Id as string;
  873. var empid = Guid.Parse(sEmpID);
  874. var employee = _employees.FirstOrDefault(x => x.ID == empid);
  875. var start = (date.Date == leave.From.Date) ? leave.FromTime : TimeSpan.FromSeconds(0);
  876. var finish = (date.Date == leave.To.Date) ? leave.ToTime : TimeSpan.FromDays(1).Subtract(TimeSpan.FromSeconds(1));
  877. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.RosterStart, date);
  878. if (roster != null)
  879. {
  880. var blocks = roster.GetBlocks(date, start, finish);
  881. foreach (var block in blocks)
  882. {
  883. var appt = new StandardLeaveAppointment(leave, _ => empid, x => x.Color, block);
  884. appointments.Add(appt);
  885. }
  886. }
  887. }
  888. }
  889. }
  890. }
  891. private void LoadLeaveRequests(CalendarAppointments appointments)
  892. {
  893. for (var date = StartDate; date < EndDate; date = date.AddDays(1))
  894. {
  895. var ids = Bookings.ResourceCollection
  896. .Cast<SchedulerResource>()
  897. .Where(x=>!String.IsNullOrWhiteSpace(x.Id as String))
  898. .Select(x => Guid.Parse(x.Id.ToString() ?? ""));
  899. var leaves = _leaverequests.Where(x =>
  900. (x.From <= date)
  901. && (x.To.Add(x.ToTime) > date)
  902. && ids.Contains(x.EmployeeID)
  903. ).ToArray();
  904. foreach (var leave in leaves)
  905. {
  906. var employee = _employees.FirstOrDefault(x => x.ID == leave.EmployeeID);
  907. var roster = RosterUtils.GetRoster(employee?.Roster, employee?.RosterStart, date);
  908. if (roster != null)
  909. {
  910. var start = (date.Date == leave.From.Date) ? leave.FromTime : TimeSpan.FromSeconds(0);
  911. var finish = (date.Date == leave.To.Date) ? leave.ToTime : TimeSpan.FromDays(1).Subtract(TimeSpan.FromSeconds(1));
  912. var blocks = roster.GetBlocks(date, start, finish);
  913. foreach (var block in blocks)
  914. {
  915. var appt = new LeaveRequestAppointment(leave, x=>x.EmployeeID, x => x.Color, block);
  916. appointments.Add(appt);
  917. }
  918. }
  919. }
  920. }
  921. }
  922. private void LoadAssignment(AssignmentModel assignment, CalendarAppointments appointments)
  923. {
  924. var model = new AssignmentAppointment(assignment, x => x.EmployeeID, x => x.Color, AssignmentType);
  925. appointments.Add(model);
  926. }
  927. private void LoadAssignments(CalendarAppointments appointments)
  928. {
  929. foreach (var assignment in _assignments)
  930. LoadAssignment(assignment, appointments);
  931. }
  932. public DataModel DataModel(Selection selection)
  933. {
  934. var ids = _assignments.Select(x => x.ID).ToArray();
  935. return new AutoDataModel<Assignment>(new Filter<Assignment>(x => x.ID).InList(ids));
  936. }
  937. // private void ResizeIntervals(double height)
  938. // {
  939. // if (Bookings.FindVisualChildren<ScrollPanel>().Any())
  940. // {
  941. //
  942. // if (height > 95 && Bookings.DaysViewSettings.EndHour - Bookings.DaysViewSettings.StartHour > 0)
  943. // {
  944. // double scrollheight = _employees.Length * 75 > Bookings.ActualWidth ? 15.0F : 0.0F;
  945. // var header = _employees.Length > 1 ? 93.0F + scrollheight : 50.0F;
  946. // Bookings.DaysViewSettings.TimeIntervalSize =
  947. // (height - header) / ((Bookings.DaysViewSettings.EndHour - Bookings.DaysViewSettings.StartHour) * 2.0F);
  948. // }
  949. // }
  950. //
  951. // // var scrollers = Bookings.FindVisualChildren<ScrollViewer>().Where(x => string.Equals(x.Name, "PART_TimeSlotScrollViewer")).ToArray();
  952. // // foreach (var scroll in scrollers)
  953. // // scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
  954. //
  955. // }
  956. private void Schedule_SizeChanged(object sender, SizeChangedEventArgs e)
  957. {
  958. //ResizeIntervals(e.NewSize.Height);
  959. ResizeColumns(e.NewSize.Width);
  960. }
  961. private void ResizeColumns(double width)
  962. {
  963. if (double.IsNaN(width) || !Bookings.FindVisualChildren<ScrollPanel>().Any())
  964. return;
  965. var maxcount = (int)width / 75;
  966. Bookings.DaysViewSettings.VisibleResourceCount = Math.Min(maxcount,
  967. _employees.Length * (Bookings.ViewType == SchedulerViewType.Day ? 1 : Bookings.ViewType == SchedulerViewType.WorkWeek ? 5 : 7));
  968. if (Bookings.ResourceCollection is ObservableCollection<SchedulerResource> resources)
  969. {
  970. var colwidth = GetResourceColumnWidth();
  971. foreach (var emp in _employees)
  972. {
  973. var resource = resources.FirstOrDefault(x => String.Equals(x.Id?.ToString(), emp.ID.ToString()));
  974. if (resource != null)
  975. {
  976. var comps = emp.Name.Split(' ');
  977. var display = emp.Name;
  978. if (colwidth < 75)
  979. display = string.Format("{0}{1}", comps[0].Length > 0 ? comps[0][..1] : "",
  980. comps.Length > 1 ? comps.Skip(1).First()[..1].ToUpper() : "");
  981. else if (colwidth < 150)
  982. display = string.Format("{0} {1}", comps.First(),
  983. comps.Length > 1 ? comps.Skip(1).First()[..1].ToUpper() : "");
  984. resource.Name = display;
  985. }
  986. }
  987. }
  988. }
  989. private T CheckGrid<T>(ref T grid) where T : new()
  990. {
  991. if (grid == null)
  992. grid = new T();
  993. return grid;
  994. }
  995. private void ReloadColumns()
  996. {
  997. ResizeColumns(Bookings.ActualWidth);
  998. var colwidth = GetResourceColumnWidth();
  999. var resources = new List<SchedulerResource>();
  1000. foreach (var emp in _employees)
  1001. {
  1002. var comps = emp.Name.Split(' ');
  1003. var display = emp.Name;
  1004. if (colwidth < 75)
  1005. display = CoreUtils.Codify(emp.Name);
  1006. else if (colwidth < 150)
  1007. display = string.Format("{0} {1}", comps.Length > 0 ? comps.First() : "", comps.Length > 1 ? comps.Skip(1).First().Substring(0, 1).ToUpper() : "");
  1008. resources.Add(new SchedulerResource { Name = display, Id = emp.ID.ToString() });
  1009. }
  1010. var sorted = new ObservableCollection<SchedulerResource>();
  1011. foreach (var resource in resources.OrderBy(x => x.Name))
  1012. sorted.Add(resource);
  1013. try
  1014. {
  1015. Bookings.DaysViewSettings.ResourceHeaderSize = sorted.Count <= 1 ? 0 : 45;
  1016. }
  1017. catch (Exception e)
  1018. {
  1019. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1020. }
  1021. //ResizeIntervals(Bookings.ActualHeight);
  1022. try
  1023. {
  1024. Bookings.ResourceCollection = sorted;
  1025. }
  1026. catch (Exception e)
  1027. {
  1028. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1029. }
  1030. bColumnsLoaded = true;
  1031. }
  1032. // private SchedulerResource GetCurrentResource()
  1033. // {
  1034. // var p = Mouse.GetPosition(Bookings);
  1035. // var panels = Bookings.FindVisualChildren<ScrollViewer>().FirstOrDefault(x => string.Equals(x.Name, "PART_ViewHeaderScrollViewer"));
  1036. // var resource = (int)((p.X + panels.HorizontalOffset - (Bookings.DaysViewSettings.TimeRulerSize + 20F)) / GetResourceColumnWidth());
  1037. // return (Bookings.ResourceCollection as Collection<SchedulerResource>)[resource];
  1038. // }
  1039. //
  1040. // private DateTime GetCurrentTime()
  1041. // {
  1042. // var p = Mouse.GetPosition(Bookings);
  1043. // var hours = (p.Y - (_employees.Length > 1 ? 95.0F : 50.0F)) / (Bookings.DaysViewSettings.TimeIntervalSize * 2F) +
  1044. // Bookings.DaysViewSettings.StartHour;
  1045. // var result = Bookings.SelectedDate.Value + TimeSpan.FromHours(hours);
  1046. // return result;
  1047. // }
  1048. private double GetResourceColumnWidth()
  1049. {
  1050. var colcount = Math.Max(1, _employees.Length);
  1051. colcount = colcount * (Bookings.ViewType == SchedulerViewType.Day ? 1 : Bookings.ViewType == SchedulerViewType.Day ? 5 : 7);
  1052. var colwidth = Bookings.ActualWidth / colcount;
  1053. var minwidth = (Bookings.ActualWidth - (Bookings.DaysViewSettings.TimeRulerSize + 20F)) / Bookings.DaysViewSettings.VisibleResourceCount;
  1054. return Math.Max(minwidth, colwidth);
  1055. }
  1056. private void Schedule_AppointmentEditorOpening(object sender, AppointmentEditorOpeningEventArgs e)
  1057. {
  1058. e.Cancel = true;
  1059. }
  1060. //private Dictionary<CalendarMenuName, MenuItem> _menuitems = new Dictionary<CalendarMenuName, MenuItem>();
  1061. MenuItem CreateMenu<T>(ItemsControl menu, CalendarMenuName name, string header, Action<T?>? action = null, T? data = null) where T : class
  1062. {
  1063. var item = new MenuItem();
  1064. item.Name = name.ToString();
  1065. item.Header = header;
  1066. if (action != null)
  1067. item.Click += (o,args) => action(data);
  1068. item.IsEnabled = data != null;
  1069. menu.Items.Add(item);
  1070. //_menuitems[name] = item;
  1071. return item;
  1072. }
  1073. private void Bookings_OnSchedulerContextMenuOpening(object? sender, SchedulerContextMenuOpeningEventArgs e)
  1074. {
  1075. e.ContextMenu.Items.Clear();
  1076. if ((e.MenuType == SchedulerContextMenuType.Appointment) && (e.MenuInfo.Appointment is AssignmentAppointment appointment))
  1077. {
  1078. if (appointment.Model.MeetingID != Guid.Empty)
  1079. CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Edit Meeting", EditMeeting, appointment.Model);
  1080. else
  1081. {
  1082. CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Edit Assignment", EditAssignment, appointment.Model);
  1083. e.ContextMenu.Items.Add(new Separator());
  1084. CreateMenu(e.ContextMenu, CalendarMenuName.Copy, "Copy Assignment", CopyAssignment, appointment.Model);
  1085. e.ContextMenu.Items.Add(new Separator());
  1086. CreateMenu(e.ContextMenu, CalendarMenuName.Fill, "Fill Available Time", FillAssignment, appointment.Model);
  1087. }
  1088. e.ContextMenu.Items.Add(new Separator());
  1089. CreateDigitalFormsMenu(e.ContextMenu, appointment);
  1090. if (appointment.Model.MeetingID != Guid.Empty)
  1091. CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Delete Meeting", DeleteMeeting, appointment.Model);
  1092. else
  1093. CreateMenu(e.ContextMenu, CalendarMenuName.Delete, "Delete Assignment", DeleteAssignment, appointment.Model);
  1094. e.ContextMenu.Items.Add(new Separator());
  1095. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomIn, "Zoom In", (data) => ZoomIn(), null);
  1096. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomOut, "Zoom Out", (data) => ZoomOut(), null);
  1097. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ResetZoom, "Reset Zoom", (data) => ResetZoom(), null);
  1098. CustomiseContextMenu?.Invoke(e.ContextMenu, new CalendarDataEventArgs<object>((e.MenuInfo.Appointment as ICalendarAppointment)?.Model));
  1099. }
  1100. else if (e.MenuType == SchedulerContextMenuType.TimeSlotCell)
  1101. {
  1102. if (Guid.TryParse(e.MenuInfo.Resource.Id?.ToString(), out Guid employeeid))
  1103. {
  1104. var slot = new CalendarTimeSlot(employeeid, e.MenuInfo.DateTime.Value);
  1105. var createmenu = new MenuItem() { Header = "Create.." };
  1106. CreateMenu(createmenu, CalendarMenuName.CreateNew, "New Assignment", (data) => CreateAssignment(slot), slot);
  1107. CreateMenu(createmenu, CalendarMenuName.CreateNew, "New Meeting", (data) => CreateMeeting(slot), slot);
  1108. e.ContextMenu.Items.Add(createmenu);
  1109. if (_copiedmodel != null)
  1110. {
  1111. e.ContextMenu.Items.Add(new Separator());
  1112. CreateMenu(e.ContextMenu, CalendarMenuName.Paste, "Paste Assignment", (data) => PasteAssignment(slot), slot);
  1113. }
  1114. e.ContextMenu.Items.Add(new Separator());
  1115. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomIn, "Zoom In", (data) => ZoomIn(), slot);
  1116. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ZoomOut, "Zoom Out", (data) => ZoomOut(), slot);
  1117. CreateMenu<object>(e.ContextMenu, CalendarMenuName.ResetZoom, "Reset Zoom", (data) => ResetZoom(), slot);
  1118. CustomiseContextMenu?.Invoke(e.ContextMenu, new CalendarDataEventArgs<CalendarTimeSlot>(slot));
  1119. }
  1120. }
  1121. }
  1122. private static void CreateDigitalFormsMenu(ContextMenu menu, AssignmentAppointment appointment)
  1123. {
  1124. var digitalForms = new MenuItem { Header = "Digital Forms" };
  1125. DynamicGridUtils.PopulateFormMenu<AssignmentForm, Assignment, AssignmentLink>(
  1126. digitalForms,
  1127. appointment.Model.ID,
  1128. () => new Client<Assignment>().Load(new Filter<Assignment>(x => x.ID).IsEqualTo(appointment.Model.ID)).First(),
  1129. false);
  1130. menu.Items.Add(digitalForms);
  1131. menu.Items.Add(new Separator());
  1132. }
  1133. public void CreateMeeting(CalendarTimeSlot slot)
  1134. {
  1135. if (slot == null)
  1136. {
  1137. MessageBox.Show("Please select an employee first!");
  1138. return;
  1139. }
  1140. var meeting = new Meeting();
  1141. meeting.Date = slot.Time.Date;
  1142. meeting.Time.Start = AdjustStartTime(slot.Time.TimeOfDay);
  1143. meeting.Time.Duration = TimeIntervalToTimeSpan(TimeInterval);
  1144. meeting.Time.Finish = meeting.Time.Start + meeting.Time.Duration;
  1145. ItemCreated?.Invoke(this, new CalendarDataEventArgs<Meeting>(meeting));
  1146. var args = new CalendarHandledEventArgs<Meeting>(meeting);
  1147. ItemEditing?.Invoke(this, args);
  1148. if (args.Status == CalendarHandledStatus.Cancel)
  1149. return;
  1150. if (args.Status == CalendarHandledStatus.Handled)
  1151. {
  1152. Refresh();
  1153. return;
  1154. }
  1155. CheckGrid(ref mg);
  1156. var items = new[] { meeting };
  1157. bool bOK = mg.EditItems(
  1158. items,
  1159. (type) =>
  1160. {
  1161. if (type == typeof(Assignment))
  1162. return LoadMeetingEmployees(meeting, slot.EmployeeID);
  1163. else if (type == typeof(MeetingItem))
  1164. return LoadMeetingItems();
  1165. return null;
  1166. },
  1167. true
  1168. );
  1169. if (bOK)
  1170. Refresh();
  1171. }
  1172. private CoreTable LoadMeetingEmployees(Meeting meeting, Guid employeeid)
  1173. {
  1174. var result = new CoreTable();
  1175. result.LoadColumns(typeof(Assignment));
  1176. var assignment = new Assignment();
  1177. assignment.EmployeeLink.ID = employeeid;
  1178. var emp = new Client<Employee>().Load(new Filter<Employee>(x => x.ID).IsEqualTo(employeeid)).FirstOrDefault();
  1179. if (emp != null)
  1180. assignment.EmployeeLink.Synchronise(emp);
  1181. result.LoadRows(new[] { assignment });
  1182. return result;
  1183. }
  1184. private CoreTable LoadMeetingItems()
  1185. {
  1186. var result = new CoreTable();
  1187. result.LoadColumns(typeof(MeetingItem));
  1188. return result;
  1189. }
  1190. private void EditMeeting(AssignmentModel model)
  1191. {
  1192. if (model == null)
  1193. {
  1194. MessageBox.Show("Please select an entry first!");
  1195. return;
  1196. }
  1197. CheckGrid(ref mg);
  1198. var meeting = new Client<Meeting>().Query(
  1199. new Filter<Meeting>(x => x.ID).IsEqualTo(model.MeetingID),
  1200. mg.LoadEditorColumns()
  1201. ).Rows.FirstOrDefault()?.ToObject<Meeting>();
  1202. if ((meeting != null) && (mg.EditItems(new[] { meeting })))
  1203. {
  1204. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Meeting>(meeting));
  1205. Refresh();
  1206. }
  1207. }
  1208. private void DeleteMeeting(AssignmentModel model)
  1209. {
  1210. if (model == null)
  1211. {
  1212. MessageBox.Show("Please select an entry first!");
  1213. return;
  1214. }
  1215. if (MessageBox.Show("Are you sure you wish to delete this meeting?", "Confirm Delete", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1216. return;
  1217. var meeting = new Meeting { ID = model.MeetingID };
  1218. new Client<Meeting>().Delete(meeting, "Meeting Deleted from Scheduler");
  1219. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Meeting>(meeting));
  1220. Refresh();
  1221. SelectionChanged?.Invoke(this, new CalendarDataEventArgs<Meeting>(null));
  1222. }
  1223. public Assignment CreateAssignment(CalendarTimeSlot slot)
  1224. {
  1225. if (slot == null)
  1226. {
  1227. MessageBox.Show("Please select an employee first!");
  1228. return null;
  1229. }
  1230. var ass = new Assignment();
  1231. ass.Date = slot.Time.Date;
  1232. ass.Booked.Start = AdjustStartTime(slot.Time.TimeOfDay);
  1233. ass.Booked.Duration = TimeIntervalToTimeSpan(TimeInterval);
  1234. ass.Booked.Finish = ass.Booked.Start + ass.Booked.Duration;
  1235. if ((AssignmentType == CalendarAssignmentType.Actual) || ((AssignmentType == CalendarAssignmentType.Automatic) && (ass.Date <= DateTime.Today)))
  1236. {
  1237. ass.Actual.Start = ass.Booked.Start;
  1238. ass.Actual.Duration = ass.Booked.Duration;
  1239. ass.Actual.Finish = ass.Actual.Start + ass.Actual.Duration;
  1240. }
  1241. ass.EmployeeLink.ID = slot.EmployeeID;
  1242. ItemCreated?.Invoke(this, new CalendarDataEventArgs<Assignment>(ass));
  1243. var args = new CalendarHandledEventArgs<Assignment>(ass);
  1244. ItemEditing?.Invoke(this, args);
  1245. if (args.Status == CalendarHandledStatus.Cancel)
  1246. return null;
  1247. if ((args.Status == CalendarHandledStatus.Handled) || CheckGrid(ref ag).EditItems(new[] { ass }))
  1248. {
  1249. UpdateAssignment(ass);
  1250. _copiedmodel = null;
  1251. }
  1252. return ass;
  1253. }
  1254. private void FillAssignment(AssignmentModel model)
  1255. {
  1256. MessageBox.Show("Not Yet Implemented");
  1257. }
  1258. private void EditAssignment(AssignmentModel model)
  1259. {
  1260. if (model == null)
  1261. {
  1262. MessageBox.Show("Please select an entry first!");
  1263. return;
  1264. }
  1265. var grid = CheckGrid(ref ag);
  1266. var ass = new Client<Assignment>().Query(new Filter<Assignment>(x => x.ID).IsEqualTo(model.ID), grid.LoadEditorColumns())
  1267. .ToObjects<Assignment>().FirstOrDefault();
  1268. if (grid.EditItems(new[] { ass }))
  1269. {
  1270. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(ass));
  1271. Refresh();
  1272. }
  1273. }
  1274. private void DeleteAssignment(AssignmentModel model)
  1275. {
  1276. if (model == null)
  1277. {
  1278. MessageBox.Show("Please select an entry first!");
  1279. return;
  1280. }
  1281. if (MessageBox.Show("Are you sure you wish to delete this assignment?", "Confirm Delete", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  1282. return;
  1283. var ass = new Assignment { ID = model.ID };
  1284. new Client<Assignment>().Delete(ass, "Assignment Deleted from Scheduler");
  1285. ItemChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(ass));
  1286. Refresh();
  1287. SelectionChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(null));
  1288. }
  1289. private AssignmentModel _copiedmodel;
  1290. private void CopyAssignment(AssignmentModel model)
  1291. {
  1292. if (model == null)
  1293. {
  1294. MessageBox.Show("Please select an entry first!");
  1295. return;
  1296. }
  1297. _copiedmodel = model;
  1298. }
  1299. private Assignment PasteAssignment(CalendarTimeSlot slot)
  1300. {
  1301. if (slot == null)
  1302. {
  1303. MessageBox.Show("Please select an employee first!");
  1304. return null;
  1305. }
  1306. var ass = _assignments.FirstOrDefault(a => a.ID == _copiedmodel.ID)?.Row?.ToObject<Assignment>();
  1307. if (ass == null)
  1308. {
  1309. MessageBox.Show("Cannot find copied entry!");
  1310. return null;
  1311. }
  1312. ass.Date = SelectedDate.Date;
  1313. ass.ID = Guid.Empty;
  1314. ass.Number = 0;
  1315. ass.CommitChanges();
  1316. ass.Booked.Start = AdjustStartTime(slot.Time.TimeOfDay);
  1317. ass.Booked.Duration = TimeIntervalToTimeSpan(TimeInterval);
  1318. ass.Booked.Finish = ass.Booked.Start + ass.Booked.Duration;
  1319. if ((AssignmentType == CalendarAssignmentType.Actual) || ((AssignmentType == CalendarAssignmentType.Automatic) && (ass.Date <= DateTime.Today)))
  1320. {
  1321. ass.Actual.Start = ass.Booked.Start;
  1322. ass.Actual.Duration = ass.Booked.Duration;
  1323. ass.Actual.Finish = ass.Actual.Start + ass.Actual.Duration;
  1324. }
  1325. ass.EmployeeLink.ID = slot.EmployeeID;
  1326. new Client<Assignment>().Save(ass, "");
  1327. UpdateAssignment(ass);
  1328. _copiedmodel = null;
  1329. return ass;
  1330. }
  1331. private void Bookings_OnAppointmentTapped(object? sender, AppointmentTappedArgs e)
  1332. {
  1333. //if (e.Appointment is AssignmentModel model)
  1334. if (e.Appointment is AssignmentAppointment appointment)
  1335. {
  1336. ICalendarDataEventArgs args = new CalendarDataEventArgs<Assignment>(
  1337. appointment.Model.Row?.ToObject<Assignment>()
  1338. );
  1339. SelectionChanged?.Invoke(this, args);
  1340. }
  1341. else
  1342. SelectionChanged?.Invoke(this, new CalendarDataEventArgs<Assignment>(null));
  1343. }
  1344. private void Calendar_OnSizeChanged(object sender, SizeChangedEventArgs e)
  1345. {
  1346. if (double.IsNaN(this.ActualHeight) || (this.ActualHeight == 0))
  1347. return;
  1348. UpdateZoom();
  1349. }
  1350. private void _settingsButton_OnClick(object sender, RoutedEventArgs e)
  1351. {
  1352. _splitPanel.View = DynamicSplitPanelView.Master;
  1353. }
  1354. private void _splitPanel_OnOnChanged(object sender, DynamicSplitPanelSettings e)
  1355. {
  1356. if (EventSuppressor.IsSet(Suppress.Events))
  1357. return;
  1358. if (e.View == DynamicSplitPanelView.Combined && SettingsVisible != CalendarSettingsVisibility.Visible)
  1359. SetSettingsVisibility(CalendarSettingsVisibility.Visible);
  1360. else if (e.View == DynamicSplitPanelView.Master && SettingsVisible == CalendarSettingsVisibility.Visible)
  1361. SetSettingsVisibility(CalendarSettingsVisibility.Hidden);
  1362. }
  1363. private void Bookings_OnQueryAppointments(object? sender, QueryAppointmentsEventArgs e)
  1364. {
  1365. if (bFirst)
  1366. return;
  1367. SelectedDate = e.VisibleDateRange.StartDate.Date;
  1368. }
  1369. private void AlwaysTodayBox_Checked(object sender, RoutedEventArgs e)
  1370. {
  1371. if (EventSuppressor.IsSet(Suppress.Events)) return;
  1372. Properties.AlwaysStartOnToday = AlwaysTodayBox.IsChecked == true;
  1373. SaveSettings?.Invoke(this, Properties);
  1374. }
  1375. }
  1376. }