TasksByStatusControl.xaml.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using InABox.WPF;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.Linq;
  9. using System.Linq.Expressions;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Data;
  16. using System.Windows.Documents;
  17. using System.Windows.Input;
  18. using System.Drawing;
  19. using System.Windows.Media;
  20. using System.Windows.Media.Imaging;
  21. using Color = System.Drawing.Color;
  22. using InABox.DynamicGrid;
  23. using InABox.Wpf;
  24. using MailKit.Search;
  25. using NPOI.SS.Formula.Functions;
  26. using System.ComponentModel;
  27. using System.Runtime.CompilerServices;
  28. using System.Collections.ObjectModel;
  29. using System.Collections.Specialized;
  30. using Syncfusion.UI.Xaml.Kanban;
  31. namespace PRSDesktop;
  32. public class TasksByStatusColumn : INotifyPropertyChanged
  33. {
  34. public KanbanStatus Status { get; }
  35. public string Title { get; }
  36. public int NumTasks { get => Tasks.Count; }
  37. public double NumHours { get => Tasks.Sum(x => x.EstimatedTime.TotalHours); }
  38. public ObservableCollection<TaskModel> Tasks { get; } = new();
  39. public TasksByStatusColumn(KanbanStatus status, string title)
  40. {
  41. Status = status;
  42. Title = title;
  43. Tasks.CollectionChanged += Tasks_CollectionChanged;
  44. }
  45. private void Tasks_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
  46. {
  47. OnPropertyChanged(nameof(Tasks));
  48. }
  49. public event PropertyChangedEventHandler? PropertyChanged;
  50. // Create the OnPropertyChanged method to raise the event
  51. // The calling member's name will be used as the parameter.
  52. protected void OnPropertyChanged([CallerMemberName] string? name = null)
  53. {
  54. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  55. if(name == nameof(Tasks))
  56. {
  57. OnPropertyChanged(nameof(NumTasks));
  58. OnPropertyChanged(nameof(NumHours));
  59. }
  60. }
  61. }
  62. public class EmployeeModel
  63. {
  64. public Guid ID { get; set; }
  65. public string Name { get; set; }
  66. public BitmapImage? Image { get; set; }
  67. public Guid ThumbnailID { get; set; }
  68. public EmployeeModel(Guid id, string name, Guid thumbnail, BitmapImage? image)
  69. {
  70. ID = id;
  71. Name = name;
  72. Image = image;
  73. ThumbnailID = thumbnail;
  74. }
  75. }
  76. public class SuspendableObservableCollection<T> : ObservableCollection<T>
  77. {
  78. private bool _notificationSupressed = false;
  79. private bool _supressNotification = false;
  80. public bool SupressNotification
  81. {
  82. get
  83. {
  84. return _supressNotification;
  85. }
  86. set
  87. {
  88. _supressNotification = value;
  89. if (_supressNotification == false && _notificationSupressed)
  90. {
  91. this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  92. _notificationSupressed = false;
  93. }
  94. }
  95. }
  96. protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  97. {
  98. if (SupressNotification)
  99. {
  100. _notificationSupressed = true;
  101. return;
  102. }
  103. base.OnCollectionChanged(e);
  104. }
  105. }
  106. /// <summary>
  107. /// Interaction logic for TasksByStatusControl.xaml
  108. /// </summary>
  109. public partial class TasksByStatusControl : UserControl, ITaskControl, INotifyPropertyChanged
  110. {
  111. private enum Suppress
  112. {
  113. This
  114. }
  115. public SuspendableObservableCollection<TasksByStatusColumn> Columns { get; private set; } = new();
  116. private List<EmployeeModel> Employees = new();
  117. public TasksByStatusControl()
  118. {
  119. InitializeComponent();
  120. }
  121. #region INotifyPropertyChanged
  122. public event PropertyChangedEventHandler? PropertyChanged;
  123. // Create the OnPropertyChanged method to raise the event
  124. // The calling member's name will be used as the parameter.
  125. protected void OnPropertyChanged([CallerMemberName] string? name = null)
  126. {
  127. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  128. }
  129. #endregion
  130. #region Setup
  131. public void Setup()
  132. {
  133. var employeesTask = Task.Run(() => LoadEmployees());
  134. var kanbanTypesTask = Task.Run(() => LoadKanbanTypes());
  135. SetupToolbar();
  136. SetupColumns();
  137. employeesTask.Wait();
  138. SetupEmployeeList();
  139. kanbanTypesTask.Wait();
  140. SetupKanbanTypesLookup(kanbanTypesTask.Result);
  141. Mode = Host.KanbanSettings.StatusSettings.CompactView ? KanbanViewMode.Compact : KanbanViewMode.Full;
  142. }
  143. private void SetupToolbar()
  144. {
  145. IncludeCompleted.Visibility = Security.IsAllowed<CanHideTaskCompletedColumn>() ? Visibility.Visible : Visibility.Collapsed;
  146. IncludeCompleted.IsChecked = IncludeCompleted.Visibility == Visibility.Visible ? Host.KanbanSettings.StatusSettings.IncludeCompleted : true;
  147. IncludeObserved.IsChecked = Host.KanbanSettings.StatusSettings.IncludeObserved;
  148. ViewType.SelectedIndex = Host.KanbanSettings.StatusSettings.CompactView ? 1 : 0;
  149. }
  150. #endregion
  151. #region Columns
  152. private void SetupColumns()
  153. {
  154. Columns.SupressNotification = true;
  155. Columns.Clear();
  156. Columns.Add(new TasksByStatusColumn(KanbanStatus.Open, "To Do"));
  157. Columns.Add(new TasksByStatusColumn(KanbanStatus.InProgress, "In Progress"));
  158. Columns.Add(new TasksByStatusColumn(KanbanStatus.Waiting, "Waiting for Others"));
  159. if (Host.KanbanSettings.StatusSettings.IncludeCompleted)
  160. Columns.Add(new TasksByStatusColumn(KanbanStatus.Complete, "Completed"));
  161. Columns.SupressNotification = false;
  162. }
  163. private TasksByStatusColumn? GetColumn(KanbanStatus category)
  164. {
  165. return Columns.FirstOrDefault(x => x.Status.Equals(category));
  166. }
  167. private void Column_ContextMenuOpening(object sender, ContextMenuEventArgs e)
  168. {
  169. if (sender is not FrameworkElement element || element.Tag is not TasksByStatusColumn column) return;
  170. var menu = element.ContextMenu;
  171. menu.Items.Clear();
  172. menu.AddItem("New Task", null, CreateTask);
  173. menu.AddItem($"Select all {column.Title} tasks", null, column, SelectAll);
  174. menu.AddItem($"Deselect all {column.Title} tasks", null, column, DeselectAll);
  175. }
  176. private void SelectColumn(TasksByStatusColumn column, bool selected)
  177. {
  178. SelectedTasks.Clear();
  179. if (selected)
  180. {
  181. SelectedTasks.AddRange(column.Tasks);
  182. foreach (var task in Tasks)
  183. task.Checked = task.Status == column.Status ? selected : !selected;
  184. }
  185. FilterKanbans();
  186. }
  187. private void DeselectAll(TasksByStatusColumn column)
  188. {
  189. SelectColumn(column, false);
  190. }
  191. private void SelectAll(TasksByStatusColumn column)
  192. {
  193. SelectColumn(column, true);
  194. }
  195. #endregion
  196. #region Kanban Types
  197. private IEnumerable<KanbanType> LoadKanbanTypes()
  198. {
  199. return Client.Query(
  200. new Filter<KanbanType>(x => x.Hidden).IsEqualTo(false),
  201. new Columns<KanbanType>(x => x.ID, x => x.Description),
  202. new SortOrder<KanbanType>(x => x.Description))
  203. .ToObjects<KanbanType>();
  204. }
  205. private void SetupKanbanTypesLookup(IEnumerable<KanbanType> kanbanTypes)
  206. {
  207. if (ClientFactory.IsSupported<KanbanType>())
  208. {
  209. var tasktypes = new Dictionary<Guid, string>
  210. {
  211. { CoreUtils.FullGuid, "All Types" },
  212. { Guid.Empty, "Unallocated Types" }
  213. };
  214. foreach(var type in kanbanTypes)
  215. {
  216. tasktypes.Add(type.ID, type.Description);
  217. }
  218. TaskTypes.ItemsSource = tasktypes;
  219. if (tasktypes.ContainsKey(Host.KanbanSettings.StatusSettings.SelectedType))
  220. TaskTypes.SelectedValue = Host.KanbanSettings.StatusSettings.SelectedType;
  221. else
  222. TaskTypes.SelectedValue = CoreUtils.FullGuid;
  223. TaskTypesLabel.Visibility = Visibility.Visible;
  224. TaskTypes.Visibility = Visibility.Visible;
  225. }
  226. else
  227. {
  228. TaskTypesLabel.Visibility = Visibility.Collapsed;
  229. TaskTypes.Visibility = Visibility.Collapsed;
  230. }
  231. }
  232. #endregion
  233. #region Employees
  234. private EmployeeModel SelectedEmployee;
  235. private void LoadEmployees()
  236. {
  237. Employees.Clear();
  238. var employeeFilter = Security.IsAllowed<CanViewOthersTasks>()
  239. ? new Filter<Employee>(x => x.CanAllocateTasks).IsEqualTo(true)
  240. .And(new Filter<Employee>(x => x.FinishDate).IsEqualTo(DateTime.MinValue)
  241. .Or(x => x.FinishDate).IsGreaterThan(DateTime.Today))
  242. : new Filter<Employee>(x => x.ID).IsEqualTo(App.EmployeeID);
  243. var employees = Client.Query<Employee>(
  244. employeeFilter,
  245. new Columns<Employee>(x => x.ID)
  246. .Add(x => x.Thumbnail.ID)
  247. .Add(x => x.Name));
  248. var anonymous = PRSDesktop.Resources.anonymous.AsBitmapImage();
  249. anonymous.Freeze();
  250. if (Security.IsAllowed<CanViewOthersTasks>())
  251. {
  252. var everyone = PRSDesktop.Resources.everyone.AsBitmapImage();
  253. everyone.Freeze();
  254. Employees.Add(new EmployeeModel(CoreUtils.FullGuid, "All Staff", Guid.Empty, everyone));
  255. Employees.Add(new EmployeeModel(Guid.Empty, "Unallocated", Guid.Empty, null));
  256. }
  257. foreach (var employee in employees.ToObjects<Employee>())
  258. {
  259. var name = employee.ID == App.EmployeeID ? "My Tasks" : employee.Name;
  260. var model = new EmployeeModel(employee.ID, name, employee.Thumbnail.ID, anonymous);
  261. if (employee.ID == App.EmployeeID)
  262. {
  263. Employees.Insert(0, model);
  264. }
  265. else
  266. {
  267. Employees.Add(model);
  268. }
  269. }
  270. }
  271. private void SetupEmployeeList()
  272. {
  273. if (Security.IsAllowed<CanViewOthersTasks>())
  274. {
  275. EmployeeListColumn.Width = new GridLength(1.0F, GridUnitType.Auto);
  276. var thumbnails = Employees
  277. .Select(e => e.ThumbnailID)
  278. .Where(x => x != Guid.Empty).ToArray();
  279. EmployeeList.ItemsSource = Employees;
  280. SelectedEmployee = Employees.First();
  281. EmployeeList.SelectedItem = SelectedEmployee;
  282. if (thumbnails.Any())
  283. new Client<Document>().Query(
  284. new Filter<Document>(x => x.ID).InList(thumbnails),
  285. new Columns<Document>(x => x.ID, x => x.Data),
  286. null,
  287. (data, error) =>
  288. {
  289. if (data != null)
  290. ProcessThumbnails(data);
  291. }
  292. );
  293. }
  294. else
  295. {
  296. EmployeeListColumn.Width = new GridLength(0.0F, GridUnitType.Pixel);
  297. EmployeeList.ItemsSource = Employees;
  298. SelectedEmployee = Employees.First();
  299. EmployeeList.SelectedItem = SelectedEmployee;
  300. }
  301. }
  302. private bool _updatingEmployees = false;
  303. private void ProcessThumbnails(CoreTable data)
  304. {
  305. Dispatcher.Invoke(() =>
  306. {
  307. foreach (var row in data.Rows)
  308. {
  309. var id = row.Get<Document, Guid>(x => x.ID);
  310. var model = Employees.FirstOrDefault(x => x.ThumbnailID.Equals(id));
  311. if (model != null)
  312. {
  313. model.Image = new BitmapImage();
  314. model.Image.LoadImage(row.Get<Document, byte[]>(x => x.Data));
  315. }
  316. }
  317. _updatingEmployees = true;
  318. EmployeeList.ItemsSource = null;
  319. EmployeeList.ItemsSource = Employees;
  320. SelectedEmployee = Employees.First();
  321. EmployeeList.SelectedItem = SelectedEmployee;
  322. _updatingEmployees = false;
  323. });
  324. }
  325. private void Employees_SelectionChanged(object sender, SelectionChangedEventArgs e)
  326. {
  327. if (_updatingEmployees || EventSuppressor.IsSet(Suppress.This))
  328. return;
  329. SelectedEmployee = (EmployeeList.SelectedItem as EmployeeModel)!;
  330. SelectedTasks.Clear();
  331. if (IsReady)
  332. Refresh();
  333. }
  334. #endregion
  335. #region Kanbans
  336. private List<TaskModel> AllTasks { get; set; } = new();
  337. private IEnumerable<TaskModel> Tasks => Columns.SelectMany(x => x.Tasks);
  338. private readonly List<TaskModel> SelectedTasks = new();
  339. private void CreateTask()
  340. {
  341. var result = Host.CreateKanban(
  342. kanban =>
  343. {
  344. kanban.EmployeeLink.ID = SelectedEmployee.ID != CoreUtils.FullGuid ? SelectedEmployee.ID : App.EmployeeID;
  345. kanban.ManagerLink.ID = App.EmployeeID;
  346. kanban.ManagerLink.UserLink.ID = ClientFactory.UserGuid;
  347. });
  348. if (result != null)
  349. Refresh();
  350. }
  351. private void DoEdit(TaskModel task)
  352. {
  353. var result = Host.EditReferences(new[] { task });
  354. if (result)
  355. {
  356. Refresh();
  357. }
  358. }
  359. private void EditTask_Executed(object sender, ExecutedRoutedEventArgs e)
  360. {
  361. if (e.Parameter is not TaskModel model) return;
  362. DoEdit(model);
  363. }
  364. private void OpenTaskMenu_Executed(object sender, ExecutedRoutedEventArgs e)
  365. {
  366. if (e.Parameter is not KanbanResources.OpenTaskMenuCommandArgs args) return;
  367. Host.PopulateMenu(this, args.Model, args.Menu);
  368. }
  369. private void SelectTask_Executed(object sender, ExecutedRoutedEventArgs e)
  370. {
  371. if (e.Parameter is not TaskModel model) return;
  372. if (!SelectedTasks.Remove(model))
  373. {
  374. SelectedTasks.Add(model);
  375. }
  376. }
  377. private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
  378. {
  379. e.CanExecute = true;
  380. }
  381. private void ItemsControl_DragOver(object sender, DragEventArgs e)
  382. {
  383. if (sender is not FrameworkElement element || element.Tag is not TasksByStatusColumn column) return;
  384. e.Effects = DragDropEffects.None;
  385. if (e.Data.GetDataPresent(typeof(TaskModel)))
  386. {
  387. var model = e.Data.GetData(typeof(TaskModel)) as TaskModel;
  388. if(model is not null && model.Status != column.Status && !SelectedTasks.Any(x => x.Locked))
  389. {
  390. e.Effects = DragDropEffects.Move;
  391. }
  392. }
  393. }
  394. private void ChangeStatus(IEnumerable<TaskModel> tasks, KanbanStatus status)
  395. {
  396. var models = tasks
  397. .Where(x => !x.Status.Equals(status))
  398. .Where(x => !x.Locked)
  399. .ToList();
  400. if (!models.Any())
  401. {
  402. return;
  403. }
  404. if(status == KanbanStatus.Complete)
  405. {
  406. if (!MessageWindow.ShowYesNo($"Are you sure you want to complete the selected tasks?", "Confirm Completion"))
  407. return;
  408. }
  409. var completed = DateTime.Now;
  410. var kanbans = Host.LoadKanbans(tasks, new Columns<Kanban>(x => x.ID).Add(x => x.Status));
  411. foreach (var kanban in kanbans)
  412. {
  413. kanban.Status = status;
  414. }
  415. if (status == KanbanStatus.Complete)
  416. {
  417. foreach (var kanban in kanbans)
  418. {
  419. kanban.Completed = completed;
  420. }
  421. }
  422. Client.Save(kanbans, $"Task Status Updated to {status}", (o, err) =>
  423. {
  424. if (err is not null)
  425. {
  426. CoreUtils.LogException("", err);
  427. }
  428. });
  429. foreach (var model in models)
  430. {
  431. model.Checked = false;
  432. model.Status = status;
  433. }
  434. if (status == KanbanStatus.Complete)
  435. {
  436. foreach (var model in models)
  437. {
  438. model.CompletedDate = completed;
  439. }
  440. }
  441. FilterKanbans();
  442. }
  443. private void ItemsControl_Drop(object sender, DragEventArgs e)
  444. {
  445. if (sender is not FrameworkElement element || element.Tag is not TasksByStatusColumn column) return;
  446. if (e.Data.GetDataPresent(typeof(TaskModel)))
  447. {
  448. ChangeStatus(SelectedModels(e.Data.GetData(typeof(TaskModel)) as TaskModel), column.Status);
  449. }
  450. }
  451. #endregion
  452. #region Filters
  453. private Guid JobFilterID = Guid.Empty;
  454. private string SearchText = "";
  455. private Guid SelectedType = CoreUtils.FullGuid;
  456. private void FilterButton_OnFilterRefresh()
  457. {
  458. Refresh();
  459. }
  460. private static Filter<T> GetSearchFilter<T>(Expression<Func<T, object?>> expression, string searchText) where T : Entity, new()
  461. {
  462. Filter<T>? result = null;
  463. var comps = searchText.Trim().Split(' ');
  464. foreach (var comp in comps)
  465. result = result == null ? new Filter<T>(expression).Contains(comp) : result.And(expression).Contains(comp);
  466. return result ?? new Filter<T>().All();
  467. }
  468. private Filter<KanbanSubscriber> GetKanbanSubscriberFilter()
  469. {
  470. var filter = new Filter<KanbanSubscriber>(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue);
  471. if (Host.Job != null)
  472. {
  473. if (Host.Job.ID != Guid.Empty)
  474. filter = filter.And(x => x.Kanban.JobLink.ID).IsEqualTo(Host.Job.ID);
  475. else
  476. filter = filter.And(x => x.Kanban.JobLink.ID).None();
  477. }
  478. // All Tasks (EmployeeID.HasValue == false) or Unallocated (EmployeeID = Guid.Empty) are retrieved directly from the Kanban Table
  479. // so if we are here, we can assume that we are pulling subscriber data
  480. var empfilter = new Filter<KanbanSubscriber>(x => x.Employee.ID).IsEqualTo(SelectedEmployee.ID);
  481. filter.Ands.Add(empfilter);
  482. if (SelectedEmployee.ID != App.EmployeeID)
  483. filter = filter.And(x => x.Kanban.Private).IsEqualTo(false);
  484. return filter;
  485. }
  486. private Filter<Kanban>? GetKanbanFilter()
  487. {
  488. var filters = new Filters<Kanban>();
  489. filters.Add(new Filter<Kanban>(x => x.Closed).IsEqualTo(DateTime.MinValue));
  490. filters.Add(FilterButton.GetFilter());
  491. if (Host.Job != null)
  492. {
  493. if (Host.Job.ID != Guid.Empty)
  494. filters.Add(new Filter<Kanban>(x => x.JobLink.ID).IsEqualTo(Host.Job.ID));
  495. else
  496. filters.Add(new Filter<Kanban>(x => x.JobLink.ID).None());
  497. }
  498. if (SelectedEmployee.ID != CoreUtils.FullGuid)
  499. {
  500. if (SelectedEmployee.ID != Guid.Empty)
  501. {
  502. var empfilter = new Filter<Kanban>(x => x.EmployeeLink.ID).IsEqualTo(SelectedEmployee.ID)
  503. .Or(x => x.ManagerLink.ID).IsEqualTo(SelectedEmployee.ID);
  504. filters.Add(empfilter);
  505. }
  506. else
  507. {
  508. filters.Add(new Filter<Kanban>(x => x.EmployeeLink.ID).IsEqualTo(SelectedEmployee.ID));
  509. }
  510. }
  511. if (SelectedEmployee.ID != App.EmployeeID)
  512. filters.Add(new Filter<Kanban>(x => x.Private).IsEqualTo(false));
  513. return filters.Combine();
  514. }
  515. private void TaskTypesLabel_OnClick(object sender, RoutedEventArgs e)
  516. {
  517. var list = new MasterList(typeof(KanbanType));
  518. list.ShowDialog();
  519. SetupKanbanTypesLookup(LoadKanbanTypes());
  520. }
  521. private void TaskTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
  522. {
  523. if (!IsReady || EventSuppressor.IsSet(Suppress.This))
  524. return;
  525. if (e.AddedItems.Count > 0)
  526. {
  527. var item = (KeyValuePair<Guid, string>)e.AddedItems[0];
  528. SelectedType = item.Key;
  529. }
  530. else
  531. {
  532. SelectedType = CoreUtils.FullGuid;
  533. }
  534. Host.KanbanSettings.StatusSettings.SelectedType = SelectedType;
  535. Host.SaveSettings();
  536. FilterKanbans();
  537. }
  538. private void JobFilterBtn_OnClick(object sender, RoutedEventArgs e)
  539. {
  540. if (JobFilterID != Guid.Empty)
  541. {
  542. JobFilterBtn.Content = "Filter Job";
  543. JobFilterID = Guid.Empty;
  544. FilterKanbans();
  545. return;
  546. }
  547. var window = new ThemableWindow();
  548. var grid = new JobGrid();
  549. grid.Reconfigure(options =>
  550. {
  551. options.Remove(DynamicGridOption.EditRows);
  552. options.Remove(DynamicGridOption.DeleteRows);
  553. options.Remove(DynamicGridOption.AddRows);
  554. options.Remove(DynamicGridOption.MultiSelect);
  555. options.Remove(DynamicGridOption.ExportData);
  556. options.Remove(DynamicGridOption.ImportData);
  557. });
  558. grid.OnSelectItem += (object sender, DynamicGridSelectionEventArgs e) =>
  559. {
  560. if (grid.SelectedRows.Count() == 0)
  561. return;
  562. else
  563. {
  564. var item = grid.SelectedRows[0];
  565. AddJobFilter(item);
  566. window.Close();
  567. }
  568. };
  569. grid.Refresh(true, true);
  570. window.Content = grid;
  571. window.ShowDialog();
  572. }
  573. private void AddJobFilter(CoreRow item)
  574. {
  575. JobFilterID = item.Get<Job, Guid>(x => x.ID);
  576. JobFilterBtn.Content = item.Get<Job, string>(x => x.JobNumber) + " (click to cancel)";
  577. FilterKanbans();
  578. }
  579. private void IncludeCompleted_Checked(object sender, RoutedEventArgs e)
  580. {
  581. if (!IsReady)
  582. return;
  583. Host.KanbanSettings.StatusSettings.IncludeCompleted = IncludeCompleted.IsChecked ?? false;
  584. Host.SaveSettings();
  585. SetupColumns();
  586. FilterKanbans();
  587. }
  588. private void IncludeObserved_Checked(object sender, RoutedEventArgs e)
  589. {
  590. if (!IsReady)
  591. return;
  592. Host.KanbanSettings.StatusSettings.IncludeObserved = IncludeObserved.IsChecked ?? false;
  593. Host.SaveSettings();
  594. FilterKanbans();
  595. }
  596. private void IncludeLocked_Checked(object sender, RoutedEventArgs e)
  597. {
  598. if (!IsReady)
  599. return;
  600. Host.KanbanSettings.StatusSettings.IncludeLocked = IncludeLocked.IsChecked ?? false;
  601. Host.SaveSettings();
  602. FilterKanbans();
  603. }
  604. private void Search_KeyUp(object sender, KeyEventArgs e)
  605. {
  606. if (string.IsNullOrWhiteSpace(Search.Text) || e.Key == Key.Return)
  607. {
  608. SearchText = Search.Text;
  609. FilterKanbans();
  610. }
  611. }
  612. #endregion
  613. #region Refresh
  614. private static Columns<Kanban> GetKanbanColumns()
  615. {
  616. return new Columns<Kanban>(
  617. x => x.ID,
  618. x => x.DueDate,
  619. x => x.Completed,
  620. x => x.Summary,
  621. x => x.Status,
  622. x => x.EmployeeLink.ID,
  623. x => x.ManagerLink.ID,
  624. x => x.Notes,
  625. x => x.Title,
  626. x => x.JobLink.ID,
  627. x => x.JobLink.JobNumber,
  628. x => x.JobLink.Name,
  629. x => x.Type.ID,
  630. x => x.Type.Code,
  631. x => x.Number,
  632. x => x.Attachments,
  633. x => x.EstimatedTime,
  634. x => x.Locked);
  635. }
  636. public void Refresh()
  637. {
  638. using var cursor = new WaitCursor();
  639. IEnumerable<Kanban> kanbans;
  640. if (SelectedEmployee.ID != CoreUtils.FullGuid && SelectedEmployee.ID != Guid.Empty)
  641. {
  642. var filter = new Filter<Kanban>(x => x.ID).InQuery(GetKanbanSubscriberFilter(), x => x.Kanban.ID);
  643. filter.And(FilterButton.GetFilter() ?? new Filter<Kanban>().All());
  644. kanbans = Client.Query(
  645. filter,
  646. GetKanbanColumns().Cast<Kanban>(),
  647. new SortOrder<Kanban>(x => x.DueDate) { Direction = SortDirection.Ascending }
  648. ).ToObjects<Kanban>();
  649. }
  650. else
  651. {
  652. kanbans = new Client<Kanban>().Query(
  653. GetKanbanFilter(),
  654. GetKanbanColumns().Cast<Kanban>(),
  655. new SortOrder<Kanban>(x => x.DueDate) { Direction = SortDirection.Ascending }
  656. ).ToObjects<Kanban>();
  657. }
  658. AllTasks = CreateModels(kanbans).ToList();
  659. FilterKanbans();
  660. }
  661. private IEnumerable<TaskModel> CreateModels(IEnumerable<Kanban> kanbans)
  662. {
  663. foreach(var kanban in kanbans)
  664. {
  665. TaskModel? model = null;
  666. try
  667. {
  668. model = new TaskModel();
  669. var employee = Employees.FirstOrDefault(x => x.ID == kanban.EmployeeLink.ID);
  670. var manager = Employees.FirstOrDefault(x => x.ID == kanban.ManagerLink.ID);
  671. model.Title = kanban.Title;
  672. model.ID = kanban.ID;
  673. model.Description = kanban.Summary ?? "";
  674. model.Status = kanban.Status;
  675. var colour = SelectedEmployee.ID == Guid.Empty
  676. || SelectedEmployee.ID == CoreUtils.FullGuid
  677. || kanban.EmployeeLink.ID == SelectedEmployee.ID
  678. ? TaskModel.KanbanColor(kanban.DueDate, kanban.Completed)
  679. : (kanban.ManagerLink.ID == SelectedEmployee.ID
  680. ? Color.Silver
  681. : Color.Plum);
  682. if (kanban.Locked)
  683. {
  684. colour = colour.MixColors(0.5F, Color.White);
  685. }
  686. model.Color = System.Windows.Media.Color.FromArgb(colour.A, colour.R, colour.G, colour.B);
  687. model.Image = employee?.Image;
  688. model.Attachments = kanban.Attachments > 0;
  689. model.DueDate = kanban.DueDate;
  690. model.CompletedDate = kanban.Completed;
  691. model.Locked = kanban.Locked;
  692. model.EstimatedTime = kanban.EstimatedTime;
  693. var notes = new List<List<string>> { new() };
  694. if (kanban.Notes is not null)
  695. {
  696. foreach (var line in kanban.Notes)
  697. {
  698. if (line.Equals("==================================="))
  699. {
  700. notes.Add(new());
  701. }
  702. else
  703. {
  704. notes.Last().Add(line);
  705. }
  706. }
  707. model.Notes = string.Join(
  708. "\n===================================\n",
  709. notes.Reverse<List<string>>().Select(x => string.Join('\n', x)));
  710. }
  711. model.EmployeeID = kanban.EmployeeLink.ID;
  712. model.ManagerID = kanban.ManagerLink.ID;
  713. var employeeString = "";
  714. if (kanban.EmployeeLink.ID != SelectedEmployee.ID)
  715. {
  716. if (kanban.EmployeeLink.ID == Guid.Empty)
  717. {
  718. employeeString = "Unallocated";
  719. }
  720. else
  721. {
  722. employeeString = employee is not null
  723. ? (employee.ID == App.EmployeeID
  724. ? App.EmployeeName
  725. : employee.Name)
  726. : "";
  727. }
  728. }
  729. var managerString = "";
  730. if (kanban.ManagerLink.ID != SelectedEmployee.ID)
  731. {
  732. if (kanban.ManagerLink.ID != Guid.Empty)
  733. {
  734. managerString = manager is not null
  735. ? (manager.ID == App.EmployeeID
  736. ? App.EmployeeName
  737. : manager.Name)
  738. : "";
  739. }
  740. }
  741. model.Manager = managerString;
  742. if (!string.IsNullOrEmpty(employeeString))
  743. {
  744. if (!managerString.IsNullOrWhiteSpace() && !managerString.Equals(employeeString))
  745. {
  746. model.AssignedTo = $"Assigned to {employeeString} by {managerString}";
  747. }
  748. else
  749. {
  750. model.AssignedTo = $"Assigned to {employeeString}";
  751. }
  752. }
  753. else
  754. {
  755. if (!managerString.IsNullOrWhiteSpace())
  756. {
  757. model.AssignedTo = $"Allocated by {managerString}";
  758. }
  759. else
  760. {
  761. model.AssignedTo = "";
  762. }
  763. }
  764. model.JobID = kanban.JobLink.ID;
  765. model.JobNumber = kanban.JobLink.JobNumber.NotWhiteSpaceOr("");
  766. model.JobName = kanban.JobLink.Name;
  767. model.Checked = SelectedTasks.Any(x => x.ID == model.ID);
  768. model.Type = new KanbanType
  769. {
  770. ID = kanban.Type.ID,
  771. Code = kanban.Type.Code
  772. };
  773. model.Number = kanban.Number;
  774. }
  775. catch(Exception e)
  776. {
  777. CoreUtils.LogException("", e);
  778. }
  779. if(model is not null)
  780. {
  781. yield return model;
  782. }
  783. }
  784. }
  785. /// <summary>
  786. /// Take the full list of kanbans loaded from the database, and filter based on the search UI elements, filtering into the columns.
  787. /// </summary>
  788. private void FilterKanbans()
  789. {
  790. IEnumerable<TaskModel> filtered;
  791. if (JobFilterID == Guid.Empty)
  792. {
  793. filtered = AllTasks;
  794. }
  795. else
  796. {
  797. filtered = AllTasks.Where(x => x.JobSearch(JobFilterID));
  798. }
  799. if (!Host.KanbanSettings.StatusSettings.IncludeLocked)
  800. {
  801. filtered = filtered.Where(x => !x.Locked);
  802. }
  803. if (!Host.KanbanSettings.StatusSettings.IncludeObserved
  804. && SelectedEmployee.ID != CoreUtils.FullGuid)
  805. {
  806. filtered = filtered.Where(x => x.EmployeeID == SelectedEmployee.ID || x.ManagerID == SelectedEmployee.ID);
  807. }
  808. if (!Host.KanbanSettings.StatusSettings.IncludeCompleted)
  809. {
  810. filtered = filtered.Where(x => x.CompletedDate.IsEmpty());
  811. }
  812. if (SelectedType != CoreUtils.FullGuid)
  813. {
  814. filtered = filtered.Where(x => x.Type.ID == SelectedType);
  815. }
  816. filtered = filtered.Where(x => x.Search(SearchText.Split()))
  817. .OrderBy(x => x.EmployeeID == SelectedEmployee.ID ? 0 : 1)
  818. .ThenBy(x => x.DueDate);
  819. SelectedTasks.Clear();
  820. foreach (var column in Columns)
  821. {
  822. column.Tasks.Clear();
  823. }
  824. foreach (var task in filtered)
  825. {
  826. var column = GetColumn(task.Status);
  827. column?.Tasks.Add(task);
  828. if (task.Checked)
  829. {
  830. SelectedTasks.Add(task);
  831. }
  832. }
  833. }
  834. #endregion
  835. #region ITaskControl
  836. public ITaskHost Host { get; set; }
  837. public KanbanViewType KanbanViewType => KanbanViewType.Status;
  838. public bool IsReady { get; set; }
  839. public string SectionName => "Tasks By Status";
  840. public DataModel DataModel(Selection selection)
  841. {
  842. var ids = SelectedModels().Select(x => x.ID).ToArray();
  843. return new AutoDataModel<Kanban>(new Filter<Kanban>(x => x.ID).InList(ids));
  844. }
  845. public IEnumerable<TaskModel> SelectedModels(TaskModel? sender = null)
  846. {
  847. if(sender is null)
  848. {
  849. return SelectedTasks;
  850. }
  851. else
  852. {
  853. var result = SelectedTasks.ToList();
  854. if (!result.Contains(sender))
  855. {
  856. result.Add(sender);
  857. }
  858. return result;
  859. }
  860. }
  861. #endregion
  862. private void Export_Click(object sender, RoutedEventArgs e)
  863. {
  864. var form = new DynamicExportForm(typeof(Kanban), GetKanbanColumns().ColumnNames());
  865. if (form.ShowDialog() != true)
  866. return;
  867. var export = new Client<Kanban>().Query(
  868. GetKanbanFilter(),
  869. new Columns<Kanban>(form.Fields),
  870. LookupFactory.DefineSort<Kanban>()
  871. );
  872. var employee = "Tasks for All Staff";
  873. if (SelectedEmployee.ID != CoreUtils.FullGuid)
  874. {
  875. if (SelectedEmployee.ID == Guid.Empty)
  876. {
  877. employee = "Unallocated Tasks";
  878. }
  879. else
  880. {
  881. var model = Employees.FirstOrDefault(x => x.ID == SelectedEmployee.ID);
  882. employee = model == null ? "Tasks for (Unknown)" : "Tasks for " + (model.ID == App.EmployeeID ? App.EmployeeName : model.Name);
  883. }
  884. }
  885. ExcelExporter.DoExport<Kanban>(
  886. export,
  887. string.Format(
  888. "{0} ({1:dd-MMM-yy})",
  889. employee,
  890. DateTime.Today
  891. )
  892. );
  893. }
  894. private KanbanViewMode _mode;
  895. public KanbanViewMode Mode
  896. {
  897. get => _mode;
  898. set
  899. {
  900. _mode = value;
  901. OnPropertyChanged();
  902. }
  903. }
  904. private void ViewType_SelectionChanged(object sender, SelectionChangedEventArgs e)
  905. {
  906. if (!IsReady || EventSuppressor.IsSet(Suppress.This))
  907. return;
  908. Mode = ViewType.SelectedIndex switch
  909. {
  910. 0 => KanbanViewMode.Full,
  911. 1 => KanbanViewMode.Compact,
  912. _ => KanbanViewMode.Full
  913. };
  914. Host.KanbanSettings.StatusSettings.CompactView = Mode == KanbanViewMode.Compact;
  915. Host.SaveSettings();
  916. }
  917. }