DigitalFormsDashboard.xaml.cs 49 KB

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