TasksByStatusControl.xaml.cs 33 KB

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