IssuesGrid.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Configuration;
  4. using InABox.Core;
  5. using InABox.DynamicGrid;
  6. using InABox.Wpf.Editors;
  7. using InABox.WPF;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Diagnostics.CodeAnalysis;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  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> _client;
  22. private IQueryProvider<Kanban> Client
  23. {
  24. get
  25. {
  26. _client ??= ClientFactory.Create<Kanban>();
  27. return _client;
  28. }
  29. }
  30. public Guid CustomerID { get; set; }
  31. public static CustomProperty CustomerProperty = new CustomProperty
  32. {
  33. Name = "CustomerID",
  34. PropertyType = typeof(string),
  35. ClassType = typeof(Kanban)
  36. };
  37. public IssuesGrid() : base()
  38. {
  39. var cols = LookupFactory.DefineColumns<Kanban>();
  40. // Minimum Columns for Lookup values
  41. foreach (var col in cols)
  42. HiddenColumns.Add(col);
  43. HiddenColumns.Add(x => x.Notes);
  44. ActionColumns.Add(new DynamicMenuColumn(BuildMenu) { Position = DynamicActionColumnPosition.End });
  45. }
  46. protected override void Init()
  47. {
  48. }
  49. protected override void DoReconfigure(DynamicGridOptions options)
  50. {
  51. options.Clear();
  52. options.AddRows = true;
  53. options.EditRows = true;
  54. }
  55. private void BuildMenu(DynamicMenuColumn column, CoreRow? row)
  56. {
  57. if (row is null) return;
  58. var menu = column.GetMenu();
  59. menu.AddItem("Add note", null, row, AddNote_Click);
  60. menu.AddItem("Attach system logs", null, row, AttachLogs_Click);
  61. menu.AddSeparator();
  62. menu.AddItem("Close issue", null, row, CloseTask_Click);
  63. }
  64. private void AttachLogs_Click(CoreRow row)
  65. {
  66. var logFile = CoreUtils.GetLogFile();
  67. var data = File.ReadAllBytes(logFile);
  68. var doc = new Document();
  69. doc.Data = data;
  70. doc.CRC = CoreUtils.CalculateCRC(data);
  71. doc.FileName = Path.GetFileName(logFile);
  72. doc.TimeStamp = File.GetLastWriteTime(logFile);
  73. ClientFactory.Save(doc, "Attached logs to task.");
  74. var kanbanDocument = new KanbanDocument();
  75. kanbanDocument.DocumentLink.CopyFrom(doc);
  76. kanbanDocument.EntityLink.CopyFrom(row.ToObject<Kanban>());
  77. ClientFactory.Save(kanbanDocument, "Attached logs to task.");
  78. }
  79. public override Kanban CreateItem()
  80. {
  81. var item = base.CreateItem();
  82. item.UserProperties["CustomerID"] = CustomerID.ToString();
  83. item.Notes = [
  84. $"Created on PRS {CoreUtils.GetVersion()}"
  85. ];
  86. // item.Status = KanbanStatus.Open;
  87. return item;
  88. }
  89. private void AddNote_Click(CoreRow row)
  90. {
  91. var kanban = row.ToObject<Kanban>();
  92. var text = "";
  93. if(TextBoxDialog.Execute("Enter note:", ref text))
  94. {
  95. text = string.Format("{0:yyyy-MM-dd HH:mm:ss}: {1}", DateTime.Now, text);
  96. kanban.Notes = kanban.Notes.Concatenate([text]);
  97. SaveItem(kanban);
  98. Refresh(false, true);
  99. }
  100. }
  101. private void CloseTask_Click(CoreRow row)
  102. {
  103. var kanban = row.ToObject<Kanban>();
  104. kanban.Completed = DateTime.Now;
  105. kanban.Closed = DateTime.Now;
  106. SaveItem(kanban);
  107. Refresh(false, true);
  108. }
  109. private Column<Kanban>[] AllowedColumns = [
  110. new(x => x.Number),
  111. new(x => x.Title),
  112. new(x => x.Description),
  113. new(x => x.Notes)];
  114. protected override void CustomiseEditor(Kanban[] items, DynamicGridColumn column, BaseEditor editor)
  115. {
  116. base.CustomiseEditor(items, column, editor);
  117. if(!AllowedColumns.Any(x => x.Property == column.ColumnName))
  118. {
  119. editor.Editable = editor.Editable.Combine(Editable.Hidden);
  120. }
  121. }
  122. public virtual CoreTable LookupValues(DataLookupEditor editor, Type parent, string columnname, BaseObject[]? items)
  123. {
  124. var client = ClientFactory.Create(editor.Type);
  125. var filter = LookupFactory.DefineLookupFilter(parent, editor.Type, columnname, items ?? (Array.CreateInstance(parent, 0) as BaseObject[])!);
  126. var columns = LookupFactory.DefineLookupColumns(parent, editor.Type, columnname);
  127. foreach (var key in editor.OtherColumns.Keys)
  128. columns.Add(key);
  129. var sort = LookupFactory.DefineSort(editor.Type);
  130. var result = client.Query(filter, columns, sort);
  131. result.Columns.Add(new CoreColumn { ColumnName = "Display", DataType = typeof(string) });
  132. foreach (var row in result.Rows)
  133. {
  134. row["Display"] = LookupFactory.FormatLookup(parent, editor.Type, row, columnname);
  135. }
  136. return result;
  137. }
  138. protected override void DefineLookups(ILookupEditorControl sender, Kanban[] items, bool async = true)
  139. {
  140. if (sender.EditorDefinition is not DataLookupEditor editor)
  141. {
  142. base.DefineLookups(sender, items, async: async);
  143. return;
  144. }
  145. var colname = sender.ColumnName;
  146. if (async)
  147. {
  148. Task.Run(() =>
  149. {
  150. try
  151. {
  152. var values = LookupValues(editor, typeof(Kanban), colname, items);
  153. Dispatcher.Invoke(
  154. () =>
  155. {
  156. try
  157. {
  158. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  159. sender.LoadLookups(values);
  160. }
  161. catch (Exception e2)
  162. {
  163. Logger.Send(LogType.Information, typeof(Kanban).Name,
  164. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  165. }
  166. }
  167. );
  168. }
  169. catch (Exception e)
  170. {
  171. Logger.Send(LogType.Information, typeof(Kanban).Name,
  172. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  173. }
  174. });
  175. }
  176. else
  177. {
  178. var values = LookupValues(editor, typeof(Kanban), colname, items);
  179. sender.LoadLookups(values);
  180. }
  181. }
  182. public override DynamicEditorPages LoadEditorPages(Kanban item)
  183. {
  184. var pages = new DynamicEditorPages
  185. {
  186. new DynamicDocumentGrid<KanbanDocument, Kanban, KanbanLink>
  187. {
  188. Client = ClientFactory
  189. }
  190. };
  191. return pages;
  192. }
  193. protected override DynamicGridColumns LoadColumns()
  194. {
  195. var columns = new DynamicGridColumns<Kanban>();
  196. columns.Add(x => x.Number);
  197. columns.Add(x => x.Title);
  198. return columns;
  199. }
  200. #region Grid Stuff
  201. protected override string FormatRecordCount(int count)
  202. {
  203. return IsPaging
  204. ? $"{base.FormatRecordCount(count)} (loading..)"
  205. : base.FormatRecordCount(count);
  206. }
  207. protected override void Reload(
  208. Filters<Kanban> criteria, Columns<Kanban> columns, ref SortOrder<Kanban>? sort,
  209. CancellationToken token, Action<CoreTable?, Exception?> action)
  210. {
  211. criteria.Add(new Filter<Kanban>(x => x.Closed).IsEqualTo(Guid.Empty));
  212. criteria.Add(new Filter<Kanban>(CustomerProperty).IsEqualTo(CustomerID.ToString()));
  213. if(Options.PageSize > 0)
  214. {
  215. var inSort = sort;
  216. Task.Run(() =>
  217. {
  218. var page = CoreRange.Database(Options.PageSize);
  219. var filter = criteria.Combine();
  220. IsPaging = true;
  221. while (!token.IsCancellationRequested)
  222. {
  223. try
  224. {
  225. var data = Client.Query(filter, columns, inSort, page);
  226. data.Offset = page.Offset;
  227. IsPaging = data.Rows.Count == page.Limit;
  228. if (token.IsCancellationRequested)
  229. {
  230. break;
  231. }
  232. action(data, null);
  233. if (!IsPaging)
  234. break;
  235. // Proposal - Let's slow it down a bit to enhance UI responsiveness?
  236. Thread.Sleep(100);
  237. page.Next();
  238. }
  239. catch (Exception e)
  240. {
  241. action(null, e);
  242. break;
  243. }
  244. }
  245. }, token);
  246. }
  247. else
  248. {
  249. Client.Query(criteria.Combine(), columns, sort, null, action);
  250. }
  251. }
  252. public override Kanban[] LoadItems(IList<CoreRow> rows)
  253. {
  254. var results = new List<Kanban>(rows.Count);
  255. for (var i = 0; i < rows.Count; i += ChunkSize)
  256. {
  257. var chunk = rows.Skip(i).Take(ChunkSize);
  258. var filter = new Filter<Kanban>(x => x.ID).InList(chunk.Select(x => x.Get<Kanban, Guid>(x => x.ID)).ToArray());
  259. var columns = DynamicGridUtils.LoadEditorColumns(Columns.None<Kanban>());
  260. var data = Client.Query(filter, columns);
  261. results.AddRange(data.ToObjects<Kanban>());
  262. }
  263. return results.ToArray();
  264. }
  265. public override Kanban LoadItem(CoreRow row)
  266. {
  267. var id = row.Get<Kanban, Guid>(x => x.ID);
  268. return Client.Query(
  269. new Filter<Kanban>(x => x.ID).IsEqualTo(id),
  270. DynamicGridUtils.LoadEditorColumns(Columns.None<Kanban>())).ToObjects<Kanban>().FirstOrDefault()
  271. ?? throw new Exception($"No Kanban with ID {id}");
  272. }
  273. public override void SaveItem(Kanban item)
  274. {
  275. Client.Save(item, "Edited by User");
  276. }
  277. public override void SaveItems(IEnumerable<Kanban> items)
  278. {
  279. Client.Save(items, "Edited by User");
  280. }
  281. public override void DeleteItems(params CoreRow[] rows)
  282. {
  283. var deletes = new List<Kanban>();
  284. foreach (var row in rows)
  285. {
  286. var delete = new Kanban
  287. {
  288. ID = row.Get<Kanban, Guid>(x => x.ID)
  289. };
  290. deletes.Add(delete);
  291. }
  292. Client.Delete(deletes, "Deleted on User Request");
  293. }
  294. #endregion
  295. }