PostUtils.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using InABox.Core.Postable;
  5. using InABox.DynamicGrid;
  6. using InABox.Wpf;
  7. using InABox.WPF;
  8. using Syncfusion.UI.Xaml.Diagram;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics.CodeAnalysis;
  12. using System.Drawing;
  13. using System.Globalization;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Windows;
  18. using System.Windows.Controls;
  19. using System.Windows.Media.Imaging;
  20. namespace PRSDesktop;
  21. public class PullResultGrid<T> : DynamicItemsListGrid<T>
  22. where T : BaseObject, IPostable, new()
  23. {
  24. private static readonly BitmapImage tick = InABox.Wpf.Resources.tick.AsBitmapImage();
  25. private static readonly BitmapImage link = PRSDesktop.Resources.link.AsBitmapImage();
  26. private static readonly BitmapImage refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
  27. private class ResultItem(PullResultItem<T> item, bool selected)
  28. {
  29. public PullResultItem<T> Item { get; set; } = item;
  30. public bool Selected { get; set; } = selected;
  31. }
  32. public bool CanSave => _items.Any(x => x.Selected);
  33. private List<ResultItem> _items;
  34. public IEnumerable<PullResultItem<T>> Selected => _items.Where(x => x.Selected).Select(x => x.Item);
  35. protected DynamicGridCustomColumnsComponent<T> ColumnsComponent;
  36. public PullResultGrid(IPullResult<T> result)
  37. {
  38. _items = result.PulledEntities.Where(x => x.Item.PostedStatus != PostedStatus.PostFailed).Select(x => new ResultItem(x, false)).ToList();
  39. Items = _items.Select(x => x.Item.Item).ToList();
  40. ColumnsComponent = new DynamicGridCustomColumnsComponent<T>(this, typeof(T).Name);
  41. }
  42. protected override DynamicGridColumns LoadColumns()
  43. {
  44. return ColumnsComponent.LoadColumns();
  45. }
  46. protected override void SaveColumns(DynamicGridColumns columns)
  47. {
  48. ColumnsComponent.SaveColumns(columns);
  49. }
  50. protected override void LoadColumnsMenu(ContextMenu menu)
  51. {
  52. ColumnsComponent.LoadColumnsMenu(menu);
  53. }
  54. private ResultItem? GetItem(CoreRow? row)
  55. {
  56. return row is not null ? _items[_recordmap[row].Index] : null;
  57. }
  58. protected override void Init()
  59. {
  60. base.Init();
  61. ActionColumns.Add(new DynamicImageColumn(Selected_Image, Selected_Click) { Position = DynamicActionColumnPosition.Start });
  62. ActionColumns.Add(new DynamicImageColumn(Action_Image)
  63. {
  64. Position = DynamicActionColumnPosition.Start,
  65. ToolTip = Action_ToolTip
  66. });
  67. }
  68. private FrameworkElement? Action_ToolTip(DynamicActionColumn column, CoreRow? row)
  69. {
  70. var item = GetItem(row);
  71. if(item is null)
  72. {
  73. return column.TextToolTip("Item Import Action");
  74. }
  75. else if(item.Item.Type == PullResultType.Linked)
  76. {
  77. return column.TextToolTip("Existing PRS item linked to external item.");
  78. }
  79. else if(item.Item.Type == PullResultType.Updated)
  80. {
  81. return column.TextToolTip("Existing PRS item updated to external item.");
  82. }
  83. else if(item.Item.Type == PullResultType.New)
  84. {
  85. return column.TextToolTip("New item imported.");
  86. }
  87. else
  88. {
  89. return null;
  90. }
  91. }
  92. private BitmapImage? Action_Image(CoreRow? row)
  93. {
  94. var item = GetItem(row);
  95. if(item is null)
  96. {
  97. return null;
  98. }
  99. else if(item.Item.Type == PullResultType.Linked)
  100. {
  101. return link;
  102. }
  103. else if(item.Item.Type == PullResultType.Updated)
  104. {
  105. return refresh;
  106. }
  107. else
  108. {
  109. return null;
  110. }
  111. }
  112. private BitmapImage? Selected_Image(CoreRow? row)
  113. {
  114. var item = GetItem(row);
  115. return (item is null || item.Selected)
  116. ? tick
  117. : null;
  118. }
  119. private bool Selected_Click(CoreRow? row)
  120. {
  121. var item = GetItem(row);
  122. if(item is not null)
  123. {
  124. item.Selected = !item.Selected;
  125. DoChanged();
  126. InvalidateRow(row!);
  127. return false;
  128. }
  129. else
  130. {
  131. var menu = new ContextMenu();
  132. menu.AddItem("Select All", null, () =>
  133. {
  134. foreach (var item in _items)
  135. {
  136. item.Selected = true;
  137. }
  138. DoChanged();
  139. InvalidateGrid();
  140. });
  141. menu.AddItem("Deselect All", null, () =>
  142. {
  143. foreach (var item in _items)
  144. {
  145. item.Selected = false;
  146. }
  147. DoChanged();
  148. InvalidateGrid();
  149. });
  150. menu.IsOpen = true;
  151. return false;
  152. }
  153. }
  154. protected override void DoReconfigure(DynamicGridOptions options)
  155. {
  156. base.DoReconfigure(options);
  157. options.Clear();
  158. options.SelectColumns = true;
  159. options.FilterRows = true;
  160. }
  161. }
  162. public static class PostUtils
  163. {
  164. private static readonly Inflector.Inflector inflector = new(new CultureInfo("en"));
  165. public static void PostEntities<T>(IDataModel<T> model, Action refresh, Action? configurePost = null)
  166. where T : Entity, IPostable, IRemotable, IPersistent, new()
  167. {
  168. bool retry;
  169. do
  170. {
  171. retry = false;
  172. try
  173. {
  174. var result = PosterUtils.Process(model);
  175. if (result is null)
  176. {
  177. MessageWindow.ShowMessage($"Processing failed", "Processing failed");
  178. refresh();
  179. }
  180. else
  181. {
  182. var failedMessages = new List<string>();
  183. var successCount = 0;
  184. foreach (var entity in result.PostedEntities)
  185. {
  186. if (entity.PostedStatus == PostedStatus.PostFailed)
  187. {
  188. failedMessages.Add(entity.PostedNote);
  189. }
  190. else
  191. {
  192. successCount++;
  193. }
  194. }
  195. if (successCount == 0)
  196. {
  197. MessageWindow.ShowMessage($"Processing failed:\n - {string.Join("\n - ", failedMessages)}", "Processing failed.");
  198. }
  199. else if (failedMessages.Count == 0)
  200. {
  201. MessageWindow.ShowMessage($"Processing successful; {successCount} items processed", "Processing successful.");
  202. }
  203. else
  204. {
  205. MessageWindow.ShowMessage($"{successCount} items succeeded, but {failedMessages.Count} failed:\n - {string.Join("\n - ", failedMessages)}", "Partial success");
  206. }
  207. refresh();
  208. }
  209. }
  210. catch (EmptyPostException)
  211. {
  212. MessageWindow.ShowMessage($"Please select at least one {typeof(T).Name}.", "Select items");
  213. }
  214. catch (PostFailedMessageException e)
  215. {
  216. MessageWindow.ShowMessage(e.Message, "Post failed");
  217. }
  218. catch (RepostedException)
  219. {
  220. MessageWindow.ShowMessage("At least one of the items you selected has already been processed. Processing cancelled.", "Already processed");
  221. }
  222. catch (PostCancelledException)
  223. {
  224. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  225. }
  226. catch (MissingSettingException e)
  227. {
  228. if (configurePost is not null && Security.CanConfigurePost<T>())
  229. {
  230. if (MessageWindow.ShowYesNo($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  231. "Configure Processing?"))
  232. {
  233. bool success = false;
  234. if (e.SettingsType.IsAssignableTo(typeof(IGlobalPosterSettings)))
  235. {
  236. success = PostableSettingsGrid.ConfigureGlobalPosterSettings(e.SettingsType);
  237. }
  238. else
  239. {
  240. success = PostableSettingsGrid.ConfigurePosterSettings<T>(e.SettingsType);
  241. }
  242. if (success && MessageWindow.ShowYesNo("Settings updated; Would you like to retry the post?", "Retry?"))
  243. {
  244. retry = true;
  245. }
  246. else
  247. {
  248. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  249. }
  250. }
  251. else
  252. {
  253. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  254. }
  255. }
  256. else
  257. {
  258. MessageWindow.ShowMessage($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}", "Unconfigured");
  259. }
  260. }
  261. catch (MissingSettingsException)
  262. {
  263. if (configurePost is not null && Security.CanConfigurePost<T>())
  264. {
  265. if (MessageWindow.ShowYesNo($"Processing has not been configured for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  266. "Configure Processing?"))
  267. {
  268. configurePost();
  269. }
  270. else
  271. {
  272. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  273. }
  274. }
  275. else
  276. {
  277. MessageWindow.ShowMessage($"Processing has not been configured for {inflector.Pluralize(typeof(T).Name)}!", "Unconfigured");
  278. }
  279. }
  280. catch (Exception e)
  281. {
  282. MessageWindow.ShowError("Processing failed.", e);
  283. refresh();
  284. }
  285. } while (retry);
  286. }
  287. public static bool ShowPullResultGrid<T>(IPullResult<T> result, [NotNullWhen(true)] out List<PullResultItem<T>>? items)
  288. where T : Entity, IPostable, IRemotable, IPersistent, new()
  289. {
  290. var resultGrid = new PullResultGrid<T>(result);
  291. var window = new DynamicContentDialog(resultGrid)
  292. {
  293. Title = "Select items to import:",
  294. CanSave = false
  295. };
  296. resultGrid.OnChanged += (o, e) => window.CanSave = resultGrid.CanSave;
  297. resultGrid.Refresh(true, true);
  298. if(window.ShowDialog() == true)
  299. {
  300. items = resultGrid.Selected.ToList();
  301. Client.Save(items.Select(x => x.Item), "Posted by user.");
  302. return true;
  303. }
  304. else
  305. {
  306. items = null;
  307. return false;
  308. }
  309. }
  310. public static void PullEntities<T>(Action refresh, Action? configurePost = null)
  311. where T : Entity, IPostable, IRemotable, IPersistent, new()
  312. {
  313. bool retry;
  314. do
  315. {
  316. retry = false;
  317. try
  318. {
  319. var result = PosterUtils.Pull<T>();
  320. if (result is null)
  321. {
  322. MessageWindow.ShowMessage($"Import failed", "Import failed");
  323. refresh();
  324. }
  325. else
  326. {
  327. List<PullResultItem<T>>? items;
  328. if (!result.PulledEntities.Any(x => x.Item.PostedStatus != PostedStatus.PostFailed))
  329. {
  330. items = result.PulledEntities.ToList();
  331. }
  332. else
  333. {
  334. ShowPullResultGrid(result, out items);
  335. }
  336. if (items is null)
  337. {
  338. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  339. }
  340. else
  341. {
  342. var failedMessages = new List<string>();
  343. var successCount = 0;
  344. var importCount = 0;
  345. var updateCount = 0;
  346. var linkCount = 0;
  347. foreach (var item in items)
  348. {
  349. if (item.Item.PostedStatus == PostedStatus.PostFailed)
  350. {
  351. failedMessages.Add(item.Item.PostedNote);
  352. }
  353. else
  354. {
  355. successCount++;
  356. switch (item.Type)
  357. {
  358. case PullResultType.New:
  359. importCount++;
  360. break;
  361. case PullResultType.Linked:
  362. linkCount++;
  363. break;
  364. case PullResultType.Updated:
  365. default:
  366. updateCount++;
  367. break;
  368. }
  369. }
  370. }
  371. if (failedMessages.Count > 0 && successCount == 0)
  372. {
  373. MessageWindow.ShowMessage($"Import failed:\n - {string.Join("\n - ", failedMessages)}", "Import failed.");
  374. }
  375. else if (failedMessages.Count == 0)
  376. {
  377. if (successCount == 0)
  378. {
  379. MessageWindow.ShowMessage($"Nothing imported.", "Import successful.");
  380. }
  381. else
  382. {
  383. MessageWindow.ShowMessage($"Import successful; {importCount} items imported, {linkCount} items linked.", "Import successful.");
  384. }
  385. }
  386. else
  387. {
  388. MessageWindow.ShowMessage($"{successCount} items succeeded, but {failedMessages.Count} failed:\n - {string.Join("\n - ", failedMessages)}", "Partial success");
  389. }
  390. refresh();
  391. }
  392. }
  393. }
  394. catch (PullFailedMessageException e)
  395. {
  396. MessageWindow.ShowMessage(e.Message, "Import failed");
  397. }
  398. catch (PullCancelledException)
  399. {
  400. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  401. }
  402. catch (MissingSettingException e)
  403. {
  404. if (configurePost is not null && Security.CanConfigurePost<T>())
  405. {
  406. if (MessageWindow.ShowYesNo($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  407. "Configure Import?"))
  408. {
  409. bool success = false;
  410. if (e.SettingsType.IsAssignableTo(typeof(IGlobalPosterSettings)))
  411. {
  412. success = PostableSettingsGrid.ConfigureGlobalPosterSettings(e.SettingsType);
  413. }
  414. else
  415. {
  416. success = PostableSettingsGrid.ConfigurePosterSettings<T>(e.SettingsType);
  417. }
  418. if (success && MessageWindow.ShowYesNo("Settings updated; Would you like to retry the import?", "Retry?"))
  419. {
  420. retry = true;
  421. }
  422. else
  423. {
  424. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  425. }
  426. }
  427. else
  428. {
  429. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  430. }
  431. }
  432. else
  433. {
  434. MessageWindow.ShowMessage($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}", "Unconfigured");
  435. }
  436. }
  437. catch (MissingSettingsException)
  438. {
  439. if (configurePost is not null && Security.CanConfigurePost<T>())
  440. {
  441. if (MessageWindow.ShowYesNo($"Importing has not been configured for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  442. "Configure Import?"))
  443. {
  444. configurePost();
  445. }
  446. else
  447. {
  448. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  449. }
  450. }
  451. else
  452. {
  453. MessageWindow.ShowMessage($"Importing has not been configured for {inflector.Pluralize(typeof(T).Name)}!", "Unconfigured");
  454. }
  455. }
  456. catch (Exception e)
  457. {
  458. MessageWindow.ShowError("Import failed.", e);
  459. refresh();
  460. }
  461. } while (retry);
  462. }
  463. public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, Action? configurePost = null)
  464. where T : Entity, IPostable, IRemotable, IPersistent, new()
  465. {
  466. if (!Security.CanPost<T>()) return;
  467. var postSettings = PosterUtils.LoadPostableSettings<T>();
  468. if (!postSettings.PosterType.IsNullOrWhiteSpace())
  469. {
  470. var posterEngine = PosterUtils.GetEngine(typeof(T));
  471. Bitmap? image = null;
  472. if (postSettings.Thumbnail.ID != Guid.Empty)
  473. {
  474. var icon = new Client<Document>()
  475. .Load(new Filter<Document>(x => x.ID).IsEqualTo(postSettings.Thumbnail.ID)).FirstOrDefault();
  476. if (icon?.Data?.Any() == true)
  477. image = new ImageConverter().ConvertFrom(icon.Data) as Bitmap;
  478. }
  479. host.CreatePanelAction(new PanelAction
  480. {
  481. Caption = postSettings.ButtonName.NotWhiteSpaceOr($"Process {inflector.Pluralize(typeof(T).Name)}"),
  482. Image = image ?? PRSDesktop.Resources.edit,
  483. OnExecute = action =>
  484. {
  485. PostEntities(
  486. model(),
  487. refresh,
  488. configurePost);
  489. }
  490. });
  491. if(posterEngine.Get(out var posterEngineType, out var _) && posterEngineType.HasInterface(typeof(IPullerEngine<>)) && postSettings.ShowPullButton)
  492. {
  493. host.CreatePanelAction(new PanelAction($"Import {inflector.Pluralize(typeof(T).Name)}", image ?? PRSDesktop.Resources.doc_xls, action =>
  494. {
  495. PullEntities<T>(refresh);
  496. }));
  497. }
  498. if (postSettings.ShowClearButton)
  499. {
  500. host.CreatePanelAction(new PanelAction
  501. {
  502. Caption = "Clear Posted Flag",
  503. Image = image ?? PRSDesktop.Resources.refresh,
  504. OnExecute = action =>
  505. {
  506. var dataModel = model();
  507. foreach(var (key, table) in dataModel.ModelTables)
  508. {
  509. table.IsDefault = false;
  510. }
  511. dataModel.SetColumns<T>(Columns.Required<T>().Add(x => x.PostedStatus).Add(x => x.PostedReference).Add(x => x.PostedNote).Add(x => x.Posted));
  512. dataModel.SetIsDefault<T>(true);
  513. dataModel.LoadModel();
  514. var items = dataModel.GetTable<T>().ToArray<T>();
  515. foreach(var item in items)
  516. {
  517. item.PostedStatus = PostedStatus.NeverPosted;
  518. item.PostedReference = "";
  519. item.PostedNote = "";
  520. item.Posted = DateTime.MinValue;
  521. }
  522. Client.Save(items, "Cleared posted flag");
  523. refresh();
  524. }
  525. });
  526. }
  527. }
  528. if (configurePost is not null)
  529. {
  530. host.CreateSetupAction(new PanelAction
  531. {
  532. Caption = $"Configure {CoreUtils.Neatify(typeof(T).Name)} Processing",
  533. OnExecute = action =>
  534. {
  535. configurePost();
  536. }
  537. });
  538. }
  539. }
  540. public static void ConfigurePost<T>()
  541. where T : Entity, IPostable, IRemotable, IPersistent, new()
  542. {
  543. var postSettings = PosterUtils.LoadPostableSettings<T>();
  544. var grid = (DynamicGridUtils.CreateDynamicGrid(typeof(DynamicGrid<>), typeof(PostableSettings)) as DynamicGrid<PostableSettings>)!;
  545. if (grid.EditItems(new PostableSettings[] { postSettings }))
  546. {
  547. PosterUtils.SavePostableSettings<T>(postSettings);
  548. }
  549. }
  550. public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, bool allowConfig)
  551. where T : Entity, IPostable, IRemotable, IPersistent, new()
  552. {
  553. CreateToolbarButtons(host, model, refresh, allowConfig ? ConfigurePost<T> : null);
  554. }
  555. #region PostColumn
  556. private static readonly BitmapImage? post = PRSDesktop.Resources.post.AsBitmapImage();
  557. private static readonly BitmapImage? tick = PRSDesktop.Resources.tick.AsBitmapImage();
  558. private static readonly BitmapImage? warning = PRSDesktop.Resources.warning.AsBitmapImage();
  559. private static readonly BitmapImage? refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
  560. public static void AddPostColumn<T>(DynamicGrid<T> grid)
  561. where T : Entity, IPostable, IRemotable, IPersistent, new()
  562. {
  563. grid.HiddenColumns.Add(x => x.PostedStatus);
  564. grid.HiddenColumns.Add(x => x.PostedNote);
  565. grid.ActionColumns.Add(new DynamicImageColumn(
  566. row =>
  567. {
  568. if (row is null)
  569. return post;
  570. return row.Get<T, PostedStatus>(x => x.PostedStatus) switch
  571. {
  572. PostedStatus.PostFailed => warning,
  573. PostedStatus.Posted => tick,
  574. PostedStatus.RequiresRepost => refresh,
  575. PostedStatus.NeverPosted or _ => null,
  576. };
  577. },
  578. null)
  579. {
  580. ToolTip = (column, row) =>
  581. {
  582. if (row is null)
  583. {
  584. return column.TextToolTip($"{CoreUtils.Neatify(typeof(T).Name)} Processed Status");
  585. }
  586. return column.TextToolTip(row.Get<T, PostedStatus>(x => x.PostedStatus) switch
  587. {
  588. PostedStatus.PostFailed => "Post failed: " + row.Get<T, string>(x => x.PostedNote),
  589. PostedStatus.RequiresRepost => "Repost required: " + row.Get<T, string>(x => x.PostedNote),
  590. PostedStatus.Posted => "Processed",
  591. PostedStatus.NeverPosted or _ => "Not posted yet",
  592. });
  593. }
  594. });
  595. }
  596. #endregion
  597. }