IssuesGrid.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.DynamicGrid;
  4. using InABox.WPF;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Windows.Controls;
  13. using System.Windows.Media;
  14. using InABox.Wpf;
  15. namespace PRSDesktop.Forms.Issues;
  16. public class IssuesGrid : DynamicGrid<Kanban>, ISpecificGrid
  17. {
  18. private readonly int ChunkSize = 500;
  19. public IQueryProviderFactory ClientFactory { get; set; }
  20. private IQueryProvider<Kanban>? _kanbanClient;
  21. private IQueryProvider<Kanban> KanbanClient
  22. {
  23. get
  24. {
  25. _kanbanClient ??= ClientFactory.Create<Kanban>();
  26. return _kanbanClient;
  27. }
  28. }
  29. private IQueryProvider<Job>? _jobClient;
  30. private IQueryProvider<Job> JobClient
  31. {
  32. get
  33. {
  34. _jobClient ??= ClientFactory.Create<Job>();
  35. return _jobClient;
  36. }
  37. }
  38. public Guid CustomerID { get; set; }
  39. // public static CustomProperty CustomerProperty = new CustomProperty
  40. // {
  41. // Name = "CustomerID",
  42. // PropertyType = typeof(string),
  43. // ClassType = typeof(Kanban)
  44. // };
  45. public IssuesGrid() : base()
  46. {
  47. var cols = LookupFactory.DefineColumns<Kanban>();
  48. // Minimum Columns for Lookup values
  49. foreach (var col in cols)
  50. HiddenColumns.Add(col);
  51. HiddenColumns.Add(x => x.Notes);
  52. ActionColumns.Add(new DynamicMenuColumn(BuildMenu) { Position = DynamicActionColumnPosition.End });
  53. }
  54. private class UIComponent : DynamicGridGridUIComponent<Kanban>
  55. {
  56. private IssuesGrid Grid;
  57. public UIComponent(IssuesGrid grid)
  58. {
  59. Grid = grid;
  60. Parent = grid;
  61. }
  62. protected override Brush? GetCellBackground(CoreRow row, DynamicColumnBase column)
  63. {
  64. var status = row.Get<Kanban, KanbanStatus>(x => x.Status);
  65. var color = status == KanbanStatus.Open
  66. ? Colors.Orange
  67. : status == KanbanStatus.InProgress
  68. ? Colors.Plum
  69. : status == KanbanStatus.Waiting
  70. ? Colors.LightGreen
  71. : Colors.Silver;
  72. return color.ToBrush(0.5);
  73. }
  74. }
  75. protected override IDynamicGridUIComponent<Kanban> CreateUIComponent()
  76. {
  77. return new UIComponent(this);
  78. }
  79. protected override void Init()
  80. {
  81. AddButton("Check for Updates", PRSDesktop.Resources.autoupdate.AsBitmapImage(), CheckForUpdates);
  82. AddButton("Open Support Session", PRSDesktop.Resources.appicon.AsBitmapImage(), OpenSupportSession);
  83. }
  84. private bool OpenSupportSession(Button button, CoreRow[] rows)
  85. {
  86. SupportUtils.OpenSupportSession();
  87. return false;
  88. }
  89. private bool CheckForUpdates(Button button, CoreRow[] rows)
  90. {
  91. if (!SupportUtils.CheckForUpdates())
  92. {
  93. if (MessageWindow.ShowYesNo(
  94. "You appear to be using the latest version already!\n\nRun the installer anyway?", "Update"))
  95. {
  96. SupportUtils.DownloadAndRunInstaller();
  97. }
  98. }
  99. return false;
  100. }
  101. protected override void DoReconfigure(DynamicGridOptions options)
  102. {
  103. options.Clear();
  104. options.AddRows = true;
  105. options.EditRows = true;
  106. options.FilterRows = true;
  107. options.HideDatabaseFilters = true;
  108. }
  109. private void BuildMenu(DynamicMenuColumn column, CoreRow? row)
  110. {
  111. if (row is null) return;
  112. var menu = column.GetMenu();
  113. menu.AddItem("Add note", null, row, AddNote_Click);
  114. menu.AddItem("Attach system logs", null, row, AttachLogs_Click);
  115. menu.AddSeparator();
  116. menu.AddItem("Close issue", null, row, CloseTask_Click);
  117. }
  118. private void AttachLogs_Click(CoreRow row)
  119. {
  120. var logFile = CoreUtils.GetLogFile();
  121. var data = File.ReadAllBytes(logFile);
  122. var doc = new Document();
  123. doc.Data = data;
  124. doc.CRC = CoreUtils.CalculateCRC(data);
  125. doc.FileName = Path.GetFileName(logFile);
  126. doc.TimeStamp = File.GetLastWriteTime(logFile);
  127. ClientFactory.Save(doc, "Attached logs to task.");
  128. var kanbanDocument = new KanbanDocument();
  129. kanbanDocument.DocumentLink.CopyFrom(doc);
  130. kanbanDocument.EntityLink.CopyFrom(row.ToObject<Kanban>());
  131. ClientFactory.Save(kanbanDocument, "Attached logs to task.");
  132. }
  133. public override Kanban CreateItem()
  134. {
  135. var item = base.CreateItem();
  136. item.UserProperties["CustomerID"] = CustomerID.ToString();
  137. item.Notes = [
  138. $"Created on PRS {CoreUtils.GetVersion()} by {App.EmployeeName} ({App.EmployeeEmail})"
  139. ];
  140. // item.Status = KanbanStatus.Open;
  141. return item;
  142. }
  143. private void AddNote_Click(CoreRow row)
  144. {
  145. var kanban = row.ToObject<Kanban>();
  146. var text = "";
  147. if(TextBoxDialog.Execute("Enter note:", ref text))
  148. {
  149. text = string.Format("{0:yyyy-MM-dd HH:mm:ss}: {1}", DateTime.Now, text);
  150. kanban.Notes = kanban.Notes.Concatenate([text]);
  151. kanban.Status = KanbanStatus.InProgress;
  152. SaveItem(kanban);
  153. Refresh(false, true);
  154. }
  155. }
  156. private void CloseTask_Click(CoreRow row)
  157. {
  158. var kanban = row.ToObject<Kanban>();
  159. kanban.Completed = DateTime.Now;
  160. kanban.Closed = DateTime.Now;
  161. SaveItem(kanban);
  162. Refresh(false, true);
  163. }
  164. private Column<Kanban>[] AllowedColumns = [
  165. new(x => x.Number),
  166. new(x => x.Title),
  167. new(x => x.Description),
  168. new(x => x.Notes)];
  169. protected override void CustomiseEditor(Kanban[] items, DynamicGridColumn column, BaseEditor editor)
  170. {
  171. base.CustomiseEditor(items, column, editor);
  172. if(!AllowedColumns.Any(x => x.Property == column.ColumnName))
  173. {
  174. editor.Editable = editor.Editable.Combine(Editable.Hidden);
  175. }
  176. }
  177. public virtual CoreTable LookupValues(DataLookupEditor editor, Type parent, string columnname, BaseObject[]? items)
  178. {
  179. var client = ClientFactory.Create(editor.Type);
  180. var filter = LookupFactory.DefineLookupFilter(parent, editor.Type, columnname, items ?? (Array.CreateInstance(parent, 0) as BaseObject[])!);
  181. var columns = LookupFactory.DefineLookupColumns(parent, editor.Type, columnname);
  182. foreach (var key in editor.OtherColumns.Keys)
  183. columns.Add(key);
  184. var sort = LookupFactory.DefineSort(editor.Type);
  185. var result = client.Query(filter, columns, sort);
  186. result.Columns.Add(new CoreColumn { ColumnName = "Display", DataType = typeof(string) });
  187. foreach (var row in result.Rows)
  188. {
  189. row["Display"] = LookupFactory.FormatLookup(parent, editor.Type, row, columnname);
  190. }
  191. return result;
  192. }
  193. protected override void DefineLookups(ILookupEditorControl sender, Kanban[] items, bool async = true)
  194. {
  195. if (sender.EditorDefinition is not DataLookupEditor editor)
  196. {
  197. base.DefineLookups(sender, items, async: async);
  198. return;
  199. }
  200. var colname = sender.ColumnName;
  201. if (async)
  202. {
  203. Task.Run(() =>
  204. {
  205. try
  206. {
  207. var values = LookupValues(editor, typeof(Kanban), colname, items);
  208. Dispatcher.Invoke(
  209. () =>
  210. {
  211. try
  212. {
  213. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  214. sender.LoadLookups(values);
  215. }
  216. catch (Exception e2)
  217. {
  218. Logger.Send(LogType.Information, typeof(Kanban).Name,
  219. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  220. }
  221. }
  222. );
  223. }
  224. catch (Exception e)
  225. {
  226. Logger.Send(LogType.Information, typeof(Kanban).Name,
  227. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  228. }
  229. });
  230. }
  231. else
  232. {
  233. var values = LookupValues(editor, typeof(Kanban), colname, items);
  234. sender.LoadLookups(values);
  235. }
  236. }
  237. public override DynamicEditorPages LoadEditorPages(Kanban item)
  238. {
  239. var pages = new DynamicEditorPages
  240. {
  241. new DynamicDocumentGrid<KanbanDocument, Kanban, KanbanLink>
  242. {
  243. Client = ClientFactory
  244. }
  245. };
  246. return pages;
  247. }
  248. protected override DynamicGridColumns LoadColumns()
  249. {
  250. var columns = new DynamicGridColumns<Kanban>();
  251. columns.Add(x => x.Number, caption: "Ticket", width: 60, alignment: Alignment.MiddleCenter);
  252. columns.Add(x => x.Title);
  253. columns.Add(x => x.CreatedBy, caption: "Created By", width: 150);
  254. columns.Add(x => x.EmployeeLink.Name, caption: "Assigned To", width: 150);
  255. columns.Add(x => x.Type.Description, caption: "Type", width: 100, alignment: Alignment.MiddleCenter);
  256. columns.Add(x => x.Status, caption: "Status", width: 80, alignment: Alignment.MiddleCenter);
  257. return columns;
  258. }
  259. #region Grid Stuff
  260. protected override string FormatRecordCount(int count)
  261. {
  262. return IsPaging
  263. ? $"{base.FormatRecordCount(count)} (loading..)"
  264. : base.FormatRecordCount(count);
  265. }
  266. protected override void Reload(
  267. Filters<Kanban> criteria, Columns<Kanban> columns, ref SortOrder<Kanban>? sort,
  268. CancellationToken token, Action<CoreTable?, Exception?> action)
  269. {
  270. criteria.Add(new Filter<Kanban>(x => x.Closed).IsEqualTo(Guid.Empty));
  271. criteria.Add(new Filter<Kanban>(x => x.Status).IsNotEqualTo(KanbanStatus.Complete));
  272. criteria.Add(new Filter<Kanban>(x => x.JobLink.Customer.ID).IsEqualTo(CustomerID));
  273. //criteria.Add(new Filter<Kanban>(CustomerProperty).IsEqualTo(CustomerID.ToString()));
  274. if(Options.PageSize > 0)
  275. {
  276. var inSort = sort;
  277. Task.Run(() =>
  278. {
  279. var page = CoreRange.Database(Options.PageSize);
  280. var filter = criteria.Combine();
  281. IsPaging = true;
  282. while (!token.IsCancellationRequested)
  283. {
  284. try
  285. {
  286. var data = KanbanClient.Query(filter, columns, inSort, page);
  287. data.Offset = page.Offset;
  288. IsPaging = data.Rows.Count == page.Limit;
  289. if (token.IsCancellationRequested)
  290. {
  291. break;
  292. }
  293. action(data, null);
  294. if (!IsPaging)
  295. break;
  296. // Proposal - Let's slow it down a bit to enhance UI responsiveness?
  297. Thread.Sleep(100);
  298. page.Next();
  299. }
  300. catch (Exception e)
  301. {
  302. action(null, e);
  303. break;
  304. }
  305. }
  306. }, token);
  307. }
  308. else
  309. {
  310. KanbanClient.Query(criteria.Combine(), columns, sort, null, action);
  311. }
  312. }
  313. public override Kanban[] LoadItems(IList<CoreRow> rows)
  314. {
  315. var results = new List<Kanban>(rows.Count);
  316. for (var i = 0; i < rows.Count; i += ChunkSize)
  317. {
  318. var chunk = rows.Skip(i).Take(ChunkSize);
  319. var filter = new Filter<Kanban>(x => x.ID).InList(chunk.Select(x => x.Get<Kanban, Guid>(x => x.ID)).ToArray());
  320. var columns = DynamicGridUtils.LoadEditorColumns(Columns.None<Kanban>());
  321. var data = KanbanClient.Query(filter, columns);
  322. results.AddRange(data.ToObjects<Kanban>());
  323. }
  324. return results.ToArray();
  325. }
  326. public override Kanban LoadItem(CoreRow row)
  327. {
  328. var id = row.Get<Kanban, Guid>(x => x.ID);
  329. return KanbanClient.Query(
  330. new Filter<Kanban>(x => x.ID).IsEqualTo(id),
  331. DynamicGridUtils.LoadEditorColumns(Columns.None<Kanban>())).ToObjects<Kanban>().FirstOrDefault()
  332. ?? throw new Exception($"No Kanban with ID {id}");
  333. }
  334. public override void SaveItem(Kanban item)
  335. {
  336. CheckJob(item);
  337. KanbanClient.Save(item, "Edited by User");
  338. }
  339. private void CheckJob(Kanban item)
  340. {
  341. if (item.ID == Guid.Empty)
  342. {
  343. item.CreatedBy = App.EmployeeName;
  344. // Check if there is an open Project Job (ie installation or periodic billing) for this Client
  345. var job = JobClient.Query(
  346. new Filter<Job>(x => x.Customer.ID).IsEqualTo(CustomerID)
  347. .And(x => x.JobType).IsEqualTo(JobType.Project)
  348. .And(x => x.JobStatus.Active).IsEqualTo(true),
  349. Columns.None<Job>()
  350. .Add(x => x.ID)
  351. .Add(x=>x.DefaultScope.ID)
  352. ).ToObjects<Job>().FirstOrDefault();
  353. // No Job ? Create a service job for this ticket
  354. if (job == null)
  355. {
  356. job = new Job();
  357. job.Name = item.Title;
  358. job.Customer.ID = CustomerID;
  359. job.JobType = JobType.Service;
  360. job.Notes = item.Notes?.ToList().ToArray() ?? [];
  361. job.UserProperties.Clear();
  362. JobClient.Save(job, "Created by Client Issues Screen");
  363. }
  364. // Created Tickets should always have a job #!
  365. item.JobLink.ID = job.ID;
  366. item.JobScope.ID = job.DefaultScope.ID;
  367. }
  368. }
  369. public override void SaveItems(IEnumerable<Kanban> items)
  370. {
  371. var list = items.ToArray();
  372. foreach (var item in list)
  373. CheckJob(item);
  374. KanbanClient.Save(list, "Edited by User");
  375. }
  376. public override void DeleteItems(params CoreRow[] rows)
  377. {
  378. var deletes = new List<Kanban>();
  379. foreach (var row in rows)
  380. {
  381. var delete = new Kanban
  382. {
  383. ID = row.Get<Kanban, Guid>(x => x.ID)
  384. };
  385. deletes.Add(delete);
  386. }
  387. KanbanClient.Delete(deletes, "Deleted on User Request");
  388. }
  389. #endregion
  390. }