DataEntryGrid.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Configuration;
  4. using InABox.Core;
  5. using InABox.DynamicGrid;
  6. using InABox.WPF;
  7. using Syncfusion.Pdf;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Windows;
  13. using System.Windows.Media.Imaging;
  14. namespace PRSDesktop;
  15. public class DataEntryCachedDocument : ICachedDocument
  16. {
  17. public DateTime TimeStamp { get; set; }
  18. public Document? Document { get; set; }
  19. public Guid ID => Document?.ID ?? Guid.Empty;
  20. public DataEntryCachedDocument() { }
  21. public DataEntryCachedDocument(Document document)
  22. {
  23. Document = document;
  24. TimeStamp = document.TimeStamp;
  25. }
  26. public void DeserializeBinary(CoreBinaryReader reader, bool full)
  27. {
  28. TimeStamp = reader.ReadDateTime();
  29. if (full)
  30. {
  31. Document = reader.ReadObject<Document>();
  32. }
  33. }
  34. public void SerializeBinary(CoreBinaryWriter writer)
  35. {
  36. writer.Write(TimeStamp);
  37. if (Document is null)
  38. {
  39. throw new Exception("Cannot serialize incomplete CachedDocument");
  40. }
  41. writer.WriteObject(Document);
  42. }
  43. }
  44. public class DataEntryCache : DocumentCache<DataEntryCachedDocument>
  45. {
  46. public override TimeSpan MaxAge => TimeSpan.FromDays(new UserConfiguration<DataEntryPanelSettings>().Load().CacheAge);
  47. private static DataEntryCache? _cache;
  48. public static DataEntryCache Cache
  49. {
  50. get
  51. {
  52. _cache ??= DocumentCaches.GetOrRegister<DataEntryCache>();
  53. return _cache;
  54. }
  55. }
  56. public DataEntryCache(): base(nameof(DataEntryCache)) { }
  57. protected override DataEntryCachedDocument? LoadDocument(Guid id)
  58. {
  59. var document = Client.Query(new Filter<Document>(x => x.ID).IsEqualTo(id))
  60. .ToObjects<Document>().FirstOrDefault();
  61. if(document is not null)
  62. {
  63. return new DataEntryCachedDocument(document);
  64. }
  65. else
  66. {
  67. return null;
  68. }
  69. }
  70. /// <summary>
  71. /// Fetch a bunch of documents from the cache or the database, optionally checking against the timestamp listed in the database.
  72. /// </summary>
  73. /// <param name="ids"></param>
  74. /// <param name="checkTimestamp">
  75. /// If <see langword="true"/>, then loads <see cref="Document.TimeStamp"/> from the database for all cached documents,
  76. /// and if they are older, updates the cache.
  77. /// </param>
  78. public IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids, bool checkTimestamp = false)
  79. {
  80. var cached = new List<Guid>();
  81. var toLoad = new List<Guid>();
  82. foreach (var docID in ids)
  83. {
  84. if (Has(docID))
  85. {
  86. cached.Add(docID);
  87. }
  88. else
  89. {
  90. toLoad.Add(docID);
  91. }
  92. }
  93. var loadedCached = new List<Document>();
  94. if (cached.Count > 0)
  95. {
  96. var docs = Client.Query(
  97. new Filter<Document>(x => x.ID).InList(cached.ToArray()),
  98. new Columns<Document>(x => x.TimeStamp, x => x.ID));
  99. foreach (var doc in docs.ToObjects<Document>())
  100. {
  101. try
  102. {
  103. var timestamp = GetHeader(doc.ID).Document.TimeStamp;
  104. if (doc.TimeStamp > timestamp)
  105. {
  106. toLoad.Add(doc.ID);
  107. }
  108. else
  109. {
  110. loadedCached.Add(GetFull(doc.ID).Document.Document!);
  111. }
  112. }
  113. catch (Exception e)
  114. {
  115. CoreUtils.LogException("", e, "Error loading cached file");
  116. toLoad.Add(doc.ID);
  117. }
  118. }
  119. }
  120. if (toLoad.Count > 0)
  121. {
  122. var loaded = Client.Query(new Filter<Document>(x => x.ID).InList(toLoad.ToArray()))
  123. .ToObjects<Document>().ToList();
  124. foreach (var loadedDoc in loaded)
  125. {
  126. Add(new DataEntryCachedDocument(loadedDoc));
  127. }
  128. return loaded.Concat(loadedCached);
  129. }
  130. else
  131. {
  132. return loadedCached;
  133. }
  134. }
  135. }
  136. public class DataEntryGrid : DynamicDataGrid<DataEntryDocument>
  137. {
  138. private List<DataEntryTag>? _tags;
  139. public DataEntryGrid()
  140. {
  141. HiddenColumns.Add(x => x.Tag.ID);
  142. HiddenColumns.Add(x => x.Tag.AppliesTo);
  143. HiddenColumns.Add(x => x.Document.ID);
  144. HiddenColumns.Add(x => x.EntityID);
  145. HiddenColumns.Add(x => x.Archived);
  146. HiddenColumns.Add(x => x.Note);
  147. ActionColumns.Add(new DynamicImageColumn(LinkedImage) { Position = DynamicActionColumnPosition.Start });
  148. var tagFilter = new Filter<DataEntryDocument>(x => x.Tag.ID).InList(GetVisibleTags().Select(x => x.ID).ToArray());
  149. if (Security.IsAllowed<CanSetupDataEntryTags>())
  150. {
  151. tagFilter.Or(x => x.Tag.ID).IsEqualTo(Guid.Empty);
  152. }
  153. var docs = Client.Query(
  154. new Filter<DataEntryDocument>(x => x.Archived).IsEqualTo(DateTime.MinValue)
  155. .And(tagFilter),
  156. new Columns<DataEntryDocument>(x => x.Document.ID));
  157. DataEntryCache.Cache.ClearOld();
  158. DataEntryCache.Cache.EnsureStrict(docs.Rows.Select(x => x.Get<DataEntryDocument, Guid>(x => x.Document.ID)).ToArray());
  159. }
  160. private static readonly BitmapImage link = PRSDesktop.Resources.link.AsBitmapImage();
  161. private BitmapImage? LinkedImage(CoreRow? arg)
  162. {
  163. return arg == null
  164. ? link
  165. : arg.Get<DataEntryDocument, Guid>(x => x.EntityID) != Guid.Empty
  166. ? link
  167. : null;
  168. }
  169. protected override void DoReconfigure(FluentList<DynamicGridOption> options)
  170. {
  171. base.DoReconfigure(options);
  172. options.BeginUpdate()
  173. .Clear()
  174. .Add(DynamicGridOption.FilterRows)
  175. .Add(DynamicGridOption.MultiSelect)
  176. .Add(DynamicGridOption.DragSource)
  177. .Add(DynamicGridOption.DragTarget)
  178. .Add(DynamicGridOption.SelectColumns)
  179. .EndUpdate();
  180. }
  181. public static List<DataEntryTag> GetVisibleTagList()
  182. {
  183. var tags = new Client<DataEntryTag>().Query().ToObjects<DataEntryTag>().ToList();
  184. var tagsList = new List<DataEntryTag>();
  185. foreach (var tag in tags)
  186. {
  187. var entity = CoreUtils.GetEntityOrNull(tag.AppliesTo);
  188. if (entity is null || Security.CanView(entity))
  189. {
  190. var tagHasEmployee = new Client<DataEntryTagDistributionEmployee>()
  191. .Query(
  192. new Filter<DataEntryTagDistributionEmployee>(x => x.Tag.ID).IsEqualTo(tag.ID)
  193. .And(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  194. new Columns<DataEntryTagDistributionEmployee>(x => x.ID))
  195. .Rows.Any();
  196. if (tagHasEmployee)
  197. {
  198. tagsList.Add(tag);
  199. }
  200. }
  201. }
  202. return tagsList;
  203. }
  204. private List<DataEntryTag> GetVisibleTags()
  205. {
  206. _tags ??= GetVisibleTagList();
  207. return _tags;
  208. }
  209. public void DoExplode()
  210. {
  211. Guid tagID = Guid.Empty;
  212. foreach (var row in SelectedRows)
  213. {
  214. var rowTag = row.Get<DataEntryDocument, Guid>(x => x.Tag.ID);
  215. if (tagID == Guid.Empty)
  216. {
  217. tagID = rowTag;
  218. }
  219. else if (rowTag != tagID)
  220. {
  221. tagID = Guid.Empty;
  222. break;
  223. }
  224. }
  225. var docIDs = SelectedRows.Select(r => r.Get<DataEntryDocument, Guid>(c => c.Document.ID)).ToArray();
  226. var docs = new Client<Document>()
  227. .Query(
  228. new Filter<Document>(x => x.ID).InList(docIDs),
  229. new Columns<Document>(x => x.ID).Add(x => x.Data).Add(x => x.FileName))
  230. .ToObjects<Document>().ToDictionary(x => x.ID, x => x);
  231. var pages = new List<DataEntryReGroupWindow.Page>();
  232. string filename = "";
  233. foreach (var docID in docIDs)
  234. {
  235. if (docs.TryGetValue(docID, out var doc))
  236. {
  237. filename = doc.FileName;
  238. var ms = new MemoryStream(doc.Data);
  239. var pdfDoc = DataEntryReGroupWindow.RenderToPDF(doc.FileName, ms);
  240. foreach (var page in DataEntryReGroupWindow.SplitIntoPages(doc.FileName, pdfDoc))
  241. {
  242. pages.Add(page);
  243. }
  244. }
  245. }
  246. if (ShowDocumentWindow(pages, filename, tagID))
  247. {
  248. // ShowDocumentWindow already saves new scans, so we just need to get rid of the old ones.
  249. DeleteItems(SelectedRows);
  250. Refresh(false,true);
  251. }
  252. }
  253. public void DoRemove()
  254. {
  255. var updates = SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToArray();
  256. foreach (var update in updates)
  257. {
  258. update.Archived = DateTime.Now;
  259. DataEntryCache.Cache.Remove(update.Document.ID);
  260. }
  261. new Client<DataEntryDocument>().Save(updates,"Removed from Data Entry Panel");
  262. Refresh(false,true);
  263. }
  264. public void DoChangeTags(Guid tagid)
  265. {
  266. var updates = SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToArray();
  267. foreach (var update in updates)
  268. {
  269. if (update.Tag.ID != tagid)
  270. {
  271. update.Tag.ID = tagid;
  272. update.EntityID = Guid.Empty;
  273. }
  274. }
  275. new Client<DataEntryDocument>().Save(updates.Where(x=>x.IsChanged()),"Updated Tags on Data Entry Panel");
  276. Refresh(false,true);
  277. }
  278. public void DoChangeNote(string note)
  279. {
  280. var updates = SelectedRows.ToObjects<DataEntryDocument>().ToArray();
  281. foreach (var update in updates)
  282. {
  283. if (!string.Equals(update.Note, note))
  284. {
  285. update.Note = note;
  286. }
  287. }
  288. Client.Save(updates.Where(x => x.IsChanged()), "Updated Note on Data Entry Panel");
  289. Refresh(false, true);
  290. }
  291. protected override DragDropEffects OnRowsDragStart(CoreRow[] rows)
  292. {
  293. var table = new CoreTable();
  294. table.Columns.Add(new CoreColumn { ColumnName = "ID", DataType = typeof(Guid) });
  295. foreach(var row in rows)
  296. {
  297. var newRow = table.NewRow();
  298. newRow.Set<Document, Guid>(x => x.ID, row.Get<DataEntryDocument, Guid>(x => x.Document.ID));
  299. table.Rows.Add(newRow);
  300. }
  301. return DragTable(typeof(Document), table);
  302. }
  303. public void UploadDocument(string filename, byte[] data, Guid tagID)
  304. {
  305. var document = new Document
  306. {
  307. FileName = filename,
  308. CRC = CoreUtils.CalculateCRC(data),
  309. TimeStamp = DateTime.Now,
  310. Data = data
  311. };
  312. new Client<Document>().Save(document, "");
  313. var dataentry = new DataEntryDocument
  314. {
  315. Document =
  316. {
  317. ID = document.ID
  318. },
  319. Tag =
  320. {
  321. ID = tagID
  322. },
  323. Employee =
  324. {
  325. ID = App.EmployeeID
  326. }
  327. };
  328. if(Path.GetExtension(filename) == ".pdf")
  329. {
  330. dataentry.Thumbnail = ImageUtils.GetPDFThumbnail(data, 256, 256);
  331. }
  332. new Client<DataEntryDocument>().Save(dataentry, "");
  333. DataEntryCache.Cache.Add(new DataEntryCachedDocument(document));
  334. Dispatcher.BeginInvoke(() =>
  335. {
  336. Refresh(false, true);
  337. });
  338. }
  339. private static PdfDocumentBase CombinePages(IEnumerable<DataEntryReGroupWindow.Page> pages)
  340. {
  341. var document = new PdfDocument();
  342. foreach (var page in pages)
  343. {
  344. document.ImportPage(page.Pdf, page.PageIndex);
  345. }
  346. return document;
  347. }
  348. public bool ShowDocumentWindow(List<DataEntryReGroupWindow.Page> pages, string filename, Guid tagID)
  349. {
  350. var window = new DataEntryReGroupWindow(pages, filename, tagID);
  351. if (window.ShowDialog() == true)
  352. {
  353. Progress.ShowModal("Uploading Files", (progress) =>
  354. {
  355. foreach (var group in window.Groups)
  356. {
  357. progress.Report($"Uploading '{group.FileName}'");
  358. var doc = CombinePages(group.Pages);
  359. byte[] data;
  360. using (var ms = new MemoryStream())
  361. {
  362. doc.Save(ms);
  363. data = ms.ToArray();
  364. }
  365. UploadDocument(group.FileName, data, group.TagID);
  366. }
  367. });
  368. return true;
  369. }
  370. return false;
  371. }
  372. public override DynamicGridColumns GenerateColumns()
  373. {
  374. var columns = new DynamicGridColumns();
  375. columns.Add<DataEntryDocument, string>(x => x.Document.FileName, 0, "Filename", "", Alignment.MiddleLeft);
  376. columns.Add<DataEntryDocument, string>(x => x.Tag.Name, 100, "Tag", "", Alignment.MiddleLeft);
  377. return columns;
  378. }
  379. protected override void Reload(Filters<DataEntryDocument> criteria, Columns<DataEntryDocument> columns, ref SortOrder<DataEntryDocument>? sort, Action<CoreTable?, Exception?> action)
  380. {
  381. criteria.Add(new Filter<DataEntryDocument>(x => x.Archived).IsEqualTo(DateTime.MinValue));
  382. var tagFilter = new Filter<DataEntryDocument>(x => x.Tag.ID).InList(GetVisibleTags().Select(x => x.ID).ToArray());
  383. if (Security.IsAllowed<CanSetupDataEntryTags>())
  384. {
  385. tagFilter.Or(x => x.Tag.ID).IsEqualTo(Guid.Empty);
  386. }
  387. criteria.Add(tagFilter);
  388. base.Reload(criteria, columns, ref sort, action);
  389. }
  390. }