DataEntryGrid.cs 13 KB

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