DigitalFormsDashboard.xaml.cs 60 KB

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