DigitalFormsDashboard.xaml.cs 60 KB

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