DynamicOneToManyGrid.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Media.Imaging;
  11. using InABox.Clients;
  12. using InABox.Configuration;
  13. using InABox.Core;
  14. using InABox.Core.Reports;
  15. using InABox.WPF;
  16. namespace InABox.DynamicGrid
  17. {
  18. public interface IDynamicOneToManyGrid<TOne, TMany> : IDynamicEditorPage
  19. {
  20. List<TMany> Items { get; }
  21. void LoadItems(TMany[] items);
  22. }
  23. public class DynamicOneToManyGrid<TOne, TMany> : DynamicGrid<TMany>, IDynamicEditorPage, IDynamicOneToManyGrid<TOne, TMany>
  24. where TOne : Entity, new() where TMany : Entity, IPersistent, IRemotable, new()
  25. {
  26. private TMany[] MasterList = Array.Empty<TMany>();
  27. private readonly PropertyInfo property;
  28. /// <summary>
  29. /// A set of columns representing which columns have been loaded from the database.
  30. /// </summary>
  31. /// <remarks>
  32. /// This is used to refresh the data when the columns change.<br/>
  33. ///
  34. /// It is <see langword="null"/> if no data has been loaded from the database (that is, the data was gotten from
  35. /// a page data handler instead.)
  36. /// </remarks>
  37. private HashSet<string>? LoadedColumns;
  38. protected DynamicGridCustomColumnsComponent<TMany> ColumnsComponent;
  39. public DynamicOneToManyGrid()
  40. {
  41. Ready = false;
  42. Items = new List<TMany>();
  43. Criteria = new Filters<TMany>();
  44. property = CoreUtils.GetOneToManyProperty(typeof(TMany), typeof(TOne));
  45. AddHiddenColumn(property.Name + "." + nameof(IEntityLink.ID));
  46. foreach (var col in LookupFactory.RequiredColumns<TMany>())
  47. HiddenColumns.Add(col);
  48. ColumnsComponent = new DynamicGridCustomColumnsComponent<TMany>(this, GetTag());
  49. }
  50. protected override void Init()
  51. {
  52. }
  53. protected override void DoReconfigure(FluentList<DynamicGridOption> options)
  54. {
  55. options.BeginUpdate();
  56. options.Add(DynamicGridOption.RecordCount)
  57. .Add(DynamicGridOption.SelectColumns);
  58. if (Security.CanEdit<TMany>() && !ReadOnly)
  59. options.Add(DynamicGridOption.AddRows).Add(DynamicGridOption.EditRows);
  60. if (Security.CanDelete<TMany>() && !ReadOnly)
  61. options.Add(DynamicGridOption.DeleteRows);
  62. if (Security.CanImport<TMany>() && !ReadOnly)
  63. options.Add(DynamicGridOption.ImportData);
  64. if (Security.CanExport<TMany>())
  65. options.Add(DynamicGridOption.ExportData);
  66. if (Security.CanMerge<TMany>())
  67. options.Add(DynamicGridOption.MultiSelect);
  68. options.EndUpdate();
  69. }
  70. private static bool IsAutoEntity => typeof(TMany).HasAttribute<AutoEntity>();
  71. protected Filters<TMany> Criteria { get; } = new Filters<TMany>();
  72. public TOne Item { get; protected set; }
  73. public List<TMany> Items { get; private set; }
  74. public void LoadItems(TMany[] items)
  75. {
  76. Items.Clear();
  77. Items.AddRange(items);
  78. Refresh(false, true);
  79. }
  80. private static string GetTag()
  81. {
  82. return typeof(TOne).Name + "." + typeof(TMany).Name;
  83. }
  84. #region IDynamicEditorPage
  85. public DynamicEditorGrid EditorGrid { get; set; }
  86. public PageType PageType => PageType.Other;
  87. public bool Ready { get; set; }
  88. private bool _readOnly;
  89. public bool ReadOnly
  90. {
  91. get => _readOnly;
  92. set
  93. {
  94. if (_readOnly != value)
  95. {
  96. _readOnly = value;
  97. Reconfigure();
  98. }
  99. }
  100. }
  101. public virtual void Load(object item, Func<Type, CoreTable?>? PageDataHandler)
  102. {
  103. Reconfigure();
  104. Item = (TOne)item;
  105. Refresh(true, false);
  106. var data = PageDataHandler?.Invoke(typeof(TMany));
  107. if (data == null)
  108. {
  109. if (Item.ID == Guid.Empty)
  110. {
  111. data = new CoreTable();
  112. data.LoadColumns(typeof(TMany));
  113. }
  114. else
  115. {
  116. var criteria = new Filters<TMany>();
  117. var exp = CoreUtils.GetPropertyExpression<TMany>(property.Name + ".ID");
  118. criteria.Add(new Filter<TMany>(exp).IsEqualTo(Item.ID).And(exp).IsNotEqualTo(Guid.Empty));
  119. criteria.AddRange(Criteria.Items);
  120. var sort = LookupFactory.DefineSort<TMany>();
  121. var columns = DynamicGridUtils.LoadEditorColumns(DataColumns());
  122. data = Client.Query(criteria.Combine(), columns, sort);
  123. LoadedColumns = columns.ColumnNames().ToHashSet();
  124. }
  125. }
  126. MasterList = data.Rows.Select(x => x.ToObject<TMany>()).ToArray();
  127. Items = MasterList.ToList();
  128. Refresh(false, true);
  129. Ready = true;
  130. }
  131. public virtual void BeforeSave(object item)
  132. {
  133. // Don't need to do anything here
  134. }
  135. public virtual void AfterSave(object item)
  136. {
  137. if (IsAutoEntity)
  138. {
  139. return;
  140. }
  141. // First remove any deleted files
  142. foreach (var map in MasterList)
  143. if (!Items.Contains(map))
  144. OnDeleteItem(map);
  145. foreach (var map in Items)
  146. {
  147. var prop = (property.GetValue(map) as IEntityLink)!;
  148. prop.ID = Item.ID;
  149. prop.Synchronise(Item);
  150. }
  151. new Client<TMany>().Save(Items.Where(x => x.IsChanged()), "Updated by User");
  152. }
  153. public Size MinimumSize()
  154. {
  155. return new Size(400, 400);
  156. }
  157. public string Caption()
  158. {
  159. var caption = typeof(TMany).GetCustomAttribute(typeof(Caption));
  160. if (caption != null)
  161. return ((Caption)caption).Text;
  162. var result = new Inflector.Inflector(new CultureInfo("en")).Pluralize(typeof(TMany).Name);
  163. return result;
  164. }
  165. public virtual int Order()
  166. {
  167. return int.MinValue;
  168. }
  169. #endregion
  170. #region DynamicGrid
  171. protected virtual void OnDeleteItem(TMany item)
  172. {
  173. if (IsAutoEntity)
  174. {
  175. return;
  176. }
  177. Client.Delete(item, typeof(TMany).Name + " Deleted by User");
  178. }
  179. protected override CoreTable LoadImportKeys(string[] fields)
  180. {
  181. var result = base.LoadImportKeys(fields);
  182. result.LoadRows(MasterList);
  183. return result;
  184. }
  185. protected override bool CustomiseImportItem(TMany item)
  186. {
  187. var result = base.CustomiseImportItem(item);
  188. if (result)
  189. {
  190. var prop = (property.GetValue(item) as IEntityLink)!;
  191. prop.ID = Item.ID;
  192. prop.Synchronise(Item);
  193. }
  194. return result;
  195. }
  196. public override DynamicGridColumns GenerateColumns()
  197. {
  198. var cols = new DynamicGridColumns();
  199. cols.AddRange(base.GenerateColumns().Where(x => !x.ColumnName.StartsWith(property.Name + ".")));
  200. return cols;
  201. }
  202. protected override DynamicGridColumns LoadColumns()
  203. {
  204. return ColumnsComponent.LoadColumns();
  205. }
  206. protected override void SaveColumns(DynamicGridColumns columns)
  207. {
  208. ColumnsComponent.SaveColumns(columns);
  209. }
  210. protected override void LoadColumnsMenu(ContextMenu menu)
  211. {
  212. base.LoadColumnsMenu(menu);
  213. ColumnsComponent.LoadColumnsMenu(menu);
  214. }
  215. protected override DynamicGridSettings LoadSettings()
  216. {
  217. var tag = GetTag();
  218. var user = Task.Run(() => new UserConfiguration<DynamicGridSettings>(tag).Load());
  219. user.Wait();
  220. return user.Result;
  221. }
  222. protected override void SaveSettings(DynamicGridSettings settings)
  223. {
  224. var tag = GetTag();
  225. new UserConfiguration<DynamicGridSettings>(tag).Save(settings);
  226. }
  227. protected override TMany CreateItem()
  228. {
  229. var result = new TMany();
  230. var prop = (property.GetValue(result) as IEntityLink)!;
  231. prop.ID = Item.ID;
  232. prop.Synchronise(Item);
  233. return result;
  234. }
  235. protected override TMany LoadItem(CoreRow row)
  236. {
  237. return Items[_recordmap[row].Index];
  238. }
  239. protected override TMany[] LoadItems(CoreRow[] rows)
  240. {
  241. var result = new List<TMany>();
  242. foreach (var row in rows)
  243. result.Add(LoadItem(row));
  244. return result.ToArray();
  245. }
  246. public override void SaveItem(TMany item)
  247. {
  248. if (!Items.Contains(item))
  249. Items.Add(item);
  250. if (item is ISequenceable) Items = Items.AsQueryable().OrderBy(x => (x as ISequenceable)!.Sequence).ToList();
  251. }
  252. protected override void DeleteItems(params CoreRow[] rows)
  253. {
  254. var items = rows.Select(LoadItem).ToList();
  255. foreach (var item in items)
  256. {
  257. Items.Remove(item);
  258. }
  259. }
  260. /// <summary>
  261. /// Load the properties of any <see cref="EntityLink{T}"/>s on this <see cref="TMany"/> where the <see cref="IEntityLink.ID"/> is not <see cref="Guid.Empty"/>.
  262. /// This allows us to populate columns of transient objects, as long as they are linked by the ID. What this actually then does is query each
  263. /// linked table with the required columns.
  264. /// </summary>
  265. /// <param name="columns"></param>
  266. private void LoadForeignProperties(Columns<TMany> columns)
  267. {
  268. // Lists of properties that we need, arranged by the entity link property which is their parent.
  269. // LinkIDProperty : (Type, Properties: [(columnName, property)], Objects)
  270. var newData = new Dictionary<IProperty, Tuple<Type, List<Tuple<string, IProperty>>, HashSet<TMany>>>();
  271. foreach (var column in columns)
  272. {
  273. var property = DatabaseSchema.Property(typeof(TMany), column.Property);
  274. if (property?.GetOuterParent(x => x.IsEntityLink) is IProperty linkProperty)
  275. {
  276. var remaining = column.Property[(linkProperty.Name.Length + 1)..];
  277. if (remaining.Equals(nameof(IEntityLink.ID)))
  278. {
  279. // This guy isn't foreign, so we don't pull him.
  280. continue;
  281. }
  282. var idProperty = DatabaseSchema.Property(typeof(TMany), linkProperty.Name + "." + nameof(IEntityLink.ID))!;
  283. var linkType = linkProperty.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>))!.GenericTypeArguments[0];
  284. if (!newData.TryGetValue(idProperty, out var data))
  285. {
  286. data = new Tuple<Type, List<Tuple<string, IProperty>>, HashSet<TMany>>(
  287. linkType,
  288. new List<Tuple<string, IProperty>>(),
  289. new HashSet<TMany>());
  290. newData.Add(idProperty, data);
  291. }
  292. var any = false;
  293. foreach (var item in Items)
  294. {
  295. if (!item.LoadedColumns.Contains(column.Property))
  296. {
  297. var linkID = (Guid)idProperty.Getter()(item);
  298. if (linkID != Guid.Empty)
  299. {
  300. any = true;
  301. data.Item3.Add(item);
  302. }
  303. }
  304. }
  305. if (any)
  306. {
  307. data.Item2.Add(new(remaining, property));
  308. }
  309. }
  310. }
  311. foreach (var (prop, data) in newData)
  312. {
  313. if (data.Item2.Any())
  314. {
  315. var ids = data.Item3.Select(prop.Getter()).Cast<Guid>().ToArray();
  316. var table = Client.Create(data.Item1).Query(
  317. Filter.Create<Entity>(data.Item1, x => x.ID).InList(ids),
  318. Columns.Create(data.Item1, data.Item2.Select(x => x.Item1).ToArray()).Add<Entity>(x => x.ID));
  319. foreach (var entity in data.Item3)
  320. {
  321. var linkID = (Guid)prop.Getter()(entity);
  322. var row = table.Rows.FirstOrDefault(x => x.Get<Entity, Guid>(x => x.ID) == linkID);
  323. if (row is not null)
  324. {
  325. foreach (var (name, property) in data.Item2)
  326. {
  327. if (!entity.LoadedColumns.Contains(property.Name))
  328. {
  329. property.Setter()(entity, row[name]);
  330. entity.LoadedColumns.Add(property.Name);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. }
  337. }
  338. protected override void Reload(Filters<TMany> criteria, Columns<TMany> columns, ref SortOrder<TMany>? sort,
  339. Action<CoreTable?, Exception?> action)
  340. {
  341. var results = new CoreTable();
  342. results.LoadColumns(typeof(TMany));
  343. if (LoadedColumns is not null)
  344. {
  345. // Figure out which columns we still need.
  346. var newColumns = columns.Where(x => !LoadedColumns.Contains(x.Property)).ToColumns();
  347. if (newColumns.Any() && typeof(TMany).GetCustomAttribute<AutoEntity>() is null)
  348. {
  349. var data = Client.Query(
  350. new Filter<TMany>(x => x.ID).InList(Items.Select(x => x.ID).Where(x => x != Guid.Empty).ToArray()),
  351. // We also need to add ID, so we know which item to fill.
  352. newColumns.Add(x => x.ID));
  353. foreach (var row in data.Rows)
  354. {
  355. var item = Items.FirstOrDefault(x => x.ID == row.Get<TMany, Guid>(y => y.ID));
  356. if (item is not null)
  357. {
  358. row.FillObject(item, overrideExisting: false);
  359. }
  360. }
  361. // Remember that we have now loaded this data.
  362. foreach (var column in newColumns)
  363. {
  364. LoadedColumns.Add(column.Property);
  365. }
  366. }
  367. }
  368. LoadForeignProperties(columns);
  369. if (sort != null)
  370. {
  371. var exp = IQueryableExtensions.ToLambda<TMany>(sort.Expression);
  372. var sorted = sort.Direction == SortDirection.Ascending
  373. ? Items.AsQueryable().OrderBy(exp)
  374. : Items.AsQueryable().OrderByDescending(exp);
  375. foreach (var then in sort.Thens)
  376. {
  377. var thexp = IQueryableExtensions.ToLambda<TMany>(then.Expression);
  378. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  379. }
  380. Items = sorted.ToList();
  381. }
  382. results.LoadRows(Items);
  383. action.Invoke(results, null);
  384. }
  385. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  386. {
  387. var type = CoreUtils.GetProperty(typeof(TMany), column.ColumnName).DeclaringType;
  388. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TOne)))
  389. return new NullEditor();
  390. return base.GetEditor(item, column);
  391. }
  392. public override void LoadEditorButtons(TMany item, DynamicEditorButtons buttons)
  393. {
  394. base.LoadEditorButtons(item, buttons);
  395. if (ClientFactory.IsSupported<AuditTrail>())
  396. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  397. }
  398. private void AuditTrailClick(object sender, object? item)
  399. {
  400. if (item is not TMany entity) return;
  401. var window = new AuditWindow(entity.ID);
  402. window.ShowDialog();
  403. }
  404. public override DynamicEditorPages LoadEditorPages(TMany item)
  405. {
  406. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  407. }
  408. protected override bool BeforePaste(IEnumerable<TMany> items, ClipAction action)
  409. {
  410. if (action == ClipAction.Copy)
  411. {
  412. foreach (var item in items)
  413. {
  414. item.ID = Guid.Empty;
  415. }
  416. }
  417. return base.BeforePaste(items, action);
  418. }
  419. #endregion
  420. }
  421. }