PostUtils.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. foreach (var item in items)
  275. {
  276. if (item.Item.PostedStatus == PostedStatus.PostFailed)
  277. {
  278. failedMessages.Add(item.Item.PostedNote);
  279. }
  280. else
  281. {
  282. successCount++;
  283. switch (item.Type)
  284. {
  285. case PullResultType.New:
  286. importCount++;
  287. break;
  288. case PullResultType.Updated:
  289. case PullResultType.Linked:
  290. default:
  291. updateCount++;
  292. break;
  293. }
  294. }
  295. }
  296. if (failedMessages.Count > 0 && successCount == 0)
  297. {
  298. MessageWindow.ShowMessage($"Import failed:\n - {string.Join("\n - ", failedMessages)}", "Import failed.");
  299. }
  300. else if (failedMessages.Count == 0)
  301. {
  302. if (successCount == 0)
  303. {
  304. MessageWindow.ShowMessage($"Nothing imported.", "Import successful.");
  305. }
  306. else
  307. {
  308. MessageWindow.ShowMessage($"Import successful; {importCount} items imported.", "Import successful.");
  309. }
  310. }
  311. else
  312. {
  313. MessageWindow.ShowMessage($"{successCount} items succeeded, but {failedMessages.Count} failed:\n - {string.Join("\n - ", failedMessages)}", "Partial success");
  314. }
  315. refresh();
  316. }
  317. }
  318. }
  319. catch (PullFailedMessageException e)
  320. {
  321. MessageWindow.ShowMessage(e.Message, "Import failed");
  322. }
  323. catch (PullCancelledException)
  324. {
  325. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  326. }
  327. catch (MissingSettingException e)
  328. {
  329. if (configurePost is not null && Security.CanConfigurePost<T>())
  330. {
  331. if (MessageWindow.ShowYesNo($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  332. "Configure Import?"))
  333. {
  334. bool success = false;
  335. if (e.SettingsType.IsAssignableTo(typeof(IGlobalPosterSettings)))
  336. {
  337. success = PostableSettingsGrid.ConfigureGlobalPosterSettings(e.SettingsType);
  338. }
  339. else
  340. {
  341. success = PostableSettingsGrid.ConfigurePosterSettings<T>(e.SettingsType);
  342. }
  343. if (success && MessageWindow.ShowYesNo("Settings updated; Would you like to retry the import?", "Retry?"))
  344. {
  345. retry = true;
  346. }
  347. else
  348. {
  349. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  350. }
  351. }
  352. else
  353. {
  354. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  355. }
  356. }
  357. else
  358. {
  359. MessageWindow.ShowMessage($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}", "Unconfigured");
  360. }
  361. }
  362. catch (MissingSettingsException)
  363. {
  364. if (configurePost is not null && Security.CanConfigurePost<T>())
  365. {
  366. if (MessageWindow.ShowYesNo($"Importing has not been configured for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  367. "Configure Import?"))
  368. {
  369. configurePost();
  370. }
  371. else
  372. {
  373. MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
  374. }
  375. }
  376. else
  377. {
  378. MessageWindow.ShowMessage($"Importing has not been configured for {inflector.Pluralize(typeof(T).Name)}!", "Unconfigured");
  379. }
  380. }
  381. catch (Exception e)
  382. {
  383. MessageWindow.ShowError("Import failed.", e);
  384. refresh();
  385. }
  386. } while (retry);
  387. }
  388. public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, Action? configurePost = null)
  389. where T : Entity, IPostable, IRemotable, IPersistent, new()
  390. {
  391. if (!Security.CanPost<T>()) return;
  392. var postSettings = PosterUtils.LoadPostableSettings<T>();
  393. if (!postSettings.PosterType.IsNullOrWhiteSpace())
  394. {
  395. var posterEngine = PosterUtils.GetEngine(typeof(T));
  396. Bitmap? image = null;
  397. if (postSettings.Thumbnail.ID != Guid.Empty)
  398. {
  399. var icon = new Client<Document>()
  400. .Load(new Filter<Document>(x => x.ID).IsEqualTo(postSettings.Thumbnail.ID)).FirstOrDefault();
  401. if (icon?.Data?.Any() == true)
  402. image = new ImageConverter().ConvertFrom(icon.Data) as Bitmap;
  403. }
  404. host.CreatePanelAction(new PanelAction
  405. {
  406. Caption = postSettings.ButtonName.NotWhiteSpaceOr($"Process {inflector.Pluralize(typeof(T).Name)}"),
  407. Image = image ?? PRSDesktop.Resources.edit,
  408. OnExecute = action =>
  409. {
  410. PostEntities(
  411. model(),
  412. refresh,
  413. configurePost);
  414. }
  415. });
  416. if(posterEngine.Get(out var posterEngineType, out var _) && posterEngineType.HasInterface(typeof(IPullerEngine<>)))
  417. {
  418. host.CreatePanelAction(new PanelAction($"Import {inflector.Pluralize(typeof(T).Name)}", image ?? PRSDesktop.Resources.doc_xls, action =>
  419. {
  420. PullEntities<T>(refresh);
  421. }));
  422. }
  423. if (postSettings.ShowClearButton)
  424. {
  425. host.CreatePanelAction(new PanelAction
  426. {
  427. Caption = "Clear Posted Flag",
  428. Image = image ?? PRSDesktop.Resources.refresh,
  429. OnExecute = action =>
  430. {
  431. var dataModel = model();
  432. foreach(var (key, table) in dataModel.ModelTables)
  433. {
  434. table.IsDefault = false;
  435. }
  436. dataModel.SetColumns<T>(Columns.Required<T>().Add(x => x.PostedStatus).Add(x => x.PostedReference).Add(x => x.PostedNote).Add(x => x.Posted));
  437. dataModel.SetIsDefault<T>(true);
  438. dataModel.LoadModel();
  439. var items = dataModel.GetTable<T>().ToArray<T>();
  440. foreach(var item in items)
  441. {
  442. item.PostedStatus = PostedStatus.NeverPosted;
  443. item.PostedReference = "";
  444. item.PostedNote = "";
  445. item.Posted = DateTime.MinValue;
  446. }
  447. Client.Save(items, "Cleared posted flag");
  448. refresh();
  449. }
  450. });
  451. }
  452. }
  453. if (configurePost is not null)
  454. {
  455. host.CreateSetupAction(new PanelAction
  456. {
  457. Caption = $"Configure {CoreUtils.Neatify(typeof(T).Name)} Processing",
  458. OnExecute = action =>
  459. {
  460. configurePost();
  461. }
  462. });
  463. }
  464. }
  465. public static void ConfigurePost<T>()
  466. where T : Entity, IPostable, IRemotable, IPersistent, new()
  467. {
  468. var postSettings = PosterUtils.LoadPostableSettings<T>();
  469. var grid = (DynamicGridUtils.CreateDynamicGrid(typeof(DynamicGrid<>), typeof(PostableSettings)) as DynamicGrid<PostableSettings>)!;
  470. if (grid.EditItems(new PostableSettings[] { postSettings }))
  471. {
  472. PosterUtils.SavePostableSettings<T>(postSettings);
  473. }
  474. }
  475. public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, bool allowConfig)
  476. where T : Entity, IPostable, IRemotable, IPersistent, new()
  477. {
  478. CreateToolbarButtons(host, model, refresh, allowConfig ? ConfigurePost<T> : null);
  479. }
  480. #region PostColumn
  481. private static readonly BitmapImage? post = PRSDesktop.Resources.post.AsBitmapImage();
  482. private static readonly BitmapImage? tick = PRSDesktop.Resources.tick.AsBitmapImage();
  483. private static readonly BitmapImage? warning = PRSDesktop.Resources.warning.AsBitmapImage();
  484. private static readonly BitmapImage? refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
  485. public static void AddPostColumn<T>(DynamicGrid<T> grid)
  486. where T : Entity, IPostable, IRemotable, IPersistent, new()
  487. {
  488. grid.HiddenColumns.Add(x => x.PostedStatus);
  489. grid.HiddenColumns.Add(x => x.PostedNote);
  490. grid.ActionColumns.Add(new DynamicImageColumn(
  491. row =>
  492. {
  493. if (row is null)
  494. return post;
  495. return row.Get<T, PostedStatus>(x => x.PostedStatus) switch
  496. {
  497. PostedStatus.PostFailed => warning,
  498. PostedStatus.Posted => tick,
  499. PostedStatus.RequiresRepost => refresh,
  500. PostedStatus.NeverPosted or _ => null,
  501. };
  502. },
  503. null)
  504. {
  505. ToolTip = (column, row) =>
  506. {
  507. if (row is null)
  508. {
  509. return column.TextToolTip($"{CoreUtils.Neatify(typeof(T).Name)} Processed Status");
  510. }
  511. return column.TextToolTip(row.Get<T, PostedStatus>(x => x.PostedStatus) switch
  512. {
  513. PostedStatus.PostFailed => "Post failed: " + row.Get<T, string>(x => x.PostedNote),
  514. PostedStatus.RequiresRepost => "Repost required: " + row.Get<T, string>(x => x.PostedNote),
  515. PostedStatus.Posted => "Processed",
  516. PostedStatus.NeverPosted or _ => "Not posted yet",
  517. });
  518. }
  519. });
  520. }
  521. #endregion
  522. }