DigitalFormsDashboard.xaml.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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 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. new Columns<Job>(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("Save to Folder", 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. File.WriteAllBytes(Path.Combine(dialog.SelectedPath, Path.ChangeExtension(number, ".pdf")), pdfData);
  681. }
  682. });
  683. MessageWindow.ShowMessage("All done!", "Success");
  684. }
  685. }
  686. }
  687. private void Export_Click()
  688. {
  689. var formName = Regex.Replace(Form?.Description ?? "", "[^ a-zA-Z0-9]", "");
  690. var filename = string.Format("{0} - {1} - {2:yyyy-MM-dd} - {3:yyyy-MM-dd}.xlsx", ParentType!.Name, formName, From, To);
  691. var options = new ExcelExportingOptions();
  692. options.ExcelVersion = ExcelVersion.Excel2013;
  693. options.ExportStackedHeaders = true;
  694. var excelEngine = DataGrid.ExportToExcel(DataGrid.View, options);
  695. var workBook = excelEngine.Excel.Workbooks[0];
  696. var sheet = workBook.Worksheets[0];
  697. sheet.Name = "Summary";
  698. sheet.UsedRange.AutofitRows();
  699. sheet.UsedRange.AutofitColumns();
  700. sheet = workBook.Worksheets.Create("Questions");
  701. sheet.Move(0);
  702. var questions = new Client<QAQuestion>().Query(new Filter<QAQuestion>(x => x.Form.ID).IsEqualTo(Form!.ID));
  703. sheet.Range[1, 1].Text = Form?.Description ?? "";
  704. sheet.Range[1, 1, 1, 3].Merge();
  705. var i = 1;
  706. foreach (var row in questions.Rows)
  707. if (!row.Get<QAQuestion, QAAnswer>(x => x.Answer).Equals(QAAnswer.Comment))
  708. {
  709. sheet.Range[i + 2, 1].Text = string.Format("{0}.", i);
  710. sheet.Range[i + 2, 2].Text = string.Format("{0}", row.Get<QAQuestion, string>(x => x.Question));
  711. sheet.Range[i + 2, 3].Text = string.Format("[{0}]", row.Get<QAQuestion, string>(x => x.Code));
  712. i++;
  713. }
  714. sheet.UsedRange.AutofitRows();
  715. sheet.UsedRange.AutofitColumns();
  716. try
  717. {
  718. workBook.SaveAs(filename);
  719. var startInfo = new ProcessStartInfo(filename);
  720. startInfo.Verb = "open";
  721. startInfo.UseShellExecute = true;
  722. Process.Start(startInfo);
  723. }
  724. catch
  725. {
  726. MessageBox.Show(string.Format("Unable to Save/Launch [{0}]!\n\nIs the file already open?", filename));
  727. }
  728. }
  729. private void ManageFilters_Click()
  730. {
  731. var filters = Properties.Filters.GetValueOrDefault(ParentType!.Name) ?? new List<DFFilter>();
  732. var gridFilters = new CoreFilterDefinitions();
  733. gridFilters.AddRange(filters.Select(x => new CoreFilterDefinition { Name = x.Name, Filter = x.Filter }));
  734. var grid = new DynamicGridFilterEditor(gridFilters, FormType!);
  735. if (grid.ShowDialog() == true)
  736. {
  737. Properties.Filters[ParentType!.Name] = grid.Filters.Select(x => new DFFilter { Name = x.Name, Filter = x.Filter }).ToList();
  738. if (CustomFilterIndex != null)
  739. {
  740. Refresh();
  741. }
  742. }
  743. }
  744. private void ExecuteFilter(Tuple<int, string, List<MenuItem>> tag, bool isChecked)
  745. {
  746. var (index, filter, items) = tag;
  747. if (isChecked)
  748. {
  749. var i = 0;
  750. foreach (var item in items)
  751. {
  752. item.IsChecked = i == index;
  753. ++i;
  754. }
  755. }
  756. if (isChecked)
  757. {
  758. CustomFilter = Serialization.Deserialize(typeof(Filter<>).MakeGenericType(FormType!), filter) as IFilter;
  759. CustomFilterIndex = index;
  760. Refresh();
  761. }
  762. else if (index == CustomFilterIndex)
  763. {
  764. CustomFilter = null;
  765. CustomFilterIndex = null;
  766. Refresh();
  767. }
  768. }
  769. private void ExecuteModule_Click(CustomModule obj)
  770. {
  771. if (!string.IsNullOrWhiteSpace(obj.Script))
  772. try
  773. {
  774. Selection selection;
  775. if (obj.SelectedRecords && obj.AllRecords)
  776. selection = RecordSelectionDialog.Execute();
  777. else if (obj.SelectedRecords)
  778. selection = Selection.Selected;
  779. else if (obj.AllRecords)
  780. selection = Selection.All;
  781. else
  782. selection = Selection.None;
  783. var result = ScriptDocument.RunCustomModule(DataModel(selection), new Dictionary<string, object[]>(), obj.Script);
  784. if (result)
  785. Refresh();
  786. }
  787. catch (CompileException c)
  788. {
  789. MessageBox.Show(c.Message);
  790. }
  791. catch (Exception err)
  792. {
  793. MessageBox.Show(CoreUtils.FormatException(err));
  794. }
  795. else
  796. MessageBox.Show("Unable to load " + obj.Name);
  797. }
  798. private void ManageModules_Click()
  799. {
  800. var section = SectionName;
  801. var dataModel = DataModel(Selection.Selected);
  802. var manager = new CustomModuleManager()
  803. {
  804. Section = section,
  805. DataModel = dataModel
  806. };
  807. manager.ShowDialog();
  808. }
  809. private void ToggleDateFilter(bool isChecked)
  810. {
  811. Properties.ShowDateFilter = isChecked;
  812. SetDateFilterVisibility(Properties.ShowDateFilter);
  813. }
  814. private void ToggleJobFilter(bool isChecked)
  815. {
  816. Properties.ShowJobFilter = isChecked;
  817. SetJobFilterVisibility(Properties.ShowJobFilter);
  818. Refresh();
  819. }
  820. #region Filtering
  821. private DateTime From { get; set; }
  822. private DateTime To { get; set; }
  823. private bool IsEntityForm { get; set; }
  824. private Type? ParentType { get; set; }
  825. private Type? FormType { get; set; }
  826. private DigitalForm? Form { get; set; }
  827. private IFilter? CustomFilter { get; set; }
  828. private int? CustomFilterIndex { get; set; }
  829. private readonly Dictionary<string, string> QuestionCodes = new();
  830. private static int WeekDay(DateTime date)
  831. {
  832. if (date.DayOfWeek == DayOfWeek.Sunday)
  833. return 7;
  834. return (int)date.DayOfWeek - 1;
  835. }
  836. private void SetupDateFilters()
  837. {
  838. switch (Properties.DateFilterType)
  839. {
  840. case DateFilterType.Today:
  841. From = DateTime.Today;
  842. To = DateTime.Today;
  843. break;
  844. case DateFilterType.Yesterday:
  845. From = DateTime.Today.AddDays(-1);
  846. To = DateTime.Today.AddDays(-1);
  847. break;
  848. case DateFilterType.Week:
  849. From = DateTime.Today.AddDays(-WeekDay(DateTime.Today));
  850. To = DateTime.Today;
  851. break;
  852. case DateFilterType.SevenDays:
  853. From = DateTime.Today.AddDays(-6);
  854. To = DateTime.Today;
  855. break;
  856. case DateFilterType.Month:
  857. From = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
  858. To = DateTime.Today;
  859. break;
  860. case DateFilterType.ThirtyDays:
  861. From = DateTime.Today.AddDays(-29);
  862. To = DateTime.Today;
  863. break;
  864. case DateFilterType.Year:
  865. From = new DateTime(DateTime.Today.Year, 1, 1);
  866. To = DateTime.Today;
  867. break;
  868. case DateFilterType.TwelveMonths:
  869. From = DateTime.Today.AddYears(-1).AddDays(1);
  870. To = DateTime.Today;
  871. break;
  872. case DateFilterType.Custom:
  873. From = Properties.FromDate;
  874. To = Properties.ToDate;
  875. break;
  876. }
  877. DateTypeBox.SelectedValue = Properties.DateFilterType;
  878. FromPicker.SelectedDate = From;
  879. ToPicker.SelectedDate = To;
  880. var enabledPicker = Properties.DateFilterType == DateFilterType.Custom;
  881. FromPicker.IsEnabled = enabledPicker;
  882. ToPicker.IsEnabled = enabledPicker;
  883. }
  884. private void SetupJobFilter()
  885. {
  886. JobBox.SelectedValue = Properties.JobID;
  887. }
  888. private void SetupFilters()
  889. {
  890. SetupDateFilters();
  891. SetupJobFilter();
  892. SetDateFilterVisibility(Properties.ShowDateFilter);
  893. SetJobFilterVisibility(Properties.ShowJobFilter);
  894. }
  895. #region Categories
  896. private static Dictionary<string, Tuple<Type, Type>>? FormInstanceTypes;
  897. private static readonly Dictionary<Type, List<Tuple<string, string>>> parentColumns = new()
  898. {
  899. { typeof(Kanban), new() { new("Parent.Number", "Task No") } },
  900. { typeof(Job), new() { new("Parent.JobNumber", "Job No") } },
  901. { typeof(JobITP), new() { new("Parent.Code", "Code") } },
  902. { typeof(Assignment), new() { new("Parent.Number", "Ass. No") } },
  903. { typeof(TimeSheet), new() { } },
  904. { typeof(LeaveRequest), new() { } },
  905. { typeof(Employee), new() { new("Parent.Code", "Employee") } },
  906. { typeof(PurchaseOrderItem), new() { new("Parent.PONumber", "PO No") } },
  907. };
  908. private static bool CategoryToType(string category, [NotNullWhen(true)] out Type? formType, [NotNullWhen(true)] out Type? parentType)
  909. {
  910. FormInstanceTypes ??= CoreUtils.TypeList(
  911. AppDomain.CurrentDomain.GetAssemblies(),
  912. x => !x.IsAbstract && x.GetInterfaces().Contains(typeof(IDigitalFormInstance))
  913. ).Select(x =>
  914. {
  915. var inter = x.GetInterfaces()
  916. .Where(x => x.IsGenericType && x.GetGenericTypeDefinition().Equals(typeof(IDigitalFormInstance<>))).FirstOrDefault();
  917. if (inter is not null)
  918. {
  919. var link = inter.GenericTypeArguments[0];
  920. var entityLinkDef = link.GetSuperclassDefinition(typeof(EntityLink<>));
  921. if (entityLinkDef is not null)
  922. {
  923. var entityType = entityLinkDef.GenericTypeArguments[0];
  924. return new Tuple<string, Type, Type>(entityType.Name, x, entityType);
  925. }
  926. }
  927. return null;
  928. }).Where(x => x is not null).ToDictionary(x => x!.Item1, x => new Tuple<Type, Type>(x!.Item2, x!.Item3));
  929. if (!FormInstanceTypes.TryGetValue(category, out var result))
  930. {
  931. formType = null;
  932. parentType = null;
  933. return false;
  934. }
  935. formType = result.Item1;
  936. parentType = result.Item2;
  937. return true;
  938. }
  939. private void SetCategory(string? category)
  940. {
  941. CustomFilter = null;
  942. CustomFilterIndex = null;
  943. if (category is null || !CategoryToType(category, out var formType, out var parentType))
  944. {
  945. IsEntityForm = false;
  946. ParentType = null;
  947. FormType = null;
  948. return;
  949. }
  950. IsEntityForm = formType.IsSubclassOfRawGeneric(typeof(EntityForm<,,>));
  951. ParentType = parentType;
  952. FormType = formType;
  953. }
  954. #endregion
  955. private string GetJobLink(string prefix, Type type)
  956. {
  957. var props = type.GetProperties().Where(x =>
  958. x.PropertyType.BaseType != null && x.PropertyType.BaseType.IsGenericType &&
  959. x.PropertyType.BaseType.GetGenericTypeDefinition() == typeof(EntityLink<>));
  960. foreach (var prop in props)
  961. {
  962. if (prop.PropertyType == typeof(JobLink))
  963. return (string.IsNullOrEmpty(prefix) ? "" : prefix + ".") + prop.Name;
  964. var result = GetJobLink((string.IsNullOrEmpty(prefix) ? "" : prefix + ".") + prop.Name, prop.PropertyType);
  965. if (!string.IsNullOrEmpty(result))
  966. return result;
  967. }
  968. return "";
  969. }
  970. /// <summary>
  971. /// Find a link from the form type to an associated <see cref="Job"/>, allowing us to filter based on jobs.
  972. /// </summary>
  973. /// <returns>The property name of the <see cref="JobLink"/>.</returns>
  974. private string GetJobLink<T>() where T : IDigitalFormInstance
  975. => GetJobLink("", typeof(T));
  976. private IKeyedQueryDef GetFormQuery<T>()
  977. where T : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  978. {
  979. var sort = LookupFactory.DefineSort<T>();
  980. var jobLink = GetJobLink<T>();
  981. var completedFilter = new Filter<T>(x => x.FormCompleted).IsGreaterThanOrEqualTo(From)
  982. .And(x => x.FormCompleted).IsLessThan(To.AddDays(1));
  983. if (Properties.ShowIncompleteForms)
  984. {
  985. completedFilter.Or(x => x.FormCompleted).IsEqualTo(FilterConstant.NoDateProvided);
  986. }
  987. var filter = new Filter<T>(x => x.Form.ID).IsEqualTo(Form!.ID)
  988. .And(x => x.FormCancelled).IsEqualTo(DateTime.MinValue)
  989. .And(completedFilter);
  990. if (Properties.JobID != Guid.Empty && Properties.ShowJobFilter)
  991. {
  992. filter.And(jobLink + ".ID").IsEqualTo(Properties.JobID);
  993. }
  994. if (CustomFilter is not null)
  995. {
  996. filter.And(CustomFilter);
  997. }
  998. var columns = new Columns<T>(x => x.ID)
  999. .Add(x => x.Number)
  1000. .Add(x => x.Description)
  1001. .Add(x => x.CreatedBy)
  1002. .Add(x => x.Created)
  1003. .Add(x => x.Form.ID)
  1004. .Add(x => x.FormData)
  1005. .Add(x => x.FormStarted)
  1006. .Add(x => x.FormCompleted)
  1007. .Add(x => x.FormCompletedBy.UserID)
  1008. .Add(x => x.Location.Timestamp)
  1009. .Add(x => x.Location.Latitude)
  1010. .Add(x => x.Location.Longitude);
  1011. if (IsEntityForm)
  1012. columns.Add(x => x.FormProcessed); //"Processed");
  1013. var parentcols = LookupFactory.DefineColumns(ParentType!);
  1014. foreach (var col in parentcols.ColumnNames())
  1015. columns.Add("Parent." + col);
  1016. if (parentColumns.TryGetValue(ParentType!, out var pColumns))
  1017. {
  1018. foreach (var (field, name) in pColumns)
  1019. {
  1020. columns.Add(field);
  1021. }
  1022. }
  1023. if (!string.IsNullOrWhiteSpace(jobLink))
  1024. columns.Add(jobLink + ".ID");
  1025. return new KeyedQueryDef<T>(filter, columns, sort);
  1026. }
  1027. #endregion
  1028. private void LoadDataIntoGrid(List<DigitalFormVariable> variables, List<QAQuestion> questions, CoreTable formData, List<string> additionalColumns, CoreTable? jobITPs)
  1029. {
  1030. var data = new DataTable();
  1031. data.Columns.Add("ID", typeof(Guid));
  1032. data.Columns.Add("Form_ID", typeof(Guid));
  1033. data.Columns.Add("Parent_ID", typeof(Guid));
  1034. data.Columns.Add("Location_Timestamp", typeof(DateTime));
  1035. data.Columns.Add("Location_Latitude", typeof(double));
  1036. data.Columns.Add("Location_Longitude", typeof(double));
  1037. data.Columns.Add("FormData", typeof(string));
  1038. data.Columns.Add("Number", typeof(string));
  1039. data.Columns.Add("Description", typeof(string));
  1040. if (ParentType == typeof(JobITP))
  1041. {
  1042. data.Columns.Add("Job No", typeof(string));
  1043. }
  1044. if (parentColumns.TryGetValue(ParentType!, out var pColumns))
  1045. {
  1046. foreach (var (field, name) in pColumns)
  1047. {
  1048. data.Columns.Add(name, typeof(string));
  1049. }
  1050. }
  1051. data.Columns.Add("Parent_Description", typeof(string));
  1052. data.Columns.Add("Created", typeof(DateTime));
  1053. data.Columns.Add("Created By", typeof(string));
  1054. data.Columns.Add("Completed", typeof(DateTime));
  1055. data.Columns.Add("Completed By", typeof(string));
  1056. if (IsEntityForm)
  1057. data.Columns.Add("Processed", typeof(bool));
  1058. if (variables.Any())
  1059. {
  1060. foreach (var variable in variables)
  1061. {
  1062. var code = variable.Code.Replace("/", " ");
  1063. QuestionCodes[code] = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(code.ToLower());
  1064. try
  1065. {
  1066. data.Columns.Add(code, typeof(string));
  1067. }
  1068. catch (DuplicateNameException)
  1069. {
  1070. MessageBox.Show($"Error: duplicate variable code {code}");
  1071. }
  1072. }
  1073. }
  1074. else if (questions.Any())
  1075. {
  1076. Questions = questions;
  1077. Progress.SetMessage("Loading Checks");
  1078. QAGrid.Clear();
  1079. QAGrid.LoadChecks(Form!.Description, Questions, new Dictionary<Guid, object>());
  1080. QAGrid.CollapseMargins();
  1081. var i = 1;
  1082. foreach (var question in Questions)
  1083. {
  1084. var id = question.ID.ToString();
  1085. if (!question.Answer.Equals(QAAnswer.Comment))
  1086. {
  1087. data.Columns.Add(id, typeof(string));
  1088. var code = question.Code;
  1089. QuestionCodes[id] = string.IsNullOrEmpty(code) ? string.Format("{0}.", i) : code;
  1090. i++;
  1091. }
  1092. }
  1093. }
  1094. foreach (var row in formData.Rows)
  1095. {
  1096. var form = (row.ToObject(FormType!) as IDigitalFormInstance)!;
  1097. if (!string.IsNullOrWhiteSpace(form.FormData))
  1098. {
  1099. var dataRow = data.NewRow();
  1100. dataRow["ID"] = form.ID;
  1101. dataRow["Form_ID"] = form.Form.ID;
  1102. dataRow["Parent_ID"] = form.ParentID();
  1103. dataRow["Location_Timestamp"] = form.Location.Timestamp;
  1104. dataRow["Location_Latitude"] = form.Location.Latitude;
  1105. dataRow["Location_Longitude"] = form.Location.Longitude;
  1106. dataRow["FormData"] = form.FormData;
  1107. dataRow["Number"] = form.Number;
  1108. dataRow["Description"] = form.Description;
  1109. var desc = new List<string>();
  1110. foreach (var col in additionalColumns)
  1111. {
  1112. var val = row[col];
  1113. if (val != null && val is not Guid)
  1114. desc.Add(val.ToString() ?? "");
  1115. }
  1116. dataRow["Parent_Description"] = string.Join(" : ", desc);
  1117. dataRow["Created"] = (form as Entity)!.Created.IsEmpty()
  1118. ? form.FormStarted
  1119. : (form as Entity)!.Created;
  1120. dataRow["Created By"] = (form as Entity)!.CreatedBy;
  1121. dataRow["Completed"] = form.FormCompleted;
  1122. dataRow["Completed By"] = form.FormCompletedBy.UserID;
  1123. if (IsEntityForm)
  1124. dataRow["Processed"] = form.FormProcessed > DateTime.MinValue;
  1125. if (ParentType == typeof(JobITP))
  1126. {
  1127. var jobITP = jobITPs!.Rows.FirstOrDefault(x => x.Get<JobITP, Guid>(x => x.ID) == form.ParentID());
  1128. if (jobITP is not null)
  1129. {
  1130. var jobID = jobITP.Get<JobITP, Guid>(x => x.Job.ID);
  1131. dataRow["Job No"] = Jobs.Where(x => x.ID == jobID).FirstOrDefault()?.JobNumber;
  1132. }
  1133. }
  1134. if (pColumns != null)
  1135. {
  1136. foreach (var (field, name) in pColumns)
  1137. {
  1138. dataRow[name] = row[field]?.ToString();
  1139. }
  1140. }
  1141. //datarow["Job No"] = (String)row[JobLink + ".JobNumber"];
  1142. var bHasData = false;
  1143. if (variables.Any())
  1144. {
  1145. var dict = Serialization.Deserialize<Dictionary<string, object?>>(form.FormData);
  1146. if (dict is not null)
  1147. {
  1148. var storage = new DFLoadStorage(dict, null);
  1149. foreach (var variable in variables)
  1150. {
  1151. var value = variable.Deserialize(storage.GetEntry(variable.Code));
  1152. var format = variable.FormatValue(value);
  1153. var sKey = variable.Code.Replace("/", " ");
  1154. if (data.Columns.Contains(sKey))
  1155. {
  1156. dataRow[sKey] = format;
  1157. bHasData = true;
  1158. }
  1159. }
  1160. }
  1161. }
  1162. else
  1163. {
  1164. var dict = Serialization.Deserialize<Dictionary<Guid, object>>(form.FormData);
  1165. if (dict is not null)
  1166. foreach (var key in dict.Keys)
  1167. if (data.Columns.Contains(key.ToString()))
  1168. {
  1169. dataRow[key.ToString()] = dict[key];
  1170. bHasData = true;
  1171. }
  1172. }
  1173. if (bHasData)
  1174. data.Rows.Add(dataRow);
  1175. }
  1176. }
  1177. DataGrid.ItemsSource = data;
  1178. IsQAForm = !variables.Any() && questions.Any();
  1179. QAGrid.Visibility = IsQAForm ? Visibility.Visible : Visibility.Collapsed;
  1180. DataGrid.Visibility = Visibility.Visible;
  1181. }
  1182. private void RefreshData<TForm>()
  1183. where TForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1184. {
  1185. var formQuery = GetFormQuery<TForm>();
  1186. var queries = new List<IKeyedQueryDef>()
  1187. {
  1188. new KeyedQueryDef<QAQuestion>(new Filter<QAQuestion>(x => x.Form.ID).IsEqualTo(Form!.ID)),
  1189. new KeyedQueryDef<DigitalFormVariable>(
  1190. new Filter<DigitalFormVariable>(x => x.Form.ID).IsEqualTo(Form.ID),
  1191. null,
  1192. new SortOrder<DigitalFormVariable>(x => x.Sequence)),
  1193. formQuery
  1194. };
  1195. if (ParentType == typeof(JobITP))
  1196. {
  1197. queries.Add(new KeyedQueryDef<JobITP>(
  1198. new Filter<JobITP>(x => x.ID).InQuery((formQuery.Filter as Filter<JobITPForm>)!, x => x.Parent.ID),
  1199. new Columns<JobITP>(x => x.ID, x => x.Job.JobNumber)));
  1200. }
  1201. var results = Client.QueryMultiple(queries);
  1202. var questions = results.Get<QAQuestion>().ToObjects<QAQuestion>().ToList();
  1203. var variables = results.Get<DigitalFormVariable>().ToObjects<DigitalFormVariable>().ToList();
  1204. var formData = results.Get(formQuery.Key);
  1205. LoadDataIntoGrid(
  1206. variables, questions,
  1207. formData,
  1208. formQuery.Columns!.ColumnNames().Where(x => x.StartsWith("Parent.")).ToList(),
  1209. ParentType == typeof(JobITP) ? results.Get<JobITP>() : null);
  1210. }
  1211. public void Refresh()
  1212. {
  1213. if (!IsSetup) return;
  1214. Questions.Clear();
  1215. QAGrid.Clear();
  1216. QAGrid.LoadChecks("", Array.Empty<QAQuestion>(), new Dictionary<Guid, object>());
  1217. DataGrid.ItemsSource = null;
  1218. if (ParentType is null || FormType is null || Form is null || Form.ID == Guid.Empty)
  1219. {
  1220. QAGrid.Visibility = Visibility.Collapsed;
  1221. DataGrid.Visibility = Visibility.Collapsed;
  1222. return;
  1223. }
  1224. var refreshMethod = typeof(DigitalFormsDashboard).GetMethod(nameof(RefreshData), BindingFlags.Instance | BindingFlags.NonPublic)!.MakeGenericMethod(FormType);
  1225. refreshMethod.Invoke(this, Array.Empty<object?>());
  1226. }
  1227. public void Shutdown(CancelEventArgs? cancel)
  1228. {
  1229. }
  1230. #region DataGrid Configuration
  1231. private class RowStyleSelector : StyleSelector
  1232. {
  1233. private Style NormalStyle;
  1234. private Style IncompleteStyle;
  1235. public RowStyleSelector()
  1236. {
  1237. NormalStyle = new Style();
  1238. NormalStyle.Setters.Add(new Setter(VirtualizingCellsControl.BackgroundProperty, new SolidColorBrush(Colors.White)));
  1239. IncompleteStyle = new Style();
  1240. IncompleteStyle.Setters.Add(new Setter(VirtualizingCellsControl.BackgroundProperty, new SolidColorBrush(Colors.LightSalmon)));
  1241. }
  1242. public override Style SelectStyle(object item, DependencyObject container)
  1243. {
  1244. var row = (item as DataRowBase)?.RowData as DataRowView;
  1245. if (row is null) return NormalStyle;
  1246. return (DateTime)row["Completed"] == DateTime.MinValue
  1247. ? IncompleteStyle
  1248. : NormalStyle;
  1249. }
  1250. }
  1251. private void DataGrid_AutoGeneratingColumn(object sender, Syncfusion.UI.Xaml.Grid.AutoGeneratingColumnArgs e)
  1252. {
  1253. e.Column.TextAlignment = TextAlignment.Center;
  1254. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Center;
  1255. e.Column.ColumnSizer = GridLengthUnitType.None;
  1256. e.Column.ImmediateUpdateColumnFilter = true;
  1257. e.Column.FilterRowCondition = FilterRowCondition.Contains;
  1258. e.Column.FilterRowOptionsVisibility = Visibility.Collapsed;
  1259. var value = (e.Column.ValueBinding as Binding)!;
  1260. if (value.Path.Path.Equals("ID") || value.Path.Path.Equals("Form_ID") || value.Path.Path.Equals("Parent_ID") ||
  1261. value.Path.Path.Equals("FormData") || value.Path.Path.Equals("Location_Latitude") || value.Path.Path.Equals("Location_Longitude"))
  1262. {
  1263. e.Cancel = true;
  1264. }
  1265. else if (value.Path.Path.Equals("Number"))
  1266. {
  1267. e.Column.Width = 80;
  1268. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1269. }
  1270. else if (value.Path.Path.Equals("Description"))
  1271. {
  1272. e.Column.Width = 250;
  1273. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1274. e.Column.TextAlignment = TextAlignment.Left;
  1275. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Left;
  1276. }
  1277. else if (value.Path.Path.Equals("Location_Timestamp"))
  1278. {
  1279. e.Column = new GridImageColumn();
  1280. e.Column.Width = DataGrid.RowHeight;
  1281. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1282. e.Column.HeaderText = "";
  1283. e.Column.Padding = new Thickness(4);
  1284. e.Column.ValueBinding = new Binding
  1285. {
  1286. Path = new PropertyPath(value.Path.Path),
  1287. Converter = new MileStoneImageConverter()
  1288. };
  1289. e.Column.MappingName = "Location.Timestamp";
  1290. }
  1291. else if (ParentType is not null && parentColumns.TryGetValue(ParentType, out var pColumns) && pColumns.Any(x => x.Item2.Equals(value.Path.Path)))
  1292. {
  1293. e.Column.ColumnSizer = GridLengthUnitType.Auto;
  1294. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1295. }
  1296. else if (value.Path.Path.Equals("Job No"))
  1297. {
  1298. e.Column.Width = 60;
  1299. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1300. }
  1301. else if (value.Path.Path.Equals("Parent_Description"))
  1302. {
  1303. e.Column.HeaderText = Categories.FirstOrDefault(x => x.Item2 == FormType)?.Item3 ?? "Parent";
  1304. e.Column.TextAlignment = TextAlignment.Left;
  1305. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Left;
  1306. e.Column.Width = 250;
  1307. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1308. }
  1309. else if (value.Path.Path.Equals("Completed"))
  1310. {
  1311. e.Column.Width = 100;
  1312. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1313. (e.Column as GridDateTimeColumn)!.DisplayBinding = new Binding {
  1314. Path = new PropertyPath(value.Path.Path),
  1315. Converter = new DateTimeToStringConverter("dd MMM yy hh:mm")
  1316. };
  1317. }
  1318. else if (value.Path.Path.Equals("Completed By"))
  1319. {
  1320. e.Column.Width = 100;
  1321. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1322. }
  1323. else if (value.Path.Path.Equals("Processed"))
  1324. {
  1325. e.Column.Width = 100;
  1326. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1327. }
  1328. else if (value.Path.Path.Equals("Created By"))
  1329. {
  1330. e.Column.Width = 100;
  1331. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1332. }
  1333. else if (value.Path.Path.Equals("Created"))
  1334. {
  1335. e.Column.Width = 100;
  1336. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1337. (e.Column as GridDateTimeColumn)!.DisplayBinding = new Binding {
  1338. Path = new PropertyPath(value.Path.Path),
  1339. Converter = new DateTimeToStringConverter("dd MMM yy hh:mm")
  1340. };
  1341. }
  1342. else
  1343. {
  1344. var data = DataGrid.ItemsSource as DataTable;
  1345. //int index = data.Columns.IndexOf(e.Column.MappingName) - 2;
  1346. //Style style = new Style(typeof(GridCell));
  1347. //e.Column.CellStyle = style;
  1348. e.Column.Width = 100;
  1349. e.Column.HeaderStyle = Application.Current.Resources["TemplateHeaderStyle"] as Style;
  1350. e.Column.HeaderText = QuestionCodes[e.Column.MappingName];
  1351. }
  1352. }
  1353. private Entity? GetEntityForm<T>(Guid id) where T : Entity, IDigitalFormInstance, IRemotable, IPersistent, new()
  1354. {
  1355. var columns = DynamicFormEditWindow.FormColumns<T>();
  1356. return new Client<T>().Query(
  1357. new Filter<T>(x => x.ID).IsEqualTo(id),
  1358. columns).Rows.FirstOrDefault()?.ToObject<T>();
  1359. }
  1360. private void DataGrid_CellDoubleTapped(object sender, Syncfusion.UI.Xaml.Grid.GridCellDoubleTappedEventArgs e)
  1361. {
  1362. if (e.RowColumnIndex.RowIndex < 2)
  1363. return;
  1364. var rowOffset = -2;
  1365. //var table = (DataGrid.ItemsSource as DataTable)!;
  1366. var row = (e.Record as DataRowView)?.Row;
  1367. if (row == null)
  1368. {
  1369. MessageBox.Show($"Unexpected Record type ({e.Record?.GetType().EntityName() ?? "NULL"}");
  1370. return;
  1371. }
  1372. var formid = (Guid)row["Form_ID"];
  1373. var formdata = (string)row["FormData"];
  1374. var id = (Guid)row["ID"];
  1375. if (FormType is null) return;
  1376. if (IsQAForm)
  1377. {
  1378. var values = new Dictionary<Guid, object>();
  1379. var formData = Serialization.Deserialize<Dictionary<string, object>>(formdata);
  1380. if (formData is not null)
  1381. {
  1382. foreach (var (idStr, value) in formData)
  1383. {
  1384. if (Guid.TryParse(idStr, out var codeID))
  1385. {
  1386. values[codeID] = value;
  1387. }
  1388. }
  1389. }
  1390. QAGrid.Clear();
  1391. QAGrid.LoadChecks(Form!.Description, Questions, values);
  1392. QAGrid.CollapseMargins();
  1393. return;
  1394. }
  1395. var entityForm = typeof(DigitalFormsDashboard)
  1396. .GetMethod(nameof(GetEntityForm), BindingFlags.NonPublic | BindingFlags.Instance)!
  1397. .MakeGenericMethod(FormType)
  1398. .Invoke(this, new object[] { id }) as IDigitalFormInstance;
  1399. if (entityForm is not null)
  1400. {
  1401. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel))
  1402. {
  1403. dataModel.Update(null);
  1404. /*typeof(QADashboard)
  1405. .GetMethod(nameof(SaveEntityForm), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
  1406. .MakeGenericMethod(formType)
  1407. .Invoke(this, new object[] { entityForm });*/
  1408. Refresh();
  1409. }
  1410. }
  1411. }
  1412. private void DataGrid_CellTapped(object sender, Syncfusion.UI.Xaml.Grid.GridCellTappedEventArgs e)
  1413. {
  1414. if (e.RowColumnIndex.ColumnIndex == 0)
  1415. {
  1416. var timestamp = (DateTime)(e.Record as DataRowView)!.Row["Location_Timestamp"];
  1417. var latitude = (double)(e.Record as DataRowView)!.Row["Location_Latitude"];
  1418. var longitude = (double)(e.Record as DataRowView)!.Row["Location_Longitude"];
  1419. var form = new MapForm(latitude, longitude, timestamp);
  1420. form.ShowDialog();
  1421. }
  1422. }
  1423. #endregion
  1424. }
  1425. }