DigitalFormUtils.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using FastReport;
  7. using FastReport.Data;
  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. var report = ReportUtils.SetupReport(null, model, true);
  258. var dfLayout = new DFLayout();
  259. dfLayout.LoadLayout(layout.Layout);
  260. var page = new ReportPage();
  261. page.Name = "Page1";
  262. page.PaperWidth = 210;
  263. page.PaperHeight = 297;
  264. page.Landscape = false;
  265. page.LeftMargin = 10;
  266. page.TopMargin = 10;
  267. page.RightMargin = 10;
  268. page.BottomMargin = 10;
  269. report.Pages.Add(page);
  270. var formData = report.GetDataSource("Form_Data");
  271. var band = new DataBand
  272. {
  273. Name = "Data1",
  274. Height = Units.Millimeters * (page.PaperHeight - (page.TopMargin + page.BottomMargin)),
  275. Width = Units.Millimeters * (page.PaperWidth - (page.LeftMargin + page.RightMargin)),
  276. PrintIfDatasourceEmpty = true,
  277. DataSource = formData
  278. };
  279. page.AddChild(band);
  280. var elementNames = new HashSet<string>();
  281. var table = new TableObject()
  282. {
  283. Name = "FormTable",
  284. ColumnCount = dfLayout.ColumnWidths.Count,
  285. RowCount = dfLayout.RowHeights.Count
  286. };
  287. band.AddChild(table);
  288. foreach(var element in dfLayout.Elements)
  289. {
  290. if (element.Row < 1 || element.Row + element.RowSpan - 1 > table.RowCount
  291. || element.Column < 1 || element.Column + element.ColumnSpan - 1 > table.ColumnCount) continue;
  292. var row = table.Rows[element.Row - 1];
  293. if(row.ChildObjects[element.Column - 1] is TableCell cell)
  294. {
  295. cell.Border.Lines = BorderLines.All;
  296. cell.ColSpan = element.ColumnSpan;
  297. cell.RowSpan = element.RowSpan;
  298. if (element is DFLayoutField field)
  299. {
  300. var manualHeight = 0.0f;
  301. cell.Name = ElementName(elementNames, $"Cell_{new string(field.Name.Where(c => !Char.IsWhiteSpace(c)).ToArray())}");
  302. var dataColumn = $"Form_Data.{field.Name}";
  303. if(field is DFLayoutEmbeddedImage || field is DFLayoutSignaturePad)
  304. {
  305. var picture = new PictureObject
  306. {
  307. DataColumn = dataColumn,
  308. Dock = System.Windows.Forms.DockStyle.Fill
  309. };
  310. cell.AddChild(picture);
  311. manualHeight = 40;
  312. }
  313. else if(field is DFLayoutMultiImage)
  314. {
  315. var image = new MultiImageObject
  316. {
  317. DataColumn = dataColumn,
  318. Dock = System.Windows.Forms.DockStyle.Fill
  319. };
  320. cell.AddChild(image);
  321. manualHeight = 40;
  322. }
  323. else if(field is DFLayoutMultiSignaturePad)
  324. {
  325. var image = new MultiSignatureObject
  326. {
  327. DataColumn = dataColumn,
  328. Dock = System.Windows.Forms.DockStyle.Fill
  329. };
  330. cell.AddChild(image);
  331. manualHeight = 40;
  332. }
  333. else
  334. {
  335. cell.Text = $"[{dataColumn}]";
  336. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, 8F, FontStyle.Italic);
  337. cell.TextColor = Color.Navy;
  338. }
  339. if(manualHeight > 0 && dfLayout.RowHeights[element.Row - 1] == "Auto")
  340. {
  341. dfLayout.RowHeights[element.Row - 1] = manualHeight.ToString();
  342. }
  343. }
  344. else if (element is DFLayoutLabel label)
  345. {
  346. var background = label.Style.BackgroundColour;
  347. if (background == Color.Empty)
  348. {
  349. label.Style.BackgroundColour = Color.WhiteSmoke;
  350. }
  351. cell.Text = label.Description;
  352. cell.Name = ElementName(elementNames, "Label_" + element.Row + "_" + element.Column);
  353. ApplyStyle(cell, label.Style);
  354. }
  355. else if (element is DFLayoutHeader header)
  356. {
  357. cell.Name = ElementName(elementNames, "Header_" + element.Row + "_" + element.Column);
  358. cell.Text = header.Header;
  359. ApplyStyle(cell, header.Style);
  360. }
  361. }
  362. }
  363. ProcessColumnWidths(band.Width, dfLayout.ColumnWidths, table.Columns);
  364. ProcessRowHeights(band.Height, dfLayout.RowHeights, table.Rows);
  365. return report;
  366. }
  367. private static void ApplyStyle(TableCell cell, DFLayoutTextStyle style)
  368. {
  369. var background = style.BackgroundColour;
  370. if(background != Color.Empty) cell.FillColor = background;
  371. var foreground = style.ForegroundColour;
  372. if (foreground != Color.Empty) cell.TextColor = foreground;
  373. FontStyle fontstyle = System.Drawing.FontStyle.Regular;
  374. if (style.IsBold)
  375. fontstyle |= System.Drawing.FontStyle.Bold;
  376. if (style.IsItalic)
  377. fontstyle |= System.Drawing.FontStyle.Italic;
  378. if (style.Underline != UnderlineType.None)
  379. fontstyle |= FontStyle.Underline;
  380. float fontsize = (float)style.FontSize * 8F / 12F;
  381. fontsize = fontsize == 0F ? 8F : fontsize;
  382. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, fontsize, fontstyle);
  383. cell.HorzAlign = style.HorizontalTextAlignment switch
  384. {
  385. DFLayoutAlignment.Start => HorzAlign.Left,
  386. DFLayoutAlignment.Middle => HorzAlign.Center,
  387. DFLayoutAlignment.End => HorzAlign.Right,
  388. DFLayoutAlignment.Stretch => HorzAlign.Justify,
  389. _ => HorzAlign.Left
  390. };
  391. cell.VertAlign = style.VerticalTextAlignment switch
  392. {
  393. DFLayoutAlignment.Start => VertAlign.Top,
  394. DFLayoutAlignment.Middle => VertAlign.Center,
  395. DFLayoutAlignment.End => VertAlign.Bottom,
  396. DFLayoutAlignment.Stretch => VertAlign.Center,
  397. _ => VertAlign.Center
  398. };
  399. cell.WordWrap = style.TextWrapping;
  400. }
  401. private static void ProcessRowHeights(float bandheight, List<string> values, TableRowCollection rows)
  402. {
  403. float fixedtotal = 0F;
  404. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  405. {
  406. if (!values[iFixed].Contains("*"))
  407. {
  408. if (!float.TryParse(values[iFixed], out float value))
  409. value = 4F;
  410. rows[iFixed].Height = Units.Millimeters * value;
  411. fixedtotal += Units.Millimeters * value;
  412. }
  413. }
  414. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  415. float startotal = 0F;
  416. for (int iStar = 0; iStar < values.Count; iStar++)
  417. {
  418. if (values[iStar].Contains('*'))
  419. {
  420. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  421. value += 1;
  422. starvalues[iStar] = value;
  423. startotal += value;
  424. }
  425. }
  426. foreach (var key in starvalues.Keys)
  427. rows[key].Height = (starvalues[key] / startotal) * (bandheight - fixedtotal);
  428. }
  429. private static void ProcessColumnWidths(float bandwidth, List<string> values, TableColumnCollection columns)
  430. {
  431. float fixedtotal = 0F;
  432. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  433. {
  434. if (!values[iFixed].Contains("*"))
  435. {
  436. if (!float.TryParse(values[iFixed], out float value))
  437. value = 20F;
  438. columns[iFixed].Width = Units.Millimeters * value;
  439. fixedtotal += Units.Millimeters * value;
  440. }
  441. }
  442. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  443. float startotal = 0F;
  444. for (int iStar = 0; iStar < values.Count; iStar++)
  445. {
  446. if (values[iStar].Contains('*'))
  447. {
  448. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  449. value += 1;
  450. starvalues[iStar] = value;
  451. startotal += value;
  452. }
  453. }
  454. foreach (var key in starvalues.Keys)
  455. columns[key].Width = (starvalues[key] / startotal) * (bandwidth - fixedtotal);
  456. }
  457. #endregion
  458. #region Data Model
  459. private static List<Type>? _entityForms;
  460. public static DataModel? GetDataModel(String appliesto, IEnumerable<DigitalFormVariable> variables)
  461. {
  462. _entityForms ??= CoreUtils.Entities
  463. .Where(x => x.IsSubclassOfRawGeneric(typeof(EntityForm<,,>)))
  464. .ToList();
  465. var entityForm = _entityForms
  466. .FirstOrDefault(x => x.GetSuperclassDefinition(typeof(EntityForm<,,>))
  467. ?.GenericTypeArguments[0].Name == appliesto);
  468. if(entityForm is not null)
  469. {
  470. var model = (Activator.CreateInstance(typeof(DigitalFormReportDataModel<>).MakeGenericType(entityForm), Filter.Create(entityForm).None(), null) as DataModel)!;
  471. (model as IDigitalFormReportDataModel)!.Variables = variables.ToArray();
  472. return model;
  473. }
  474. return null;
  475. }
  476. #endregion
  477. }
  478. }