DimensionUnit.cs 11 KB

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