DynamicOneToManyGrid.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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);
  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. protected override void Reload(Filters<TMany> criteria, Columns<TMany> columns, ref SortOrder<TMany>? sort,
  261. Action<CoreTable?, Exception?> action)
  262. {
  263. var results = new CoreTable();
  264. results.LoadColumns(typeof(TMany));
  265. if (LoadedColumns is not null)
  266. {
  267. // Figure out which columns we still need.
  268. var newColumns = columns.Where(x => !LoadedColumns.Contains(x.Property)).ToColumns();
  269. if (newColumns.Any() && typeof(TMany).GetCustomAttribute<AutoEntity>() is null)
  270. {
  271. var data = Client.Query(
  272. new Filter<TMany>(x => x.ID).InList(Items.Select(x => x.ID).Where(x => x != Guid.Empty).ToArray()),
  273. // We also need to add ID, so we know which item to fill.
  274. newColumns.Add(x => x.ID));
  275. foreach (var row in data.Rows)
  276. {
  277. var item = Items.FirstOrDefault(x => x.ID == row.Get<TMany, Guid>(y => y.ID));
  278. if (item is not null)
  279. {
  280. row.FillObject(item, overrideExisting: false);
  281. }
  282. }
  283. // Remember that we have now loaded this data.
  284. foreach (var column in newColumns)
  285. {
  286. LoadedColumns.Add(column.Property);
  287. }
  288. }
  289. }
  290. if (sort != null)
  291. {
  292. var exp = IQueryableExtensions.ToLambda<TMany>(sort.Expression);
  293. var sorted = sort.Direction == SortDirection.Ascending
  294. ? Items.AsQueryable().OrderBy(exp)
  295. : Items.AsQueryable().OrderByDescending(exp);
  296. foreach (var then in sort.Thens)
  297. {
  298. var thexp = IQueryableExtensions.ToLambda<TMany>(then.Expression);
  299. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  300. }
  301. Items = sorted.ToList();
  302. }
  303. results.LoadRows(Items);
  304. action.Invoke(results, null);
  305. }
  306. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  307. {
  308. var type = CoreUtils.GetProperty(typeof(TMany), column.ColumnName).DeclaringType;
  309. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TOne)))
  310. return new NullEditor();
  311. return base.GetEditor(item, column);
  312. }
  313. public override void LoadEditorButtons(TMany item, DynamicEditorButtons buttons)
  314. {
  315. base.LoadEditorButtons(item, buttons);
  316. if (ClientFactory.IsSupported<AuditTrail>())
  317. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  318. }
  319. private void AuditTrailClick(object sender, object? item)
  320. {
  321. if (item is not TMany entity) return;
  322. var window = new AuditWindow(entity.ID);
  323. window.ShowDialog();
  324. }
  325. public override DynamicEditorPages LoadEditorPages(TMany item)
  326. {
  327. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  328. }
  329. protected override bool BeforePaste(IEnumerable<TMany> items, ClipAction action)
  330. {
  331. if (action == ClipAction.Copy)
  332. {
  333. foreach (var item in items)
  334. {
  335. item.ID = Guid.Empty;
  336. }
  337. }
  338. return base.BeforePaste(items, action);
  339. }
  340. #endregion
  341. }
  342. }