JobStore.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using Comal.Classes;
  2. using InABox.Core;
  3. namespace Comal.Stores
  4. {
  5. public class JobStore : ScheduleActionStore<Job>
  6. {
  7. protected override void BeforeSave(Job entity)
  8. {
  9. base.BeforeSave(entity);
  10. if (entity.ID == Guid.Empty)
  11. {
  12. var defstatus = Provider.Query(
  13. new Filter<JobStatus>(x => x.Default).IsEqualTo(true),
  14. Columns.None<JobStatus>().Add(x => x.ID)
  15. ).Rows.FirstOrDefault()?.ToObject<JobStatus>();
  16. if (defstatus != null)
  17. entity.JobStatus.CopyFrom(defstatus);
  18. }
  19. if (!entity.Account.IsValid() && entity.Customer.IsValid())
  20. {
  21. Customer final = null;
  22. var customer = Provider.Load(new Filter<Customer>(x => x.ID).IsEqualTo(entity.Customer.ID)).FirstOrDefault();
  23. if (customer != null)
  24. {
  25. final = customer;
  26. if (customer.Account.IsValid())
  27. {
  28. var account = Provider.Load(new Filter<Customer>(x => x.ID).IsEqualTo(customer.Account.ID)).FirstOrDefault();
  29. if (account != null)
  30. final = account;
  31. }
  32. }
  33. entity.Account.Synchronise(final ?? new Customer());
  34. }
  35. StoreUtils.Geocode(entity.SiteAddress);
  36. }
  37. protected override void AfterSave(Job entity)
  38. {
  39. base.AfterSave(entity);
  40. if(entity.HasOriginalValue(x => x.ID))
  41. CreateDefaultScope(entity);
  42. }
  43. private void CreateDefaultScope(Job job)
  44. {
  45. var scope = new JobScope
  46. {
  47. Description = "Default Scope",
  48. Type = JobScopeType.Contract
  49. };
  50. scope.Job.ID = job.ID;
  51. FindSubStore<JobScope>().Save(scope, "Created automatically on job creation.");
  52. // Save the job again, with a default scope set. We create a lighter job so we're not saving all the same properties over again.
  53. var lightJob = new Job().SetID(job.ID);
  54. lightJob.DefaultScope.ID = scope.ID;
  55. Provider.Save(lightJob);
  56. // Update default scope for sending the entity back to the client.
  57. job.DefaultScope.ID = scope.ID;
  58. }
  59. protected override void AfterDelete(Job entity)
  60. {
  61. base.AfterDelete(entity);
  62. var setoutstore = FindSubStore<Setout>();
  63. var setouts = setoutstore.Query(
  64. new Filter<Setout>(x => x.JobLink.ID).IsEqualTo(entity.ID),
  65. null).ToObjects<Setout>();
  66. setoutstore.Delete(setouts, "Cascaded Delete from Job");
  67. }
  68. }
  69. }