DimensionUnit.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. using InABox.Clients;
  2. using InABox.Core;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Linq;
  7. namespace Comal.Classes
  8. {
  9. public abstract class DimensionUnit : Entity, IRemotable, IPersistent, ISequenceable, IDimensionUnit
  10. {
  11. [UniqueCodeEditor(Visible = Visible.Default, Editable = Editable.Enabled)]
  12. [EditorSequence(1)]
  13. public virtual String Code { get; set; }
  14. [TextBoxEditor]
  15. [EditorSequence(2)]
  16. public virtual String Description { get; set; }
  17. [CheckBoxEditor]
  18. [EditorSequence(3)]
  19. public virtual bool HasQuantity { get; set; } = false;
  20. [CheckBoxEditor]
  21. [EditorSequence(4)]
  22. public virtual bool HasLength { get; set; } = false;
  23. [CheckBoxEditor]
  24. [EditorSequence(5)]
  25. public virtual bool HasWidth { get; set; } = false;
  26. [CheckBoxEditor]
  27. [EditorSequence(6)]
  28. public virtual bool HasHeight { get; set; } = false;
  29. [CheckBoxEditor]
  30. [EditorSequence(7)]
  31. public virtual bool HasWeight { get; set; } = false;
  32. [ExpressionEditor(null, typeof(DimensionsExpressionModelGenerator))]
  33. [EditorSequence(8)]
  34. public virtual string Formula { get; set; } = "1";
  35. [ExpressionEditor(null, typeof(DimensionsExpressionModelGenerator))]
  36. [EditorSequence(9)]
  37. public virtual string Format { get; set; } = "\"EACH\"";
  38. [ScriptEditor]
  39. [EditorSequence(10)]
  40. public virtual string Conversion { get; set; } = "";
  41. [NullEditor]
  42. public long Sequence { get; set; }
  43. public bool HasDimensions() => HasHeight || HasWidth || HasLength || HasWeight || HasQuantity;
  44. public static string ConvertDimensionsMethodName() => "ConvertDimensions";
  45. public static string DefaultConvertDimensionsScript()
  46. {
  47. return
  48. "using Comal.Classes;\n"+
  49. "\n"+
  50. "public class Module\n"+
  51. "{\n"+
  52. " public double Quantity { get; set; }\n"+
  53. " public double Cost { get; set; }\n"+
  54. " public IDimensions Dimensions { get; set; }\n"+
  55. "\n" +
  56. " public bool " + ConvertDimensionsMethodName() + "()\n"+
  57. " {\n"+
  58. " // Update Dimensions and Quantity here\n"+
  59. " // eg. the following will explode a pack into its component parts:\n"+
  60. " // \n"+
  61. " // var qty = Dimensions.Quantity;\n"+
  62. " // if (qty.IsEffectivelyEqual(0.0))\n"+
  63. " // return false;\n"+
  64. " // \n"+
  65. " // Dimensions.Quantity = 1;\n"+
  66. " // Quantity *= qty;\n"+
  67. " // Cost /= qty;\n"+
  68. " // return true;\n"+
  69. " }\n"+
  70. "}\n";
  71. }
  72. public bool Validate(List<String> errors)
  73. {
  74. bool result = true;
  75. var variables = new Dictionary<string, object?>()
  76. {
  77. { "Quantity", 1.00F },
  78. { "Length", 1.00F },
  79. { "Width", 1.00F },
  80. { "Height", 1.00F },
  81. { "Weight", 1.00F }
  82. };
  83. try
  84. {
  85. var expr = new CoreExpression(Formula);
  86. expr.Evaluate(variables);
  87. result = true;
  88. }
  89. catch (Exception e)
  90. {
  91. errors.Add($"{Code}: Formula [{Formula}] => {e.Message}");
  92. result = false;
  93. }
  94. try
  95. {
  96. var expr = new CoreExpression(Format);
  97. expr.Evaluate(variables);
  98. result = true;
  99. }
  100. catch (Exception e)
  101. {
  102. errors.Add($"{Code}: Format [{Format}] => {e.Message}");
  103. result = false;
  104. }
  105. return result;
  106. }
  107. private class DimensionsExpressionModelGenerator : IExpressionModelGenerator
  108. {
  109. public List<string> GetVariables(object?[] items)
  110. {
  111. var dimensionUnits = items.Select(x => x as IDimensionUnit).Where(x => x != null).Cast<IDimensionUnit>();
  112. var variables = new List<string>();
  113. if (dimensionUnits.All(x => x.HasQuantity)) variables.Add("Quantity");
  114. if (dimensionUnits.All(x => x.HasLength)) variables.Add("Length");
  115. if (dimensionUnits.All(x => x.HasWidth)) variables.Add("Width");
  116. if (dimensionUnits.All(x => x.HasHeight)) variables.Add("Height");
  117. if (dimensionUnits.All(x => x.HasWeight)) variables.Add("Weight");
  118. return variables;
  119. }
  120. }
  121. public override string ToString()
  122. {
  123. return $"(ProductDimensionUnit: {Code})";
  124. }
  125. }
  126. public static class DimensionUnitUtils
  127. {
  128. public static Dictionary<Type, int> UpdateExpressions<T, TLink>(T[] items, IProgress<string> progress)
  129. where T : DimensionUnit, new()
  130. where TLink : DimensionUnitLink<T>
  131. {
  132. var dimensionTypes = new List<(Type dimType, Type linkType)>();
  133. foreach(var entity in CoreUtils.Entities)
  134. {
  135. var def = entity.GetSuperclassDefinition(typeof(Dimensions<,>));
  136. if(def != null && def.GenericTypeArguments[1] == typeof(T))
  137. {
  138. dimensionTypes.Add((entity, def.GenericTypeArguments[0]));
  139. }
  140. }
  141. var updateTypes = new Dictionary<Type, List<IProperty>>();
  142. foreach(var entity in CoreUtils.Entities)
  143. {
  144. if(entity.IsSubclassOf(typeof(Entity))
  145. && !entity.HasAttribute<AutoEntity>()
  146. && entity.HasInterface<IRemotable>())
  147. {
  148. foreach(var property in DatabaseSchema.Properties(entity))
  149. {
  150. if (property.Parent is null
  151. || property.Parent.Parent is null
  152. || property.IsCalculated
  153. || property.Parent.HasParentEntityLink()
  154. || !typeof(TLink).IsAssignableFrom(property.Parent.PropertyType)
  155. || !property.Name.EndsWith(".ID")) continue;
  156. var dimType = dimensionTypes.FirstOrDefault(x => property.Parent.Parent.PropertyType == x.dimType);
  157. if(dimType.dimType != null)
  158. {
  159. var propList = updateTypes.GetValueOrAdd(entity);
  160. propList.Add(property.Parent.Parent);
  161. }
  162. }
  163. }
  164. }
  165. var nResults = new Dictionary<Type, int>();
  166. var ids = items.ToArray(x => x.ID);
  167. foreach(var (type, properties) in updateTypes)
  168. {
  169. var columns = Columns.Create(type, ColumnTypeFlags.Required);
  170. foreach(var prop in properties)
  171. {
  172. columns.Add(prop.Name + "." + Dimensions.unitid.Property);
  173. columns.Add(prop.Name + "." + Dimensions.quantity.Property);
  174. columns.Add(prop.Name + "." + Dimensions.length.Property);
  175. columns.Add(prop.Name + "." + Dimensions.width.Property);
  176. columns.Add(prop.Name + "." + Dimensions.height.Property);
  177. columns.Add(prop.Name + "." + Dimensions.weight.Property);
  178. columns.Add(prop.Name + "." + Dimensions.unitSize.Property);
  179. columns.Add(prop.Name + "." + Dimensions.value.Property);
  180. }
  181. IFilter? filter = null;
  182. foreach(var prop in properties)
  183. {
  184. var newFilter = Filter.Create(type, prop.Name + "." + Dimensions.unitid.Property, Operator.InList, ids);
  185. if(filter is null)
  186. {
  187. filter = newFilter;
  188. }
  189. else
  190. {
  191. filter = filter.Or(newFilter);
  192. }
  193. }
  194. if(filter != null)
  195. {
  196. progress.Report($"Updating {CoreUtils.Neatify(type.GetCaption())}");
  197. var nTotal = Client.Create(type).Query(filter, Columns.None(type).Add("ID")).Rows.Count;
  198. var nProcessed = 0;
  199. var nResult = 0;
  200. var done = false;
  201. var percentStep = Math.Max(nTotal / 100, 1);
  202. var range = CoreRange.Database(1000);
  203. while(nProcessed < nTotal && !done)
  204. {
  205. var rows = Client.Create(type).Query(filter, columns, range: range).Rows;
  206. if (rows.Count == 0) break;
  207. if(rows.Count < 1000)
  208. {
  209. done = true;
  210. }
  211. range.Next();
  212. var results = new List<Entity>(rows.Count);
  213. for(int i = 0; i < rows.Count; ++i)
  214. {
  215. if(nProcessed % percentStep == 0)
  216. {
  217. progress.Report($"Updating {CoreUtils.Neatify(type.GetCaption())}: {(double)nProcessed / (double)nTotal * 100:F0}%");
  218. }
  219. var obj = (rows[i].ToObject(type) as Entity)!;
  220. foreach(var property in properties)
  221. {
  222. var id = CoreUtils.GetPropertyValue(obj, property.Name + "." + Dimensions.unitid.Property);
  223. if(id is Guid guid)
  224. {
  225. var unit = items.First(x => x.ID == guid);
  226. var dim = (property.Getter()(obj) as IDimensions)!;
  227. dim.Calculate(dim.Quantity, dim.Length, dim.Width, dim.Height, dim.Weight, unit.Formula, unit.Format);
  228. }
  229. }
  230. if (obj.IsChanged())
  231. {
  232. results.Add(obj);
  233. nResult++;
  234. }
  235. nProcessed++;
  236. }
  237. Client.Create(type).Save(results, "Updated Value and UnitSize to match dimension unit.");
  238. }
  239. nResults[type] = nResult;
  240. }
  241. }
  242. return nResults;
  243. }
  244. }
  245. }