DigitalForm.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using InABox.Core.Reports;
  7. using Newtonsoft.Json.Linq;
  8. using TextFieldParserStandard;
  9. namespace InABox.Core
  10. {
  11. // public abstract class DigitalFormsCount : CoreAggregate<DigitalForm, DigitalFormLayout, Guid>
  12. // {
  13. // public override Expression<Func<DigitalFormLayout, Guid>> Aggregate => x => x.ID;
  14. //
  15. // public override Filter<DigitalFormLayout> Filter =>
  16. // new Filter<DigitalFormLayout>(x => x.Type).IsEqualTo(DFLayoutType.Mobile)
  17. // .And(x=>x.Active).IsEqualTo(true);
  18. //
  19. // public override Dictionary<Expression<Func<DigitalFormLayout, object>>, Expression<Func<DigitalForm, object>>> Links =>
  20. // new Dictionary<Expression<Func<DigitalFormLayout, object>>, Expression<Func<DigitalForm, object>>>()
  21. // {
  22. // { DigitalFormLayout => DigitalFormLayout.Form.ID, DigitalForm => DigitalForm.ID }
  23. // };
  24. //
  25. // public override AggregateCalculation Calculation => AggregateCalculation.Count;
  26. // }
  27. //
  28. // public class ActiveMobileFormsCount : DigitalFormsCount
  29. // {
  30. // public override Filter<DigitalFormLayout> Filter =>
  31. // new Filter<DigitalFormLayout>(x => x.Type).IsEqualTo(DFLayoutType.Mobile)
  32. // .And(x=>x.Active).IsEqualTo(true);
  33. // }
  34. //
  35. // public class ActiveFormsCount : DigitalFormsCount
  36. // {
  37. // public override Filter<DigitalFormLayout> Filter =>
  38. // new Filter<DigitalFormLayout>(x=>x.Active).IsEqualTo(true);
  39. // }
  40. [UserTracking("Digital Forms")]
  41. public class DigitalForm : Entity, IRemotable, IPersistent, ILicense<DigitalFormsLicense>//, IDuplicatable
  42. {
  43. /// <summary>
  44. /// The following functions support PNG, BMP and JPEG
  45. /// </summary>
  46. /// <param name="data"></param>
  47. /// <returns></returns>
  48. private static readonly byte[] bmpHeader = Encoding.ASCII.GetBytes("BM");
  49. private static readonly byte[] pngHeader = { 137, 80, 78, 71 };
  50. private static readonly byte[] jpegHeader = { 255, 216, 255, 224 };
  51. private static readonly byte[] jpeg2Header = { 255, 216, 255, 225 };
  52. [UniqueCodeEditor(Visible = Visible.Default, Editable = Editable.Enabled)]
  53. [EditorSequence(1)]
  54. public string Code { get; set; }
  55. [TextBoxEditor]
  56. [EditorSequence(2)]
  57. public string Description { get; set; }
  58. [ComboLookupEditor(typeof(DigitalFormCategoryLookups))]
  59. [EditorSequence(3)]
  60. public string AppliesTo { get; set; }
  61. [CheckBoxEditor]
  62. [EditorSequence(4)]
  63. public bool Active { get; set; } = true;
  64. [CheckBoxEditor]
  65. [EditorSequence(5)]
  66. public bool Secure { get; set; } = false;
  67. [CheckBoxEditor]
  68. [EditorSequence(6)]
  69. public bool Final { get; set; } = false;
  70. [EditorSequence(7)]
  71. public DigitalFormGroupLink Group { get; set; }
  72. [EditorSequence(8)]
  73. [ExpressionEditor(null, ToolTip = "Evaluates to a string which becomes the description of the form when saved.")]
  74. public string DescriptionExpression { get; set; } = "";
  75. [EditorSequence(9)]
  76. [ExpressionEditor(null, ToolTip = "Evaluates to a string which becomes the filename of the form when saved.")]
  77. public string ExportExpression { get; set; } = "";
  78. [NullEditor]
  79. public string Report { get; set; }
  80. // [NullEditor]
  81. // [Aggregate(typeof(ActiveFormsCount))]
  82. // public int ActiveForms { get; set; }
  83. //
  84. // [NullEditor]
  85. // [Aggregate(typeof(ActiveMobileFormsCount))]
  86. // public int ActiveMobileForms { get; set; }
  87. public IEntityDuplicator GetDuplicator()
  88. {
  89. var result = new EntityDuplicator<DigitalForm>();
  90. result.AddChild<DigitalForm, DigitalFormVariable, DigitalFormLink>(x => x.Form);
  91. result.AddChild<DigitalForm, DigitalFormLayout, DigitalFormLink>(x => x.Form);
  92. return result;
  93. }
  94. public override string ToString()
  95. {
  96. return string.Format("{0}: {1}", Code, Description);
  97. }
  98. private static bool IsValidImage(byte[] data)
  99. {
  100. return bmpHeader.SequenceEqual(data.Take(bmpHeader.Length))
  101. || pngHeader.SequenceEqual(data.Take(pngHeader.Length))
  102. || jpegHeader.SequenceEqual(data.Take(jpegHeader.Length))
  103. || jpeg2Header.SequenceEqual(data.Take(jpeg2Header.Length));
  104. }
  105. private static bool IsValidImage(string base64Data)
  106. {
  107. var firstBytes = base64Data.Substring(0, Math.Min(8, base64Data.Length));
  108. return IsValidImage(Convert.FromBase64String(firstBytes));
  109. }
  110. /// <summary>
  111. /// Takes a serialized FormData string and BlobData string and deserializes into one dictionary.
  112. /// The result of this is just as if you were deserializing formData as per usual.
  113. /// </summary>
  114. /// <param name="formData"></param>
  115. /// <param name="blobData"></param>
  116. /// <returns></returns>
  117. public static DFLoadStorage? DeserializeFormData(string formData, string? blobData)
  118. {
  119. var values = Serialization.Deserialize<Dictionary<string, object?>>(formData);
  120. if (values is null)
  121. return null;
  122. if (blobData.IsNullOrWhiteSpace())
  123. return new DFLoadStorage(values, null);
  124. var blobs = Serialization.Deserialize<Dictionary<string, object?>>(blobData);
  125. return new DFLoadStorage(values, blobs);
  126. }
  127. /// <summary>
  128. /// Like <see cref="DeserializeFormData(string, string?)"/>, but takes the FormData and BlobData from <paramref name="form"/>,
  129. /// rather than having to specify them manually.
  130. /// </summary>
  131. /// <param name="form"></param>
  132. /// <returns></returns>
  133. public static DFLoadStorage? DeserializeFormData(IDigitalFormInstance form)
  134. => DeserializeFormData(form.FormData, form.BlobData);
  135. /// <summary>
  136. /// Takes a form instance, set of variables and some saved values, and serializes the FormData and BlobData into the respective
  137. /// fields of <paramref name="form"/>.
  138. /// </summary>
  139. /// <remarks>
  140. /// Doesn't return anything, but saves the serialized results directly into form.FormData and form.BlobData.
  141. /// It choose which fields should be saved into BlobData based on whether the form field has the <see cref="IDFBlobField"/> interface.
  142. /// <br/>
  143. /// <paramref name="values"/> should be the same as what you pass into <see cref="Serialization.Serialize(object?, bool)"/>.
  144. /// </remarks>
  145. /// <param name="form">The form instance.</param>
  146. /// <param name="variables">The variables associated with the digital form.</param>
  147. /// <param name="storage">The values to save.</param>
  148. public static void SerializeFormData(IDigitalFormInstance form, ICollection<DigitalFormVariable> variables, DFSaveStorage storage)
  149. {
  150. form.FormData = Serialization.Serialize(storage.FormData);
  151. form.BlobData = Serialization.Serialize(storage.BlobData);
  152. }
  153. private static string? GetVariableData(DigitalFormVariable variable, object value)
  154. {
  155. // TODO: Replace with a function on DFLayoutField or something
  156. var fieldType = variable.FieldType();
  157. if (fieldType == typeof(DFLayoutEmbeddedImage)
  158. || fieldType == typeof(DFLayoutSignaturePad))
  159. {
  160. if (value is byte[]) return IsValidImage((byte[])value) ? Convert.ToBase64String((byte[])value) : null;
  161. var str = value.ToString();
  162. return IsValidImage(str) ? str : null;
  163. }
  164. else if(fieldType == typeof(DFLayoutMultiImage))
  165. {
  166. if (value is JArray || value is IEnumerable<string>) return Serialization.Serialize(value);
  167. return null;
  168. }
  169. return variable.FormatValue(value);
  170. }
  171. /// <summary>
  172. /// Generates a database FormData from a dictionary of objects. Returns null if the data is invalid (specifically if
  173. /// any required fields are not present.
  174. /// </summary>
  175. /// <param name="values">.NET objects</param>
  176. /// <param name="variables">The variables of the form needed to be encoded</param>
  177. /// <returns>A string with JSON-encoded FormData, or null if validation requirements are not met.</returns>
  178. public static string? GenerateFormData(Dictionary<string, object> values, IEnumerable<DigitalFormVariable> variables, Entity entity)
  179. {
  180. var data = new Dictionary<string, string>();
  181. foreach (var variable in variables)
  182. if (values.TryGetValue(variable.Code, out var value))
  183. {
  184. var properties = variable.CreateProperties();
  185. if (!string.IsNullOrWhiteSpace(properties.Property))
  186. {
  187. if (variable.FieldType() == typeof(DFLayoutLookupField))
  188. {
  189. if (values.TryGetValue($"{variable.Code}$ID", out var idStr) && Guid.TryParse((string)idStr, out var id))
  190. CoreUtils.SetPropertyValue(entity, properties.Property, id);
  191. }
  192. else
  193. {
  194. CoreUtils.SetPropertyValue(entity, properties.Property, value);
  195. }
  196. }
  197. if (value != null)
  198. {
  199. var varData = GetVariableData(variable, value);
  200. if (varData != null)
  201. data[variable.Code] = varData;
  202. }
  203. }
  204. else if (variable.Required)
  205. {
  206. return null;
  207. }
  208. return Serialization.Serialize(data);
  209. }
  210. /// <summary>
  211. /// Creates a dictionary of objects from a database FormData
  212. /// </summary>
  213. /// <param name="formData">A string with JSON-encoded FormData</param>
  214. /// <param name="variables">The variables of the form needed to be encoded</param>
  215. /// <returns></returns>
  216. public static Dictionary<string, object?> ParseFormData(string formData, IEnumerable<DigitalFormVariable> variables, Entity entity)
  217. {
  218. var data = new Dictionary<string, object?>();
  219. // Could be null
  220. var formObject = new DFLoadStorage(Serialization.Deserialize<Dictionary<string, object?>>(formData) ?? new Dictionary<string, object?>(), null);
  221. foreach (var variable in variables)
  222. {
  223. object? value = null;
  224. var code = variable.Code;
  225. var properties = variable.CreateProperties();
  226. if (!string.IsNullOrWhiteSpace(properties.Property))
  227. {
  228. value = CoreUtils.GetPropertyValue(entity, properties.Property);
  229. if (variable.FieldType() == typeof(DFLayoutLookupField))
  230. {
  231. code = variable.Code + "$ID";
  232. }
  233. }
  234. else if (value == null)
  235. {
  236. value = properties.Deserialize(formObject.GetEntry(code));
  237. }
  238. if (value != null)
  239. {
  240. data[code] = value;
  241. }
  242. }
  243. return data;
  244. }
  245. }
  246. }