Calendar.xaml.cs 56 KB

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