LeaveCalendar.xaml.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Diagnostics;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using System.Windows.Data;
  12. using System.Windows.Input;
  13. using System.Windows.Media;
  14. using Comal.Classes;
  15. using InABox.Clients;
  16. using InABox.Configuration;
  17. using InABox.Core;
  18. using InABox.DynamicGrid;
  19. using InABox.WPF;
  20. using Microsoft.Win32;
  21. using PRS.Shared;
  22. using PRSDesktop.Grids;
  23. using Syncfusion.UI.Xaml.Grid;
  24. using Syncfusion.UI.Xaml.Grid.Converter;
  25. using Syncfusion.UI.Xaml.Grid.Helpers;
  26. using Syncfusion.Windows.Tools.Controls;
  27. using Syncfusion.XlsIO;
  28. using Activity = Comal.Classes.Activity;
  29. using SelectionChangedEventArgs = System.Windows.Controls.SelectionChangedEventArgs;
  30. namespace PRSDesktop
  31. {
  32. public class LeaveValue
  33. {
  34. public LeaveValue(Guid id, Guid employee, DateTime date, Guid activity, LeaveRequestStatus status, bool standard)
  35. {
  36. ID = id;
  37. Employee = employee;
  38. Date = date;
  39. Activity = activity;
  40. Status = status;
  41. Standard = standard;
  42. }
  43. public Guid ID { get; set; }
  44. public Guid Employee { get; set; }
  45. public DateTime Date { get; set; }
  46. public Guid Activity { get; set; }
  47. public LeaveRequestStatus Status { get; set; }
  48. public bool Standard { get; set; }
  49. }
  50. public class LeaveBackgroundConverter : IValueConverter
  51. {
  52. public Dictionary<Guid, Color>? Colors { get; set; }
  53. // Guid - EmployeeID
  54. // DateTime - Employee Start Date
  55. // DateTime - Employee Finish Date
  56. // EmployeeRoster[] Roster Data
  57. // DateTime - Roster Start
  58. public List<Tuple<Guid, DateTime, DateTime, EmployeeRosterItem[], DateTime>> Rosters { get; set; }
  59. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  60. {
  61. if(value is not LeaveValue val)
  62. return DependencyProperty.UnsetValue;
  63. if (val.ID == Guid.Empty)
  64. {
  65. var tuple = Rosters?.FirstOrDefault(x => x.Item1 == val.Employee);
  66. if (tuple == null)
  67. return new SolidColorBrush(System.Windows.Media.Colors.Red) { Opacity = 0.8 };
  68. if ( (!tuple.Item2.IsEmpty() && (tuple.Item2 > val.Date)) || (!tuple.Item3.IsEmpty() && (tuple.Item3 < val.Date)))
  69. return new SolidColorBrush(System.Windows.Media.Colors.LightGray) { Opacity = 0.8 };
  70. var roster = RosterUtils.GetRoster(tuple?.Item4, tuple?.Item5, val.Date);
  71. return (roster?.Enabled == true)
  72. ? roster?.Duration < 5.0F
  73. ? new System.Windows.Media.LinearGradientBrush(
  74. System.Windows.Media.Colors.LightYellow,
  75. System.Windows.Media.Colors.LightGray,
  76. 90.0F
  77. ) { Opacity = 0.8 }
  78. : new SolidColorBrush(System.Windows.Media.Colors.LightYellow) { Opacity = 0.8 }
  79. : new SolidColorBrush(System.Windows.Media.Colors.LightGray) { Opacity = 0.8 };
  80. }
  81. else
  82. {
  83. if (val.Status != LeaveRequestStatus.Approved)
  84. return new SolidColorBrush(System.Windows.Media.Colors.DimGray) { Opacity = 0.8 };
  85. if (Colors != null)
  86. if (Colors.ContainsKey(val.Activity))
  87. return new SolidColorBrush(Colors[val.Activity]) { Opacity = 0.5 };
  88. }
  89. return DependencyProperty.UnsetValue;
  90. }
  91. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  92. {
  93. throw new NotImplementedException();
  94. }
  95. }
  96. public class LeaveForegroundConverter : IValueConverter
  97. {
  98. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  99. {
  100. if (value is LeaveValue val
  101. && val.ID != Guid.Empty
  102. && val.Status != LeaveRequestStatus.Approved)
  103. {
  104. return new SolidColorBrush(Colors.LightGray);
  105. }
  106. return DependencyProperty.UnsetValue;
  107. }
  108. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  109. {
  110. throw new NotImplementedException();
  111. }
  112. }
  113. public class LeaveFontStyleConverter : IValueConverter
  114. {
  115. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  116. {
  117. if (value is LeaveValue val
  118. && val.ID != Guid.Empty
  119. && val.Status != LeaveRequestStatus.Approved)
  120. {
  121. return FontStyles.Italic;
  122. }
  123. return DependencyProperty.UnsetValue;
  124. }
  125. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  126. {
  127. throw new NotImplementedException();
  128. }
  129. }
  130. public class LeaveFontWeightConverter : IValueConverter
  131. {
  132. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  133. {
  134. return FontWeights.Bold;
  135. }
  136. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  137. {
  138. throw new NotImplementedException();
  139. }
  140. }
  141. public class LeaveContentConverter : IValueConverter
  142. {
  143. public Dictionary<Guid, string>? Abbreviations { get; set; }
  144. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  145. {
  146. if (value is not LeaveValue val)
  147. return DependencyProperty.UnsetValue;
  148. return Abbreviations?.ContainsKey(val.Activity) == true ? Abbreviations[val.Activity] : DependencyProperty.UnsetValue;
  149. }
  150. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  151. {
  152. throw new NotImplementedException();
  153. }
  154. }
  155. /// <summary>
  156. /// Interaction logic for LeaveCalendar.xaml
  157. /// </summary>
  158. public partial class LeaveCalendar : UserControl
  159. {
  160. private readonly CoreTable _activities;
  161. private readonly Dictionary<Guid, string> _activityCodes = new();
  162. private readonly Dictionary<Guid, Color> _activityColors = new();
  163. private readonly Dictionary<Guid, string> _employees = new();
  164. private readonly List<Tuple<Guid, DateTime, DateTime, EmployeeRosterItem[], DateTime>> _rosters = new();
  165. private readonly CoreTable _employeeteams;
  166. private LeaveSettings _settings;
  167. private readonly Dictionary<Guid, string> _teams = new();
  168. private bool bReady;
  169. private LeaveRequestGrid? lg;
  170. private StandardLeaveGrid? sg;
  171. public LeaveCalendar()
  172. {
  173. InitializeComponent();
  174. //dataGrid.ScrollMode = ScrollMode.Async;
  175. LoadSettings();
  176. StartDate.DateTime = DateTime.Today;
  177. EndDate.DateTime = DateTime.Today.AddYears(1);
  178. var setups = new MultiQuery();
  179. setups.Add<EmployeeTeam>(null, null, new SortOrder<EmployeeTeam>(x => x.TeamLink.Code).ThenBy(x => x.EmployeeLink.Name));
  180. setups.Add<Activity>(new Filter<Activity>(x => x.IsLeave).IsEqualTo(true));
  181. setups.Query();
  182. _employeeteams = setups.Get<EmployeeTeam>();
  183. _activities = setups.Get<Activity>();
  184. _teams = _employeeteams.ToDictionary<EmployeeTeam, Guid, string>(c => c.TeamLink.ID, c => c.TeamLink.Name);
  185. if (_teams.ContainsKey(Guid.Empty))
  186. _teams.Remove(Guid.Empty);
  187. var teams = _employeeteams.ToDictionary<EmployeeTeam, Guid, string>(c => c.TeamLink.ID, c => c.TeamLink.Name);
  188. teams[CoreUtils.FullGuid] = "Multiple Teams";
  189. Teams.ItemsSource = teams;
  190. Teams.SelectedValue = _settings.GroupID;
  191. ChangeSelectedTeams(_settings.GroupID);
  192. SelectedTeams.ItemsSource = _teams;
  193. foreach (KeyValuePair<Guid, string> pair in SelectedTeams.Items)
  194. if (_settings.SelectedGroups.Contains(pair.Key))
  195. SelectedTeams.SelectedItems.Add(pair);
  196. LoadEmployees(false);
  197. foreach (var row in _activities.Rows)
  198. {
  199. var id = row.Get<Activity, Guid>(c => c.ID);
  200. var color = row.Get<Activity, string>(c => c.Color);
  201. if (!string.IsNullOrWhiteSpace(color))
  202. _activityColors[id] = (Color)ColorConverter.ConvertFromString(color);
  203. var code = Codify(row.Get<Activity, string>(c => c.Description));
  204. _activityCodes[id] = Codify(code);
  205. }
  206. var rosterstarts = _employeeteams.ToDictionary<EmployeeTeam, Guid, DateTime>(x => x.EmployeeLink.ID, x => x.EmployeeLink.RosterStart);
  207. var startdates = _employeeteams.ToDictionary<EmployeeTeam, Guid, DateTime>(x => x.EmployeeLink.ID, x => x.EmployeeLink.StartDate);
  208. var finishdates = _employeeteams.ToDictionary<EmployeeTeam, Guid, DateTime>(x => x.EmployeeLink.ID, x => x.EmployeeLink.FinishDate);
  209. var rosters = _employeeteams.ToDictionary<EmployeeTeam, Guid, String>(x => x.EmployeeLink.ID, x => x.EmployeeLink.Roster);
  210. foreach (var empid in startdates.Keys)
  211. {
  212. var startdate = startdates[empid];
  213. var finishdate = finishdates[empid];
  214. var roster = !String.IsNullOrWhiteSpace(rosters[empid])
  215. ? Serialization.Deserialize<List<EmployeeRosterItem>>(rosters[empid]).ToArray()
  216. : null;
  217. var rosterstart = rosterstarts[empid];
  218. _rosters.Add(new Tuple<Guid, DateTime, DateTime, EmployeeRosterItem[], DateTime>(empid, startdate, finishdate, roster, rosterstart));
  219. }
  220. bReady = true;
  221. }
  222. private static string Codify(string name)
  223. {
  224. if (string.IsNullOrWhiteSpace(name))
  225. return "??";
  226. var result = "";
  227. var comps = name.ToUpper().Split(' ');
  228. foreach (var comp in comps)
  229. if (comp.Any())
  230. result += comp.First();
  231. return string.IsNullOrWhiteSpace(result) ? "??" : result;
  232. }
  233. [MemberNotNull(nameof(_settings))]
  234. private void LoadSettings()
  235. {
  236. _settings = new UserConfiguration<LeaveSettings>().Load();
  237. if (!_settings.SelectedGroups.Any() && _settings.GroupID != Guid.Empty)
  238. _settings.SelectedGroups.Add(_settings.GroupID);
  239. if (_settings.ListSize == 0.0F)
  240. _settings.ListSize = 200.0F;
  241. }
  242. private void SaveSettings()
  243. {
  244. if (!bReady)
  245. return;
  246. try
  247. {
  248. _settings.GroupID = Teams.SelectedValue != null ? (Guid)Teams.SelectedValue : Guid.Empty;
  249. _settings.SelectedGroups.Clear();
  250. foreach (var sel in SelectedTeams.SelectedItems)
  251. {
  252. var grp = (KeyValuePair<Guid, string>)sel;
  253. _settings.SelectedGroups.Add(grp.Key);
  254. }
  255. _settings.SelectedEmployees.Clear();
  256. foreach (var sel in SelectedEmployees.SelectedItems)
  257. {
  258. var grp = (KeyValuePair<Guid, string>)sel;
  259. _settings.SelectedEmployees.Add(grp.Key);
  260. }
  261. if (EmployeeGrid.RowDefinitions[1].ActualHeight != 0.0F)
  262. _settings.ListSize = EmployeeGrid.RowDefinitions[1].ActualHeight;
  263. }
  264. catch (Exception e)
  265. {
  266. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  267. }
  268. Task.Run(() => { new UserConfiguration<LeaveSettings>().Save(_settings); });
  269. }
  270. public void Refresh()
  271. {
  272. if (!bReady)
  273. return;
  274. using (new WaitCursor())
  275. {
  276. _employees.Clear();
  277. var crosstab = new List<LeaveValue>();
  278. MultiQuery query = new MultiQuery();
  279. var empfilter = new Filter<LeaveRequest>(x => x.EmployeeLink.ID).IsEqualTo(CoreUtils.FullGuid);
  280. foreach (var sel in SelectedEmployees.Items)
  281. {
  282. var emp = (KeyValuePair<Guid, string>)sel;
  283. if (SelectedEmployees.SelectedItems.Contains(emp))
  284. {
  285. empfilter = empfilter.Or(x => x.EmployeeLink.ID).IsEqualTo(emp.Key);
  286. _employees[emp.Key] = emp.Value;
  287. }
  288. }
  289. var start = StartDate.DateTime ?? DateTime.Today;
  290. var end = EndDate.DateTime ?? DateTime.Today.AddYears(1);
  291. var leavefilter = new Filter<LeaveRequest>(x => x.To).IsGreaterThanOrEqualTo(start)
  292. .And(x => x.From).IsLessThanOrEqualTo(end)
  293. .And(x => x.Status).IsNotEqualTo(LeaveRequestStatus.Rejected);
  294. leavefilter.Ands.Add(empfilter);
  295. query.Add<LeaveRequest>(
  296. leavefilter,
  297. new Columns<LeaveRequest>(x => x.ID)
  298. .Add(x => x.EmployeeLink.ID)
  299. .Add(x => x.From)
  300. .Add(x=>x.FromTime)
  301. .Add(x => x.To)
  302. .Add(x=>x.ToTime)
  303. .Add(x => x.LeaveType.ID)
  304. .Add(x => x.LeaveType.Description)
  305. .Add(x => x.Status)
  306. );
  307. query.Add<StandardLeave>(
  308. new Filter<StandardLeave>(x => x.To).IsGreaterThanOrEqualTo(start).And(x => x.From).IsLessThanOrEqualTo(end),
  309. new Columns<StandardLeave>(x => x.ID)
  310. .Add(x => x.From)
  311. .Add(x=>x.FromTime)
  312. .Add(x => x.To)
  313. .Add(x=>x.ToTime)
  314. .Add(x => x.LeaveType.ID)
  315. );
  316. query.Query();
  317. var leaverequests = query.Get<LeaveRequest>();
  318. var standardleaves = query.Get<StandardLeave>();
  319. foreach (var standardrow in standardleaves.Rows)
  320. {
  321. var id = standardrow.Get<StandardLeave, Guid>(x => x.ID);
  322. var actid = standardrow.Get<StandardLeave, Guid>(x => x.LeaveType.ID);
  323. var from = standardrow.Get<StandardLeave, DateTime>(x => x.From);
  324. from = from < start ? start : from;
  325. var to = standardrow.Get<StandardLeave, DateTime>(x => x.To);
  326. to = to > end ? end : to;
  327. for (var date = from; date <= to; date = date.AddDays(1))
  328. foreach (var empid in _employees.Keys)
  329. crosstab.Add(new LeaveValue(id, empid, date, actid, LeaveRequestStatus.Approved, true));
  330. }
  331. foreach (var leaverow in leaverequests.Rows)
  332. {
  333. var id = leaverow.Get<LeaveRequest, Guid>(x => x.ID);
  334. var empid = leaverow.Get<LeaveRequest, Guid>(x => x.EmployeeLink.ID);
  335. var actid = leaverow.Get<LeaveRequest, Guid>(x => x.LeaveType.ID);
  336. var status = leaverow.Get<LeaveRequest, LeaveRequestStatus>(x => x.Status);
  337. var from = leaverow.Get<LeaveRequest, DateTime>(x => x.From);
  338. from = from < start ? start : from;
  339. var to = leaverow.Get<LeaveRequest, DateTime>(x => x.To);
  340. to = to > end ? end : to;
  341. var totime = leaverow.Get<LeaveRequest, TimeSpan>(x => x.ToTime);
  342. for (var date = from; date < to.Add(totime); date = date.AddDays(1))
  343. crosstab.Add(new LeaveValue(id, empid, date, actid, status, false));
  344. }
  345. var data = new DataTable();
  346. data.Columns.Add("Date", typeof(DateTime));
  347. foreach (var employee in _employees.Keys)
  348. data.Columns.Add(employee.ToString(), typeof(object));
  349. for (var date = start; date <= end; date = date.AddDays(1))
  350. {
  351. var values = new List<object> { date };
  352. foreach (var employee in _employees.Keys)
  353. {
  354. LeaveValue value = null;
  355. var roster = _rosters.FirstOrDefault(x => x.Item1 == employee);
  356. if (roster != null)
  357. {
  358. var curroster = RosterUtils.GetRoster(roster.Item4, roster.Item5, date);
  359. if (curroster?.Enabled == true)
  360. {
  361. value = crosstab.FirstOrDefault(x => x.Employee.Equals(employee) && x.Date.Equals(date) && x.Standard);
  362. if (value == null)
  363. value = crosstab.FirstOrDefault(x => x.Employee.Equals(employee) && x.Date.Equals(date) && !x.Standard);
  364. }
  365. }
  366. values.Add(value ?? new LeaveValue(Guid.Empty, employee, date, Guid.Empty, LeaveRequestStatus.InProgress, false));
  367. }
  368. data.Rows.Add(values.ToArray());
  369. }
  370. dataGrid.ItemsSource = data;
  371. }
  372. }
  373. private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e)
  374. {
  375. e.Column.TextAlignment = TextAlignment.Center;
  376. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Center;
  377. e.Column.ColumnSizer = GridLengthUnitType.None;
  378. var value = (e.Column.ValueBinding as Binding)!;
  379. if (value.Path.Path.Equals("Date"))
  380. {
  381. e.Column.Width = 100;
  382. e.Column.HeaderStyle = Resources["DateHeaderStyle"] as Style;
  383. e.Column.AllowFocus = false;
  384. }
  385. else
  386. {
  387. var style = new Style(typeof(GridCell));
  388. style.Setters.Add(new Setter(BackgroundProperty,
  389. new Binding(value.Path.Path)
  390. {
  391. Converter = new LeaveBackgroundConverter
  392. {
  393. Colors = _activityColors,
  394. Rosters = _rosters
  395. }
  396. }));
  397. style.Setters.Add(new Setter(ForegroundProperty, new Binding(value.Path.Path) { Converter = new LeaveForegroundConverter() }));
  398. style.Setters.Add(new Setter(FontStyleProperty, new Binding(value.Path.Path) { Converter = new LeaveFontStyleConverter() }));
  399. style.Setters.Add(new Setter(FontWeightProperty, new Binding(value.Path.Path) { Converter = new LeaveFontWeightConverter() }));
  400. e.Column.CellStyle = style;
  401. e.Column.Width = 30;
  402. e.Column.HeaderStyle = Resources["ContentHeaderStyle"] as Style;
  403. e.Column.HeaderText = _employees[Guid.Parse(value.Path.Path)];
  404. e.Column.DisplayBinding = new Binding
  405. { Path = new PropertyPath(e.Column.MappingName), Converter = new LeaveContentConverter { Abbreviations = _activityCodes } };
  406. //e.Column.ValueBinding = new Binding() { Path = new PropertyPath(e.Column.MappingName), Converter = new LeaveContentConverter() };
  407. //e.Column.UseBindingValue = true;
  408. e.Column.AllowFocus = true;
  409. }
  410. }
  411. //private void DataGrid_FilterItemsPopulating(object sender, GridFilterItemsPopulatingEventArgs e)
  412. //{
  413. // e.FilterControl.FilterMode = FilterMode.AdvancedFilter;
  414. //}
  415. private void GetSelectionData(out DateTime from, out DateTime to, out Guid[] ids)
  416. {
  417. var emps = new List<Guid>();
  418. from = DateTime.MaxValue;
  419. to = DateTime.MinValue;
  420. foreach (var cell in dataGrid.GetSelectedCells())
  421. {
  422. var binding = (cell.Column.ValueBinding as Binding)!;
  423. if (Guid.TryParse(binding.Path.Path, out var emp))
  424. if (!emps.Contains(emp))
  425. emps.Add(emp);
  426. var row = (cell.RowData as DataRowView)!;
  427. var date = (DateTime)row.Row.ItemArray.First()!;
  428. if (date < from)
  429. from = date;
  430. if (date > to)
  431. to = date;
  432. }
  433. ids = emps.Any() ? emps.ToArray() : _employees.Keys.ToArray();
  434. }
  435. private bool HasData()
  436. {
  437. foreach (var cell in dataGrid.GetSelectedCells())
  438. {
  439. if (!cell.IsDataRowCell)
  440. continue;
  441. var propertyCollection = dataGrid.View.GetPropertyAccessProvider();
  442. var cellValue = propertyCollection.GetValue(cell.RowData, cell.Column.MappingName);
  443. if (cellValue is LeaveValue leaveValue && leaveValue.ID != Guid.Empty)
  444. return true;
  445. }
  446. return false;
  447. }
  448. private Guid[] GetLeaveIDs(bool standard)
  449. {
  450. List<Guid> result = new List<Guid>();
  451. foreach (var cell in dataGrid.GetSelectedCells())
  452. {
  453. if (cell.IsDataRowCell)
  454. {
  455. var propertyCollection = dataGrid.View.GetPropertyAccessProvider();
  456. var cellvalue = propertyCollection.GetValue(cell.RowData, cell.Column.MappingName) as LeaveValue;
  457. if (cellvalue != null && (cellvalue.ID != Guid.Empty) && (cellvalue.Standard == standard) && !result.Contains(cellvalue.ID))
  458. result.Add(cellvalue.ID);
  459. }
  460. }
  461. return result.ToArray();
  462. }
  463. private LeaveValue? GetData(GridCellInfo cell)
  464. {
  465. if (!cell.IsDataRowCell)
  466. return null;
  467. var propertyCollection = dataGrid.View.GetPropertyAccessProvider();
  468. var cellValue = propertyCollection.GetValue(cell.RowData, cell.Column.MappingName);
  469. return cellValue is LeaveValue leaveValue && leaveValue.ID != Guid.Empty ? leaveValue : null;
  470. }
  471. private bool HasData(GridCellInfo cell)
  472. {
  473. if (cell?.IsDataRowCell != true)
  474. return false;
  475. var propertyCollection = dataGrid.View.GetPropertyAccessProvider();
  476. var cellValue = propertyCollection.GetValue(cell.RowData, cell.Column.MappingName);
  477. return cellValue is LeaveValue leaveValue && leaveValue.ID != Guid.Empty;
  478. }
  479. private void CreateLeaveRequestClick(object sender, RoutedEventArgs e)
  480. {
  481. var activity = ((sender as MenuItem)!.Tag as Activity)!;
  482. GetSelectionData(out var from, out var to, out var ids);
  483. var leaves = new List<LeaveRequest>();
  484. foreach (var id in ids)
  485. {
  486. var leave = new LeaveRequest
  487. {
  488. From = from,
  489. To = to
  490. };
  491. leave.LeaveType.ID = activity.ID;
  492. leave.EmployeeLink.ID = id;
  493. leaves.Add(leave);
  494. }
  495. lg ??= new LeaveRequestGrid();
  496. if (lg.EditItems(leaves.ToArray()))
  497. {
  498. Progress.ShowModal("Checking Forms...", progress =>
  499. {
  500. List<LeaveRequestForm> updates = new List<LeaveRequestForm>();
  501. var table = new Client<ActivityForm>().Query(
  502. new Filter<ActivityForm>(x => x.Activity.ID).IsEqualTo(leaves.First().LeaveType.ID)
  503. .And(x => x.Form.AppliesTo)
  504. .IsEqualTo(typeof(LeaveRequest).EntityName().Split('.').Last())
  505. );
  506. foreach (var leave in leaves)
  507. {
  508. foreach (var row in table.Rows)
  509. {
  510. var activityform = row.ToObject<ActivityForm>();
  511. var leaveform = new LeaveRequestForm();
  512. leaveform.Parent.ID = leave.ID;
  513. leaveform.Form.ID = activityform.Form.ID;
  514. leaveform.Form.Synchronise(activityform.Form);
  515. var model =
  516. new DigitalFormDataModel<LeaveRequest, LeaveRequestLink, LeaveRequestForm>(leave,
  517. leaveform);
  518. leaveform.Description = model.EvaluateExpression(activityform.Form.DescriptionExpression) ?? activityform.Form.Description;
  519. updates.Add(leaveform);
  520. }
  521. }
  522. if (updates.Any())
  523. {
  524. progress.Report("Saving forms...");
  525. new Client<LeaveRequestForm>().Save(updates, "Created from Leave Calendar");
  526. }
  527. });
  528. Refresh();
  529. }
  530. }
  531. private void CreateStandardLeaveClick(object sender, RoutedEventArgs e)
  532. {
  533. GetSelectionData(out var from, out var to, out var ids);
  534. var leave = new StandardLeave
  535. {
  536. From = from,
  537. To = to
  538. };
  539. sg ??= new StandardLeaveGrid();
  540. if (sg.EditItems(new StandardLeave[] { leave }))
  541. Refresh();
  542. }
  543. private IEnumerable<LeaveRequest> GetSelectedLeaveRequests()
  544. {
  545. var ids = GetLeaveIDs(false);
  546. if (ids.Any())
  547. {
  548. lg ??= new LeaveRequests();
  549. var table = new Client<LeaveRequest>().Query(
  550. new Filter<LeaveRequest>(x => x.ID).InList(ids),
  551. lg.LoadEditorColumns()
  552. );
  553. var result = table.Rows.Select(x => x.ToObject<LeaveRequest>()).ToArray();
  554. return result;
  555. }
  556. return new LeaveRequest[] { };
  557. }
  558. private IEnumerable<StandardLeave> GetSelectedStandardLeaves()
  559. {
  560. var ids = GetLeaveIDs(true);
  561. if (ids.Any())
  562. {
  563. sg ??= new StandardLeaveGrid();
  564. var table = new Client<StandardLeave>().Query(
  565. new Filter<StandardLeave>(x => x.ID).InList(ids),
  566. sg.LoadEditorColumns()
  567. );
  568. var result = table.Rows.Select(x => x.ToObject<StandardLeave>()).ToArray();
  569. return result;
  570. }
  571. return new StandardLeave[] { };
  572. }
  573. private void EditLeaveClick(object sender, RoutedEventArgs e)
  574. {
  575. var requests = GetSelectedLeaveRequests().ToArray();
  576. if (requests.Any())
  577. {
  578. lg ??= new LeaveRequests();
  579. if (lg.EditItems(requests))
  580. Refresh();
  581. return;
  582. }
  583. var standards = GetSelectedStandardLeaves().ToArray();
  584. if (standards.Any())
  585. {
  586. sg ??= new StandardLeaveGrid();
  587. if (sg.EditItems(standards))
  588. Refresh();
  589. return;
  590. }
  591. MessageBox.Show("Nothing to edit!");
  592. }
  593. private void DeleteLeaveClick(object sender, RoutedEventArgs e)
  594. {
  595. var requests = GetSelectedLeaveRequests().ToArray();
  596. if (requests.Any())
  597. {
  598. if (MessageBox.Show("Delete Leave Request Information?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning) ==
  599. MessageBoxResult.Yes)
  600. {
  601. using (new WaitCursor())
  602. new Client<LeaveRequest>().Delete(requests, "Deleted from Calendar");
  603. Refresh();
  604. }
  605. return;
  606. }
  607. var standards = GetSelectedStandardLeaves().ToArray();
  608. if (standards.Any())
  609. {
  610. if (MessageBox.Show("Delete Standard Leave Information?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning) ==
  611. MessageBoxResult.Yes)
  612. {
  613. using (new WaitCursor())
  614. new Client<StandardLeave>().Delete(standards, "Deleted from Calendar");
  615. Refresh();
  616. }
  617. return;
  618. }
  619. MessageBox.Show("Nothing to delete!");
  620. }
  621. // private void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  622. // {
  623. // if (e.RightButton == MouseButtonState.Pressed)
  624. // {
  625. // var vc = dataGrid.GetVisualContainer();
  626. // var point = e.GetPosition(vc);
  627. // var rci = vc.PointToCellRowColumnIndex(point);
  628. //
  629. // if (rci.RowIndex == 0 || rci.ColumnIndex == 0)
  630. // return;
  631. //
  632. // var menu = new ContextMenu();
  633. // if (!HasData(dataGrid.CurrentCellInfo))
  634. // foreach (var row in _activities.Rows)
  635. // {
  636. // var createleave = new MenuItem
  637. // {
  638. // Header = row.Get<Activity, string>(c => c.Description),
  639. // Tag = row.ToObject<Activity>()
  640. // };
  641. // createleave.Click += CreateLeaveRequestClick;
  642. // menu.Items.Add(createleave);
  643. // }
  644. //
  645. // if (HasData())
  646. // {
  647. // var deleteleave = new MenuItem { Header = "Delete Leave" };
  648. // deleteleave.Click += DeleteLeaveClick;
  649. // menu.Items.Add(deleteleave);
  650. // }
  651. //
  652. // dataGrid.ContextMenu = menu;
  653. // menu.IsOpen = true;
  654. // }
  655. // }
  656. private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
  657. {
  658. var vc = dataGrid.GetVisualContainer();
  659. var p = Mouse.GetPosition(vc);
  660. var rci = vc.PointToCellRowColumnIndex(p);
  661. if (rci.RowIndex < 1 || rci.ColumnIndex < 1)
  662. {
  663. e.Handled = true;
  664. return;
  665. }
  666. dataGrid.ContextMenu.Items.Clear();
  667. var bCreate = !HasData(dataGrid.CurrentCellInfo);
  668. var bEdit = HasData();
  669. if (bCreate)
  670. {
  671. var createleaveheader = new MenuItem { Header = "Create Leave Request" };
  672. foreach (var row in _activities.Rows)
  673. {
  674. var createleave = new MenuItem
  675. {
  676. Header = row.Get<Activity, string>(c => c.Description),
  677. Tag = row.ToObject<Activity>()
  678. };
  679. createleave.Click += CreateLeaveRequestClick;
  680. createleaveheader.Items.Add(createleave);
  681. }
  682. dataGrid.ContextMenu.Items.Add(createleaveheader);
  683. dataGrid.ContextMenu.Items.Add(new Separator());
  684. var createstandardleave = new MenuItem { Header = "Create Standard Leave" };
  685. createstandardleave.Click += CreateStandardLeaveClick;
  686. dataGrid.ContextMenu.Items.Add(createstandardleave);
  687. }
  688. if (bEdit && bCreate)
  689. dataGrid.ContextMenu.Items.Add(new Separator());
  690. if (bEdit)
  691. {
  692. var editleave = new MenuItem { Header = "Edit Leave" };
  693. editleave.Click += EditLeaveClick;
  694. dataGrid.ContextMenu.Items.Add(editleave);
  695. dataGrid.ContextMenu.Items.Add(new Separator());
  696. var deleteleave = new MenuItem { Header = "Delete Leave" };
  697. deleteleave.Click += DeleteLeaveClick;
  698. dataGrid.ContextMenu.Items.Add(deleteleave);
  699. var cell = GetData(dataGrid.CurrentCellInfo); // not-null because bEdit.
  700. if (cell != null)
  701. {
  702. dataGrid.ContextMenu.Items.Add(new Separator());
  703. var formsItem = new MenuItem { Header = "Digital Forms" };
  704. DynamicGridUtils.PopulateFormMenu<LeaveRequestForm, LeaveRequest, LeaveRequestLink>(
  705. formsItem,
  706. cell.ID,
  707. () => new Client<LeaveRequest>().Load(new Filter<LeaveRequest>(x => x.ID).IsEqualTo(cell.ID)).First());
  708. dataGrid.ContextMenu.Items.Add(formsItem);
  709. }
  710. }
  711. }
  712. private void DateTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  713. {
  714. if (!bReady)
  715. return;
  716. Refresh();
  717. }
  718. private void SyncSelectedTeams(Guid teamid)
  719. {
  720. var bOldReady = bReady;
  721. bReady = false;
  722. if (teamid != CoreUtils.FullGuid)
  723. {
  724. SelectedTeams.SelectedItems.Clear();
  725. foreach (KeyValuePair<Guid, string> sel in SelectedTeams.Items)
  726. if (sel.Key == teamid)
  727. SelectedTeams.SelectedItems.Add(sel);
  728. }
  729. LoadEmployees(true);
  730. bReady = bOldReady;
  731. }
  732. private void GroupsSelectionChanged(object sender, SelectionChangedEventArgs e)
  733. {
  734. if (Teams.SelectedValue == null)
  735. return;
  736. var teamid = (Guid)Teams.SelectedValue;
  737. ChangeSelectedTeams(teamid);
  738. SyncSelectedTeams(teamid);
  739. }
  740. private void ChangeSelectedTeams(Guid teamid)
  741. {
  742. if (teamid == CoreUtils.FullGuid)
  743. {
  744. EmployeeGrid.RowDefinitions[1].Height = new GridLength(_settings.ListSize, GridUnitType.Pixel);
  745. EmployeeGrid.RowDefinitions[2].Height = new GridLength(1, GridUnitType.Auto);
  746. }
  747. else
  748. {
  749. var oldbReady = bReady;
  750. bReady = false;
  751. EmployeeGrid.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Pixel);
  752. EmployeeGrid.RowDefinitions[2].Height = new GridLength(0, GridUnitType.Pixel);
  753. bReady = oldbReady;
  754. }
  755. //bHandled = false;
  756. }
  757. //bool bHandled = false;
  758. //private void SelectedTeams_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  759. //{
  760. // if (!bReady)
  761. // return;
  762. // if (!bHandled)
  763. // LoadEmployees();
  764. // bHandled = !bHandled;
  765. //}
  766. private void SelectedTeams_ItemChecked(object sender, ItemCheckedEventArgs e)
  767. {
  768. if (!bReady)
  769. return;
  770. LoadEmployees(true);
  771. }
  772. private void LoadEmployees(bool selectall)
  773. {
  774. var emps = new Dictionary<Guid, string>();
  775. foreach (var pair in SelectedTeams.SelectedItems)
  776. if (pair != null)
  777. {
  778. var key = ((KeyValuePair<Guid, string>)pair).Key;
  779. foreach (var row in _employeeteams.Rows.Where(r =>
  780. r.Get<EmployeeTeam, Guid>(c => c.TeamLink.ID).Equals(key) || key.Equals(CoreUtils.FullGuid)))
  781. emps[row.Get<EmployeeTeam, Guid>(c => c.EmployeeLink.ID)] = row.Get<EmployeeTeam, string>(c => c.EmployeeLink.Name);
  782. }
  783. var bOldReady = bReady;
  784. bReady = false;
  785. SelectedEmployees.ItemsSource = emps;
  786. foreach (var item in SelectedEmployees.Items)
  787. {
  788. var pair = (KeyValuePair<Guid, string>)item;
  789. if (_settings.SelectedEmployees.Contains(pair.Key) || selectall)
  790. SelectedEmployees.SelectedItems.Add(item);
  791. }
  792. bReady = bOldReady;
  793. SaveSettings();
  794. Refresh();
  795. }
  796. private void EmployeesSelectionChanged(object sender, SelectionChangedEventArgs e)
  797. {
  798. if (!bReady || e.AddedItems.Count == 0 || e.AddedItems[0] == null)
  799. return;
  800. //ReloadColumns();
  801. SaveSettings();
  802. Refresh();
  803. }
  804. private void Export_Click(object sender, RoutedEventArgs e)
  805. {
  806. var options = new ExcelExportingOptions
  807. {
  808. ExcelVersion = ExcelVersion.Excel2013
  809. };
  810. var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
  811. var workBook = excelEngine.Excel.Workbooks[0];
  812. var dlg = new SaveFileDialog
  813. {
  814. Filter = "Excel Files (*.xlsx)|*.xlsx",
  815. FileName = typeof(LeaveRequest).EntityName().Split('.').Last() + ".xlsx"
  816. };
  817. if (dlg.ShowDialog() == true)
  818. try
  819. {
  820. workBook.SaveAs(dlg.FileName);
  821. Process.Start(new ProcessStartInfo(dlg.FileName) { UseShellExecute = true });
  822. }
  823. catch (Exception e2)
  824. {
  825. MessageBox.Show("Error saving spreadsheet!\n\n" + e2.Message);
  826. }
  827. //workBook.SaveAs("Leave Requests.xlsx");
  828. }
  829. private void SelectedTeams_SizeChanged(object sender, SizeChangedEventArgs e)
  830. {
  831. SaveSettings();
  832. }
  833. }
  834. }