ProjectsGrid.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using Comal.Classes;
  8. using Comal.Classes.SecurityDescriptors;
  9. using InABox.Clients;
  10. using InABox.Configuration;
  11. using InABox.Core;
  12. using InABox.DynamicGrid;
  13. using InABox.Integration.Logikal;
  14. using InABox.Wpf;
  15. using InABox.WPF;
  16. using PRSDesktop.Integrations.V6;
  17. using PRSDesktop.Integrations.Logikal;
  18. namespace PRSDesktop;
  19. public class JobGridSettings : IUserConfigurationSettings
  20. {
  21. [Obsolete]
  22. private CoreFilterDefinition? _currentFilter;
  23. [Obsolete]
  24. public CoreFilterDefinition? CurrentFilter
  25. {
  26. get => _currentFilter;
  27. set
  28. {
  29. if (value is not null)
  30. {
  31. Filters = new DynamicGridSelectedFilterSettings(new List<ICoreFilterDefinition> { value }, false, null);
  32. }
  33. }
  34. }
  35. public DynamicGridSelectedFilterSettings Filters { get; set; } = new();
  36. }
  37. public class ProjectsGrid : DynamicDataGrid<Job>
  38. {
  39. private Guid _statusid = Guid.Empty;
  40. private JobGridSettings _settings;
  41. public ProjectsGrid()
  42. {
  43. _settings = new UserConfiguration<JobGridSettings>().Load();
  44. FilterComponent.SetSettings(_settings.Filters, false);
  45. FilterComponent.OnFiltersSelected += FilterComponent_OnFilterSelected;
  46. HiddenColumns.Add(x => x.ID);
  47. HiddenColumns.Add(x => x.JobNumber);
  48. HiddenColumns.Add(x => x.Name);
  49. HiddenColumns.Add(x => x.Customer.ID);
  50. HiddenColumns.Add(x => x.Customer.Code);
  51. HiddenColumns.Add(x => x.Customer.Name);
  52. HiddenColumns.Add(x => x.Customer.Terms.ID);
  53. HiddenColumns.Add(x => x.Customer.Terms.Code);
  54. HiddenColumns.Add(x => x.Customer.Terms.Description);
  55. HiddenColumns.Add(x => x.Customer.Terms.Calculation);
  56. HiddenColumns.Add(x => x.SiteAddress.Street);
  57. HiddenColumns.Add(x => x.SiteAddress.City);
  58. HiddenColumns.Add(x => x.SiteAddress.State);
  59. HiddenColumns.Add(x => x.SiteAddress.PostCode);
  60. HiddenColumns.Add(x => x.Account.ID);
  61. HiddenColumns.Add(x => x.Account.Code);
  62. HiddenColumns.Add(x => x.Account.Name);
  63. HiddenColumns.Add(x => x.Account.Terms.ID);
  64. HiddenColumns.Add(x => x.Account.Terms.Code);
  65. HiddenColumns.Add(x => x.Account.Terms.Description);
  66. HiddenColumns.Add(x => x.Account.Terms.Calculation);
  67. HiddenColumns.Add(x => x.Notes);
  68. HiddenColumns.Add(x => x.JobStatus.ID);
  69. HiddenColumns.Add(x => x.JobStatus.Active);
  70. HiddenColumns.Add(x => x.DefaultScope.ID);
  71. HiddenColumns.Add(x => x.SourceRef);
  72. ActionColumns.Add(new DynamicMapColumn<Job>(this, x => x.SiteAddress));
  73. //ActionColumns.Add(new DynamicMenuColumn(BuildMenu));
  74. }
  75. protected override void DoReconfigure(DynamicGridOptions options)
  76. {
  77. base.DoReconfigure(options);
  78. options.RecordCount = true;
  79. options.SelectColumns = true;
  80. options.FilterRows = true;
  81. }
  82. // private void BuildMenu(DynamicMenuColumn column, CoreRow? row)
  83. // {
  84. // if (Security.IsAllowed<CanCancelAllJobRequisitions>())
  85. // {
  86. // column.AddItem("Cancel all active requisitions", null, CancelJobRequisitions_Click);
  87. // }
  88. // if (Security.IsAllowed<CanReleaseJobReserves>())
  89. // {
  90. // column.AddItem("Release Job Reserves", null, ReleaseJobReserves_Click);
  91. // }
  92. // }
  93. //
  94. // private void CancelJobRequisitions_Click(CoreRow? obj)
  95. // {
  96. // var job = obj?.ToObject<Job>();
  97. // if (job is null)
  98. // {
  99. // MessageWindow.ShowMessage("Please select a job.", "No job selected");
  100. // return;
  101. // }
  102. //
  103. // if(MessageWindow.ShowYesNoCancel("Are you sure you wish to do this? This will cancel all requisitions for this job.", "Confirm") != MessageWindowResult.Yes)
  104. // {
  105. // MessageWindow.ShowMessage("No action taken.", "Process aborted");
  106. // return;
  107. // }
  108. //
  109. // var requisitionItems = Client.Query(
  110. // new Filter<JobRequisitionItem>(x => x.Requisition.Job.ID).IsEqualTo(job.ID)
  111. // .And(x => x.Status).IsNotEqualTo(JobRequisitionItemStatus.Cancelled)
  112. // .And(x => x.Status).IsNotEqualTo(JobRequisitionItemStatus.Issued)
  113. // .And(x => x.Status).IsNotEqualTo(JobRequisitionItemStatus.Archived),
  114. // new Columns<JobRequisitionItem>(x => x.ID)
  115. // .Add(x => x.Cancelled))
  116. // .ToList<JobRequisitionItem>();
  117. // foreach(var jri in requisitionItems)
  118. // {
  119. // jri.Cancelled = DateTime.Now;
  120. // }
  121. // Client.Save(requisitionItems, "Cancelled all job requisitions for job");
  122. // MessageWindow.ShowMessage("All job requisitions cancelled.", "Success");
  123. // }
  124. //
  125. // private void ReleaseJobReserves_Click(CoreRow? obj)
  126. // {
  127. // var job = obj?.ToObject<Job>();
  128. // if (job is null)
  129. // {
  130. // MessageWindow.ShowMessage("Please select a job.", "No job selected");
  131. // return;
  132. // }
  133. //
  134. // if(MessageWindow.ShowYesNoCancel("Are you sure you wish to do this? This will release all reserves for this job.", "Confirm") != MessageWindowResult.Yes)
  135. // {
  136. // MessageWindow.ShowMessage("No action taken.", "Process aborted");
  137. // return;
  138. // }
  139. //
  140. // var movements = Client.Query<StockMovement>(
  141. // new Filter<StockMovement>(x => x.Job.ID).IsEqualTo(job.ID),
  142. // new Columns<StockMovement>(x => x.Units)
  143. // .Add(x => x.Location.ID)
  144. // .Add(x => x.Product.ID)
  145. // .Add(x => x.Style.ID)
  146. // .AddDimensionsColumns(x => x.Dimensions)
  147. // .Add(x => x.Cost)
  148. // .Add(x => x.OrderItem.ID)
  149. // .Add(x => x.JobRequisitionItem.ID))
  150. // .ToObjects<StockMovement>()
  151. // .GroupBy(x => new
  152. // {
  153. // Location = x.Location.ID,
  154. // Product = x.Product.ID,
  155. // Style = x.Style.ID,
  156. // x.Dimensions,
  157. // x.Cost,
  158. // OrderItem = x.OrderItem.ID,
  159. // JobRequisitionItem = x.JobRequisitionItem.ID
  160. // })
  161. // .Select(x => new { x.Key, Units = x.Sum(x => x.Units) });
  162. //
  163. // var toSave = new List<StockMovement>();
  164. // foreach(var group in movements)
  165. // {
  166. // var from = new StockMovement();
  167. // from.Location.ID = group.Key.Location;
  168. // from.Style.ID = group.Key.Style;
  169. // from.Product.ID = group.Key.Product;
  170. // from.Dimensions.CopyFrom(group.Key.Dimensions);
  171. //
  172. // var to = from.CreateMovement();
  173. //
  174. // from.Job.ID = job.ID;
  175. //
  176. // from.Cost = group.Key.Cost;
  177. // to.Cost = group.Key.Cost;
  178. // from.OrderItem.ID = group.Key.OrderItem;
  179. // to.OrderItem.ID = group.Key.OrderItem;
  180. // from.JobRequisitionItem.ID = group.Key.JobRequisitionItem;
  181. // to.JobRequisitionItem.ID = group.Key.JobRequisitionItem;
  182. //
  183. // from.Type = StockMovementType.TransferOut;
  184. // to.Type = StockMovementType.TransferIn;
  185. // to.Transaction = from.Transaction;
  186. //
  187. // from.Units = -group.Units;
  188. // to.Units = group.Units;
  189. //
  190. // toSave.Add(from);
  191. // toSave.Add(to);
  192. // }
  193. // Client.Save(toSave, "Released all job stock.");
  194. // MessageWindow.ShowMessage("All job stock reserves released.", "Success");
  195. // }
  196. public Guid StatusID
  197. {
  198. get => _statusid;
  199. set
  200. {
  201. _statusid = value;
  202. }
  203. }
  204. protected override void Reload(
  205. Filters<Job> criteria, Columns<Job> columns, ref SortOrder<Job>? sort,
  206. CancellationToken token, Action<CoreTable?, Exception?> action)
  207. {
  208. if (_statusid != Guid.Empty)
  209. criteria.Add(new Filter<Job>(x => x.JobStatus.ID).IsEqualTo(_statusid));
  210. //criteria.Add(new Filter<Job>(x => x.JobType).IsEqualTo(JobType.Project));
  211. sort = new SortOrder<Job>(x => x.JobNumber, SortDirection.Descending);
  212. base.Reload(criteria, columns, ref sort, token, action);
  213. }
  214. public override DynamicEditorPages LoadEditorPages(Job item)
  215. {
  216. var pages = new DynamicEditorPages(new IDynamicEditorPage[]
  217. {
  218. new DynamicManyToManyGrid<JobDocument,Job>(),
  219. //new DynamicManyToManyGrid<JobStyle,Job>(),
  220. new DynamicOneToManyGrid<Job,JobDocumentSetTag>(),
  221. new JobFormDefinitionGrid(),
  222. //new DynamicOneToManyGrid<Job, JobProductMapping>(),
  223. });
  224. return pages;
  225. }
  226. private LogikalSettings? _logikalSettings;
  227. private V6Settings? _v6Settings;
  228. protected override void DoAdd(bool openEditorOnDirectEdit = false)
  229. {
  230. ContextMenu? menu = null;
  231. if (Security.IsAllowed<ImportV6Projects>())
  232. {
  233. _v6Settings ??= new GlobalConfiguration<V6Settings>().Load();
  234. if (_v6Settings.ImportProjects == V6ProjectType.Project)
  235. {
  236. menu ??= new ContextMenu();
  237. var item = new MenuItem()
  238. {
  239. Header = "Import from V6",
  240. Icon = new Image() { Source = PRSDesktop.Resources.v6.AsBitmapImage() }
  241. };
  242. item.Click += ImportFromV6;
  243. menu.Items.Add(item);
  244. }
  245. }
  246. if (Security.IsAllowed<ImportLogikalProjects>())
  247. {
  248. _logikalSettings ??= new GlobalConfiguration<LogikalSettings>().Load();
  249. if (_logikalSettings.ImportProjects == LogikalProjectType.Project)
  250. {
  251. menu ??= new ContextMenu();
  252. var item = new MenuItem()
  253. {
  254. Header = "Import from Logikal",
  255. Icon = new Image() { Source = PRSDesktop.Resources.logikal.AsBitmapImage() }
  256. };
  257. item.Click += ImportFromLogikal;
  258. menu.Items.Add(item);
  259. }
  260. }
  261. if (menu != null)
  262. {
  263. menu.Items.Insert(0,new Separator());
  264. var item = new MenuItem()
  265. {
  266. Header = "New Project"
  267. };
  268. item.Click += (o, e) => base.DoAdd(openEditorOnDirectEdit);
  269. menu.Items.Insert(0,item);
  270. menu.IsOpen = true;
  271. }
  272. else
  273. base.DoAdd(openEditorOnDirectEdit);
  274. }
  275. private void ImportFromLogikal(object sender, RoutedEventArgs e)
  276. {
  277. LogikalClient.Instance.Initialize()
  278. .Error(error =>
  279. {
  280. MessageWindow.ShowMessage($"Unable to locate Logikal App!\n\n{error.Message}", "Error");
  281. })
  282. .Success<LogikalInitializeResponse>(initialize =>
  283. {
  284. LogikalClient.Instance.Connect(initialize.Path)
  285. .Error(error => MessageWindow.ShowMessage($"Unable to connect to Logikal!\n\n{initialize.Path}\n\n{error.Message}", "Error"))
  286. .Success<LogikalConnectResponse>(connect =>
  287. {
  288. LogikalClient.Instance.Login()
  289. .Error(error =>
  290. MessageWindow.ShowMessage($"Unable to log in to Logikal!\n\n{error.Message}", "Error"))
  291. .Success<LogikalLoginResponse>(login =>
  292. {
  293. var import = new LogikalProjectImport(FilterLogikalProjects, CreateLogikalProject);
  294. if (import.ShowDialog() == true)
  295. Refresh(false, true);
  296. });
  297. });
  298. });
  299. }
  300. private List<string>? _logikalSources;
  301. private bool FilterLogikalProjects(LogikalProject project)
  302. {
  303. _logikalSettings ??= new GlobalConfiguration<LogikalSettings>().Load();
  304. if (_logikalSettings.UseLogikalProjectNumber)
  305. {
  306. _logikalSources ??= Client.Query(
  307. null,
  308. Columns.None<Job>().Add(x => x.JobNumber)
  309. ).Rows
  310. .Select(r => r.Get<Job, string>(c => c.JobNumber))
  311. .ToList();
  312. return !string.IsNullOrWhiteSpace(project.JobNumber) && !_logikalSources.Contains($"{_logikalSettings.ProjectPrefix}{project.JobNumber}");
  313. }
  314. else
  315. {
  316. _logikalSources ??= Client.Query(
  317. new Filter<Job>(x => x.SourceRef).BeginsWith("Logikal:"),
  318. Columns.None<Job>().Add(x => x.SourceRef)
  319. ).Rows
  320. .Select(r => r.Get<Job, string>(c => c.SourceRef))
  321. .ToList();
  322. return !_logikalSources.Contains(project.GetReference());
  323. }
  324. }
  325. private void CreateLogikalProject(LogikalProject project)
  326. {
  327. _logikalSettings ??= new GlobalConfiguration<LogikalSettings>().Load();
  328. var _job = new Job();
  329. if (_logikalSettings.UseLogikalProjectNumber)
  330. _job.JobNumber = $"{_logikalSettings.ProjectPrefix}{project.JobNumber}";
  331. else
  332. _job.SourceRef = project.GetReference();
  333. _job.Name = project?.Title ?? "New Logikal Project";
  334. //_job.Customer.CopyFrom(_customer);
  335. //_job.Account.CopyFrom(_customer.Account);
  336. // _job.SiteAddress.Street = project.Street;
  337. // _job.SiteAddress.City = project.City;
  338. // _job.SiteAddress.State = project.State;
  339. // _job.SiteAddress.PostCode = project.PostCode;
  340. Client.Save(_job,"Imported From Logikal");
  341. if (_logikalSources != null)
  342. _logikalSources.Add(project.GetReference());
  343. // var _scope = Client.Query(
  344. // new Filter<JobScope>(x=>x.ID).IsEqualTo(_job.DefaultScope.ID),
  345. // Columns.Required<JobScope>()
  346. // ).Rows.FirstOrDefault()?.ToObject<JobScope>();
  347. // if (_scope != null)
  348. // {
  349. // _scope.ExTax = project.SellPrice;
  350. // Client.Save(_scope, "Imported From V6");
  351. // }
  352. }
  353. private void ImportFromV6(object sender, RoutedEventArgs e)
  354. {
  355. var _client = new V6Client();
  356. if (!_client.Connect())
  357. {
  358. MessageBox.Show("Unable to connect to V6!");
  359. return;
  360. }
  361. var import = new V6ProjectSelection(_client,FilterV6Projects,CreateV6Project);
  362. if (import.ShowDialog() == true)
  363. Refresh(false,true);
  364. }
  365. private List<string>? _v6Sources;
  366. private bool FilterV6Projects(V6Project project)
  367. {
  368. _v6Settings ??= new GlobalConfiguration<V6Settings>().Load();
  369. if (_v6Settings.UseV6QuoteNumber)
  370. {
  371. _v6Sources ??= Client.Query(
  372. null,
  373. Columns.None<Job>().Add(x => x.JobNumber)
  374. ).Rows
  375. .Select(r => r.Get<Job, string>(c => c.JobNumber))
  376. .ToList();
  377. return !_v6Sources.Contains($"{_v6Settings.ProjectPrefix}{project.Number}");
  378. }
  379. else
  380. {
  381. _v6Sources ??= Client.Query(
  382. new Filter<Job>(x => x.SourceRef).BeginsWith("V6:"),
  383. Columns.None<Job>().Add(x => x.SourceRef)
  384. ).Rows
  385. .Select(r => r.Get<Job, string>(c => c.SourceRef))
  386. .ToList();
  387. return !_v6Sources.Contains(project.GetReference());
  388. }
  389. }
  390. private void CreateV6Project(V6Project project)
  391. {
  392. _v6Settings ??= new GlobalConfiguration<V6Settings>().Load();
  393. var _job = new Job();
  394. var _customer = new Customer();
  395. if (!string.IsNullOrWhiteSpace(project.ClientID))
  396. {
  397. _customer = Client.Query(
  398. new Filter<Customer>(x => x.Code).IsEqualTo(project.ClientID),
  399. Columns.Required<Customer>()
  400. ).ToObjects<Customer>()
  401. .FirstOrDefault();
  402. if (_customer == null)
  403. {
  404. _customer = new Customer();
  405. _customer.Code = project.ClientID;
  406. _customer.Name = project.ClientName;
  407. _customer.Delivery.Street = project.Street;
  408. _customer.Delivery.City = project.City;
  409. _customer.Delivery.State = project.State;
  410. _customer.Delivery.PostCode = project.PostCode;
  411. Client.Save(_customer, "Imported From V6");
  412. }
  413. }
  414. if (_v6Settings.UseV6QuoteNumber)
  415. _job.JobNumber = $"{_v6Settings.ProjectPrefix}{project.Number}";
  416. else
  417. _job.SourceRef = project.GetReference();
  418. _job.Name = project.Title;
  419. _job.Customer.CopyFrom(_customer);
  420. _job.Account.CopyFrom(_customer.Account);
  421. _job.SiteAddress.Street = project.Street;
  422. _job.SiteAddress.City = project.City;
  423. _job.SiteAddress.State = project.State;
  424. _job.SiteAddress.PostCode = project.PostCode;
  425. Client.Save(_job,"Imported From V6");
  426. if (_v6Sources != null)
  427. _v6Sources.Add($"V6:{project.Number}");
  428. var _scope = Client.Query(
  429. new Filter<JobScope>(x=>x.ID).IsEqualTo(_job.DefaultScope.ID),
  430. Columns.Required<JobScope>()
  431. ).Rows.FirstOrDefault()?.ToObject<JobScope>();
  432. if (_scope != null)
  433. {
  434. _scope.ExTax = project.SellPrice;
  435. Client.Save(_scope, "Imported From V6");
  436. }
  437. }
  438. public override Job CreateItem()
  439. {
  440. var result = base.CreateItem();
  441. result.JobType = JobType.Project;
  442. return result;
  443. }
  444. protected override void CustomiseEditor(IDynamicEditorForm form, Job[] items, DynamicGridColumn column, BaseEditor editor)
  445. {
  446. base.CustomiseEditor(form, items, column, editor);
  447. if(new Column<Job>(x => x.Customer.ID).IsEqualTo(column.ColumnName) && editor is CodePopupEditor popup)
  448. {
  449. popup.CanAdd = Security.CanEdit<Customer>();
  450. }
  451. }
  452. protected override Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, Job[] items, string name, object value)
  453. {
  454. var result = base.EditorValueChanged(editor, items, name, value);
  455. if (name.Equals("Customer.ID"))
  456. {
  457. // false here because a customer has a defaultcontact
  458. // and we need to load the lookups before we set the default value
  459. var contact = editor.FindEditor("Contact.ID") as ILookupEditorControl;
  460. if (contact != null)
  461. DefineLookups(contact,items,false);
  462. }
  463. return result;
  464. }
  465. private void FilterComponent_OnFilterSelected(DynamicGridSelectedFilterSettings settings)
  466. {
  467. _settings.Filters = settings;
  468. new UserConfiguration<JobGridSettings>().Save(_settings);
  469. }
  470. }