DigitalForm.cs 12 KB

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