PostUtils.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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.Drawing;
  11. using System.Globalization;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Media.Imaging;
  17. namespace PRSDesktop;
  18. public static class PostUtils
  19. {
  20. private static readonly Inflector.Inflector inflector = new(new CultureInfo("en"));
  21. public static void PostEntities<T>(IDataModel<T> model, Action refresh, Action? configurePost = null)
  22. where T : Entity, IPostable, IRemotable, IPersistent, new()
  23. {
  24. bool retry;
  25. do
  26. {
  27. retry = false;
  28. try
  29. {
  30. var result = PosterUtils.Process(model);
  31. if (result is null)
  32. {
  33. MessageWindow.ShowMessage($"Processing failed", "Processing failed");
  34. refresh();
  35. }
  36. else
  37. {
  38. var failedMessages = new List<string>();
  39. var successCount = 0;
  40. foreach (var entity in result.PostedEntities)
  41. {
  42. if (entity.PostedStatus == PostedStatus.PostFailed)
  43. {
  44. failedMessages.Add(entity.PostedNote);
  45. }
  46. else
  47. {
  48. successCount++;
  49. }
  50. }
  51. if (successCount == 0)
  52. {
  53. MessageWindow.ShowMessage($"Processing failed:\n - {string.Join("\n - ", failedMessages)}", "Processing failed.");
  54. }
  55. else if (failedMessages.Count == 0)
  56. {
  57. MessageWindow.ShowMessage($"Processing successful; {successCount} items processed", "Processing successful.");
  58. }
  59. else
  60. {
  61. MessageWindow.ShowMessage($"{successCount} items succeeded, but {failedMessages.Count} failed:\n - {string.Join("\n - ", failedMessages)}", "Partial success");
  62. }
  63. refresh();
  64. }
  65. }
  66. catch (EmptyPostException)
  67. {
  68. MessageWindow.ShowMessage($"Please select at least one {typeof(T).Name}.", "Select items");
  69. }
  70. catch (PostFailedMessageException e)
  71. {
  72. MessageWindow.ShowMessage(e.Message, "Post failed");
  73. }
  74. catch (RepostedException)
  75. {
  76. MessageWindow.ShowMessage("At least one of the items you selected has already been processed. Processing cancelled.", "Already processed");
  77. }
  78. catch (PostCancelledException)
  79. {
  80. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  81. }
  82. catch (MissingSettingException e)
  83. {
  84. if (configurePost is not null && Security.CanConfigurePost<T>())
  85. {
  86. if (MessageWindow.ShowYesNo($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  87. "Configure Processing?"))
  88. {
  89. bool success = false;
  90. if (e.SettingsType.IsAssignableTo(typeof(IGlobalPosterSettings)))
  91. {
  92. success = PostableSettingsGrid.ConfigureGlobalPosterSettings(e.SettingsType);
  93. }
  94. else
  95. {
  96. success = PostableSettingsGrid.ConfigurePosterSettings<T>(e.SettingsType);
  97. }
  98. if (success && MessageWindow.ShowYesNo("Settings updated; Would you like to retry the post?", "Retry?"))
  99. {
  100. retry = true;
  101. }
  102. else
  103. {
  104. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  105. }
  106. }
  107. else
  108. {
  109. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  110. }
  111. }
  112. else
  113. {
  114. MessageWindow.ShowMessage($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}", "Unconfigured");
  115. }
  116. }
  117. catch (MissingSettingsException)
  118. {
  119. if (configurePost is not null && Security.CanConfigurePost<T>())
  120. {
  121. if (MessageWindow.ShowYesNo($"Processing has not been configured for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
  122. "Configure Processing?"))
  123. {
  124. configurePost();
  125. }
  126. else
  127. {
  128. MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
  129. }
  130. }
  131. else
  132. {
  133. MessageWindow.ShowMessage($"Processing has not been configured for {inflector.Pluralize(typeof(T).Name)}!", "Unconfigured");
  134. }
  135. }
  136. catch (Exception e)
  137. {
  138. MessageWindow.ShowError("Processing failed.", e);
  139. refresh();
  140. }
  141. } while (retry);
  142. }
  143. public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, Action? configurePost = null)
  144. where T : Entity, IPostable, IRemotable, IPersistent, new()
  145. {
  146. var postSettings = PosterUtils.LoadPostableSettings<T>();
  147. if (Security.CanPost<T>() && !postSettings.PosterType.IsNullOrWhiteSpace())
  148. {
  149. Bitmap? image = null;
  150. if (postSettings.Thumbnail.ID != Guid.Empty)
  151. {
  152. var icon = new Client<Document>()
  153. .Load(new Filter<Document>(x => x.ID).IsEqualTo(postSettings.Thumbnail.ID)).FirstOrDefault();
  154. if (icon?.Data?.Any() == true)
  155. image = new ImageConverter().ConvertFrom(icon.Data) as Bitmap;
  156. }
  157. host.CreatePanelAction(new PanelAction
  158. {
  159. Caption = postSettings.ButtonName.NotWhiteSpaceOr($"Process {inflector.Pluralize(typeof(T).Name)}"),
  160. Image = image ?? PRSDesktop.Resources.edit,
  161. OnExecute = action =>
  162. {
  163. PostEntities(
  164. model(),
  165. refresh,
  166. configurePost);
  167. }
  168. });
  169. if (postSettings.ShowClearButton)
  170. {
  171. host.CreatePanelAction(new PanelAction
  172. {
  173. Caption = "Clear Posted Flag",
  174. Image = image ?? PRSDesktop.Resources.refresh,
  175. OnExecute = action =>
  176. {
  177. var dataModel = model();
  178. foreach(var (key, table) in dataModel.ModelTables)
  179. {
  180. table.IsDefault = false;
  181. }
  182. dataModel.SetColumns<T>(Columns.Required<T>().Add(x => x.PostedStatus).Add(x => x.PostedReference).Add(x => x.PostedNote).Add(x => x.Posted));
  183. dataModel.SetIsDefault<T>(true);
  184. dataModel.LoadModel();
  185. var items = dataModel.GetTable<T>().ToArray<T>();
  186. foreach(var item in items)
  187. {
  188. item.PostedStatus = PostedStatus.NeverPosted;
  189. item.PostedReference = "";
  190. item.PostedNote = "";
  191. item.Posted = DateTime.MinValue;
  192. }
  193. Client.Save(items, "Cleared posted flag");
  194. refresh();
  195. }
  196. });
  197. }
  198. }
  199. if (configurePost is not null && Security.CanConfigurePost<T>())
  200. {
  201. host.CreateSetupAction(new PanelAction
  202. {
  203. Caption = $"Configure {CoreUtils.Neatify(typeof(T).Name)} Processing",
  204. OnExecute = action =>
  205. {
  206. configurePost();
  207. }
  208. });
  209. }
  210. }
  211. public static void ConfigurePost<T>()
  212. where T : Entity, IPostable, IRemotable, IPersistent, new()
  213. {
  214. var postSettings = PosterUtils.LoadPostableSettings<T>();
  215. var grid = (DynamicGridUtils.CreateDynamicGrid(typeof(DynamicGrid<>), typeof(PostableSettings)) as DynamicGrid<PostableSettings>)!;
  216. if (grid.EditItems(new PostableSettings[] { postSettings }))
  217. {
  218. PosterUtils.SavePostableSettings<T>(postSettings);
  219. }
  220. }
  221. public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, bool allowConfig)
  222. where T : Entity, IPostable, IRemotable, IPersistent, new()
  223. {
  224. CreateToolbarButtons(host, model, refresh, allowConfig ? ConfigurePost<T> : null);
  225. }
  226. #region PostColumn
  227. private static readonly BitmapImage? post = PRSDesktop.Resources.post.AsBitmapImage();
  228. private static readonly BitmapImage? tick = PRSDesktop.Resources.tick.AsBitmapImage();
  229. private static readonly BitmapImage? warning = PRSDesktop.Resources.warning.AsBitmapImage();
  230. private static readonly BitmapImage? refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
  231. public static void AddPostColumn<T>(DynamicGrid<T> grid)
  232. where T : Entity, IPostable, IRemotable, IPersistent, new()
  233. {
  234. grid.HiddenColumns.Add(x => x.PostedStatus);
  235. grid.HiddenColumns.Add(x => x.PostedNote);
  236. grid.ActionColumns.Add(new DynamicImageColumn(
  237. row =>
  238. {
  239. if (row is null)
  240. return post;
  241. return row.Get<T, PostedStatus>(x => x.PostedStatus) switch
  242. {
  243. PostedStatus.PostFailed => warning,
  244. PostedStatus.Posted => tick,
  245. PostedStatus.RequiresRepost => refresh,
  246. PostedStatus.NeverPosted or _ => null,
  247. };
  248. },
  249. null)
  250. {
  251. ToolTip = (column, row) =>
  252. {
  253. if (row is null)
  254. {
  255. return column.TextToolTip($"{CoreUtils.Neatify(typeof(T).Name)} Processed Status");
  256. }
  257. return column.TextToolTip(row.Get<T, PostedStatus>(x => x.PostedStatus) switch
  258. {
  259. PostedStatus.PostFailed => "Post failed: " + row.Get<T, string>(x => x.PostedNote),
  260. PostedStatus.RequiresRepost => "Repost required: " + row.Get<T, string>(x => x.PostedNote),
  261. PostedStatus.Posted => "Processed",
  262. PostedStatus.NeverPosted or _ => "Not posted yet",
  263. });
  264. }
  265. });
  266. }
  267. #endregion
  268. }