DigitalFormsDashboard.xaml.cs 56 KB

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