SaveEvent.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.Database;
  4. using InABox.Scripting;
  5. using Inflector;
  6. using Newtonsoft.Json;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics.CodeAnalysis;
  10. using System.Linq;
  11. using System.Text;
  12. namespace PRS.Shared.Events;
  13. public class SaveEvent<T> : IEvent<SaveEventDataModel<T>>
  14. where T : Entity, new()
  15. {
  16. public Type Entity => typeof(T);
  17. public IEventDataModelDefinition DataModelDefinition()
  18. {
  19. return new SaveEventDataModelDefinition<T>(this);
  20. }
  21. public Notification GenerateNotification(SaveEventDataModel<T> model)
  22. {
  23. var notification = new Notification();
  24. notification.Title = $"Updated {typeof(T).Name}";
  25. notification.Description = $"Updated {typeof(T).Name}";
  26. if(model.Entity.ID != Guid.Empty)
  27. {
  28. notification.EntityType = CoreUtils.EntityName(model.EntityType);
  29. notification.EntityID = model.Entity.ID;
  30. }
  31. return notification;
  32. }
  33. public void Init(IStore store, IEventData evData, SaveEventDataModel<T> model)
  34. {
  35. if (model.Entity.ID != Guid.Empty)
  36. {
  37. var loadCols = Columns.None<T>();
  38. var prefix = $"{typeof(T).Name}.";
  39. foreach (var variable in evData.ReferencedVariables)
  40. {
  41. if (variable.StartsWith(prefix))
  42. {
  43. var varName = variable[prefix.Length..];
  44. if (!model.Entity.HasOriginalValue(varName))
  45. {
  46. loadCols.Add(varName);
  47. }
  48. }
  49. }
  50. var data = store.Provider.Query(
  51. new Filter<T>(x => x.ID).IsEqualTo(model.Entity.ID),
  52. loadCols);
  53. if(data.Rows.Count > 0)
  54. {
  55. data.Rows[0].FillObject(model.Entity);
  56. }
  57. }
  58. }
  59. }
  60. public class SaveEventDataModelDefinition<T>(SaveEvent<T> ev) : IEventDataModelDefinition
  61. where T : Entity, new()
  62. {
  63. private IEventVariable[]? variables;
  64. public IEnumerable<IEventVariable> GetVariables()
  65. {
  66. if(variables is null)
  67. {
  68. variables = DatabaseSchema.AllProperties(ev.Entity).Select(x => new StandardEventVariable($"{typeof(T).Name}.{x.Name}", x.PropertyType)).ToArray();
  69. variables.SortBy(x => x.Name);
  70. }
  71. return variables;
  72. }
  73. public IEventVariable? GetVariable(string name)
  74. {
  75. if(variables is null)
  76. {
  77. var prefix = $"{typeof(T).Name}.";
  78. if (name.StartsWith(prefix))
  79. {
  80. name = name[prefix.Length..];
  81. var prop = DatabaseSchema.Property(ev.Entity, name);
  82. if(prop is null)
  83. {
  84. return null;
  85. }
  86. else
  87. {
  88. return new StandardEventVariable(prop.Name, prop.PropertyType);
  89. }
  90. }
  91. else
  92. {
  93. return null;
  94. }
  95. }
  96. else
  97. {
  98. return variables.FirstOrDefault(x => x.Name == name);
  99. }
  100. }
  101. }
  102. public class SaveEventDataModel<T>(T entity, IStore store) : IEventDataModel, ITypedEventDataModel
  103. where T : Entity, new()
  104. {
  105. public T Entity { get; set; } = entity;
  106. public Type EntityType => typeof(T);
  107. public IStore Store { get; } = store;
  108. public bool TryGetVariable(string name, out object? value)
  109. {
  110. var prefix = $"{typeof(T).Name}.";
  111. if (name.StartsWith(prefix))
  112. {
  113. name = name[prefix.Length..];
  114. var prop = DatabaseSchema.Property(typeof(T), name);
  115. if(prop != null)
  116. {
  117. value = prop.Getter()(Entity);
  118. return true;
  119. }
  120. }
  121. value = null;
  122. return false;
  123. }
  124. }
  125. #region Triggers
  126. [Caption("New Record")]
  127. public class CreatedSaveEventTrigger<T> : IEventTrigger<SaveEvent<T>, SaveEventDataModel<T>>
  128. where T : Entity, new()
  129. {
  130. public string Description => "New Record";
  131. public IEnumerable<string> ReferencedVariables => [];
  132. public bool Check(SaveEventDataModel<T> dataModel)
  133. {
  134. return dataModel.Entity.HasOriginalValue(x => x.ID);
  135. }
  136. }
  137. [Caption("Property Changed")]
  138. public class PropertyChangedSaveEventTrigger<T> : IEventTrigger<SaveEvent<T>, SaveEventDataModel<T>>
  139. where T : Entity, new()
  140. {
  141. [JsonIgnore]
  142. public IProperty? TriggerProperty { get; set; }
  143. [JsonProperty(PropertyName = "TriggerProperty")]
  144. private string? _property
  145. {
  146. get => TriggerProperty?.Name;
  147. set
  148. {
  149. TriggerProperty = value is null ? null : DatabaseSchema.PropertyStrict(typeof(T), value);
  150. }
  151. }
  152. public string Description => TriggerProperty is null
  153. ? $"{typeof(T).GetCaption()} changed"
  154. : $"{typeof(T).GetCaption()}.{TriggerProperty.Name} changed";
  155. public IEnumerable<string> ReferencedVariables => [];
  156. public bool Check(SaveEventDataModel<T> dataModel)
  157. {
  158. if(TriggerProperty is null)
  159. {
  160. return false;
  161. }
  162. if (!dataModel.Entity.HasOriginalValue(TriggerProperty.Name))
  163. {
  164. return false;
  165. }
  166. return true;
  167. }
  168. }
  169. [Caption("Filter")]
  170. public class FilterSaveEventTrigger<T> : IEventTrigger<SaveEvent<T>, SaveEventDataModel<T>>
  171. where T : Entity, new()
  172. {
  173. public Filter<T>? Filter { get; set; }
  174. public IEnumerable<string> ReferencedVariables => GetReferencedProperties(Filter).Select(x => $"{typeof(T).Name}.{x}");
  175. public string Description => Filter?.ToString() ?? "Blank Filter";
  176. public bool Check(SaveEventDataModel<T> dataModel)
  177. {
  178. return Filter.Match(dataModel.Entity, dataModel.Store.GetQueryProviderFactory());
  179. }
  180. private IEnumerable<string> GetReferencedProperties(Filter<T>? filter)
  181. {
  182. if (filter is null) yield break;
  183. if(filter.Operator != Operator.All && filter.Operator != Operator.None
  184. && !filter.Property.IsNullOrWhiteSpace())
  185. {
  186. yield return filter.Property;
  187. }
  188. foreach(var prop in filter.Ands.Concat(filter.Ors).SelectMany(GetReferencedProperties))
  189. {
  190. yield return prop;
  191. }
  192. }
  193. }
  194. [Caption("Custom Script")]
  195. public class ScriptSaveEventTrigger<T> : IEventTrigger<SaveEvent<T>, SaveEventDataModel<T>>
  196. where T : Entity, new()
  197. {
  198. public string Description => "Custom Script";
  199. private ScriptDocument? _scriptDocument;
  200. private ScriptDocument? ScriptDocument
  201. {
  202. get
  203. {
  204. if(_scriptDocument is null && Script is not null)
  205. {
  206. _scriptDocument = new(Script);
  207. _scriptDocument.Compile();
  208. }
  209. return _scriptDocument;
  210. }
  211. }
  212. private string? _script;
  213. public string? Script
  214. {
  215. get => _script;
  216. set
  217. {
  218. if(_script != value)
  219. {
  220. _script = value;
  221. _scriptDocument = null;
  222. }
  223. }
  224. }
  225. public IEnumerable<string> ReferencedVariables
  226. {
  227. get
  228. {
  229. var method = ScriptDocument?.GetMethod(methodName: "RequiredColumns");
  230. if(method is not null)
  231. {
  232. var cols = Columns.None<T>();
  233. method.Invoke(ScriptDocument!.GetObject(), [cols]);
  234. return cols.ColumnNames().Select(x => $"{typeof(T).Name}.{x}");
  235. }
  236. else
  237. {
  238. return [];
  239. }
  240. }
  241. }
  242. public string DefaultScript()
  243. {
  244. return @"using PRS.Shared.Events;
  245. public class Module
  246. {
  247. public void RequiredColumns(Columns<" + typeof(T).Name + @"> columns)
  248. {
  249. // Modify 'columns' as required to get the required columns for the 'model.Entity'. If you don't provide these,
  250. // the data you require in 'Execute' may not be present. Example:
  251. // columns.Add(x => x.ID);
  252. }
  253. public bool Check(SaveEventDataModel<" + typeof(T).Name + @"> model)
  254. {
  255. // Return true if model.Entity meets the requirements for this event trigger.
  256. return true;
  257. }
  258. }";
  259. }
  260. public bool Check(SaveEventDataModel<T> dataModel)
  261. {
  262. if (ScriptDocument is null) return false;
  263. return ScriptDocument.Execute(methodname: "Check", parameters: [dataModel]);
  264. }
  265. }
  266. #endregion
  267. #region Actions
  268. [Caption("Custom Script")]
  269. public class ScriptSaveEventAction<T> : IEventAction<SaveEvent<T>>
  270. where T : Entity, new()
  271. {
  272. private ScriptDocument? _scriptDocument;
  273. private ScriptDocument? ScriptDocument
  274. {
  275. get
  276. {
  277. if(_scriptDocument is null && Script is not null)
  278. {
  279. _scriptDocument = new(Script);
  280. _scriptDocument.SetValue("Result", null);
  281. _scriptDocument.Compile();
  282. }
  283. return _scriptDocument;
  284. }
  285. }
  286. private string? _script;
  287. public string? Script
  288. {
  289. get => _script;
  290. set
  291. {
  292. if(_script != value)
  293. {
  294. _script = value;
  295. _scriptDocument = null;
  296. }
  297. }
  298. }
  299. public IEnumerable<string> ReferencedVariables
  300. {
  301. get
  302. {
  303. var method = ScriptDocument?.GetMethod(methodName: "RequiredColumns");
  304. if(method is not null)
  305. {
  306. var cols = Columns.None<T>();
  307. method.Invoke(ScriptDocument!.GetObject(), [cols]);
  308. return cols.ColumnNames().Select(x => $"{typeof(T).Name}.{x}");
  309. }
  310. else
  311. {
  312. return [];
  313. }
  314. }
  315. }
  316. public string Description => "Custom Script";
  317. public string DefaultScript()
  318. {
  319. return @"using PRS.Shared.Events;
  320. public class Module
  321. {
  322. public object? Result { get; set; }
  323. public void RequiredColumns(Columns<" + typeof(T).Name + @"> columns)
  324. {
  325. // Modify 'columns' as required to get the required columns for the 'model.Entity'. If you don't provide these,
  326. // the data you require in 'Execute' may not be present. Example:
  327. // columns.Add(x => x.ID);
  328. }
  329. public bool Execute(SaveEventDataModel<" + typeof(T).Name + @"> model)
  330. {
  331. // Do anything you want with model.Entity, and then save return-value to 'Result', or leave it as 'null' if no return value is needed.
  332. return true;
  333. }
  334. }";
  335. }
  336. public object? Execute(IEventDataModel dataModel)
  337. {
  338. if (ScriptDocument is null) return null;
  339. var model = dataModel.RootModel<SaveEventDataModel<T>>();
  340. if(ScriptDocument.Execute(methodname: "Execute", parameters: [model]))
  341. {
  342. return ScriptDocument.GetValue("Result");
  343. }
  344. else
  345. {
  346. return null;
  347. }
  348. }
  349. }
  350. [Caption("Create Entity")]
  351. public class CreateEntitySaveEventAction<T> : IEventAction<SaveEvent<T>>
  352. where T : Entity, new()
  353. {
  354. [JsonProperty(Order = 1)]
  355. public Type? EntityType { get; set; }
  356. [JsonIgnore]
  357. public List<PropertyInitializer> Initializers { get; set; } = new List<PropertyInitializer>();
  358. private ScriptDocument? _scriptDocument;
  359. private ScriptDocument? ScriptDocument
  360. {
  361. get
  362. {
  363. if(_scriptDocument is null && Script is not null)
  364. {
  365. _scriptDocument = new(Script);
  366. _scriptDocument.Compile();
  367. }
  368. return _scriptDocument;
  369. }
  370. }
  371. private string? _script;
  372. public string? Script
  373. {
  374. get => _script;
  375. set
  376. {
  377. if(_script != value)
  378. {
  379. _script = value;
  380. _scriptDocument = null;
  381. }
  382. }
  383. }
  384. private IEnumerable<string> ScriptReferencedVariables
  385. {
  386. get
  387. {
  388. var method = ScriptDocument?.GetMethod(methodName: "RequiredColumns");
  389. if(method is not null)
  390. {
  391. var cols = Columns.None<T>();
  392. method.Invoke(ScriptDocument!.GetObject(), [cols]);
  393. return cols.ColumnNames().Select(x => $"{typeof(T).Name}.{x}");
  394. }
  395. else
  396. {
  397. return [];
  398. }
  399. }
  400. }
  401. public string DefaultScript()
  402. {
  403. if (EntityType is null) return "Please select an entity type first.";
  404. return @"using PRS.Shared.Events;
  405. public class Module
  406. {
  407. public void RequiredColumns(Columns<" + typeof(T).Name + @"> columns)
  408. {
  409. // Modify 'columns' as required to get the required columns for the 'model.Entity'. If you don't provide these,
  410. // the data you require in 'Execute' may not be present. Example:
  411. // columns.Add(x => x.ID);
  412. }
  413. public void Execute(SaveEventDataModel<" + typeof(T).Name + @"> model, " + EntityType.Name + " new" + EntityType.Name + @")
  414. {
  415. // Modify new" + EntityType.Name + @" as you wish, using model.Entity to get the required data. This method runs after
  416. // the property initializers (in the previous screen) for the Create Entity action have run.
  417. }
  418. }";
  419. }
  420. public string Description => $"Create New {EntityType?.Name ?? "Entity"}";
  421. public IEnumerable<string> ReferencedVariables => Initializers.SelectMany(x => x.ReferencedVariables).Concat(ScriptReferencedVariables);
  422. public object? Execute(IEventDataModel dataModel)
  423. {
  424. if(EntityType is null)
  425. {
  426. return null;
  427. }
  428. var entity = (Activator.CreateInstance(EntityType) as Entity)!;
  429. foreach(var initializer in Initializers)
  430. {
  431. initializer.Execute(entity, dataModel);
  432. }
  433. if(ScriptDocument is not null)
  434. {
  435. var model = dataModel.RootModel<SaveEventDataModel<T>>();
  436. ScriptDocument.Execute(methodname: "Execute", parameters: [model, entity]);
  437. }
  438. DbFactory.FindStore(EntityType, Guid.Empty, "", default, "", Logger.Main).Save(entity, "");
  439. return entity;
  440. }
  441. #region Serialization Stuff
  442. [JsonProperty(Order = 2, PropertyName = "Initializers")]
  443. private PropertyInitializerSerializationItem[] _initializers
  444. {
  445. get => Initializers.ToArray(x => new PropertyInitializerSerializationItem { Property = x.Property.Name, Value = x.Value });
  446. set
  447. {
  448. Initializers.Clear();
  449. Initializers.AddRange(value.Select(x => new PropertyInitializer(EntityType!, x)));
  450. }
  451. }
  452. #endregion
  453. }
  454. internal class PropertyInitializerSerializationItem
  455. {
  456. public string Property { get; set; }
  457. public string Value { get; set; }
  458. }
  459. public class PropertyInitializer
  460. {
  461. public IProperty Property { get; set; }
  462. private CoreExpression? _valueExpression;
  463. private CoreExpression ValueExpression
  464. {
  465. get
  466. {
  467. _valueExpression ??= new CoreExpression(Value, Property.PropertyType);
  468. return _valueExpression;
  469. }
  470. }
  471. private string _value;
  472. public string Value
  473. {
  474. get => _value;
  475. [MemberNotNull(nameof(_value))]
  476. set
  477. {
  478. if(value != _value)
  479. {
  480. _value = value;
  481. _valueExpression = null;
  482. }
  483. }
  484. }
  485. public IEnumerable<string> ReferencedVariables => ValueExpression.ReferencedVariables;
  486. internal PropertyInitializer(Type entityType, PropertyInitializerSerializationItem item)
  487. {
  488. Value = item.Value;
  489. Property = DatabaseSchema.PropertyStrict(entityType, item.Property);
  490. }
  491. public PropertyInitializer(IProperty property, string value)
  492. {
  493. Property = property;
  494. Value = value;
  495. }
  496. public void Execute(Entity entity, IEventDataModel dataModel)
  497. {
  498. Property.Setter()(entity, ValueExpression.Evaluate(dataModel));
  499. }
  500. }
  501. #endregion