TimesheetGrid.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Media.Imaging;
  9. using Comal.Classes;
  10. using InABox.Clients;
  11. using InABox.Configuration;
  12. using InABox.Core;
  13. using InABox.DynamicGrid;
  14. using InABox.WPF;
  15. namespace PRSDesktop
  16. {
  17. public class TimeSheetGridSettings : IUserConfigurationSettings
  18. {
  19. [Obsolete]
  20. private CoreFilterDefinition? _currentFilter;
  21. [Obsolete]
  22. public CoreFilterDefinition? CurrentFilter
  23. {
  24. get => _currentFilter;
  25. set
  26. {
  27. if (value is not null)
  28. {
  29. Filters = new DynamicGridSelectedFilterSettings(new List<ICoreFilterDefinition> { value }, false, null);
  30. }
  31. }
  32. }
  33. public DynamicGridSelectedFilterSettings Filters { get; set; } = new();
  34. }
  35. public class TimesheetGrid : DynamicDataGrid<TimeSheet>
  36. {
  37. private readonly BitmapImage leave = PRSDesktop.Resources.leave.AsBitmapImage();
  38. private LeaveRequestGrid? leavegrid;
  39. private readonly BitmapImage post = PRSDesktop.Resources.post.AsBitmapImage();
  40. private readonly BitmapImage tick = PRSDesktop.Resources.tick.AsBitmapImage();
  41. private readonly BitmapImage warning = PRSDesktop.Resources.warning.AsBitmapImage();
  42. private static readonly BitmapImage? refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
  43. private TimeSheetGridSettings _settings;
  44. protected override void Init()
  45. {
  46. base.Init();
  47. _settings = new UserConfiguration<TimeSheetGridSettings>().Load();
  48. FilterComponent.SetSettings(_settings.Filters, false);
  49. FilterComponent.OnFiltersSelected += FilterComponent_OnFilterSelected;
  50. ActionColumns.Add(new DynamicMenuColumn(BuildMenu) { Position = DynamicActionColumnPosition.Start });
  51. ActionColumns.Add(new DynamicMapColumn<TimeSheet>(this, x => x.StartLocation));
  52. //HiddenColumns.Add(x => x.StartLocation.Timestamp);
  53. //HiddenColumns.Add(x => x.StartLocation.Latitude);
  54. //HiddenColumns.Add(x => x.StartLocation.Longitude);
  55. ActionColumns.Add(new DynamicMapColumn<TimeSheet>(this, x => x.FinishLocation));
  56. //HiddenColumns.Add(x => x.FinishLocation.Timestamp);
  57. //HiddenColumns.Add(x => x.FinishLocation.Latitude);
  58. //HiddenColumns.Add(x => x.FinishLocation.Longitude);
  59. //ActionColumns.Add(new DynamicImageColumn() { Image = WarningImage });
  60. ActionColumns.Add(new DynamicTickColumn<TimeSheet, DateTime>(x => x.Approved, tick, tick, null));
  61. //ActionColumns.Add(new DynamicTickColumn<TimeSheet, DateTime>(x => x.Processed, post, tick, null));
  62. ActionColumns.Add(new DynamicImageColumn(Posted_Image, null)
  63. {
  64. ToolTip = Posted_ToolTip
  65. });
  66. HiddenColumns.Add(x => x.Date);
  67. HiddenColumns.Add(x => x.Start);
  68. HiddenColumns.Add(x => x.Finish);
  69. HiddenColumns.Add(x => x.Duration);
  70. HiddenColumns.Add(x => x.ApprovedStart);
  71. HiddenColumns.Add(x => x.ApprovedFinish);
  72. //HiddenColumns.Add(x => x.ApprovedHours);
  73. HiddenColumns.Add(x => x.ApprovedDuration);
  74. HiddenColumns.Add(x => x.EmployeeLink.ID);
  75. HiddenColumns.Add(x => x.LeaveRequestLink.ID);
  76. HiddenColumns.Add(x => x.JobLink.ID);
  77. HiddenColumns.Add(x => x.JobLink.Deleted);
  78. HiddenColumns.Add(x => x.Approved);
  79. HiddenColumns.Add(x => x.PostedNote);
  80. HiddenColumns.Add(x => x.PostedStatus);
  81. if (Security.CanView<Employee>())
  82. AddButton("Employee", PRSDesktop.Resources.anonymous.AsBitmapImage(Color.White), EditEmployee);
  83. if (Security.IsAllowed<CanApproveTimesheets>())
  84. {
  85. AddButton("Approve", tick, ApproveTimeSheet);
  86. AddButton("UnApprove", warning, UnApproveTimeSheet);
  87. }
  88. if (Security.CanView<LeaveRequest>())
  89. AddButton("Create Leave", leave, CreateLeaveRequest);
  90. }
  91. protected override void DoReconfigure(DynamicGridOptions options)
  92. {
  93. base.DoReconfigure(options);
  94. options.SelectColumns = true;
  95. options.FilterRows = true;
  96. options.MultiSelect = true;
  97. options.RecordCount = true;
  98. }
  99. public DateTime StartDate { get; set; } = DateTime.MinValue;
  100. public DateTime EndDate { get; set; } = DateTime.MaxValue;
  101. public string Search { get; set; } = "";
  102. public bool ApprovedOnly { get; set; } = false;
  103. private FrameworkElement? Posted_ToolTip(DynamicActionColumn column, CoreRow? row)
  104. {
  105. if (row is null)
  106. {
  107. return column.TextToolTip("Timesheet Processed Status");
  108. }
  109. return column.TextToolTip(row.Get<TimeSheet, PostedStatus>(x => x.PostedStatus) switch
  110. {
  111. PostedStatus.PostFailed => "Post failed: " + row.Get<TimeSheet, string>(x => x.PostedNote),
  112. PostedStatus.RequiresRepost => "Repost required: " + row.Get<TimeSheet, string>(x => x.PostedNote),
  113. PostedStatus.Posted => "Processed",
  114. PostedStatus.NeverPosted or _ => "Not posted yet",
  115. });
  116. }
  117. private BitmapImage? Posted_Image(CoreRow? row)
  118. {
  119. if (row is null)
  120. return post;
  121. return row.Get<TimeSheet, PostedStatus>(x => x.PostedStatus) switch
  122. {
  123. PostedStatus.PostFailed => warning,
  124. PostedStatus.Posted => tick,
  125. PostedStatus.RequiresRepost => refresh,
  126. PostedStatus.NeverPosted or _ => null,
  127. };
  128. }
  129. private void BuildMenu(DynamicMenuColumn column, CoreRow? row)
  130. {
  131. if (row == null) return;
  132. var formsItem = column.AddItem("Digital Forms", PRSDesktop.Resources.kanban, null);
  133. DynamicGridUtils.PopulateFormMenu<TimeSheetForm, TimeSheet, TimeSheetLink>(
  134. formsItem,
  135. row.Get<TimeSheet, Guid>(x => x.ID),
  136. () => row.ToObject<TimeSheet>());
  137. }
  138. public override TimeSheet CreateItem()
  139. {
  140. var result = base.CreateItem();
  141. result.Date = DateTime.Today;
  142. return result;
  143. }
  144. private Tuple<Guid, DateTime, string>[] GroupTimeSheets(CoreRow[] rows)
  145. {
  146. var results = new List<Tuple<Guid, DateTime, string>>();
  147. foreach (var row in rows)
  148. {
  149. var date = row.Get<TimeSheet, DateTime>(x => x.Date);
  150. var empid = row.Get<TimeSheet, Guid>(x => x.EmployeeLink.ID);
  151. var name = row.Get<TimeSheet, string>(x => x.EmployeeLink.Name);
  152. if (!results.Any(x => x.Item1.Equals(empid) && x.Item2.Equals(date)))
  153. results.Add(new Tuple<Guid, DateTime, string>(empid, date, name));
  154. }
  155. return results.OrderBy(x => x.Item3).ThenBy(x => x.Item2).ToArray();
  156. }
  157. private bool CheckApproval(TimeSheet time)
  158. {
  159. time.ApprovedStart = time.Start.Round(new TimeSpan(0, 15, 0));
  160. time.ApprovedFinish = time.Finish.Round(new TimeSpan(0, 15, 0));
  161. time.Approved = DateTime.Now;
  162. return true;
  163. }
  164. private bool ApproveTimeSheet(Button sender, CoreRow[] rows)
  165. {
  166. if (!rows.Any())
  167. {
  168. MessageBox.Show("Please select at least one row to process!");
  169. return false;
  170. }
  171. Progress.Show("");
  172. Progress.SetMessage("Loading Time Sheets");
  173. var employeedays = GroupTimeSheets(rows);
  174. var updates = new List<TimeSheet>();
  175. var lastemp = Guid.Empty;
  176. Employee? emp = null;
  177. foreach (var day in employeedays)
  178. {
  179. var date = day.Item2;
  180. var empid = day.Item1;
  181. var name = day.Item3;
  182. if (empid != lastemp)
  183. {
  184. Progress.SetMessage("Processing: " + name);
  185. emp = new Client<Employee>().Load(new Filter<Employee>(x => x.ID).IsEqualTo(empid)).FirstOrDefault();
  186. lastemp = empid;
  187. }
  188. if (emp != null)
  189. {
  190. var times = new Client<TimeSheet>().Load(new Filter<TimeSheet>(x => x.Date).IsEqualTo(date)
  191. .And(x => x.EmployeeLink.ID).IsEqualTo(empid)
  192. .And(x => x.Approved).IsEqualTo(DateTime.MinValue)
  193. .And(x => x.Finish).IsNotEqualTo(new TimeSpan(0))
  194. );
  195. if (times.Length > 0)
  196. {
  197. // Rules:
  198. // if the employee has a usual start / usual end set, it will be treated as salary,
  199. // and the approved times will always reflect the usual, eather than the actual times
  200. // Then, it will go through each timesheet, and wind back the start / finish time IF
  201. // a: timesheet is joblinked
  202. // b: job has a usual start / end
  203. // b: timesheet activity == job.usual activity
  204. var first = times.OrderBy(x => x.Start).First();
  205. var start = first.Start.Round(new TimeSpan(0, 15, 0));
  206. var last = times.OrderBy(x => x.Finish).Last();
  207. var finish = last.Finish.Round(new TimeSpan(0, 15, 0));
  208. var jobfilter = new Filter<Job>(x => x.ID).IsEqualTo(Guid.Empty);
  209. Array.ForEach(times, t => jobfilter.Ors.Add(new Filter<Job>(j => j.ID).IsEqualTo(t.JobLink.ID)));
  210. var jobs = new Client<Job>().Query(jobfilter,
  211. Columns.None<Job>().Add(x => x.ID, x => x.UsualStart, x => x.UsualFinish, x => x.UsualActivity.ID));
  212. for (var i = 0; i < times.Length; i++)
  213. {
  214. //Progress.SetMessage(String.Format("Checking Time Sheet({0:F2}% complete)", (i * 100.0F) / (double)times.Length));
  215. var time = times[i];
  216. time.ApprovedStart = time == first || time.Start < start ? start : time.Start;
  217. time.ApprovedFinish = time == last || time.Finish > finish ? finish : time.Finish;
  218. var job = jobs.Rows.Where(r => r.Get<Job, Guid>(c => c.ID).Equals(time.JobLink.ID)
  219. && Entity.IsEntityLinkValid<Job, ActivityLink>(x => x.UsualActivity, r)
  220. && r.Get<Job, Guid>(c => c.UsualActivity.ID).Equals(time.ActivityLink.ID)
  221. ).FirstOrDefault();
  222. if (job != null)
  223. {
  224. var jobstart = job.Get<Job, TimeSpan>(x => x.UsualStart);
  225. if (jobstart > new TimeSpan(0) && time.Start < jobstart)
  226. time.ApprovedStart = jobstart;
  227. var jobend = job.Get<Job, TimeSpan>(x => x.UsualFinish);
  228. if (jobend > new TimeSpan(0) && time.Finish > jobend)
  229. time.ApprovedFinish = jobend;
  230. }
  231. if (time.ApprovedFinish < time.ApprovedStart)
  232. time.ApprovedFinish = time.ApprovedStart;
  233. time.Approved = DateTime.Now;
  234. updates.Add(time);
  235. }
  236. }
  237. }
  238. }
  239. if (updates.Any())
  240. {
  241. Progress.SetMessage("Updating Database");
  242. new Client<TimeSheet>().Save(updates, "Approving Time Sheets");
  243. }
  244. Progress.Close();
  245. MessageBox.Show("All Done");
  246. return true;
  247. }
  248. private bool UnApproveTimeSheet(Button sender, CoreRow[] rows)
  249. {
  250. if (!rows.Any())
  251. {
  252. MessageBox.Show("Please select at least one row to process!");
  253. return false;
  254. }
  255. Progress.Show("");
  256. Progress.SetMessage("Processing Time Sheets");
  257. var employeedays = GroupTimeSheets(rows);
  258. var updates = new List<TimeSheet>();
  259. foreach (var day in employeedays)
  260. {
  261. var date = day.Item2;
  262. var empid = day.Item1;
  263. var name = day.Item3;
  264. Progress.SetMessage("Clearing Approvals for " + name);
  265. var times = new Client<TimeSheet>().Load(new Filter<TimeSheet>(x => x.Date).IsEqualTo(date)
  266. .And(x => x.EmployeeLink.ID).IsEqualTo(empid)
  267. );
  268. for (var i = 0; i < times.Length; i++)
  269. {
  270. //Progress.SetMessage(String.Format("Clearing Approval ({0:F2}% complete)", (i * 100.0F) / (double)times.Length));
  271. var time = times[i];
  272. time.ApprovedStart = new TimeSpan(0);
  273. time.ApprovedFinish = new TimeSpan(0);
  274. time.Approved = DateTime.MinValue;
  275. updates.Add(time);
  276. }
  277. }
  278. if (updates.Any())
  279. {
  280. Progress.SetMessage("Updating Database");
  281. new Client<TimeSheet>().Save(updates, "Clearing Approvals");
  282. }
  283. Progress.Close();
  284. MessageBox.Show("All Done");
  285. return true;
  286. }
  287. private bool EditEmployee(Button btn, CoreRow[] rows)
  288. {
  289. if (rows.Length != 1)
  290. {
  291. MessageBox.Show("Please select a single employee!");
  292. return false;
  293. }
  294. var row = rows.First();
  295. var employee = new Client<Employee>().Load(new Filter<Employee>(x => x.ID).IsEqualTo(row.Get<TimeSheet, Guid>(c => c.EmployeeLink.ID)))
  296. .FirstOrDefault();
  297. if (employee == null)
  298. {
  299. MessageBox.Show("Cannot Locate Employee!");
  300. return false;
  301. }
  302. var employeegrid = new EmployeeGrid();
  303. return employeegrid.EditItems(new[] { employee });
  304. }
  305. private bool CreateLeaveRequest(Button arg1, CoreRow[] arg2)
  306. {
  307. var leave = new LeaveRequest();
  308. leave.From = DateTime.Today;
  309. leave.To = DateTime.Today;
  310. leavegrid ??= new LeaveRequestGrid();
  311. return leavegrid.EditItems(new[] { leave });
  312. }
  313. protected override Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, TimeSheet[] items, string name, object value)
  314. {
  315. var result = base.EditorValueChanged(editor, items, name, value);
  316. if (name == "ActivityLink.ID")
  317. {
  318. ReloadForms<TimeSheet, TimeSheetForm, ActivityForm>(editor, items.FirstOrDefault(), x => x.Activity.ID,
  319. value != null ? (Guid)value : Guid.Empty);
  320. }
  321. else if (name.Equals("EmployeeLink.ID"))
  322. {
  323. var activity = editor.FindEditor("ActivityLink.ID") as ILookupEditorControl;
  324. if (activity != null)
  325. DefineLookups(activity, items);
  326. }
  327. return result;
  328. }
  329. protected override void AfterLoad(IDynamicEditorForm editor, TimeSheet[] items)
  330. {
  331. base.AfterLoad(editor, items);
  332. if (items.FirstOrDefault().ID == Guid.Empty)
  333. ReloadForms<TimeSheet, TimeSheetForm, ActivityForm>(editor, items.FirstOrDefault(), x => x.Activity.ID,
  334. items.FirstOrDefault().ActivityLink.ID);
  335. }
  336. //private BitmapImage WarningImage(DataRow row)
  337. //{
  338. // if (row == null)
  339. // return warning;
  340. // if (row.Get<TimeSheet, DateTime>(x => x.Approved) != DateTime.MinValue)
  341. // return null;
  342. // TimeSpan start = row.Get<TimeSheet, TimeSpan>(x => x.Start);
  343. // if (start.Equals(new TimeSpan(0)))
  344. // return warning;
  345. // TimeSpan finish = row.Get<TimeSheet, TimeSpan>(x => x.Finish);
  346. // if (finish.Equals(new TimeSpan(0)))
  347. // return warning;
  348. // TimeSpan actual = row.Get<TimeSheet, TimeSpan>(x => x.Duration);
  349. // TimeSpan approved = row.Get<TimeSheet, TimeSpan>(x => x.ApprovedDuration);
  350. // if (!actual.Equals(approved))
  351. // return warning;
  352. // return null;
  353. //}
  354. //private bool ApproveClick(DataRow row)
  355. //{
  356. // if (row == null)
  357. // return false;
  358. // Guid id = row.Get<TimeSheet, Guid>(x => x.ID);
  359. // TimeSheet timesheet = new Client<TimeSheet>().Load(new Filter<TimeSheet>(x => x.ID).IsEqualTo(id)).FirstOrDefault();
  360. // if (timesheet != null)
  361. // {
  362. // timesheet.Approved = timesheet.Approved.IsEmpty() ? DateTime.Now : DateTime.MinValue;
  363. // new Client<TimeSheet>().Save(timesheet, "Toggled Approval flag");
  364. // return true;
  365. // }
  366. // return false;
  367. //}
  368. protected override void Reload(
  369. Filters<TimeSheet> criteria, Columns<TimeSheet> columns, ref SortOrder<TimeSheet>? sort,
  370. CancellationToken token, Action<CoreTable?, Exception?> action)
  371. {
  372. var filter = new Filter<TimeSheet>(x => x.Processed).IsEqualTo(DateTime.MinValue);
  373. if (!string.IsNullOrWhiteSpace(Search))
  374. filter = filter.TextSearch(Search, x => x.EmployeeLink.Name, x => x.Address, x => x.Notes);
  375. criteria.Add(filter);
  376. criteria.Add(new Filter<TimeSheet>(x => x.EmployeeLink.FinishDate).IsEqualTo(DateTime.MinValue).Or(x => x.EmployeeLink.FinishDate)
  377. .IsGreaterThanOrEqualTo(DateTime.Today));
  378. criteria.Add(new Filter<TimeSheet>(x => x.Date).IsGreaterThanOrEqualTo(StartDate.Date));
  379. criteria.Add(new Filter<TimeSheet>(x => x.Date).IsLessThan(EndDate == DateTime.MaxValue ? DateTime.MaxValue : EndDate.AddDays(1)));
  380. if (ApprovedOnly)
  381. criteria.Add(new Filter<TimeSheet>(x => x.Approved).IsNotEqualTo(DateTime.MinValue));
  382. base.Reload(criteria, columns, ref sort, token, action);
  383. }
  384. protected override bool CanDeleteItems(CoreRow[] rows)
  385. {
  386. var result = true;
  387. foreach (var row in rows)
  388. {
  389. if (row.IsEntityLinkValid<TimeSheet, LeaveRequestLink>(x => x.LeaveRequestLink))
  390. result = false;
  391. }
  392. if (!result)
  393. MessageBox.Show(
  394. "You cannot delete timesheets linked to Leave Requests!\n\nPlease un-approve or delete the related Leave Request instead.");
  395. return result;
  396. }
  397. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  398. {
  399. var result = base.GetEditor(item, column)?.CloneEditor();
  400. if (result == null)
  401. return null;
  402. if (!Security.IsAllowed<CanApproveTimesheets>() &&
  403. (column.ColumnName.Equals("ApprovedStart") || column.ColumnName.Equals("ApprovedFinish") ||
  404. column.ColumnName.Equals("Approved")))
  405. result.Editable = Editable.Disabled;
  406. if (!Security.IsAllowed<CanChangeStartFinishTimes>() &&
  407. (column.ColumnName.Equals("Date") || column.ColumnName.Equals("Start") || column.ColumnName.Equals("Finish")))
  408. result.Editable = Editable.Disabled;
  409. if (!Security.IsAllowed<CanArchiveTimesheets>() && column.ColumnName.Equals("Processed"))
  410. result.Editable = Editable.Disabled;
  411. return result;
  412. }
  413. private void FilterComponent_OnFilterSelected(DynamicGridSelectedFilterSettings settings)
  414. {
  415. _settings.Filters = settings;
  416. new UserConfiguration<TimeSheetGridSettings>().Save(_settings);
  417. }
  418. }
  419. }