TasksByStatusControl.xaml.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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 string Category { 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(string category, string title)
  40. {
  41. Category = category;
  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("Open", "To Do"));
  157. Columns.Add(new TasksByStatusColumn("In Progress", "In Progress"));
  158. Columns.Add(new TasksByStatusColumn("Waiting", "Waiting for Others"));
  159. if (Host.KanbanSettings.StatusSettings.IncludeCompleted)
  160. Columns.Add(new TasksByStatusColumn("Complete", "Completed"));
  161. Columns.SupressNotification = false;
  162. }
  163. private TasksByStatusColumn? GetColumn(string category)
  164. {
  165. return Columns.FirstOrDefault(x => x.Category.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 = string.Equals(task.Category, column.Category) ? 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(true);
  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(true);
  350. }
  351. private void DoEdit(TaskModel task)
  352. {
  353. var result = Host.EditReferences(new[] { task });
  354. if (result)
  355. {
  356. Refresh(true);
  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.Category != column.Category && !SelectedTasks.Any(x => x.Locked))
  389. {
  390. e.Effects = DragDropEffects.Move;
  391. }
  392. }
  393. }
  394. private void ChangeStatus(IEnumerable<TaskModel> tasks, string status)
  395. {
  396. var models = tasks
  397. .Where(x => !x.Category.Equals(status))
  398. .Where(x => !x.Locked)
  399. .ToList();
  400. if (!models.Any())
  401. {
  402. return;
  403. }
  404. if(status.Equals(Kanban.COMPLETE))
  405. {
  406. if (MessageBox.Show($"Are you sure you want to complete the selected tasks?", "Confirm Completion",
  407. MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  408. return;
  409. }
  410. var completed = DateTime.Now;
  411. var kanbans = Host.LoadKanbans(tasks, new Columns<Kanban>(x => x.ID).Add(x => x.Category));
  412. foreach (var kanban in kanbans)
  413. {
  414. kanban.Category = status;
  415. }
  416. if (status.Equals(Kanban.COMPLETE))
  417. {
  418. foreach (var kanban in kanbans)
  419. {
  420. kanban.Completed = completed;
  421. }
  422. }
  423. Client.Save(kanbans, $"Task Status Updated to {status}", (o, err) =>
  424. {
  425. if (err is not null)
  426. {
  427. CoreUtils.LogException("", err);
  428. }
  429. });
  430. foreach (var model in models)
  431. {
  432. model.Checked = false;
  433. model.Category = status;
  434. }
  435. if (status.Equals(Kanban.COMPLETE))
  436. {
  437. foreach (var model in models)
  438. {
  439. model.CompletedDate = completed;
  440. }
  441. }
  442. FilterKanbans();
  443. }
  444. private void ItemsControl_Drop(object sender, DragEventArgs e)
  445. {
  446. if (sender is not FrameworkElement element || element.Tag is not TasksByStatusColumn column) return;
  447. e.Effects = DragDropEffects.None;
  448. if (e.Data.GetDataPresent(typeof(TaskModel)))
  449. {
  450. ChangeStatus(SelectedModels(e.Data.GetData(typeof(TaskModel)) as TaskModel), column.Category);
  451. }
  452. }
  453. #endregion
  454. #region Filters
  455. private Guid JobFilterID = Guid.Empty;
  456. private string SearchText = "";
  457. private Guid SelectedType = CoreUtils.FullGuid;
  458. private static Filter<T> GetSearchFilter<T>(Expression<Func<T, object?>> expression, string searchText) where T : Entity, new()
  459. {
  460. Filter<T>? result = null;
  461. var comps = searchText.Trim().Split(' ');
  462. foreach (var comp in comps)
  463. result = result == null ? new Filter<T>(expression).Contains(comp) : result.And(expression).Contains(comp);
  464. return result ?? new Filter<T>().All();
  465. }
  466. private Filter<KanbanSubscriber> GetKanbanSubscriberFilter()
  467. {
  468. var filter = new Filter<KanbanSubscriber>(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue);
  469. if (Host.Job != null)
  470. {
  471. if (Host.Job.ID != Guid.Empty)
  472. filter = filter.And(x => x.Kanban.JobLink.ID).IsEqualTo(Host.Job.ID);
  473. else
  474. filter = filter.And(x => x.Kanban.JobLink.ID).None();
  475. }
  476. // All Tasks (EmployeeID.HasValue == false) or Unallocated (EmployeeID = Guid.Empty) are retrieved directly from the Kanban Table
  477. // so if we are here, we can assume that we are pulling subscriber data
  478. var empfilter = new Filter<KanbanSubscriber>(x => x.Employee.ID).IsEqualTo(SelectedEmployee.ID);
  479. filter.Ands.Add(empfilter);
  480. if (SelectedEmployee.ID != App.EmployeeID)
  481. filter = filter.And(x => x.Kanban.Private).IsEqualTo(false);
  482. return filter;
  483. }
  484. private Filter<Kanban> GetKanbanFilter()
  485. {
  486. var filter = new Filter<Kanban>(x => x.Closed).IsEqualTo(DateTime.MinValue);
  487. if (Host.Job != null)
  488. {
  489. if (Host.Job.ID != Guid.Empty)
  490. filter = filter.And(x => x.JobLink.ID).IsEqualTo(Host.Job.ID);
  491. else
  492. filter = filter.And(x => x.JobLink.ID).None();
  493. }
  494. if (SelectedEmployee.ID != CoreUtils.FullGuid)
  495. {
  496. if (SelectedEmployee.ID != Guid.Empty)
  497. {
  498. var empfilter = new Filter<Kanban>(x => x.EmployeeLink.ID).IsEqualTo(SelectedEmployee.ID)
  499. .Or(x => x.ManagerLink.ID).IsEqualTo(SelectedEmployee.ID);
  500. filter.Ands.Add(empfilter);
  501. }
  502. else
  503. {
  504. filter = filter.And(x => x.EmployeeLink.ID).IsEqualTo(SelectedEmployee.ID);
  505. }
  506. }
  507. if (SelectedEmployee.ID != App.EmployeeID)
  508. filter = filter.And(x => x.Private).IsEqualTo(false);
  509. return filter;
  510. }
  511. private void TaskTypesLabel_OnClick(object sender, RoutedEventArgs e)
  512. {
  513. var list = new MasterList(typeof(KanbanType));
  514. list.ShowDialog();
  515. SetupKanbanTypesLookup(LoadKanbanTypes());
  516. }
  517. private void TaskTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
  518. {
  519. if (!IsReady || EventSuppressor.IsSet(Suppress.This))
  520. return;
  521. if (e.AddedItems.Count > 0)
  522. {
  523. var item = (KeyValuePair<Guid, string>)e.AddedItems[0];
  524. SelectedType = item.Key;
  525. }
  526. else
  527. {
  528. SelectedType = CoreUtils.FullGuid;
  529. }
  530. Host.KanbanSettings.StatusSettings.SelectedType = SelectedType;
  531. Host.SaveSettings();
  532. FilterKanbans();
  533. }
  534. private void JobFilterBtn_OnClick(object sender, RoutedEventArgs e)
  535. {
  536. if (JobFilterID != Guid.Empty)
  537. {
  538. JobFilterBtn.Content = "Filter Job";
  539. JobFilterID = Guid.Empty;
  540. FilterKanbans();
  541. return;
  542. }
  543. var window = new ThemableWindow();
  544. var grid = new JobGrid();
  545. grid.Reconfigure(options =>
  546. {
  547. options.Remove(DynamicGridOption.EditRows);
  548. options.Remove(DynamicGridOption.DeleteRows);
  549. options.Remove(DynamicGridOption.AddRows);
  550. options.Remove(DynamicGridOption.MultiSelect);
  551. options.Remove(DynamicGridOption.ExportData);
  552. options.Remove(DynamicGridOption.ImportData);
  553. });
  554. grid.OnSelectItem += (object sender, DynamicGridSelectionEventArgs e) =>
  555. {
  556. if (grid.SelectedRows.Count() == 0)
  557. return;
  558. else
  559. {
  560. var item = grid.SelectedRows[0];
  561. AddJobFilter(item);
  562. window.Close();
  563. }
  564. };
  565. grid.Refresh(true, true);
  566. window.Content = grid;
  567. window.ShowDialog();
  568. }
  569. private void AddJobFilter(CoreRow item)
  570. {
  571. JobFilterID = item.Get<Job, Guid>(x => x.ID);
  572. JobFilterBtn.Content = item.Get<Job, string>(x => x.JobNumber) + " (click to cancel)";
  573. FilterKanbans();
  574. }
  575. private void IncludeCompleted_Checked(object sender, RoutedEventArgs e)
  576. {
  577. if (!IsReady)
  578. return;
  579. Host.KanbanSettings.StatusSettings.IncludeCompleted = IncludeCompleted.IsChecked ?? false;
  580. Host.SaveSettings();
  581. SetupColumns();
  582. FilterKanbans();
  583. }
  584. private void IncludeObserved_Checked(object sender, RoutedEventArgs e)
  585. {
  586. if (!IsReady)
  587. return;
  588. Host.KanbanSettings.StatusSettings.IncludeObserved = IncludeObserved.IsChecked ?? false;
  589. Host.SaveSettings();
  590. FilterKanbans();
  591. }
  592. private void IncludeLocked_Checked(object sender, RoutedEventArgs e)
  593. {
  594. if (!IsReady)
  595. return;
  596. Host.KanbanSettings.StatusSettings.IncludeLocked = IncludeLocked.IsChecked ?? false;
  597. Host.SaveSettings();
  598. FilterKanbans();
  599. }
  600. private void Search_KeyUp(object sender, KeyEventArgs e)
  601. {
  602. if (string.IsNullOrWhiteSpace(Search.Text) || e.Key == Key.Return)
  603. {
  604. SearchText = Search.Text;
  605. FilterKanbans();
  606. }
  607. }
  608. #endregion
  609. #region Refresh
  610. private static Columns<IKanban> GetKanbanColumns()
  611. {
  612. return new Columns<IKanban>(
  613. x => x.ID,
  614. x => x.DueDate,
  615. x => x.Completed,
  616. x => x.Summary,
  617. x => x.Category,
  618. x => x.EmployeeLink.ID,
  619. x => x.ManagerLink.ID,
  620. x => x.Notes,
  621. x => x.Title,
  622. x => x.JobLink.ID,
  623. x => x.JobLink.JobNumber,
  624. x => x.JobLink.Name,
  625. x => x.Type.ID,
  626. x => x.Type.Code,
  627. x => x.Number,
  628. x => x.Attachments,
  629. x => x.Locked);
  630. }
  631. public void Refresh(bool resetselection)
  632. {
  633. using var cursor = new WaitCursor();
  634. IEnumerable<IKanban> kanbans;
  635. if (SelectedEmployee.ID != CoreUtils.FullGuid && SelectedEmployee.ID != Guid.Empty)
  636. {
  637. var columns = new Columns<KanbanSubscriber>();
  638. var kanbanColumn = new Column<KanbanSubscriber>(x => x.Kanban);
  639. foreach(var column in GetKanbanColumns().ColumnNames())
  640. {
  641. columns.Add(new Column<KanbanSubscriber>($"{kanbanColumn.Property}.{column}"));
  642. }
  643. kanbans = new Client<KanbanSubscriber>().Query(
  644. GetKanbanSubscriberFilter(),
  645. columns,
  646. new SortOrder<KanbanSubscriber>(x => x.Kanban.DueDate) { Direction = SortDirection.Ascending }
  647. ).ToObjects<KanbanSubscriber>().Select(x => x.Kanban);
  648. }
  649. else
  650. {
  651. kanbans = new Client<Kanban>().Query(
  652. GetKanbanFilter(),
  653. GetKanbanColumns().Cast<Kanban>(),
  654. new SortOrder<Kanban>(x => x.DueDate) { Direction = SortDirection.Ascending }
  655. ).ToObjects<Kanban>();
  656. }
  657. AllTasks = CreateModels(kanbans).ToList();
  658. FilterKanbans();
  659. }
  660. private IEnumerable<TaskModel> CreateModels(IEnumerable<IKanban> kanbans)
  661. {
  662. foreach(var kanban in kanbans)
  663. {
  664. TaskModel? model = null;
  665. try
  666. {
  667. model = new TaskModel();
  668. var employee = Employees.FirstOrDefault(x => x.ID == kanban.EmployeeLink.ID);
  669. var manager = Employees.FirstOrDefault(x => x.ID == kanban.ManagerLink.ID);
  670. model.Title = kanban.Title;
  671. model.ID = kanban.ID;
  672. model.Description = kanban.Summary ?? "";
  673. model.Category = kanban.Category;
  674. var colour = SelectedEmployee.ID == Guid.Empty
  675. || SelectedEmployee.ID == CoreUtils.FullGuid
  676. || kanban.EmployeeLink.ID == SelectedEmployee.ID
  677. ? TaskModel.KanbanColor(kanban.DueDate, kanban.Completed)
  678. : (kanban.ManagerLink.ID == SelectedEmployee.ID
  679. ? Color.Silver
  680. : Color.Plum);
  681. if (kanban.Locked)
  682. {
  683. colour = colour.MixColors(0.5F, Color.White);
  684. }
  685. model.Color = System.Windows.Media.Color.FromArgb(colour.A, colour.R, colour.G, colour.B);
  686. model.Image = employee?.Image;
  687. model.Attachments = kanban.Attachments > 0;
  688. model.DueDate = kanban.DueDate;
  689. model.CompletedDate = kanban.Completed;
  690. model.Locked = kanban.Locked;
  691. var notes = new List<List<string>> { new() };
  692. if (kanban.Notes is not null)
  693. {
  694. foreach (var line in kanban.Notes)
  695. {
  696. if (line.Equals("==================================="))
  697. {
  698. notes.Add(new());
  699. }
  700. else
  701. {
  702. notes.Last().Add(line);
  703. }
  704. }
  705. model.Notes = string.Join(
  706. "\n===================================\n",
  707. notes.Reverse<List<string>>().Select(x => string.Join('\n', x)));
  708. }
  709. model.EmployeeID = kanban.EmployeeLink.ID;
  710. model.ManagerID = kanban.ManagerLink.ID;
  711. var employeeString = "";
  712. if (kanban.EmployeeLink.ID != SelectedEmployee.ID)
  713. {
  714. if (kanban.EmployeeLink.ID == Guid.Empty)
  715. {
  716. employeeString = "Unallocated";
  717. }
  718. else
  719. {
  720. employeeString = employee is not null
  721. ? (employee.ID == App.EmployeeID
  722. ? App.EmployeeName
  723. : employee.Name)
  724. : "";
  725. }
  726. }
  727. var managerString = "";
  728. if (kanban.ManagerLink.ID != SelectedEmployee.ID)
  729. {
  730. if (kanban.ManagerLink.ID != Guid.Empty)
  731. {
  732. managerString = manager is not null
  733. ? (manager.ID == App.EmployeeID
  734. ? App.EmployeeName
  735. : manager.Name)
  736. : "";
  737. }
  738. }
  739. model.Manager = managerString;
  740. if (!string.IsNullOrEmpty(employeeString))
  741. {
  742. if (!managerString.IsNullOrWhiteSpace() && !managerString.Equals(employeeString))
  743. {
  744. model.AssignedTo = $"Assigned to {employeeString} by {managerString}";
  745. }
  746. else
  747. {
  748. model.AssignedTo = $"Assigned to {employeeString}";
  749. }
  750. }
  751. else
  752. {
  753. if (!managerString.IsNullOrWhiteSpace())
  754. {
  755. model.AssignedTo = $"Allocated by {managerString}";
  756. }
  757. }
  758. model.JobID = kanban.JobLink.ID;
  759. model.JobNumber = kanban.JobLink.JobNumber.NotWhiteSpaceOr("");
  760. model.JobName = kanban.JobLink.Name;
  761. model.Checked = SelectedTasks.Any(x => x.ID == model.ID);
  762. model.Type = new KanbanType
  763. {
  764. ID = kanban.Type.ID,
  765. Code = kanban.Type.Code
  766. };
  767. model.Number = kanban.Number;
  768. }
  769. catch(Exception e)
  770. {
  771. CoreUtils.LogException("", e);
  772. }
  773. if(model is not null)
  774. {
  775. yield return model;
  776. }
  777. }
  778. }
  779. /// <summary>
  780. /// Take the full list of kanbans loaded from the database, and filter based on the search UI elements, filtering into the columns.
  781. /// </summary>
  782. private void FilterKanbans()
  783. {
  784. Progress.Show("Loading");
  785. IEnumerable<TaskModel> filtered;
  786. if (JobFilterID == Guid.Empty)
  787. {
  788. filtered = AllTasks;
  789. }
  790. else
  791. {
  792. filtered = AllTasks.Where(x => x.JobSearch(JobFilterID));
  793. }
  794. if (!Host.KanbanSettings.StatusSettings.IncludeLocked)
  795. {
  796. filtered = filtered.Where(x => !x.Locked);
  797. }
  798. if (!Host.KanbanSettings.StatusSettings.IncludeObserved
  799. && SelectedEmployee.ID != CoreUtils.FullGuid)
  800. {
  801. filtered = filtered.Where(x => x.EmployeeID == SelectedEmployee.ID || x.ManagerID == SelectedEmployee.ID);
  802. }
  803. if (!Host.KanbanSettings.StatusSettings.IncludeCompleted)
  804. {
  805. filtered = filtered.Where(x => x.CompletedDate.IsEmpty());
  806. }
  807. if (SelectedType != CoreUtils.FullGuid)
  808. {
  809. filtered = filtered.Where(x => x.Type.ID == SelectedType);
  810. }
  811. filtered = filtered.Where(x => x.Search(SearchText.Split()))
  812. .OrderBy(x => x.EmployeeID == SelectedEmployee.ID ? 0 : 1)
  813. .ThenBy(x => x.DueDate);
  814. foreach (var column in Columns)
  815. {
  816. column.Tasks.Clear();
  817. }
  818. foreach (var task in filtered)
  819. {
  820. var column = GetColumn(task.Category);
  821. column?.Tasks.Add(task);
  822. }
  823. Progress.Close();
  824. }
  825. #endregion
  826. #region ITaskControl
  827. public ITaskHost Host { get; set; }
  828. public KanbanViewType KanbanViewType => KanbanViewType.Status;
  829. public bool IsReady { get; set; }
  830. public string SectionName => "Tasks By Status";
  831. public DataModel DataModel(Selection selection)
  832. {
  833. var ids = SelectedModels().Select(x => x.ID).ToArray();
  834. return new AutoDataModel<Kanban>(new Filter<Kanban>(x => x.ID).InList(ids));
  835. }
  836. public IEnumerable<TaskModel> SelectedModels(TaskModel? sender = null)
  837. {
  838. if(sender is null)
  839. {
  840. return SelectedTasks;
  841. }
  842. else
  843. {
  844. var result = SelectedTasks.ToList();
  845. if (!result.Contains(sender))
  846. {
  847. result.Add(sender);
  848. }
  849. return result;
  850. }
  851. }
  852. #endregion
  853. private void Export_Click(object sender, RoutedEventArgs e)
  854. {
  855. var form = new DynamicExportForm(typeof(Kanban), GetKanbanColumns().ColumnNames());
  856. if (form.ShowDialog() != true)
  857. return;
  858. var export = new Client<Kanban>().Query(
  859. GetKanbanFilter(),
  860. new Columns<Kanban>(form.Fields),
  861. LookupFactory.DefineSort<Kanban>()
  862. );
  863. var employee = "Tasks for All Staff";
  864. if (SelectedEmployee.ID != CoreUtils.FullGuid)
  865. {
  866. if (SelectedEmployee.ID == Guid.Empty)
  867. {
  868. employee = "Unallocated Tasks";
  869. }
  870. else
  871. {
  872. var model = Employees.FirstOrDefault(x => x.ID == SelectedEmployee.ID);
  873. employee = model == null ? "Tasks for (Unknown)" : "Tasks for " + (model.ID == App.EmployeeID ? App.EmployeeName : model.Name);
  874. }
  875. }
  876. ExcelExporter.DoExport<Kanban>(
  877. export,
  878. string.Format(
  879. "{0} ({1:dd-MMM-yy})",
  880. employee,
  881. DateTime.Today
  882. )
  883. );
  884. }
  885. private KanbanViewMode _mode;
  886. public KanbanViewMode Mode
  887. {
  888. get => _mode;
  889. set
  890. {
  891. _mode = value;
  892. OnPropertyChanged();
  893. }
  894. }
  895. private void ViewType_SelectionChanged(object sender, SelectionChangedEventArgs e)
  896. {
  897. if (!IsReady || EventSuppressor.IsSet(Suppress.This))
  898. return;
  899. Mode = ViewType.SelectedIndex switch
  900. {
  901. 0 => KanbanViewMode.Full,
  902. 1 => KanbanViewMode.Compact,
  903. _ => KanbanViewMode.Full
  904. };
  905. Host.KanbanSettings.StatusSettings.CompactView = Mode == KanbanViewMode.Compact;
  906. Host.SaveSettings();
  907. }
  908. }