Calendar.xaml.cs 61 KB

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