DigitalFormUtils.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using System.Windows.Forms;
  7. using FastReport;
  8. using FastReport.Table;
  9. using FastReport.Utils;
  10. using InABox.Core;
  11. using InABox.Scripting;
  12. using InABox.Wpf.Reports;
  13. using InABox.Wpf.Reports.CustomObjects;
  14. using UnderlineType = InABox.Core.UnderlineType;
  15. namespace InABox.DynamicGrid
  16. {
  17. public static class DigitalFormUtils
  18. {
  19. #region Layout Importer
  20. private class Cell
  21. {
  22. public string Content { get; set; }
  23. public int Row { get; set; }
  24. public int Column { get; set; }
  25. public int RowSpan { get; set; } = 1;
  26. public int ColumnSpan { get; set; } = 1;
  27. public ICell InnerCell { get; set; }
  28. public Cell(int row, int column, string content, ICell cell)
  29. {
  30. Row = row;
  31. Column = column;
  32. Content = content;
  33. InnerCell = cell;
  34. }
  35. }
  36. private static void DeleteColumn(List<Cell> cells, int column)
  37. {
  38. foreach(var cell in cells)
  39. {
  40. if(cell.Column <= column && cell.Column + cell.ColumnSpan - 1 >= column)
  41. {
  42. --cell.ColumnSpan;
  43. }
  44. else if(cell.Column > column)
  45. {
  46. --cell.Column;
  47. }
  48. }
  49. cells.RemoveAll(x => x.ColumnSpan < 0);
  50. }
  51. private static List<Cell> GetCells(ISheet sheet)
  52. {
  53. var grid = new Dictionary<int, Dictionary<int, Cell>>();
  54. for (int rowIdx = sheet.FirstRow; rowIdx <= sheet.LastRow; ++rowIdx)
  55. {
  56. var row = sheet.GetRow(rowIdx);
  57. if (row is not null && row.FirstColumn >= 0)
  58. {
  59. var rowCells = new Dictionary<int, Cell>();
  60. for (int colIdx = row.FirstColumn; colIdx <= row.LastColumn; ++colIdx)
  61. {
  62. var cell = row.GetCell(colIdx);
  63. if (cell is not null)
  64. {
  65. rowCells.Add(colIdx, new Cell(rowIdx, colIdx, cell.GetValue(), cell));
  66. }
  67. }
  68. grid.Add(rowIdx, rowCells);
  69. }
  70. }
  71. foreach (var region in sheet.GetMergedCells())
  72. {
  73. for (int r = region.FirstRow; r <= region.LastRow; ++r)
  74. {
  75. if (!grid.TryGetValue(r, out var row)) continue;
  76. for (int c = region.FirstColumn; c <= region.LastColumn; ++c)
  77. {
  78. if ((r - region.FirstRow) + (c - region.FirstColumn) != 0)
  79. {
  80. row.Remove(c);
  81. }
  82. }
  83. if (row.Count == 0)
  84. {
  85. grid.Remove(r);
  86. }
  87. }
  88. if (grid.TryGetValue(region.FirstRow, out var cRow) && cRow.TryGetValue(region.FirstColumn, out var cCell))
  89. {
  90. cCell.RowSpan = region.LastRow - region.FirstRow + 1;
  91. cCell.ColumnSpan = region.LastColumn - region.FirstColumn + 1;
  92. }
  93. }
  94. var cells = new List<Cell>();
  95. foreach (var row in grid.Values)
  96. {
  97. foreach (var cell in row.Values)
  98. {
  99. cells.Add(cell);
  100. }
  101. }
  102. return cells;
  103. }
  104. private static Regex VariableRegex = new(@"^\[(?<VAR>[^:\]]+)(?::(?<TYPE>[^:\]]*))?(?::(?<PROPERTIES>[^\]]*))?\]$");
  105. private static Regex HeaderRegex = new(@"^{(?<HEADER>[^:}]+)(?::(?<COLLAPSED>[^}]*))?}$");
  106. public static DFLayout LoadLayout(ISpreadsheet spreadsheet)
  107. {
  108. var sheet = spreadsheet.GetSheet(0);
  109. var cells = GetCells(sheet);
  110. int firstRow = int.MaxValue;
  111. int lastRow = 0;
  112. int firstCol = int.MaxValue;
  113. int lastCol = 0;
  114. foreach (var cell in cells)
  115. {
  116. firstCol = Math.Min(cell.Column, firstCol);
  117. lastCol = Math.Max(cell.Column + cell.ColumnSpan - 1, lastCol);
  118. firstRow = Math.Min(cell.Row, firstRow);
  119. lastRow = Math.Max(cell.Row + cell.RowSpan - 1, lastRow);
  120. }
  121. var layout = new DFLayout();
  122. var columnWidths = new Dictionary<int, float>();
  123. var colOffset = 0;
  124. for (int col = firstCol; col <= lastCol; ++col)
  125. {
  126. var width = sheet.GetColumnWidth(col);
  127. if(width == float.MinValue)
  128. {
  129. layout.ColumnWidths.Add("10*");
  130. }
  131. else if(width <= 0f)
  132. {
  133. DeleteColumn(cells, col);
  134. }
  135. else
  136. {
  137. layout.ColumnWidths.Add($"{width}*");
  138. }
  139. }
  140. for (int row = firstRow; row <= lastRow; ++row)
  141. layout.RowHeights.Add("Auto");
  142. foreach(var cell in cells)
  143. {
  144. var style = cell.InnerCell.GetStyle();
  145. if (string.IsNullOrWhiteSpace(cell.Content) && style.Foreground == Color.Empty) continue;
  146. DFLayoutControl? control;
  147. var content = cell.Content?.Trim() ?? "";
  148. var headermatch = HeaderRegex.Match(content);
  149. var variablematch = VariableRegex.Match(content);
  150. if (headermatch.Success)
  151. {
  152. var text = headermatch.Groups["HEADER"];
  153. var collapsed = headermatch.Groups["COLLAPSED"];
  154. var header = new DFLayoutHeader()
  155. {
  156. Header = text.Value,
  157. Collapsed = collapsed.Success && String.Equals(collapsed.Value.ToUpper(),"COLLAPSED"),
  158. Style = CreateStyle(style)
  159. };
  160. control = header;
  161. }
  162. else if (variablematch.Success)
  163. {
  164. var variableName = variablematch.Groups["VAR"];
  165. var variableType = variablematch.Groups["TYPE"];
  166. var variableProps = variablematch.Groups["PROPERTIES"];
  167. Type? fieldType = null;
  168. if (variableType.Success)
  169. fieldType = DFUtils.GetFieldType(variableType.Value);
  170. fieldType ??= typeof(DFLayoutStringField);
  171. var field = (Activator.CreateInstance(fieldType) as DFLayoutField)!;
  172. field.Name = variableName.Value;
  173. if (variableProps.Success)
  174. {
  175. if (field is DFLayoutOptionField option)
  176. option.Properties.Options = variableProps.Value;
  177. if (field is DFLayoutStringField text)
  178. text.Properties.TextWrapping = style.WrapText;
  179. // need to populate other variable types here
  180. }
  181. control = field;
  182. }
  183. else
  184. {
  185. control = new DFLayoutLabel
  186. {
  187. Caption = content,
  188. Style = CreateStyle(style)
  189. };
  190. }
  191. if(control is not null)
  192. {
  193. control.Row = cell.Row - firstRow + 1;
  194. control.Column = cell.Column - firstCol + 1 - colOffset;
  195. control.RowSpan = cell.RowSpan;
  196. control.ColumnSpan = cell.ColumnSpan;
  197. layout.Elements.Add(control);
  198. }
  199. }
  200. return layout;
  201. }
  202. private static DFLayoutTextStyle CreateStyle(ICellStyle style)
  203. {
  204. if (style == null)
  205. return new DFLayoutTextStyle();
  206. var result = new DFLayoutTextStyle
  207. {
  208. FontSize = style.Font.FontSize,
  209. IsItalic = style.Font.Italic,
  210. IsBold = style.Font.Bold,
  211. Underline = style.Font.Underline switch
  212. {
  213. Scripting.UnderlineType.None => UnderlineType.None,
  214. Scripting.UnderlineType.Single or Scripting.UnderlineType.SingleAccounting => UnderlineType.Single,
  215. Scripting.UnderlineType.Double or Scripting.UnderlineType.DoubleAccounting => UnderlineType.Double,
  216. _ => UnderlineType.None
  217. },
  218. BackgroundColour = style.Background,
  219. ForegroundColour = style.Font.Colour,
  220. HorizontalTextAlignment = style.HorizontalAlignment switch
  221. {
  222. CellAlignment.Middle => DFLayoutAlignment.Middle,
  223. CellAlignment.End => DFLayoutAlignment.End,
  224. CellAlignment.Justify => DFLayoutAlignment.Stretch,
  225. _ => DFLayoutAlignment.Start
  226. },
  227. VerticalTextAlignment = style.VerticalAlignment switch
  228. {
  229. CellAlignment.Start => DFLayoutAlignment.Start,
  230. CellAlignment.End => DFLayoutAlignment.End,
  231. CellAlignment.Justify => DFLayoutAlignment.Stretch,
  232. _ => DFLayoutAlignment.Middle
  233. },
  234. TextWrapping = style.WrapText
  235. };
  236. return result;
  237. }
  238. #endregion
  239. #region Report Generator
  240. private static string ElementName(HashSet<string> names, string name)
  241. {
  242. int i = 0;
  243. if(names.Contains(name))
  244. {
  245. string newName;
  246. do
  247. {
  248. newName = $"{name}{i}";
  249. ++i;
  250. } while (names.Contains(newName));
  251. name = newName;
  252. }
  253. return name;
  254. }
  255. public static Report? GenerateReport(DigitalFormLayout layout, DataModel model)
  256. {
  257. bool IsValidChar(char c) => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789".Contains(c);
  258. var report = ReportUtils.SetupReport(null, model, true);
  259. var dfLayout = new DFLayout();
  260. dfLayout.LoadLayout(layout.Layout);
  261. var page = new ReportPage();
  262. page.Name = "Page1";
  263. page.PaperWidth = 210;
  264. page.PaperHeight = 297;
  265. page.Landscape = false;
  266. page.LeftMargin = 10;
  267. page.TopMargin = 10;
  268. page.RightMargin = 10;
  269. page.BottomMargin = 10;
  270. report.Pages.Add(page);
  271. var formData = report.GetDataSource("Form_Data");
  272. var band = new DataBand
  273. {
  274. Name = "Data1",
  275. Height = Units.Millimeters * (page.PaperHeight - (page.TopMargin + page.BottomMargin)),
  276. Width = Units.Millimeters * (page.PaperWidth - (page.LeftMargin + page.RightMargin)),
  277. PrintIfDatasourceEmpty = true,
  278. DataSource = formData,
  279. StartNewPage = true
  280. };
  281. page.AddChild(band);
  282. var logo = new PictureObject()
  283. {
  284. Height = 20F * Units.Millimeters,
  285. Width = 30F * Units.Millimeters,
  286. DataColumn = "CompanyLogo.Data"
  287. };
  288. band.AddChild(logo);
  289. var company = new TextObject()
  290. {
  291. Left = band.Width - (90F * Units.Millimeters),
  292. Width = 90F * Units.Millimeters,
  293. Height = 5F * Units.Millimeters,
  294. Text = "[CompanyInformation.CompanyName]",
  295. HorzAlign = HorzAlign.Right,
  296. VertAlign = VertAlign.Center,
  297. Font = new System.Drawing.Font("Arial", 12F, FontStyle.Bold)
  298. };
  299. band.AddChild(company);
  300. var address = new TextObject()
  301. {
  302. Left = band.Width - (90F * Units.Millimeters),
  303. Width = 90F * Units.Millimeters,
  304. Height = 15F * Units.Millimeters,
  305. Top = 5F * Units.Millimeters,
  306. Text = "[CompanyInformation.PostalAddress_Street]\n[CompanyInformation.PostalAddress_City] [CompanyInformation.PostalAddress_PostCode]",
  307. HorzAlign = HorzAlign.Right,
  308. VertAlign = VertAlign.Top,
  309. Font = new System.Drawing.Font("Arial", 12F)
  310. };
  311. band.AddChild(address);
  312. var instancetable = model
  313. .GetType()
  314. .GetInterfaces()
  315. .FirstOrDefault(x => x.IsConstructedGenericType && x.GetGenericTypeDefinition() == typeof(IDataModel<>))?
  316. .GetGenericArguments()
  317. .FirstOrDefault()?
  318. .EntityName()
  319. .Split('.')
  320. .Last();
  321. var title = new TextObject()
  322. {
  323. Top = 23F * Units.Millimeters,
  324. Width = band.Width,
  325. Height = 6F * Units.Millimeters,
  326. Text = $"[Form_Data.{instancetable}.Number] - {layout.Form.Description}",
  327. HorzAlign = HorzAlign.Center,
  328. VertAlign = VertAlign.Center,
  329. Font = new System.Drawing.Font("Arial", 14F, FontStyle.Bold)
  330. };
  331. band.AddChild(title);
  332. /*
  333. <TextObject Name="Text2" Left="500.85" Top="28.35" Width="207.9" Height="56.7" Text="16 Madrid Place&#13;&#10;Maddington WA 6109&#13;&#10;Phone: (08) 9492 1200&#13;&#10;Email: admin@com-al.com.au" HorzAlign="Right" Font="Arial, 9pt"/>
  334. <PictureObject Name="Picture1" Left="9.45" Top="9.45" Width="113.4" Height="75.6" DataColumn="CompanyLogo.Data"/>
  335. <TextObject Name="Text1" Left="444.15" Top="9.45" Width="264.6" Height="18.9" Text="Com-Al Windows Pty Ltd" HorzAlign="Right" Font="Arial, 10pt, style=Bold" TextFill.Color="RoyalBlue"/>
  336. <TextObject Name="Text3" Left="9.45" Top="103.95" Width="699.3" Height="28.35" Text="TEST &amp; TAG REPORT: [KanbanForm.Number]" HorzAlign="Center" VertAlign="Center" Font="Arial, 14pt, style=Bold"/>
  337. */
  338. var elementNames = new HashSet<string>();
  339. var table = new TableObject()
  340. {
  341. Name = "FormTable",
  342. ColumnCount = dfLayout.ColumnWidths.Count,
  343. RowCount = dfLayout.RowHeights.Count,
  344. Top = 32F * Units.Millimeters
  345. };
  346. band.AddChild(table);
  347. foreach(var element in dfLayout.Elements)
  348. {
  349. if (element.Row < 1 || element.Row + element.RowSpan - 1 > table.RowCount
  350. || element.Column < 1 || element.Column + element.ColumnSpan - 1 > table.ColumnCount) continue;
  351. var row = table.Rows[element.Row - 1];
  352. if(row.ChildObjects[element.Column - 1] is TableCell cell)
  353. {
  354. cell.Border.Lines = BorderLines.All;
  355. cell.ColSpan = element.ColumnSpan;
  356. cell.RowSpan = element.RowSpan;
  357. if (element is DFLayoutField field)
  358. {
  359. var manualHeight = 0.0f;
  360. cell.Name = ElementName(elementNames, $"Cell_{new string(field.Name.Where(c => IsValidChar(c)).ToArray())}");
  361. var dataColumn = $"Form_Data.{field.Name}";
  362. if(field is DFLayoutEmbeddedImage || field is DFLayoutSignaturePad)
  363. {
  364. var picture = new PictureObject
  365. {
  366. DataColumn = dataColumn,
  367. Dock = DockStyle.Fill,
  368. Padding = new Padding(5,5,5,5)
  369. };
  370. cell.AddChild(picture);
  371. manualHeight = 40;
  372. }
  373. else if(field is DFLayoutMultiImage)
  374. {
  375. var image = new MultiImageObject
  376. {
  377. DataColumn = dataColumn,
  378. Dock = DockStyle.Fill,
  379. Padding = new Padding(5,5,5,5)
  380. };
  381. cell.AddChild(image);
  382. manualHeight = 40;
  383. }
  384. else if(field is DFLayoutMultiSignaturePad)
  385. {
  386. var image = new MultiSignatureObject
  387. {
  388. DataColumn = dataColumn,
  389. Dock = DockStyle.Fill,
  390. Padding = new Padding(5,5,5,5)
  391. };
  392. cell.AddChild(image);
  393. manualHeight = 40;
  394. }
  395. else
  396. {
  397. cell.Text = $"[{dataColumn}]";
  398. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, 10F, FontStyle.Italic);
  399. cell.TextColor = Color.Navy;
  400. cell.HorzAlign = HorzAlign.Left;
  401. cell.VertAlign = VertAlign.Center;
  402. if (field is DFLayoutStringField lsf)
  403. cell.WordWrap = lsf.Properties.TextWrapping;
  404. }
  405. if(manualHeight > 0 && dfLayout.RowHeights[element.Row - 1] == "Auto")
  406. {
  407. dfLayout.RowHeights[element.Row - 1] = manualHeight.ToString();
  408. }
  409. }
  410. else if (element is DFLayoutLabel label)
  411. {
  412. var background = label.Style.BackgroundColour;
  413. if (background == Color.Empty)
  414. {
  415. label.Style.BackgroundColour = Color.WhiteSmoke;
  416. }
  417. cell.Text = label.Description;
  418. cell.Name = ElementName(elementNames, "Label_" + element.Row + "_" + element.Column);
  419. ApplyStyle(cell, label.Style);
  420. }
  421. else if (element is DFLayoutHeader header)
  422. {
  423. cell.Name = ElementName(elementNames, "Header_" + element.Row + "_" + element.Column);
  424. cell.Text = header.Header;
  425. ApplyStyle(cell, header.Style);
  426. }
  427. }
  428. }
  429. ProcessColumnWidths(band.Width, dfLayout.ColumnWidths, table.Columns);
  430. ProcessRowHeights(band.Height, dfLayout.RowHeights, table.Rows);
  431. return report;
  432. }
  433. private static void ApplyStyle(TableCell cell, DFLayoutTextStyle style)
  434. {
  435. var background = style.BackgroundColour;
  436. if(background != Color.Empty) cell.FillColor = background;
  437. var foreground = style.ForegroundColour;
  438. if (foreground != Color.Empty) cell.TextColor = foreground;
  439. FontStyle fontstyle = System.Drawing.FontStyle.Regular;
  440. if (style.IsBold)
  441. fontstyle |= System.Drawing.FontStyle.Bold;
  442. if (style.IsItalic)
  443. fontstyle |= System.Drawing.FontStyle.Italic;
  444. if (style.Underline != UnderlineType.None)
  445. fontstyle |= FontStyle.Underline;
  446. float fontsize = (float)style.FontSize;
  447. fontsize = fontsize == 0F ? 10F : fontsize;
  448. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, fontsize, fontstyle);
  449. cell.HorzAlign = style.HorizontalTextAlignment switch
  450. {
  451. DFLayoutAlignment.Start => HorzAlign.Left,
  452. DFLayoutAlignment.Middle => HorzAlign.Center,
  453. DFLayoutAlignment.End => HorzAlign.Right,
  454. DFLayoutAlignment.Stretch => HorzAlign.Justify,
  455. _ => HorzAlign.Left
  456. };
  457. cell.VertAlign = style.VerticalTextAlignment switch
  458. {
  459. DFLayoutAlignment.Start => VertAlign.Top,
  460. DFLayoutAlignment.Middle => VertAlign.Center,
  461. DFLayoutAlignment.End => VertAlign.Bottom,
  462. DFLayoutAlignment.Stretch => VertAlign.Center,
  463. _ => VertAlign.Center
  464. };
  465. cell.WordWrap = style.TextWrapping;
  466. }
  467. private static void ProcessRowHeights(float bandheight, List<string> values, TableRowCollection rows)
  468. {
  469. float fixedtotal = 0F;
  470. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  471. {
  472. if (!values[iFixed].Contains("*"))
  473. {
  474. if (!float.TryParse(values[iFixed], out float value))
  475. value = 25F / Units.Millimeters;
  476. else
  477. value = value / (1.5f * Units.Millimeters);
  478. rows[iFixed].Height = Units.Millimeters * value;
  479. fixedtotal += Units.Millimeters * value;
  480. }
  481. }
  482. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  483. float startotal = 0F;
  484. for (int iStar = 0; iStar < values.Count; iStar++)
  485. {
  486. if (values[iStar].Contains('*'))
  487. {
  488. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  489. value += 1;
  490. starvalues[iStar] = value;
  491. startotal += value;
  492. }
  493. }
  494. foreach (var key in starvalues.Keys)
  495. rows[key].Height = (starvalues[key] / startotal) * (bandheight - fixedtotal);
  496. }
  497. private static void ProcessColumnWidths(float bandwidth, List<string> values, TableColumnCollection columns)
  498. {
  499. float fixedtotal = 0F;
  500. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  501. {
  502. if (!values[iFixed].Contains("*"))
  503. {
  504. if (!float.TryParse(values[iFixed], out float value))
  505. value = 40F;
  506. columns[iFixed].Width = Units.Millimeters * value;
  507. fixedtotal += Units.Millimeters * value;
  508. }
  509. }
  510. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  511. float startotal = 0F;
  512. for (int iStar = 0; iStar < values.Count; iStar++)
  513. {
  514. if (values[iStar].Contains('*'))
  515. {
  516. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  517. value += 1;
  518. starvalues[iStar] = value;
  519. startotal += value;
  520. }
  521. }
  522. foreach (var key in starvalues.Keys)
  523. columns[key].Width = (starvalues[key] / startotal) * (bandwidth - fixedtotal);
  524. }
  525. #endregion
  526. #region Data Model
  527. private static List<Type>? _entityForms;
  528. public static DataModel? GetDataModel(String appliesto, IEnumerable<DigitalFormVariable> variables)
  529. {
  530. _entityForms ??= CoreUtils.Entities
  531. .Where(x => x.IsSubclassOfRawGeneric(typeof(EntityForm<,,>)))
  532. .ToList();
  533. var entityForm = _entityForms
  534. .FirstOrDefault(x => x.GetSuperclassDefinition(typeof(EntityForm<,,>))
  535. ?.GenericTypeArguments[0].Name == appliesto);
  536. if(entityForm is not null)
  537. {
  538. var model = (Activator.CreateInstance(typeof(DigitalFormReportDataModel<>).MakeGenericType(entityForm), Filter.Create(entityForm).None(), null) as DataModel)!;
  539. (model as IDigitalFormReportDataModel)!.Variables = variables.ToArray();
  540. return model;
  541. }
  542. return null;
  543. }
  544. #endregion
  545. }
  546. }