DataEntryGrid.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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.MultiSelect)
  175. .Add(DynamicGridOption.DragSource)
  176. .Add(DynamicGridOption.DragTarget)
  177. .Add(DynamicGridOption.SelectColumns)
  178. .EndUpdate();
  179. }
  180. public static List<DataEntryTag> GetVisibleTagList()
  181. {
  182. var tags = new Client<DataEntryTag>().Query().ToObjects<DataEntryTag>().ToList();
  183. var tagsList = new List<DataEntryTag>();
  184. foreach (var tag in tags)
  185. {
  186. var entity = CoreUtils.GetEntityOrNull(tag.AppliesTo);
  187. if (entity is null || Security.CanView(entity))
  188. {
  189. var tagHasEmployee = new Client<DataEntryTagDistributionEmployee>()
  190. .Query(
  191. new Filter<DataEntryTagDistributionEmployee>(x => x.Tag.ID).IsEqualTo(tag.ID)
  192. .And(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  193. new Columns<DataEntryTagDistributionEmployee>(x => x.ID))
  194. .Rows.Any();
  195. if (tagHasEmployee)
  196. {
  197. tagsList.Add(tag);
  198. }
  199. }
  200. }
  201. return tagsList;
  202. }
  203. private List<DataEntryTag> GetVisibleTags()
  204. {
  205. _tags ??= GetVisibleTagList();
  206. return _tags;
  207. }
  208. public void DoExplode()
  209. {
  210. Guid tagID = Guid.Empty;
  211. foreach (var row in SelectedRows)
  212. {
  213. var rowTag = row.Get<DataEntryDocument, Guid>(x => x.Tag.ID);
  214. if (tagID == Guid.Empty)
  215. {
  216. tagID = rowTag;
  217. }
  218. else if (rowTag != tagID)
  219. {
  220. tagID = Guid.Empty;
  221. break;
  222. }
  223. }
  224. var docIDs = SelectedRows.Select(r => r.Get<DataEntryDocument, Guid>(c => c.Document.ID)).ToArray();
  225. var docs = new Client<Document>()
  226. .Query(
  227. new Filter<Document>(x => x.ID).InList(docIDs),
  228. new Columns<Document>(x => x.ID).Add(x => x.Data).Add(x => x.FileName))
  229. .ToObjects<Document>().ToDictionary(x => x.ID, x => x);
  230. var pages = new List<DataEntryReGroupWindow.Page>();
  231. string filename = "";
  232. foreach (var docID in docIDs)
  233. {
  234. if (docs.TryGetValue(docID, out var doc))
  235. {
  236. filename = doc.FileName;
  237. var ms = new MemoryStream(doc.Data);
  238. var pdfDoc = DataEntryReGroupWindow.RenderToPDF(doc.FileName, ms);
  239. foreach (var page in DataEntryReGroupWindow.SplitIntoPages(doc.FileName, pdfDoc))
  240. {
  241. pages.Add(page);
  242. }
  243. }
  244. }
  245. if (ShowDocumentWindow(pages, filename, tagID))
  246. {
  247. // ShowDocumentWindow already saves new scans, so we just need to get rid of the old ones.
  248. DeleteItems(SelectedRows);
  249. Refresh(false,true);
  250. }
  251. }
  252. public void DoRemove()
  253. {
  254. var updates = SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToArray();
  255. foreach (var update in updates)
  256. {
  257. update.Archived = DateTime.Now;
  258. DataEntryCache.Cache.Remove(update.Document.ID);
  259. }
  260. new Client<DataEntryDocument>().Save(updates,"Removed from Data Entry Panel");
  261. Refresh(false,true);
  262. }
  263. public void DoChangeTags(Guid tagid)
  264. {
  265. var updates = SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToArray();
  266. foreach (var update in updates)
  267. {
  268. if (update.Tag.ID != tagid)
  269. {
  270. update.Tag.ID = tagid;
  271. update.EntityID = Guid.Empty;
  272. }
  273. }
  274. new Client<DataEntryDocument>().Save(updates.Where(x=>x.IsChanged()),"Updated Tags on Data Entry Panel");
  275. Refresh(false,true);
  276. }
  277. public void DoChangeNote(string note)
  278. {
  279. var updates = SelectedRows.ToObjects<DataEntryDocument>().ToArray();
  280. foreach (var update in updates)
  281. {
  282. if (!string.Equals(update.Note, note))
  283. {
  284. update.Note = note;
  285. }
  286. }
  287. Client.Save(updates.Where(x => x.IsChanged()), "Updated Note on Data Entry Panel");
  288. Refresh(false, true);
  289. }
  290. protected override DragDropEffects OnRowsDragStart(CoreRow[] rows)
  291. {
  292. var table = new CoreTable();
  293. table.Columns.Add(new CoreColumn { ColumnName = "ID", DataType = typeof(Guid) });
  294. foreach(var row in rows)
  295. {
  296. var newRow = table.NewRow();
  297. newRow.Set<Document, Guid>(x => x.ID, row.Get<DataEntryDocument, Guid>(x => x.Document.ID));
  298. table.Rows.Add(newRow);
  299. }
  300. return DragTable(typeof(Document), table);
  301. }
  302. public void UploadDocument(string filename, byte[] data, Guid tagID)
  303. {
  304. var document = new Document
  305. {
  306. FileName = filename,
  307. CRC = CoreUtils.CalculateCRC(data),
  308. TimeStamp = DateTime.Now,
  309. Data = data
  310. };
  311. new Client<Document>().Save(document, "");
  312. var dataentry = new DataEntryDocument
  313. {
  314. Document =
  315. {
  316. ID = document.ID
  317. },
  318. Tag =
  319. {
  320. ID = tagID
  321. },
  322. Employee =
  323. {
  324. ID = App.EmployeeID
  325. }
  326. };
  327. if(Path.GetExtension(filename) == ".pdf")
  328. {
  329. dataentry.Thumbnail = ImageUtils.GetPDFThumbnail(data, 256, 256);
  330. }
  331. new Client<DataEntryDocument>().Save(dataentry, "");
  332. DataEntryCache.Cache.Add(new DataEntryCachedDocument(document));
  333. Dispatcher.BeginInvoke(() =>
  334. {
  335. Refresh(false, true);
  336. });
  337. }
  338. private static PdfDocumentBase CombinePages(IEnumerable<DataEntryReGroupWindow.Page> pages)
  339. {
  340. var document = new PdfDocument();
  341. foreach (var page in pages)
  342. {
  343. document.ImportPage(page.Pdf, page.PageIndex);
  344. }
  345. return document;
  346. }
  347. public bool ShowDocumentWindow(List<DataEntryReGroupWindow.Page> pages, string filename, Guid tagID)
  348. {
  349. var window = new DataEntryReGroupWindow(pages, filename, tagID);
  350. if (window.ShowDialog() == true)
  351. {
  352. Progress.ShowModal("Uploading Files", (progress) =>
  353. {
  354. foreach (var group in window.Groups)
  355. {
  356. progress.Report($"Uploading '{group.FileName}'");
  357. var doc = CombinePages(group.Pages);
  358. byte[] data;
  359. using (var ms = new MemoryStream())
  360. {
  361. doc.Save(ms);
  362. data = ms.ToArray();
  363. }
  364. UploadDocument(group.FileName, data, group.TagID);
  365. }
  366. });
  367. return true;
  368. }
  369. return false;
  370. }
  371. protected override void GenerateColumns(DynamicGridColumns columns)
  372. {
  373. columns.Add<DataEntryDocument, string>(x => x.Document.FileName, 0, "Filename", "", Alignment.MiddleLeft);
  374. columns.Add<DataEntryDocument, string>(x => x.Tag.Name, 100, "Tag", "", Alignment.MiddleLeft);
  375. }
  376. protected override void Reload(Filters<DataEntryDocument> criteria, Columns<DataEntryDocument> columns, ref SortOrder<DataEntryDocument>? sort, Action<CoreTable?, Exception?> action)
  377. {
  378. criteria.Add(new Filter<DataEntryDocument>(x => x.Archived).IsEqualTo(DateTime.MinValue));
  379. var tagFilter = new Filter<DataEntryDocument>(x => x.Tag.ID).InList(GetVisibleTags().Select(x => x.ID).ToArray());
  380. if (Security.IsAllowed<CanSetupDataEntryTags>())
  381. {
  382. tagFilter.Or(x => x.Tag.ID).IsEqualTo(Guid.Empty);
  383. }
  384. criteria.Add(tagFilter);
  385. base.Reload(criteria, columns, ref sort, action);
  386. }
  387. }