DigitalFormsDashboard.xaml.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using InABox.DynamicGrid;
  5. using InABox.Reports;
  6. using InABox.Core.Reports;
  7. using InABox.Scripting;
  8. using InABox.WPF;
  9. using InABox.Wpf;
  10. using PRSDesktop.Configuration;
  11. using PRSDesktop.Forms;
  12. using PRSDesktop.WidgetGroups;
  13. using Syncfusion.UI.Xaml.Grid;
  14. using Syncfusion.UI.Xaml.Grid.Converter;
  15. using Syncfusion.XlsIO;
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using System.Data;
  20. using System.Diagnostics;
  21. using System.Diagnostics.CodeAnalysis;
  22. using System.Linq;
  23. using System.Linq.Expressions;
  24. using System.Reflection;
  25. using System.Text;
  26. using System.Text.RegularExpressions;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using System.Windows;
  30. using System.Windows.Controls;
  31. using System.Windows.Data;
  32. using System.Windows.Documents;
  33. using System.Windows.Input;
  34. using System.Windows.Media;
  35. using InABox.Configuration;
  36. using SelectionChangedEventArgs = System.Windows.Controls.SelectionChangedEventArgs;
  37. using InABox.Wpf.Reports;
  38. using System.ComponentModel;
  39. using Syncfusion.Windows.Shared;
  40. using System.Globalization;
  41. using System.Windows.Media.Imaging;
  42. using System.Drawing;
  43. using Image = System.Windows.Controls.Image;
  44. using Microsoft.Win32;
  45. using Syncfusion.CompoundFile.DocIO.Net;
  46. using System.IO;
  47. using sun.security.krb5.@internal;
  48. using Columns = InABox.Core.Columns;
  49. namespace PRSDesktop;
  50. public enum DateFilterType
  51. {
  52. Today,
  53. Yesterday,
  54. Week,
  55. SevenDays,
  56. Month,
  57. ThirtyDays,
  58. Year,
  59. TwelveMonths,
  60. Custom
  61. }
  62. public class DFFilter : BaseObject
  63. {
  64. [EditorSequence(1)]
  65. [TextBoxEditor]
  66. public string Name { get; set; } = "";
  67. [EditorSequence(2)]
  68. [FilterEditor]
  69. public string Filter { get; set; } = "";
  70. }
  71. internal class MileStoneImageConverter : IValueConverter
  72. {
  73. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  74. {
  75. return Equals(value, DateTime.MinValue) ? null : Resources.milestone.AsBitmapImage();
  76. }
  77. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  78. {
  79. return null;
  80. }
  81. }
  82. public class DigitalFormsDashboardProperties : IUserConfigurationSettings, IDashboardProperties
  83. {
  84. public bool ShowJobFilter { get; set; } = false;
  85. public bool ShowDateFilter { get; set; } = true;
  86. public bool ShowIncompleteForms { get; set; } = false;
  87. public bool UseIconsForFormTypes { get; set; } = false;
  88. public string? Category { get; set; }
  89. public Guid SelectedForm { get; set; }
  90. public Guid JobID { get; set; }
  91. public DateFilterType DateFilterType { get; set; } = DateFilterType.Today;
  92. public DateTime FromDate { get; set; }
  93. public DateTime ToDate { get; set; }
  94. public Dictionary<string, List<DFFilter>> Filters { get; set; } = new();
  95. }
  96. public class DigitalFormsDashboardElement : DashboardElement<DigitalFormsDashboard, Common, DigitalFormsDashboardProperties> { }
  97. /// <summary>
  98. /// Interaction logic for DigitalFormsDashboard.xaml
  99. /// </summary>
  100. public partial class DigitalFormsDashboard : UserControl,
  101. IDashboardWidget<Common, DigitalFormsDashboardProperties>,
  102. IBasePanel,
  103. IRequiresSecurity<CanViewDigitalFormsDashbaord>,
  104. IHeaderDashboard, IActionsDashboard
  105. {
  106. public DigitalFormsDashboardProperties Properties { get; set; }
  107. public event LoadSettings<DigitalFormsDashboardProperties>? LoadSettings;
  108. public event SaveSettings<DigitalFormsDashboardProperties>? SaveSettings;
  109. private List<DigitalForm> DigitalForms;
  110. private List<Job> Jobs;
  111. private List<Tuple<string, Type?, string>> Categories;
  112. public DashboardHeader Header { get; set; } = new();
  113. private bool IsQAForm = false;
  114. private List<QAQuestion> Questions = new();
  115. private bool IsSetup = false;
  116. public DigitalFormsDashboard()
  117. {
  118. InitializeComponent();
  119. DataGrid.RowStyleSelector = new RowStyleSelector();
  120. }
  121. public void Setup()
  122. {
  123. var results = Client.QueryMultiple(
  124. new KeyedQueryDef<DigitalForm>(new Filter<DigitalForm>(x => x.Active).IsEqualTo(true)),
  125. new KeyedQueryDef<Job>(
  126. LookupFactory.DefineFilter<Job>(),
  127. Columns.None<Job>().Add(x => x.ID)
  128. .Add(x => x.JobNumber)
  129. .Add(x => x.Name)));
  130. DigitalForms = results.Get<DigitalForm>().ToObjects<DigitalForm>().ToList();
  131. var categories = new DigitalFormCategoryLookups(null);
  132. categories.OnAfterGenerateLookups += (sender, entries) => { entries.Insert(0, new LookupEntry("", "Select Category")); };
  133. Categories = categories.AsTable("AppliesTo")
  134. .Rows.Select(x =>
  135. {
  136. var appliesTo = x.Get<string>("AppliesTo");
  137. if (CategoryToType(appliesTo, out var formType, out var parentType))
  138. {
  139. return new Tuple<string, Type?, string>(appliesTo, formType, x.Get<string>("Display"));
  140. }
  141. else
  142. {
  143. return new Tuple<string, Type?, string>(appliesTo, null, x.Get<string>("Display"));
  144. }
  145. }).ToList();
  146. Jobs = results.Get<Job>().ToObjects<Job>().ToList();
  147. Jobs.Insert(0, new Job { ID = Guid.Empty, JobNumber = "ALL", Name = "All Jobs" });
  148. SetupHeader();
  149. SetupFilters();
  150. IsSetup = true;
  151. }
  152. #region Header
  153. private StackPanel CategoryButtonPanel;
  154. private Dictionary<Type, Button> CategoryButtons = new();
  155. private ComboBox CategoryBox;
  156. private ComboBox FormBox;
  157. private ComboBox JobBox;
  158. private ComboBox IncompleteFormsBox;
  159. private ComboBox DateTypeBox;
  160. private Label FromLabel;
  161. private DatePicker FromPicker;
  162. private Label ToLabel;
  163. private DatePicker ToPicker;
  164. private Button Print;
  165. private Button FilterBtn;
  166. private static Dictionary<DateFilterType, string> FilterTypes = new()
  167. {
  168. { DateFilterType.Today, "Today" },
  169. { DateFilterType.Yesterday, "Yesterday" },
  170. { DateFilterType.Week, "Week to Date" },
  171. { DateFilterType.SevenDays, "Last 7 Days" },
  172. { DateFilterType.Month, "Month to Date" },
  173. { DateFilterType.ThirtyDays, "Last 30 Days" },
  174. { DateFilterType.Year, "Year to Date" },
  175. { DateFilterType.TwelveMonths, "Last 12 Months" },
  176. { DateFilterType.Custom, "Custom" }
  177. };
  178. private static readonly SolidColorBrush EnabledBrush = new SolidColorBrush(Colors.LightYellow);
  179. private static readonly SolidColorBrush DisabledBrush = new SolidColorBrush(Colors.LightGray);
  180. private static readonly Dictionary<Type, Bitmap> CategoryImages = new()
  181. {
  182. { typeof(AssignmentForm), PRSDesktop.Resources.assignments },
  183. { typeof(KanbanForm), PRSDesktop.Resources.kanban },
  184. { typeof(JobForm), PRSDesktop.Resources.project },
  185. { typeof(JobITPForm), PRSDesktop.Resources.checklist },
  186. { typeof(EmployeeForm), PRSDesktop.Resources.employees },
  187. { typeof(LeaveRequestForm), PRSDesktop.Resources.leave },
  188. { typeof(ManufacturingPacketStage), PRSDesktop.Resources.factory },
  189. { typeof(TimeSheetForm), PRSDesktop.Resources.time },
  190. { typeof(PurchaseOrderItemForm), PRSDesktop.Resources.purchase },
  191. { typeof(DeliveryForm), PRSDesktop.Resources.truck },
  192. };
  193. public void SetupHeader()
  194. {
  195. CategoryBox = new ComboBox
  196. {
  197. Width = 150,
  198. VerticalContentAlignment = VerticalAlignment.Center,
  199. Margin = new Thickness(0, 0, 5, 0)
  200. };
  201. CategoryBox.ItemsSource = Categories;
  202. CategoryBox.SelectedValuePath = "Item1";
  203. CategoryBox.DisplayMemberPath = "Item3";
  204. CategoryBox.SelectedValue = Properties.Category;
  205. CategoryBox.SelectionChanged += Category_SelectionChanged;
  206. CategoryButtonPanel = new StackPanel
  207. {
  208. Orientation = Orientation.Horizontal,
  209. Margin = new Thickness(0, 0, 5, 0)
  210. };
  211. CategoryButtons.Clear();
  212. foreach(var (appliesTo, category, display) in Categories)
  213. {
  214. if(category is null)
  215. {
  216. continue;
  217. }
  218. var button = new Button();
  219. button.Tag = appliesTo;
  220. button.Margin = new Thickness(0, 0, 2, 0);
  221. button.BorderBrush = new SolidColorBrush(Colors.Gray);
  222. button.BorderThickness = new Thickness(0.75);
  223. button.Width = 25D;
  224. button.Padding = new Thickness(2);
  225. button.ToolTip = category.EntityName().Split('.').Last().SplitCamelCase();
  226. if (CategoryImages.TryGetValue(category, out var image))
  227. {
  228. button.Content = new Image { Source = image.AsBitmapImage() };
  229. }
  230. else
  231. {
  232. button.Content = display;
  233. }
  234. button.Click += CatagoryButton_Click;
  235. CategoryButtons.Add(category, button);
  236. CategoryButtonPanel.Children.Add(button);
  237. }
  238. if (Properties.UseIconsForFormTypes)
  239. {
  240. CategoryButtonPanel.Visibility = Visibility.Visible;
  241. CategoryBox.Visibility = Visibility.Collapsed;
  242. }
  243. else
  244. {
  245. CategoryButtonPanel.Visibility = Visibility.Collapsed;
  246. CategoryBox.Visibility = Visibility.Visible;
  247. }
  248. FormBox = new ComboBox
  249. {
  250. Width = 250,
  251. VerticalContentAlignment = VerticalAlignment.Center,
  252. Margin = new Thickness(0, 0, 5, 0),
  253. IsEnabled = false
  254. };
  255. FormBox.SelectionChanged += FormBox_SelectionChanged;
  256. FormBox.ItemsSource = new Dictionary<DigitalForm, string> { };
  257. JobBox = new ComboBox
  258. {
  259. Width = 250,
  260. Margin = new Thickness(0, 0, 5, 0),
  261. VerticalContentAlignment = VerticalAlignment.Center
  262. };
  263. JobBox.ItemsSource = Jobs.ToDictionary(x => x.ID, x => $"{x.JobNumber} : {x.Name}");
  264. JobBox.SelectedIndex = 0;
  265. JobBox.SelectedValuePath = "Key";
  266. JobBox.DisplayMemberPath = "Value";
  267. JobBox.SelectionChanged += JobBox_SelectionChanged;
  268. DateTypeBox = new ComboBox
  269. {
  270. Width = 120,
  271. VerticalContentAlignment = VerticalAlignment.Center
  272. };
  273. DateTypeBox.ItemsSource = FilterTypes;
  274. DateTypeBox.SelectedValuePath = "Key";
  275. DateTypeBox.DisplayMemberPath = "Value";
  276. DateTypeBox.SelectedValue = Properties.DateFilterType;
  277. DateTypeBox.SelectionChanged += DateTypeBox_SelectionChanged;
  278. FromLabel = new Label { Content = "From", VerticalContentAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0) };
  279. FromPicker = new DatePicker
  280. {
  281. Width = 100,
  282. Background = new SolidColorBrush(Colors.LightYellow),
  283. VerticalContentAlignment = VerticalAlignment.Center,
  284. FirstDayOfWeek = DayOfWeek.Monday,
  285. Margin = new Thickness(0, 0, 5, 0)
  286. };
  287. FromPicker.SelectedDateChanged += FromPicker_SelectedDateChanged;
  288. ToLabel = new Label { Content = "To", VerticalContentAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0) };
  289. ToPicker = new DatePicker
  290. {
  291. Width = 100,
  292. Background = new SolidColorBrush(Colors.LightYellow),
  293. VerticalContentAlignment = VerticalAlignment.Center,
  294. FirstDayOfWeek = DayOfWeek.Monday,
  295. Margin = new Thickness(0, 0, 5, 0)
  296. };
  297. ToPicker.SelectedDateChanged += ToPicker_SelectedDateChanged;
  298. IncompleteFormsBox = new ComboBox
  299. {
  300. Width = 130,
  301. Margin = new Thickness(0, 0, 5, 0),
  302. VerticalContentAlignment = VerticalAlignment.Center
  303. };
  304. IncompleteFormsBox.ItemsSource = new List<Tuple<string, bool>>
  305. {
  306. new Tuple<string, bool>("Completed Forms", false),
  307. new Tuple<string, bool>("All Forms", true)
  308. };
  309. IncompleteFormsBox.DisplayMemberPath = "Item1";
  310. IncompleteFormsBox.SelectedValuePath = "Item2";
  311. IncompleteFormsBox.SelectedValue = Properties.ShowIncompleteForms;
  312. IncompleteFormsBox.SelectionChanged += IncompleteFormsBox_SelectionChanged;
  313. Print = new Button
  314. {
  315. Width = 25,
  316. Height = 25,
  317. Content = new Image { Source = PRSDesktop.Resources.printer.AsBitmapImage() }
  318. };
  319. Print.Click += Print_Click;
  320. FilterBtn = new Button
  321. {
  322. Width = 25,
  323. Height = 25,
  324. Content = new Image { Source = InABox.Wpf.Resources.filter.AsBitmapImage() },
  325. Margin = new Thickness(0, 0, 5, 0)
  326. };
  327. FilterBtn.Click += Filter_Click;
  328. Header.BeginUpdate()
  329. .Clear()
  330. .Add(CategoryBox)
  331. .Add(CategoryButtonPanel)
  332. .Add(FormBox)
  333. .Add(JobBox)
  334. .Add(DateTypeBox)
  335. .Add(FromLabel)
  336. .Add(FromPicker)
  337. .Add(ToLabel)
  338. .Add(ToPicker)
  339. .Add(IncompleteFormsBox)
  340. .AddRight(FilterBtn)
  341. .AddRight(Print)
  342. .EndUpdate();
  343. UpdateCategory(Properties.Category);
  344. }
  345. private void IncompleteFormsBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  346. {
  347. Properties.ShowIncompleteForms = (bool)IncompleteFormsBox.SelectedValue;
  348. Refresh();
  349. }
  350. private void Filter_Click(object sender, RoutedEventArgs e)
  351. {
  352. var menu = new ContextMenu();
  353. menu.AddCheckItem("Use Form Type Icons", ToggleFormTypeIcons, isChecked: Properties.UseIconsForFormTypes);
  354. menu.AddCheckItem("Show Date Filter", ToggleDateFilter, Properties.ShowDateFilter);
  355. menu.AddCheckItem("Show Job Filter", ToggleJobFilter, Properties.ShowJobFilter);
  356. menu.AddSeparator();
  357. if (ParentType is not null)
  358. {
  359. if (Properties.Filters.TryGetValue(ParentType.Name, out var filters))
  360. {
  361. var i = 0;
  362. var items = new List<MenuItem>();
  363. foreach (var filter in filters)
  364. {
  365. items.Add(menu.AddCheckItem(
  366. filter.Name,
  367. new Tuple<int, string, List<MenuItem>>(i, filter.Filter, items),
  368. ExecuteFilter,
  369. i == CustomFilterIndex));
  370. ++i;
  371. }
  372. }
  373. menu.AddSeparatorIfNeeded();
  374. menu.AddItem("Manage Filters", InABox.Wpf.Resources.filter, ManageFilters_Click);
  375. }
  376. menu.IsOpen = true;
  377. }
  378. private void ToggleFormTypeIcons(bool isChecked)
  379. {
  380. Properties.UseIconsForFormTypes = !Properties.UseIconsForFormTypes;
  381. if (Properties.UseIconsForFormTypes)
  382. {
  383. CategoryButtonPanel.Visibility = Visibility.Visible;
  384. CategoryBox.Visibility = Visibility.Collapsed;
  385. }
  386. else
  387. {
  388. CategoryButtonPanel.Visibility = Visibility.Collapsed;
  389. CategoryBox.Visibility = Visibility.Visible;
  390. }
  391. }
  392. private void Print_Click(object sender, RoutedEventArgs e)
  393. {
  394. var menu = new ContextMenu();
  395. foreach (var report in ReportUtils.LoadReports(SectionName, DataModel(Selection.None)))
  396. {
  397. menu.AddItem(report.Name, PRSDesktop.Resources.printer, report, PrintReport_Click);
  398. }
  399. if (Security.IsAllowed<CanDesignReports>())
  400. {
  401. menu.AddSeparatorIfNeeded();
  402. menu.AddItem("Manage Reports", PRSDesktop.Resources.printer, ManageReports_Click);
  403. }
  404. menu.IsOpen = true;
  405. }
  406. private void PrintReport_Click(ReportTemplate obj)
  407. {
  408. Selection selection;
  409. if (obj.SelectedRecords && obj.AllRecords)
  410. selection = RecordSelectionDialog.Execute();
  411. else if (obj.SelectedRecords)
  412. selection = Selection.Selected;
  413. else if (obj.AllRecords)
  414. selection = Selection.All;
  415. else
  416. selection = Selection.None;
  417. ReportUtils.PreviewReport(obj, DataModel(selection), false, Security.IsAllowed<CanDesignReports>());
  418. }
  419. private void ManageReports_Click()
  420. {
  421. var manager = new ReportManager()
  422. {
  423. DataModel = DataModel(Selection.None),
  424. Section = SectionName,
  425. Populate = true
  426. };
  427. manager.ShowDialog();
  428. }
  429. private void Search_KeyUp(object sender, KeyEventArgs e)
  430. {
  431. Refresh();
  432. }
  433. private void JobBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  434. {
  435. Properties.JobID = (Guid)JobBox.SelectedValue;
  436. Refresh();
  437. }
  438. private void SetDateFilterVisibility(bool visible)
  439. {
  440. var visibility = visible ? Visibility.Visible : Visibility.Collapsed;
  441. FromLabel.Visibility = visibility;
  442. FromPicker.Visibility = visibility;
  443. ToLabel.Visibility = visibility;
  444. ToPicker.Visibility = visibility;
  445. DateTypeBox.Visibility = visibility;
  446. }
  447. private void SetJobFilterVisibility(bool visible)
  448. {
  449. var visibility = visible ? Visibility.Visible : Visibility.Collapsed;
  450. JobBox.Visibility = visibility;
  451. }
  452. private void DateTypeBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  453. {
  454. var filterType = (DateFilterType)DateTypeBox.SelectedValue;
  455. Properties.DateFilterType = filterType;
  456. if (filterType == DateFilterType.Custom)
  457. {
  458. if (FromPicker.SelectedDate == null || FromPicker.SelectedDate == DateTime.MinValue)
  459. {
  460. Properties.FromDate = DateTime.Today;
  461. }
  462. else
  463. {
  464. Properties.FromDate = FromPicker.SelectedDate.Value;
  465. }
  466. if (ToPicker.SelectedDate == null || ToPicker.SelectedDate == DateTime.MinValue)
  467. {
  468. Properties.ToDate = DateTime.Today;
  469. }
  470. else
  471. {
  472. Properties.ToDate = ToPicker.SelectedDate.Value;
  473. }
  474. }
  475. SetupDateFilters();
  476. Refresh();
  477. }
  478. private void FromPicker_SelectedDateChanged(object? sender, SelectionChangedEventArgs e)
  479. {
  480. Properties.FromDate = FromPicker.SelectedDate ?? DateTime.Today;
  481. Refresh();
  482. }
  483. private void ToPicker_SelectedDateChanged(object? sender, SelectionChangedEventArgs e)
  484. {
  485. Properties.ToDate = ToPicker.SelectedDate ?? DateTime.Today;
  486. Refresh();
  487. }
  488. private bool _changing = false;
  489. private void UpdateCategory(string? category)
  490. {
  491. _changing = true;
  492. Properties.Category = category;
  493. SetCategory(Properties.Category);
  494. foreach(var (type, button) in CategoryButtons)
  495. {
  496. if(type == FormType)
  497. {
  498. button.Background = EnabledBrush;
  499. }
  500. else
  501. {
  502. button.Background = DisabledBrush;
  503. }
  504. }
  505. var jobLink = FormType is not null ? GetJobLink("", FormType) : "";
  506. if (string.IsNullOrWhiteSpace(jobLink))
  507. {
  508. var jobID = Properties.JobID;
  509. JobBox.SelectedValue = Guid.Empty;
  510. JobBox.IsEnabled = false;
  511. Properties.JobID = jobID;
  512. }
  513. else
  514. {
  515. JobBox.SelectedValue = Properties.JobID;
  516. JobBox.IsEnabled = true;
  517. }
  518. if (ParentType is null)
  519. {
  520. FormBox.IsEnabled = false;
  521. FormBox.ItemsSource = new Dictionary<DigitalForm, string> { };
  522. }
  523. else
  524. {
  525. var forms = DigitalForms.Where(x => x.AppliesTo == ParentType.Name).ToList();
  526. forms.Insert(0, new DigitalForm { ID = Guid.Empty, Description = "Select Form" });
  527. FormBox.ItemsSource = forms;
  528. if (Properties.SelectedForm != Guid.Empty && forms.Where(x => x.ID == Properties.SelectedForm).FirstOrDefault() is DigitalForm form)
  529. {
  530. FormBox.SelectedItem = form;
  531. }
  532. else
  533. {
  534. FormBox.SelectedIndex = 0;
  535. }
  536. FormBox.DisplayMemberPath = "Description";
  537. FormBox.IsEnabled = true;
  538. }
  539. _changing = false;
  540. OnUpdateDataModel?.Invoke(SectionName, DataModel(Selection.None));
  541. }
  542. private void CatagoryButton_Click(object sender, RoutedEventArgs e)
  543. {
  544. UpdateCategory(((sender as Button)!.Tag as string)!);
  545. Refresh();
  546. }
  547. private void Category_SelectionChanged(object sender, SelectionChangedEventArgs e)
  548. {
  549. UpdateCategory((CategoryBox.SelectedValue as string)!);
  550. Refresh();
  551. }
  552. private void FormBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  553. {
  554. Form = FormBox.SelectedValue as DigitalForm;
  555. Properties.SelectedForm = Form?.ID ?? Guid.Empty;
  556. if (!_changing)
  557. {
  558. OnUpdateDataModel?.Invoke(SectionName, DataModel(Selection.None));
  559. }
  560. Refresh();
  561. }
  562. #endregion
  563. #region IBasePanel
  564. public bool IsReady { get; set; }
  565. public event DataModelUpdateEvent? OnUpdateDataModel;
  566. public void CreateToolbarButtons(IPanelHost host)
  567. {
  568. host.CreatePanelAction(new PanelAction("Export Forms", PRSDesktop.Resources.disk, action => SaveToFolder_Click()));
  569. }
  570. public void Heartbeat(TimeSpan time)
  571. {
  572. }
  573. public Dictionary<string, object[]> Selected()
  574. {
  575. return new Dictionary<string, object[]>();
  576. }
  577. #endregion
  578. public string SectionName
  579. {
  580. get
  581. {
  582. if (Form is null || Form.ID == Guid.Empty)
  583. return "Digital Forms";
  584. return Form.ID.ToString() ?? "Digital Forms";
  585. }
  586. }
  587. public DataModel DataModel(Selection selection)
  588. {
  589. if (FormType is null || Form is null || Form.ID == Guid.Empty)
  590. {
  591. return new AutoDataModel<DigitalForm>(new Filter<DigitalForm>().None());
  592. }
  593. IFilter filter;
  594. switch (selection)
  595. {
  596. case Selection.Selected:
  597. var formids = DataGrid.SelectedItems.Select(x => (x as DataRowView)!.Row["ID"]).ToArray();
  598. filter = Filter.Create<Entity>(FormType, x => x.ID).InList(formids);
  599. break;
  600. case Selection.All:
  601. filter = Filter.Create(FormType).All();
  602. break;
  603. case Selection.None:
  604. default:
  605. filter = Filter.Create(FormType).None();
  606. break;
  607. }
  608. return (Activator.CreateInstance(typeof(DigitalFormReportDataModel<>)!
  609. .MakeGenericType(FormType), new object?[] { filter, Form.ID }) as DataModel)!;
  610. }
  611. public void BuildActionsMenu(ContextMenu menu)
  612. {
  613. menu.AddItem("Export", InABox.Wpf.Resources.doc_xls, Export_Click, Form is not null && Form.ID != Guid.Empty);
  614. var loadingModules = menu.AddItem("Loading Modules...", null, null, false);
  615. Task.Run(() =>
  616. {
  617. return CustomModuleUtils.LoadCustomModuleThumbnails(SectionName, DataModel(Selection.None));
  618. }).ContinueWith((task) =>
  619. {
  620. var modules = task.Result;
  621. var index = menu.Items.IndexOf(loadingModules);
  622. menu.Items.RemoveAt(index);
  623. foreach (var (module, image) in modules)
  624. {
  625. menu.AddItem(module.Name, image, module, ExecuteModule_Click, index: index);
  626. ++index;
  627. }
  628. }, TaskScheduler.FromCurrentSynchronizationContext());
  629. if (Security.IsAllowed<CanCustomiseModules>())
  630. {
  631. menu.AddSeparatorIfNeeded();
  632. menu.AddItem("Manage Modules", PRSDesktop.Resources.script, ManageModules_Click);
  633. }
  634. }
  635. private void SaveToFolder_Click()
  636. {
  637. if (Form is null || FormType is null)
  638. {
  639. MessageWindow.ShowMessage("Please select a form first.", "Select form");
  640. return;
  641. }
  642. var model = DataModel(Selection.None);
  643. var reports = ReportUtils.LoadReports(Form.ID.ToString(), model).Where(x => x.Visible).ToList();
  644. var method = typeof(DigitalFormsDashboard).GetMethod("SaveToFolder", BindingFlags.Instance | BindingFlags.NonPublic)!.MakeGenericMethod(FormType);
  645. if (reports.Count == 0)
  646. {
  647. MessageWindow.ShowMessage("No reports are currently defined for this Digital Form!", "No report found");
  648. return;
  649. }
  650. if(reports.Count == 1)
  651. {
  652. method.Invoke(this, new object[] { reports[0] });
  653. return;
  654. }
  655. var menu = new ContextMenu();
  656. foreach (var report in reports)
  657. menu.AddItem(report.Name, null, report, r => method.Invoke(this, new[] { r }));
  658. menu.IsOpen = true;
  659. }
  660. private void SaveToFolder<TForm>(ReportTemplate report)
  661. where TForm : Entity, IDigitalFormInstance, IRemotable, IPersistent, new()
  662. {
  663. using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
  664. {
  665. var result = dialog.ShowDialog();
  666. if(result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(dialog.SelectedPath))
  667. {
  668. var data = DataGrid.SelectedItems.OfType<DataRowView>().Select(x => x.Row).ToList();
  669. Progress.ShowModal("Saving forms", progress =>
  670. {
  671. foreach (var row in data)
  672. {
  673. var id = (Guid)row["ID"];
  674. var number = (string)row["Number"];
  675. progress.Report($"Saving form {number}");
  676. var dataModel = new DigitalFormReportDataModel<TForm>(
  677. new Filter<TForm>(x => x.ID).IsEqualTo(id),
  678. Form!.ID);
  679. var pdfData = ReportUtils.ReportToPDF(report, dataModel, true);
  680. var expr = dataModel.EvaluateExpression(Form.ExportExpression)?.Trim();
  681. var filename = String.IsNullOrWhiteSpace(expr)
  682. ? number
  683. : $"{number} - {CoreUtils.SanitiseFileName(expr)}";
  684. File.WriteAllBytes(Path.Combine(dialog.SelectedPath, Path.ChangeExtension(filename, ".pdf")), pdfData);
  685. }
  686. });
  687. Process.Start("explorer.exe" , dialog.SelectedPath);
  688. }
  689. }
  690. }
  691. private void Export_Click()
  692. {
  693. var formName = Regex.Replace(Form?.Description ?? "", "[^ a-zA-Z0-9]", "");
  694. var filename = string.Format("{0} - {1} - {2:yyyy-MM-dd} - {3:yyyy-MM-dd}.xlsx", ParentType!.Name, formName, From, To);
  695. var options = new ExcelExportingOptions();
  696. options.ExcelVersion = ExcelVersion.Excel2013;
  697. options.ExportStackedHeaders = true;
  698. var excelEngine = DataGrid.ExportToExcel(DataGrid.View, options);
  699. var workBook = excelEngine.Excel.Workbooks[0];
  700. var sheet = workBook.Worksheets[0];
  701. sheet.Name = "Summary";
  702. sheet.UsedRange.AutofitRows();
  703. sheet.UsedRange.AutofitColumns();
  704. sheet = workBook.Worksheets.Create("Questions");
  705. sheet.Move(0);
  706. var questions = new Client<QAQuestion>().Query(new Filter<QAQuestion>(x => x.Form.ID).IsEqualTo(Form!.ID));
  707. sheet.Range[1, 1].Text = Form?.Description ?? "";
  708. sheet.Range[1, 1, 1, 3].Merge();
  709. var i = 1;
  710. foreach (var row in questions.Rows)
  711. if (!row.Get<QAQuestion, QAAnswer>(x => x.Answer).Equals(QAAnswer.Comment))
  712. {
  713. sheet.Range[i + 2, 1].Text = string.Format("{0}.", i);
  714. sheet.Range[i + 2, 2].Text = string.Format("{0}", row.Get<QAQuestion, string>(x => x.Question));
  715. sheet.Range[i + 2, 3].Text = string.Format("[{0}]", row.Get<QAQuestion, string>(x => x.Code));
  716. i++;
  717. }
  718. sheet.UsedRange.AutofitRows();
  719. sheet.UsedRange.AutofitColumns();
  720. try
  721. {
  722. workBook.SaveAs(filename);
  723. var startInfo = new ProcessStartInfo(filename);
  724. startInfo.Verb = "open";
  725. startInfo.UseShellExecute = true;
  726. Process.Start(startInfo);
  727. }
  728. catch
  729. {
  730. MessageBox.Show(string.Format("Unable to Save/Launch [{0}]!\n\nIs the file already open?", filename));
  731. }
  732. }
  733. private void ManageFilters_Click()
  734. {
  735. var filters = Properties.Filters.GetValueOrDefault(ParentType!.Name) ?? new List<DFFilter>();
  736. var gridFilters = new CoreFilterDefinitions();
  737. gridFilters.AddRange(filters.Select(x => new CoreFilterDefinition { Name = x.Name, Filter = x.Filter }));
  738. var grid = new DynamicGridFilterEditor(gridFilters, FormType!);
  739. if (grid.ShowDialog() == true)
  740. {
  741. Properties.Filters[ParentType!.Name] = grid.Filters.Select(x => new DFFilter { Name = x.Name, Filter = x.Filter }).ToList();
  742. if (CustomFilterIndex != null)
  743. {
  744. Refresh();
  745. }
  746. }
  747. }
  748. private void ExecuteFilter(Tuple<int, string, List<MenuItem>> tag, bool isChecked)
  749. {
  750. var (index, filter, items) = tag;
  751. if (isChecked)
  752. {
  753. var i = 0;
  754. foreach (var item in items)
  755. {
  756. item.IsChecked = i == index;
  757. ++i;
  758. }
  759. }
  760. if (isChecked)
  761. {
  762. CustomFilter = Serialization.Deserialize(typeof(Filter<>).MakeGenericType(FormType!), filter) as IFilter;
  763. CustomFilterIndex = index;
  764. Refresh();
  765. }
  766. else if (index == CustomFilterIndex)
  767. {
  768. CustomFilter = null;
  769. CustomFilterIndex = null;
  770. Refresh();
  771. }
  772. }
  773. private void ExecuteModule_Click(CustomModule obj)
  774. {
  775. if (!string.IsNullOrWhiteSpace(obj.Script))
  776. try
  777. {
  778. Selection selection;
  779. if (obj.SelectedRecords && obj.AllRecords)
  780. selection = RecordSelectionDialog.Execute();
  781. else if (obj.SelectedRecords)
  782. selection = Selection.Selected;
  783. else if (obj.AllRecords)
  784. selection = Selection.All;
  785. else
  786. selection = Selection.None;
  787. var result = ScriptDocument.RunCustomModule(DataModel(selection), new Dictionary<string, object[]>(), obj.Script);
  788. if (result)
  789. Refresh();
  790. }
  791. catch (CompileException c)
  792. {
  793. MessageBox.Show(c.Message);
  794. }
  795. catch (Exception err)
  796. {
  797. MessageBox.Show(CoreUtils.FormatException(err));
  798. }
  799. else
  800. MessageBox.Show("Unable to load " + obj.Name);
  801. }
  802. private void ManageModules_Click()
  803. {
  804. var section = SectionName;
  805. var dataModel = DataModel(Selection.Selected);
  806. var manager = new CustomModuleManager()
  807. {
  808. Section = section,
  809. DataModel = dataModel
  810. };
  811. manager.ShowDialog();
  812. }
  813. private void ToggleDateFilter(bool isChecked)
  814. {
  815. Properties.ShowDateFilter = isChecked;
  816. SetDateFilterVisibility(Properties.ShowDateFilter);
  817. }
  818. private void ToggleJobFilter(bool isChecked)
  819. {
  820. Properties.ShowJobFilter = isChecked;
  821. SetJobFilterVisibility(Properties.ShowJobFilter);
  822. Refresh();
  823. }
  824. #region Filtering
  825. private DateTime From { get; set; }
  826. private DateTime To { get; set; }
  827. private bool IsEntityForm { get; set; }
  828. private Type? ParentType { get; set; }
  829. private Type? FormType { get; set; }
  830. private DigitalForm? Form { get; set; }
  831. private IFilter? CustomFilter { get; set; }
  832. private int? CustomFilterIndex { get; set; }
  833. private readonly Dictionary<string, string> QuestionCodes = new();
  834. private static int WeekDay(DateTime date)
  835. {
  836. if (date.DayOfWeek == DayOfWeek.Sunday)
  837. return 7;
  838. return (int)date.DayOfWeek - 1;
  839. }
  840. private void SetupDateFilters()
  841. {
  842. switch (Properties.DateFilterType)
  843. {
  844. case DateFilterType.Today:
  845. From = DateTime.Today;
  846. To = DateTime.Today;
  847. break;
  848. case DateFilterType.Yesterday:
  849. From = DateTime.Today.AddDays(-1);
  850. To = DateTime.Today.AddDays(-1);
  851. break;
  852. case DateFilterType.Week:
  853. From = DateTime.Today.AddDays(-WeekDay(DateTime.Today));
  854. To = DateTime.Today;
  855. break;
  856. case DateFilterType.SevenDays:
  857. From = DateTime.Today.AddDays(-6);
  858. To = DateTime.Today;
  859. break;
  860. case DateFilterType.Month:
  861. From = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
  862. To = DateTime.Today;
  863. break;
  864. case DateFilterType.ThirtyDays:
  865. From = DateTime.Today.AddDays(-29);
  866. To = DateTime.Today;
  867. break;
  868. case DateFilterType.Year:
  869. From = new DateTime(DateTime.Today.Year, 1, 1);
  870. To = DateTime.Today;
  871. break;
  872. case DateFilterType.TwelveMonths:
  873. From = DateTime.Today.AddYears(-1).AddDays(1);
  874. To = DateTime.Today;
  875. break;
  876. case DateFilterType.Custom:
  877. From = Properties.FromDate;
  878. To = Properties.ToDate;
  879. break;
  880. }
  881. DateTypeBox.SelectedValue = Properties.DateFilterType;
  882. FromPicker.SelectedDate = From;
  883. ToPicker.SelectedDate = To;
  884. var enabledPicker = Properties.DateFilterType == DateFilterType.Custom;
  885. FromPicker.IsEnabled = enabledPicker;
  886. ToPicker.IsEnabled = enabledPicker;
  887. }
  888. private void SetupJobFilter()
  889. {
  890. JobBox.SelectedValue = Properties.JobID;
  891. }
  892. private void SetupFilters()
  893. {
  894. SetupDateFilters();
  895. SetupJobFilter();
  896. SetDateFilterVisibility(Properties.ShowDateFilter);
  897. SetJobFilterVisibility(Properties.ShowJobFilter);
  898. }
  899. #region Categories
  900. private static Dictionary<string, Tuple<Type, Type>>? FormInstanceTypes;
  901. private static readonly Dictionary<Type, List<Tuple<string, string>>> parentColumns = new()
  902. {
  903. { typeof(Kanban), new() { new("Parent.Number", "Task No") } },
  904. { typeof(Job), new() { new("Parent.JobNumber", "Job No") } },
  905. { typeof(JobITP), new() { new("Parent.Code", "Code") } },
  906. { typeof(Assignment), new() { new("Parent.Number", "Ass. No") } },
  907. { typeof(TimeSheet), new() { } },
  908. { typeof(LeaveRequest), new() { } },
  909. { typeof(Employee), new() { new("Parent.Code", "Employee") } },
  910. { typeof(PurchaseOrderItem), new() { new("Parent.PONumber", "PO No") } },
  911. };
  912. private static bool CategoryToType(string category, [NotNullWhen(true)] out Type? formType, [NotNullWhen(true)] out Type? parentType)
  913. {
  914. FormInstanceTypes ??= CoreUtils.TypeList(
  915. AppDomain.CurrentDomain.GetAssemblies(),
  916. x => !x.IsAbstract && x.GetInterfaces().Contains(typeof(IDigitalFormInstance))
  917. ).Select(x =>
  918. {
  919. var inter = x.GetInterfaces()
  920. .Where(x => x.IsGenericType && x.GetGenericTypeDefinition().Equals(typeof(IDigitalFormInstance<>))).FirstOrDefault();
  921. if (inter is not null)
  922. {
  923. var link = inter.GenericTypeArguments[0];
  924. var entityLinkDef = link.GetSuperclassDefinition(typeof(EntityLink<>));
  925. if (entityLinkDef is not null)
  926. {
  927. var entityType = entityLinkDef.GenericTypeArguments[0];
  928. return new Tuple<string, Type, Type>(entityType.Name, x, entityType);
  929. }
  930. }
  931. return null;
  932. }).Where(x => x is not null).ToDictionary(x => x!.Item1, x => new Tuple<Type, Type>(x!.Item2, x!.Item3));
  933. if (!FormInstanceTypes.TryGetValue(category, out var result))
  934. {
  935. formType = null;
  936. parentType = null;
  937. return false;
  938. }
  939. formType = result.Item1;
  940. parentType = result.Item2;
  941. return true;
  942. }
  943. private void SetCategory(string? category)
  944. {
  945. CustomFilter = null;
  946. CustomFilterIndex = null;
  947. if (category is null || !CategoryToType(category, out var formType, out var parentType))
  948. {
  949. IsEntityForm = false;
  950. ParentType = null;
  951. FormType = null;
  952. return;
  953. }
  954. IsEntityForm = formType.IsSubclassOfRawGeneric(typeof(EntityForm<,,>));
  955. ParentType = parentType;
  956. FormType = formType;
  957. }
  958. #endregion
  959. private string GetJobLink(string prefix, Type type)
  960. {
  961. var props = type.GetProperties().Where(x =>
  962. x.PropertyType.BaseType != null && x.PropertyType.BaseType.IsGenericType &&
  963. x.PropertyType.BaseType.GetGenericTypeDefinition() == typeof(EntityLink<>));
  964. foreach (var prop in props)
  965. {
  966. if (prop.PropertyType == typeof(JobLink))
  967. return (string.IsNullOrEmpty(prefix) ? "" : prefix + ".") + prop.Name;
  968. var result = GetJobLink((string.IsNullOrEmpty(prefix) ? "" : prefix + ".") + prop.Name, prop.PropertyType);
  969. if (!string.IsNullOrEmpty(result))
  970. return result;
  971. }
  972. return "";
  973. }
  974. /// <summary>
  975. /// Find a link from the form type to an associated <see cref="Job"/>, allowing us to filter based on jobs.
  976. /// </summary>
  977. /// <returns>The property name of the <see cref="JobLink"/>.</returns>
  978. private string GetJobLink<T>() where T : IDigitalFormInstance
  979. => GetJobLink("", typeof(T));
  980. private IKeyedQueryDef GetFormQuery<T>()
  981. where T : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  982. {
  983. var sort = LookupFactory.DefineSort<T>();
  984. var jobLink = GetJobLink<T>();
  985. var completedFilter = new Filter<T>(x => x.FormCompleted).IsGreaterThanOrEqualTo(From)
  986. .And(x => x.FormCompleted).IsLessThan(To.AddDays(1));
  987. if (Properties.ShowIncompleteForms)
  988. {
  989. completedFilter.Or(x => x.FormCompleted).IsEqualTo(FilterConstant.Null);
  990. }
  991. var filter = new Filter<T>(x => x.Form.ID).IsEqualTo(Form!.ID)
  992. .And(x => x.FormCancelled).IsEqualTo(DateTime.MinValue)
  993. .And(completedFilter);
  994. if (Properties.JobID != Guid.Empty && Properties.ShowJobFilter)
  995. {
  996. filter.And(jobLink + ".ID").IsEqualTo(Properties.JobID);
  997. }
  998. if (CustomFilter is not null)
  999. {
  1000. filter.And(CustomFilter);
  1001. }
  1002. var columns = Columns.None<T>().Add(x => x.ID)
  1003. .Add(x => x.Number)
  1004. .Add(x => x.Description)
  1005. .Add(x => x.CreatedBy)
  1006. .Add(x => x.Created)
  1007. .Add(x => x.Form.ID)
  1008. .Add(x => x.FormData)
  1009. .Add(x => x.FormStarted)
  1010. .Add(x => x.FormCompleted)
  1011. .Add(x => x.FormCompletedBy.UserID)
  1012. .Add(x => x.Location.Timestamp)
  1013. .Add(x => x.Location.Latitude)
  1014. .Add(x => x.Location.Longitude);
  1015. if (IsEntityForm)
  1016. columns.Add(x => x.FormProcessed); //"Processed");
  1017. var parentcols = LookupFactory.DefineColumns(ParentType!);
  1018. foreach (var col in parentcols.ColumnNames())
  1019. columns.Add("Parent." + col);
  1020. if (parentColumns.TryGetValue(ParentType!, out var pColumns))
  1021. {
  1022. foreach (var (field, name) in pColumns)
  1023. {
  1024. columns.Add(field);
  1025. }
  1026. }
  1027. if (!string.IsNullOrWhiteSpace(jobLink))
  1028. columns.Add(jobLink + ".ID");
  1029. return new KeyedQueryDef<T>(filter, columns, sort);
  1030. }
  1031. #endregion
  1032. private void LoadDataIntoGrid(List<DigitalFormVariable> variables, List<QAQuestion> questions, CoreTable formData, List<string> additionalColumns, CoreTable? jobITPs)
  1033. {
  1034. var data = new DataTable();
  1035. data.Columns.Add("ID", typeof(Guid));
  1036. data.Columns.Add("Form_ID", typeof(Guid));
  1037. data.Columns.Add("Parent_ID", typeof(Guid));
  1038. data.Columns.Add("Location_Timestamp", typeof(DateTime));
  1039. data.Columns.Add("Location_Latitude", typeof(double));
  1040. data.Columns.Add("Location_Longitude", typeof(double));
  1041. data.Columns.Add("FormData", typeof(string));
  1042. data.Columns.Add("Number", typeof(string));
  1043. data.Columns.Add("Description", typeof(string));
  1044. if (ParentType == typeof(JobITP))
  1045. {
  1046. data.Columns.Add("Job No", typeof(string));
  1047. }
  1048. if (parentColumns.TryGetValue(ParentType!, out var pColumns))
  1049. {
  1050. foreach (var (field, name) in pColumns)
  1051. {
  1052. data.Columns.Add(name, typeof(string));
  1053. }
  1054. }
  1055. data.Columns.Add("Parent_Description", typeof(string));
  1056. data.Columns.Add("Created", typeof(DateTime));
  1057. data.Columns.Add("Created By", typeof(string));
  1058. data.Columns.Add("Completed", typeof(DateTime));
  1059. data.Columns.Add("Completed By", typeof(string));
  1060. if (IsEntityForm)
  1061. data.Columns.Add("Processed", typeof(bool));
  1062. if (variables.Any())
  1063. {
  1064. foreach (var variable in variables)
  1065. {
  1066. var code = variable.Code.Replace("/", " ");
  1067. QuestionCodes[code] = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(code.ToLower());
  1068. try
  1069. {
  1070. data.Columns.Add(code, typeof(string));
  1071. }
  1072. catch (DuplicateNameException)
  1073. {
  1074. MessageBox.Show($"Error: duplicate variable code {code}");
  1075. }
  1076. }
  1077. }
  1078. else if (questions.Any())
  1079. {
  1080. Questions = questions;
  1081. Progress.SetMessage("Loading Checks");
  1082. QAGrid.Clear();
  1083. QAGrid.LoadChecks(Form!.Description, Questions, new Dictionary<Guid, object>());
  1084. QAGrid.CollapseMargins();
  1085. var i = 1;
  1086. foreach (var question in Questions)
  1087. {
  1088. var id = question.ID.ToString();
  1089. if (!question.Answer.Equals(QAAnswer.Comment))
  1090. {
  1091. data.Columns.Add(id, typeof(string));
  1092. var code = question.Code;
  1093. QuestionCodes[id] = string.IsNullOrEmpty(code) ? string.Format("{0}.", i) : code;
  1094. i++;
  1095. }
  1096. }
  1097. }
  1098. foreach (var row in formData.Rows)
  1099. {
  1100. var form = (row.ToObject(FormType!) as IDigitalFormInstance)!;
  1101. if (true) //(!string.IsNullOrWhiteSpace(form.FormData))
  1102. {
  1103. var dataRow = data.NewRow();
  1104. dataRow["ID"] = form.ID;
  1105. dataRow["Form_ID"] = form.Form.ID;
  1106. dataRow["Parent_ID"] = form.ParentID();
  1107. dataRow["Location_Timestamp"] = form.Location.Timestamp;
  1108. dataRow["Location_Latitude"] = form.Location.Latitude;
  1109. dataRow["Location_Longitude"] = form.Location.Longitude;
  1110. dataRow["FormData"] = form.FormData;
  1111. dataRow["Number"] = form.Number;
  1112. dataRow["Description"] = form.Description;
  1113. var desc = new List<string>();
  1114. foreach (var col in additionalColumns)
  1115. {
  1116. var val = row[col];
  1117. if (val != null && val is not Guid)
  1118. desc.Add(val.ToString() ?? "");
  1119. }
  1120. dataRow["Parent_Description"] = string.Join(" : ", desc);
  1121. dataRow["Created"] = (form as Entity)!.Created.IsEmpty()
  1122. ? form.FormStarted
  1123. : (form as Entity)!.Created;
  1124. dataRow["Created By"] = (form as Entity)!.CreatedBy;
  1125. dataRow["Completed"] = form.FormCompleted;
  1126. dataRow["Completed By"] = form.FormCompletedBy.UserID;
  1127. if (IsEntityForm)
  1128. dataRow["Processed"] = form.FormProcessed > DateTime.MinValue;
  1129. if (ParentType == typeof(JobITP))
  1130. {
  1131. var jobITP = jobITPs!.Rows.FirstOrDefault(x => x.Get<JobITP, Guid>(x => x.ID) == form.ParentID());
  1132. if (jobITP is not null)
  1133. {
  1134. var jobID = jobITP.Get<JobITP, Guid>(x => x.Job.ID);
  1135. dataRow["Job No"] = Jobs.Where(x => x.ID == jobID).FirstOrDefault()?.JobNumber;
  1136. }
  1137. }
  1138. if (pColumns != null)
  1139. {
  1140. foreach (var (field, name) in pColumns)
  1141. {
  1142. dataRow[name] = row[field]?.ToString();
  1143. }
  1144. }
  1145. //datarow["Job No"] = (String)row[JobLink + ".JobNumber"];
  1146. var bHasData = false;
  1147. if (variables.Any())
  1148. {
  1149. var dict = Serialization.Deserialize<Dictionary<string, object?>>(form.FormData);
  1150. if (dict is not null)
  1151. {
  1152. var storage = new DFLoadStorage(dict, null);
  1153. foreach (var variable in variables)
  1154. {
  1155. var value = variable.Deserialize(storage.GetEntry(variable.Code));
  1156. var format = variable.FormatValue(value);
  1157. var sKey = variable.Code.Replace("/", " ");
  1158. if (data.Columns.Contains(sKey))
  1159. {
  1160. dataRow[sKey] = format;
  1161. bHasData = true;
  1162. }
  1163. }
  1164. }
  1165. }
  1166. else
  1167. {
  1168. var dict = Serialization.Deserialize<Dictionary<Guid, object>>(form.FormData);
  1169. if (dict is not null)
  1170. foreach (var key in dict.Keys)
  1171. if (data.Columns.Contains(key.ToString()))
  1172. {
  1173. dataRow[key.ToString()] = dict[key];
  1174. bHasData = true;
  1175. }
  1176. }
  1177. //if (bHasData)
  1178. data.Rows.Add(dataRow);
  1179. }
  1180. }
  1181. DataGrid.ItemsSource = data;
  1182. IsQAForm = !variables.Any() && questions.Any();
  1183. QAGrid.Visibility = IsQAForm ? Visibility.Visible : Visibility.Collapsed;
  1184. DataGrid.Visibility = Visibility.Visible;
  1185. }
  1186. private void RefreshData<TForm>()
  1187. where TForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1188. {
  1189. var formQuery = GetFormQuery<TForm>();
  1190. var queries = new List<IKeyedQueryDef>()
  1191. {
  1192. new KeyedQueryDef<QAQuestion>(new Filter<QAQuestion>(x => x.Form.ID).IsEqualTo(Form!.ID)),
  1193. new KeyedQueryDef<DigitalFormVariable>(
  1194. new Filter<DigitalFormVariable>(x => x.Form.ID).IsEqualTo(Form.ID),
  1195. null,
  1196. new SortOrder<DigitalFormVariable>(x => x.Sequence)),
  1197. formQuery
  1198. };
  1199. if (ParentType == typeof(JobITP))
  1200. {
  1201. queries.Add(new KeyedQueryDef<JobITP>(
  1202. new Filter<JobITP>(x => x.ID).InQuery((formQuery.Filter as Filter<JobITPForm>)!, x => x.Parent.ID),
  1203. Columns.None<JobITP>().Add(x => x.ID, x => x.Job.JobNumber)));
  1204. }
  1205. var results = Client.QueryMultiple(queries);
  1206. var questions = results.Get<QAQuestion>().ToObjects<QAQuestion>().ToList();
  1207. var variables = results.Get<DigitalFormVariable>().ToObjects<DigitalFormVariable>().ToList();
  1208. var formData = results.Get(formQuery.Key);
  1209. LoadDataIntoGrid(
  1210. variables, questions,
  1211. formData,
  1212. formQuery.Columns!.ColumnNames().Where(x => x.StartsWith("Parent.")).ToList(),
  1213. ParentType == typeof(JobITP) ? results.Get<JobITP>() : null);
  1214. }
  1215. public void Refresh()
  1216. {
  1217. if (!IsSetup) return;
  1218. Questions.Clear();
  1219. QAGrid.Clear();
  1220. QAGrid.LoadChecks("", Array.Empty<QAQuestion>(), new Dictionary<Guid, object>());
  1221. DataGrid.ItemsSource = null;
  1222. if (ParentType is null || FormType is null || Form is null || Form.ID == Guid.Empty)
  1223. {
  1224. QAGrid.Visibility = Visibility.Collapsed;
  1225. DataGrid.Visibility = Visibility.Collapsed;
  1226. return;
  1227. }
  1228. var refreshMethod = typeof(DigitalFormsDashboard).GetMethod(nameof(RefreshData), BindingFlags.Instance | BindingFlags.NonPublic)!.MakeGenericMethod(FormType);
  1229. refreshMethod.Invoke(this, Array.Empty<object?>());
  1230. }
  1231. public void Shutdown(CancelEventArgs? cancel)
  1232. {
  1233. }
  1234. #region DataGrid Configuration
  1235. private class RowStyleSelector : StyleSelector
  1236. {
  1237. private Style NormalStyle;
  1238. private Style IncompleteStyle;
  1239. public RowStyleSelector()
  1240. {
  1241. NormalStyle = new Style();
  1242. NormalStyle.Setters.Add(new Setter(VirtualizingCellsControl.BackgroundProperty, new SolidColorBrush(Colors.White)));
  1243. IncompleteStyle = new Style();
  1244. IncompleteStyle.Setters.Add(new Setter(VirtualizingCellsControl.BackgroundProperty, new SolidColorBrush(Colors.LightSalmon)));
  1245. }
  1246. public override Style SelectStyle(object item, DependencyObject container)
  1247. {
  1248. var row = (item as DataRowBase)?.RowData as DataRowView;
  1249. if (row is null) return NormalStyle;
  1250. return (DateTime)row["Completed"] == DateTime.MinValue
  1251. ? IncompleteStyle
  1252. : NormalStyle;
  1253. }
  1254. }
  1255. private void DataGrid_AutoGeneratingColumn(object sender, Syncfusion.UI.Xaml.Grid.AutoGeneratingColumnArgs e)
  1256. {
  1257. e.Column.TextAlignment = TextAlignment.Center;
  1258. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Center;
  1259. e.Column.ColumnSizer = GridLengthUnitType.None;
  1260. e.Column.ImmediateUpdateColumnFilter = true;
  1261. e.Column.FilterRowCondition = FilterRowCondition.Contains;
  1262. e.Column.FilterRowOptionsVisibility = Visibility.Collapsed;
  1263. var value = (e.Column.ValueBinding as Binding)!;
  1264. if (value.Path.Path.Equals("ID") || value.Path.Path.Equals("Form_ID") || value.Path.Path.Equals("Parent_ID") ||
  1265. value.Path.Path.Equals("FormData") || value.Path.Path.Equals("Location_Latitude") || value.Path.Path.Equals("Location_Longitude"))
  1266. {
  1267. e.Cancel = true;
  1268. }
  1269. else if (value.Path.Path.Equals("Number"))
  1270. {
  1271. e.Column.Width = 80;
  1272. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1273. }
  1274. else if (value.Path.Path.Equals("Description"))
  1275. {
  1276. e.Column.Width = 250;
  1277. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1278. e.Column.TextAlignment = TextAlignment.Left;
  1279. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Left;
  1280. }
  1281. else if (value.Path.Path.Equals("Location_Timestamp"))
  1282. {
  1283. e.Column = new GridImageColumn();
  1284. e.Column.Width = DataGrid.RowHeight;
  1285. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1286. e.Column.HeaderText = "";
  1287. e.Column.Padding = new Thickness(4);
  1288. e.Column.ValueBinding = new Binding
  1289. {
  1290. Path = new PropertyPath(value.Path.Path),
  1291. Converter = new MileStoneImageConverter()
  1292. };
  1293. e.Column.MappingName = "Location.Timestamp";
  1294. }
  1295. else if (ParentType is not null && parentColumns.TryGetValue(ParentType, out var pColumns) && pColumns.Any(x => x.Item2.Equals(value.Path.Path)))
  1296. {
  1297. e.Column.ColumnSizer = GridLengthUnitType.Auto;
  1298. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1299. }
  1300. else if (value.Path.Path.Equals("Job No"))
  1301. {
  1302. e.Column.Width = 60;
  1303. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1304. }
  1305. else if (value.Path.Path.Equals("Parent_Description"))
  1306. {
  1307. e.Column.HeaderText = Categories.FirstOrDefault(x => x.Item2 == FormType)?.Item3 ?? "Parent";
  1308. e.Column.TextAlignment = TextAlignment.Left;
  1309. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Left;
  1310. e.Column.Width = 250;
  1311. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1312. }
  1313. else if (value.Path.Path.Equals("Completed"))
  1314. {
  1315. e.Column.Width = 100;
  1316. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1317. (e.Column as GridDateTimeColumn)!.DisplayBinding = new Binding {
  1318. Path = new PropertyPath(value.Path.Path),
  1319. Converter = new DateTimeToStringConverter("dd MMM yy hh:mm")
  1320. };
  1321. }
  1322. else if (value.Path.Path.Equals("Completed By"))
  1323. {
  1324. e.Column.Width = 100;
  1325. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1326. }
  1327. else if (value.Path.Path.Equals("Processed"))
  1328. {
  1329. e.Column.Width = 100;
  1330. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1331. }
  1332. else if (value.Path.Path.Equals("Created By"))
  1333. {
  1334. e.Column.Width = 100;
  1335. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1336. }
  1337. else if (value.Path.Path.Equals("Created"))
  1338. {
  1339. e.Column.Width = 100;
  1340. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1341. (e.Column as GridDateTimeColumn)!.DisplayBinding = new Binding {
  1342. Path = new PropertyPath(value.Path.Path),
  1343. Converter = new DateTimeToStringConverter("dd MMM yy hh:mm")
  1344. };
  1345. }
  1346. else
  1347. {
  1348. var data = DataGrid.ItemsSource as DataTable;
  1349. //int index = data.Columns.IndexOf(e.Column.MappingName) - 2;
  1350. //Style style = new Style(typeof(GridCell));
  1351. //e.Column.CellStyle = style;
  1352. e.Column.Width = 100;
  1353. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1354. e.Column.HeaderText = QuestionCodes[e.Column.MappingName];
  1355. }
  1356. }
  1357. private Entity? GetEntityForm<T>(Guid id) where T : Entity, IDigitalFormInstance, IRemotable, IPersistent, new()
  1358. {
  1359. var columns = DynamicFormEditWindow.FormColumns<T>();
  1360. return new Client<T>().Query(
  1361. new Filter<T>(x => x.ID).IsEqualTo(id),
  1362. columns).Rows.FirstOrDefault()?.ToObject<T>();
  1363. }
  1364. private void DataGrid_CellDoubleTapped(object sender, Syncfusion.UI.Xaml.Grid.GridCellDoubleTappedEventArgs e)
  1365. {
  1366. if (e.RowColumnIndex.RowIndex < 2)
  1367. return;
  1368. var rowOffset = -2;
  1369. //var table = (DataGrid.ItemsSource as DataTable)!;
  1370. var row = (e.Record as DataRowView)?.Row;
  1371. if (row == null)
  1372. {
  1373. MessageBox.Show($"Unexpected Record type ({e.Record?.GetType().EntityName() ?? "NULL"}");
  1374. return;
  1375. }
  1376. var formid = (Guid)row["Form_ID"];
  1377. var formdata = (string)row["FormData"];
  1378. var id = (Guid)row["ID"];
  1379. if (FormType is null) return;
  1380. if (IsQAForm)
  1381. {
  1382. var values = new Dictionary<Guid, object>();
  1383. var formData = Serialization.Deserialize<Dictionary<string, object>>(formdata);
  1384. if (formData is not null)
  1385. {
  1386. foreach (var (idStr, value) in formData)
  1387. {
  1388. if (Guid.TryParse(idStr, out var codeID))
  1389. {
  1390. values[codeID] = value;
  1391. }
  1392. }
  1393. }
  1394. QAGrid.Clear();
  1395. QAGrid.LoadChecks(Form!.Description, Questions, values);
  1396. QAGrid.CollapseMargins();
  1397. return;
  1398. }
  1399. var entityForm = typeof(DigitalFormsDashboard)
  1400. .GetMethod(nameof(GetEntityForm), BindingFlags.NonPublic | BindingFlags.Instance)!
  1401. .MakeGenericMethod(FormType)
  1402. .Invoke(this, new object[] { id }) as IDigitalFormInstance;
  1403. if (entityForm is not null)
  1404. {
  1405. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel))
  1406. {
  1407. dataModel.Update(null);
  1408. /*typeof(QADashboard)
  1409. .GetMethod(nameof(SaveEntityForm), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
  1410. .MakeGenericMethod(formType)
  1411. .Invoke(this, new object[] { entityForm });*/
  1412. Refresh();
  1413. }
  1414. }
  1415. }
  1416. private void DataGrid_CellTapped(object sender, Syncfusion.UI.Xaml.Grid.GridCellTappedEventArgs e)
  1417. {
  1418. if (e.RowColumnIndex.ColumnIndex == 0)
  1419. {
  1420. var timestamp = (DateTime)(e.Record as DataRowView)!.Row["Location_Timestamp"];
  1421. var latitude = (double)(e.Record as DataRowView)!.Row["Location_Latitude"];
  1422. var longitude = (double)(e.Record as DataRowView)!.Row["Location_Longitude"];
  1423. var form = new MapForm(latitude, longitude, timestamp);
  1424. form.ShowDialog();
  1425. }
  1426. }
  1427. #endregion
  1428. }