IssuesGrid.cs 15 KB

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