IssuesGrid.cs 14 KB

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