PostUtils.cs 22 KB

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