PanelHost.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. using Comal.Classes;
  2. using FastReport;
  3. using InABox.Clients;
  4. using InABox.Configuration;
  5. using InABox.Core;
  6. using InABox.Core.Reports;
  7. using InABox.DynamicGrid;
  8. using InABox.Scripting;
  9. using InABox.Wpf;
  10. using InABox.Wpf.Reports;
  11. using InABox.WPF;
  12. using PRSDesktop.Configuration;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.ComponentModel;
  16. using System.Drawing;
  17. using System.Linq;
  18. using System.Reflection;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. using System.Windows;
  22. using System.Windows.Controls;
  23. namespace PRSDesktop;
  24. public interface IPanelHostControl
  25. {
  26. void ClearActions();
  27. void CreatePanelAction(PanelAction action);
  28. void ClearReports();
  29. void CreateReport(PanelAction action);
  30. }
  31. public class PanelHost : IPanelHost
  32. {
  33. public IBasePanel? CurrentPanel { get; private set; }
  34. public string CurrentModuleName { get; private set; } = "";
  35. private readonly IPanelHostControl HostControl;
  36. private readonly List<IPanelActionItem> SetupActions = new();
  37. public PanelHost(IPanelHostControl hostControl)
  38. {
  39. HostControl = hostControl;
  40. }
  41. #region Module Tracking
  42. private int TrackedClicks;
  43. private int TrackedKeys;
  44. private DateTime TrackedTicks = DateTime.MinValue;
  45. public void IncrementTrackingModuleClick()
  46. {
  47. if (CurrentPanel is not null)
  48. TrackedClicks++;
  49. }
  50. public void IncrementTrackingModuleKey()
  51. {
  52. if (CurrentPanel is not null)
  53. TrackedKeys++;
  54. }
  55. #endregion
  56. #region IPanelHost
  57. void IPanelHost.CreatePanelAction(PanelAction action)
  58. {
  59. HostControl.CreatePanelAction(action);
  60. }
  61. void IPanelHost.CreateReport(PanelAction action)
  62. {
  63. HostControl.CreateReport(action);
  64. }
  65. void IPanelHost.CreateSetupAction(PanelAction action)
  66. {
  67. SetupActions.Add(action);
  68. }
  69. void IPanelHost.CreateSetupSeparator()
  70. {
  71. SetupActions.Add(new PanelActionSeparator());
  72. }
  73. #endregion
  74. #region Panel Properties
  75. private void InitializePanelProperties(IBasePanel panel)
  76. {
  77. var propertiesInterface = panel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>));
  78. if (propertiesInterface is not null)
  79. {
  80. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  81. var method = typeof(PanelHost)
  82. .GetMethod(nameof(InitializePanelPropertiesGeneric), BindingFlags.NonPublic | BindingFlags.Instance)
  83. ?.MakeGenericMethod(panel.GetType(), propertiesType)
  84. .Invoke(this, new object?[] { panel });
  85. }
  86. }
  87. private void InitializePanelPropertiesGeneric<TPanel, TProperties>(TPanel panel)
  88. where TPanel : IPropertiesPanel<TProperties>
  89. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  90. {
  91. panel.Properties = LoadPanelProperties<TPanel, TProperties>();
  92. }
  93. private TProperties LoadPanelProperties<TPanel, TProperties>()
  94. where TPanel : IPropertiesPanel<TProperties>
  95. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  96. {
  97. var config = new GlobalConfiguration<TProperties>();
  98. return config.Load();
  99. }
  100. private void SavePanelProperties<TPanel, TProperties>(TProperties properties)
  101. where TPanel : IPropertiesPanel<TProperties>
  102. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  103. {
  104. var config = new GlobalConfiguration<TProperties>();
  105. config.Save(properties);
  106. }
  107. private void EditPanelProperties<TPanel, TProperties>()
  108. where TPanel : IPropertiesPanel<TProperties>
  109. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  110. {
  111. var properties = LoadPanelProperties<TPanel, TProperties>();
  112. bool result;
  113. if (DynamicGridUtils.TryFindDynamicGrid(typeof(DynamicGrid<>), typeof(TProperties), out var gridType))
  114. {
  115. var grid = (Activator.CreateInstance(gridType) as DynamicGrid<TProperties>)!;
  116. result = grid.EditItems(new TProperties[] { properties });
  117. }
  118. else
  119. {
  120. var grid = new DynamicItemsListGrid<TProperties>();
  121. result = grid.EditItems(new TProperties[] { properties });
  122. }
  123. if (result)
  124. {
  125. SavePanelProperties<TPanel, TProperties>(properties);
  126. }
  127. }
  128. private void ConfigurePanel()
  129. {
  130. if (CurrentPanel is null) return;
  131. var propertiesInterface = CurrentPanel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>))!;
  132. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  133. var method = typeof(MainWindow)
  134. .GetMethod(nameof(EditPanelProperties), BindingFlags.NonPublic | BindingFlags.Instance)
  135. ?.MakeGenericMethod(CurrentPanel.GetType(), propertiesType)
  136. .Invoke(this, Array.Empty<object?>());
  137. }
  138. #endregion
  139. #region Actions
  140. private void ReloadActions(string sectionName, DataModel model)
  141. {
  142. SetupActions.Clear();
  143. HostControl.ClearActions();
  144. HostControl.ClearReports();
  145. CreateModules(sectionName, model);
  146. if (CurrentPanel != null)
  147. {
  148. CurrentPanel.CreateToolbarButtons(this);
  149. }
  150. CreateReports(sectionName, model);
  151. }
  152. #endregion
  153. #region Custom Modules
  154. private void CreateModules(string section, DataModel model)
  155. {
  156. if (ClientFactory.IsSupported<CustomModule>())
  157. {
  158. foreach (var (module, image) in CustomModuleUtils.LoadCustomModuleThumbnails(section, model))
  159. {
  160. HostControl.CreatePanelAction(new PanelAction
  161. {
  162. Caption = module.Name ?? "",
  163. Image = image,
  164. OnExecute = (action) =>
  165. {
  166. ClickModule(action, module);
  167. }
  168. });
  169. }
  170. }
  171. }
  172. private void ClickModule(PanelAction action, CustomModule code)
  173. {
  174. if (CurrentPanel != null)
  175. {
  176. if (!string.IsNullOrWhiteSpace(code.Script))
  177. try
  178. {
  179. Selection selection;
  180. if (code.SelectedRecords && code.AllRecords)
  181. selection = RecordSelectionDialog.Execute();
  182. else if (code.SelectedRecords)
  183. selection = Selection.Selected;
  184. else if (code.AllRecords)
  185. selection = Selection.All;
  186. else
  187. selection = Selection.None;
  188. var result = ScriptDocument.RunCustomModule(CurrentPanel.DataModel(selection), CurrentPanel.Selected(), code.Script);
  189. if (result)
  190. CurrentPanel.Refresh();
  191. }
  192. catch (CompileException c)
  193. {
  194. MessageWindow.ShowError(c.Message, c, shouldLog: false);
  195. }
  196. catch (Exception err)
  197. {
  198. MessageWindow.ShowError($"Unable to load {action.Caption}", err);
  199. }
  200. else
  201. MessageWindow.ShowMessage("Unable to load " + action.Caption, "Error", image: MessageWindow.WarningImage);
  202. }
  203. }
  204. private void ManageModules(PanelAction action)
  205. {
  206. if (CurrentPanel != null)
  207. {
  208. var section = CurrentPanel.SectionName;
  209. var dataModel = CurrentPanel.DataModel(Selection.Selected);
  210. var manager = new CustomModuleManager()
  211. {
  212. Section = section,
  213. DataModel = dataModel
  214. };
  215. manager.ShowDialog();
  216. ReloadActions(section, dataModel);
  217. }
  218. }
  219. #endregion
  220. #region Reports
  221. private IEnumerable<ReportExportDefinition> AddTemplateDefinitions()
  222. {
  223. if (CurrentPanel is null)
  224. return new List<ReportExportDefinition>() { new ReportExportDefinition("Email Report", PRSDesktop.Resources.email, ReportExportType.PDF,
  225. PRSEmailUtils.DoEmailReport)};
  226. else
  227. return PRSEmailUtils.CreateTemplateDefinitions(CurrentPanel.DataModel(Selection.None));
  228. }
  229. public static PanelAction CreateReportAction(ReportTemplate template, Func<Selection, DataModel> getDataModel)
  230. {
  231. var action = new PanelAction
  232. {
  233. Caption = template.Name,
  234. Image = PRSDesktop.Resources.printer,
  235. OnExecute = (action) =>
  236. {
  237. PrintReport(template.ID, getDataModel);
  238. }
  239. };
  240. if (Security.IsAllowed<CanDesignReports>())
  241. {
  242. var menu = new ContextMenu();
  243. menu.AddItem("Design Report", PRSDesktop.Resources.pencil, () => DesignReport(template.ID, getDataModel));
  244. action.Menu = menu;
  245. }
  246. return action;
  247. }
  248. private void CreateReports(string section, DataModel model)
  249. {
  250. if (CurrentPanel is null) return;
  251. var client = new Client<ReportTemplate>();
  252. var templates = ReportUtils.LoadReports(section, model, new Columns<ReportTemplate>(x => x.ID, x => x.Name));
  253. foreach (var template in templates)
  254. {
  255. HostControl.CreateReport(CreateReportAction(template, CurrentPanel.DataModel));
  256. }
  257. }
  258. private static void DesignReport(Guid templateID, Func<Selection, DataModel> getDataModel)
  259. {
  260. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(templateID)).FirstOrDefault();
  261. if (template is null)
  262. {
  263. Logger.Send(LogType.Error, "", $"No Report Template with ID '{templateID}'");
  264. MessageWindow.ShowMessage("Report does not exist!", "Error", image: MessageWindow.WarningImage);
  265. return;
  266. }
  267. ReportUtils.DesignReport(template, getDataModel(Selection.None));
  268. }
  269. private static void PrintReport(Guid id, Func<Selection, DataModel> getDataModel)
  270. {
  271. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(id)).FirstOrDefault();
  272. if (template == null)
  273. {
  274. Logger.Send(LogType.Error, "", $"No Report Template with ID '{id}'");
  275. MessageWindow.ShowMessage("Report does not exist!", "Error", image: MessageWindow.WarningImage);
  276. return;
  277. }
  278. var selection = Selection.None;
  279. if (template.SelectedRecords && template.AllRecords)
  280. selection = RecordSelectionDialog.Execute();
  281. else if (template.SelectedRecords)
  282. selection = Selection.Selected;
  283. else if (template.AllRecords)
  284. selection = Selection.All;
  285. else
  286. MessageWindow.ShowMessage(
  287. "Report must have either [Selected Records] or [All Records] checked to display!",
  288. "Error",
  289. image: MessageWindow.WarningImage);
  290. if (selection != Selection.None)
  291. ReportUtils.PreviewReport(template, getDataModel(selection), false, Security.IsAllowed<CanDesignReports>());
  292. }
  293. private void ManageReports(PanelAction action)
  294. {
  295. if (CurrentPanel is null)
  296. return;
  297. var section = CurrentPanel.SectionName;
  298. var model = CurrentPanel.DataModel(Selection.None);
  299. if (model == null)
  300. {
  301. MessageWindow.ShowMessage("No DataModel for " + CurrentPanel.SectionName, "No DataModel");
  302. return;
  303. }
  304. var form = new ReportManager { DataModel = model, Section = section, Populate = true };
  305. form.ShowDialog();
  306. ReloadActions(section, model);
  307. }
  308. private void ManageEmailTemplates(PanelAction action)
  309. {
  310. if (CurrentPanel is null)
  311. return;
  312. var section = CurrentPanel.SectionName;
  313. var model = CurrentPanel.DataModel(Selection.None);
  314. if (model == null)
  315. {
  316. MessageWindow.ShowMessage("No DataModel for " + section, "No DataModel");
  317. return;
  318. }
  319. var window = new EmailTemplateManagerWindow(model);
  320. window.ShowDialog();
  321. }
  322. #endregion
  323. #region Public Interface
  324. public void InitialiseSetupMenu(ContextMenu menu)
  325. {
  326. var items = new List<IPanelActionItem>();
  327. items.AddRange(SetupActions);
  328. items.Add(new PanelActionSeparator());
  329. if (Security.IsAllowed<CanCustomiseModules>())
  330. {
  331. items.Add(new PanelAction("Custom Modules", PRSDesktop.Resources.script, ManageModules));
  332. }
  333. if (Security.IsAllowed<CanDesignReports>())
  334. {
  335. items.Add(new PanelAction("Reports", PRSDesktop.Resources.printer, ManageReports));
  336. }
  337. if (Security.IsAllowed<CanDesignReports>())
  338. {
  339. items.Add(new PanelAction("Email Templates", PRSDesktop.Resources.email, ManageEmailTemplates));
  340. }
  341. for (var i = 0; i < items.Count; ++i)
  342. {
  343. var item = items[i];
  344. if (item is PanelAction setupAction)
  345. {
  346. menu.AddItem(setupAction.Caption, setupAction.Image, setupAction, setupAction.OnExecute);
  347. }
  348. else if (item is PanelActionSeparator && i > 0 && i < items.Count - 1)
  349. {
  350. var last = items[i - 1];
  351. if (last is not PanelActionSeparator)
  352. menu.AddSeparator();
  353. }
  354. }
  355. if (CurrentPanel?.GetType().HasInterface(typeof(IPropertiesPanel<>)) == true && Security.IsAllowed<CanConfigurePanels>())
  356. {
  357. var securityInterface = CurrentPanel?.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<,>));
  358. var canConfigure = false;
  359. if (securityInterface is not null)
  360. {
  361. var token = securityInterface.GenericTypeArguments[1];
  362. canConfigure = Security.IsAllowed(token);
  363. }
  364. else
  365. {
  366. canConfigure = Security.IsAllowed<CanConfigurePanels>();
  367. }
  368. if (canConfigure)
  369. {
  370. menu.AddItem("Configure Panel", PRSDesktop.Resources.edit, ConfigurePanel);
  371. }
  372. }
  373. if (menu.Items.Count == 0)
  374. {
  375. menu.AddItem("No Items", null, null, false);
  376. }
  377. }
  378. public IBasePanel LoadPanel(Type T, string moduleName)
  379. {
  380. return (LoadPanelMethod.MakeGenericMethod(T).Invoke(this, new object[] { moduleName })
  381. as IBasePanel)!;
  382. }
  383. private static readonly MethodInfo LoadPanelMethod = typeof(PanelHost)
  384. .GetMethods().First(x => x.Name == nameof(LoadPanel) && x.IsGenericMethod);
  385. public T LoadPanel<T>(string moduleName) where T : class, IBasePanel, new()
  386. {
  387. var panel = new T();
  388. CurrentPanel = panel;
  389. ReportUtils.ExportDefinitions.Clear();
  390. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  391. InitializePanelProperties(panel);
  392. CurrentModuleName = moduleName;
  393. TrackedTicks = DateTime.Now;
  394. CurrentPanel.IsReady = false;
  395. CurrentPanel.Setup();
  396. CurrentPanel.IsReady = true;
  397. CurrentPanel.OnUpdateDataModel += ReloadActions;
  398. var model = CurrentPanel.DataModel(Selection.None);
  399. var section = CurrentPanel.SectionName;
  400. ReloadActions(section, model);
  401. return panel;
  402. }
  403. public void Refresh()
  404. {
  405. CurrentPanel?.Refresh();
  406. }
  407. private void Heartbeat(TimeSpan time, bool closing)
  408. {
  409. if (!closing && time.TotalMinutes < 5)
  410. return;
  411. TrackedTicks = DateTime.Now;
  412. if (CurrentPanel is not null)
  413. {
  414. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0}", CurrentPanel_Label));
  415. if (ClientFactory.IsSupported<ModuleTracking>())
  416. {
  417. var keys = TrackedKeys;
  418. TrackedKeys = 0;
  419. var clicks = TrackedClicks;
  420. TrackedClicks = 0;
  421. var tracking = new ModuleTracking
  422. {
  423. Date = DateTime.Today,
  424. Module = CurrentModuleName,
  425. Clicks = clicks,
  426. Keys = keys,
  427. ActiveTime = clicks + keys > 0 ? time : new TimeSpan(),
  428. IdleTime = clicks + keys == 0 ? time : new TimeSpan()
  429. };
  430. tracking.User.ID = ClientFactory.UserGuid;
  431. new Client<ModuleTracking>().Save(tracking, "", (mt, ex) => { });
  432. }
  433. CurrentPanel.Heartbeat(time);
  434. }
  435. }
  436. public void Heartbeat()
  437. {
  438. Heartbeat(DateTime.Now - TrackedTicks, false);
  439. }
  440. public void UnloadPanel(CancelEventArgs? cancel)
  441. {
  442. if (CurrentPanel != null)
  443. {
  444. Heartbeat(DateTime.Now - TrackedTicks, true);
  445. try
  446. {
  447. CurrentPanel.Shutdown(cancel);
  448. if (cancel?.Cancel == true)
  449. {
  450. return;
  451. }
  452. }
  453. catch (Exception e)
  454. {
  455. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Error in UnloadPanel(): {0}\n{1}", e.Message, e.StackTrace));
  456. }
  457. TrackedTicks = DateTime.MinValue;
  458. CurrentModuleName = "";
  459. TrackedClicks = 0;
  460. TrackedKeys = 0;
  461. }
  462. }
  463. #endregion
  464. }