DigitalFormsDashboard.xaml.cs 50 KB

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