DataModel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Comal.Classes;
  6. using InABox.Clients;
  7. using InABox.Core;
  8. using InABox.Mobile;
  9. using InABox.Rpc;
  10. namespace PRS.Mobile
  11. {
  12. public class GPSEventArgs : EventArgs
  13. {
  14. }
  15. public delegate void GPSLocationUpdatedEvent(GPSEventArgs args);
  16. public class BluetoothEventArgs : EventArgs
  17. {
  18. }
  19. public delegate void BluetoothScanFinishedEvent(BluetoothEventArgs args);
  20. public class DataModel : IModelHost
  21. {
  22. public event GPSLocationUpdatedEvent GPSLocationUpdated;
  23. public event BluetoothScanFinishedEvent BluetoothScanFinished;
  24. /// <summary>
  25. /// All Active Employees of the Company
  26. /// </summary>
  27. public EmployeeDetailModel CurrentEmployee { get; private set; }
  28. private readonly object _employeelock = new object();
  29. private EmployeeDetailShell _me;
  30. /// <summary>
  31. /// EmployeeDetails for Currently Logged in User
  32. /// </summary>
  33. public EmployeeDetailShell Me
  34. {
  35. get
  36. {
  37. lock (_employeelock)
  38. {
  39. if (_me == null)
  40. {
  41. CurrentEmployee.Refresh(false);
  42. _me = CurrentEmployee.FirstOrDefault(x => x.UserID == ClientFactory.UserGuid);
  43. }
  44. }
  45. return _me;
  46. }
  47. }
  48. /// <summary>
  49. /// All Active Employees of the Company
  50. /// </summary>
  51. public EmployeeModel Employees { get; private set; }
  52. /// <summary>
  53. /// All Employee Teams for the Company
  54. /// Should this be just teams I am a part of, or all available teams
  55. /// Need to implement a Security Token to differentiate
  56. /// </summary>
  57. public EmployeeTeamModel EmployeeTeams { get; private set; }
  58. /// <summary>
  59. /// Current Employee Form Instances for this employee
  60. /// </summary>
  61. public EmployeeFormModel EmployeeForms { get; private set; }
  62. public EmployeeQualificationModel EmployeeQualifications { get; private set; }
  63. /// <summary>
  64. /// Available Activity Codes for this Employee
  65. /// </summary>
  66. public ActivityModel Activities { get; private set; }
  67. /// <summary>
  68. /// All Available Contacts - used in Deliveries
  69. /// </summary>
  70. public ContactModel Contacts { get; private set; }
  71. /// <summary>
  72. /// All Defined Bluetooth-enabled Gates
  73. /// </summary>
  74. public BluetoothGateModel BluetoothGates { get; private set; }
  75. /// <summary>
  76. /// Unprocessed Timesheets for Currently Logged in User
  77. /// </summary>
  78. public TimeSheetModel TimeSheets { get; private set; }
  79. /// <summary>
  80. /// List of Jobs that Currently Logged in User has access To
  81. /// </summary>
  82. public JobModel Jobs { get; private set; }
  83. /// <summary>
  84. /// List of Assignments for ??? need to specify this.
  85. /// Can I see other people's assignments? (Security Token)
  86. /// How far back / forward can I look.
  87. /// This smells Transient, or maybe split into lookups (for all)
  88. /// and shells (for mine)
  89. /// Possibly need a back/forward window as well?
  90. /// </summary>
  91. public AssignmentModel Assignments { get; private set; }
  92. /// <summary>
  93. /// Master Product Catalogue for the company
  94. /// This should be split into Lookups and Shells
  95. /// </summary>
  96. public ProductModel Products { get; private set; }
  97. /// <summary>
  98. /// Master Product Groups List (Lookup?)
  99. /// </summary>
  100. public ProductGroupModel ProductGroups { get; private set; }
  101. /// <summary>
  102. /// All GPS Tracker Devices registered by the company
  103. /// </summary>
  104. public GPSTrackerModel GPSTrackers { get; private set; }
  105. /// <summary>
  106. /// Master Equipment Register
  107. /// </summary>
  108. public EquipmentModel Equipment { get; private set; }
  109. /// <summary>
  110. /// Master List of Equipment Groups
  111. /// </summary>
  112. public EquipmentGroupModel EquipmentGroups { get; private set; }
  113. /// <summary>
  114. /// Master List of Available Delivery Types
  115. /// </summary>
  116. public DeliveryTypeModel DeliveryTypes { get; private set; }
  117. /// <summary>
  118. /// List of all Deliveries
  119. /// hmmm.. should be configurable?
  120. /// </summary>
  121. public DeliveryModel Deliveries { get; private set; }
  122. /// <summary>
  123. /// List of all available Delivery Barcodes
  124. /// hmmm.. should be configurable?
  125. /// </summary>
  126. public DeliveryItemModel DeliveryItems { get; private set; }
  127. /// <summary>
  128. /// My Notifications (open only?)
  129. /// </summary>
  130. public NotificationModel Notifications { get; private set; }
  131. /// <summary>
  132. /// All Tasks I am subscribed to
  133. /// </summary>
  134. public KanbanModel Kanbans { get; private set; }
  135. /// <summary>
  136. /// All Kanban Types
  137. /// </summary>
  138. public KanbanTypeModel KanbanTypes { get; private set; }
  139. /// <summary>
  140. /// Available Form Library - this includes all "Applies To" values
  141. /// You can filter to a specific type by using the "Search" function
  142. /// </summary>
  143. public DigitalFormModel DigitalForms { get; private set; }
  144. // The list of open task-kased forms for the current user
  145. // Specifically for us in the "Forms" module
  146. // This overlaps the "Task" module a fair amount, but it provides
  147. // an alternative paradigm for tasks
  148. public KanbanFormModel KanbanForms { get; private set; }
  149. /// <summary>
  150. /// List of Employees, along with Clock on / off status
  151. /// </summary>
  152. public InOutModel InOut { get; private set; }
  153. /// <summary>
  154. /// List of Open Purchase Orders
  155. /// </summary>
  156. public PurchaseOrderModel PurchaseOrders { get; private set; }
  157. public ManufacturingFactoryModel ManufacturingFactories { get; private set; }
  158. public ManufacturingPacketModel ManufacturingPackets { get; private set; }
  159. public DataModel()
  160. {
  161. Reset();
  162. }
  163. public void Reset()
  164. {
  165. _me = null;
  166. CurrentEmployee = new EmployeeDetailModel(this,
  167. () => new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  168. );
  169. Employees = new EmployeeModel(this,
  170. LookupFactory.DefineFilter<Employee>);
  171. EmployeeTeams = new EmployeeTeamModel(this,
  172. () => new Filter<EmployeeTeam>(x => x.EmployeeLink.ID)
  173. .InQuery(LookupFactory.DefineFilter<Employee>(), x => x.ID)
  174. );
  175. EmployeeForms = new EmployeeFormModel(this,
  176. () => new Filter<EmployeeForm>(x => x.Parent.ID).IsEqualTo(App.Data.Me.ID)
  177. );
  178. EmployeeQualifications = new EmployeeQualificationModel(this,
  179. () => new Filter<EmployeeQualification>(x => x.Employee.ID).IsEqualTo(App.Data.Me.ID)
  180. );
  181. Activities = new ActivityModel(this,
  182. () => new Filter<EmployeeActivity>(x => x.Employee.ID).IsEqualTo(App.Data.Me.ID)
  183. );
  184. InOut = new InOutModel(this,
  185. () => new Filters<Employee>()
  186. .Add(LookupFactory.DefineFilter<Employee>())
  187. .Add(new Filter<Employee>(x=>x.ID).IsNotEqualTo(App.Data.Me.ID).And(x=>x.ShowOnInOutBoard).IsEqualTo(true))
  188. .Combine()
  189. );
  190. Jobs = new JobModel(this, MyJobsFilter) { FileName = "job.index" };
  191. Products = new ProductModel(this,
  192. LookupFactory.DefineFilter<Product>);
  193. ProductGroups = new ProductGroupModel(this,
  194. LookupFactory.DefineFilter<ProductGroup>);
  195. GPSTrackers = new GPSTrackerModel(this,
  196. LookupFactory.DefineFilter<GPSTracker>);
  197. Equipment = new EquipmentModel(this,
  198. () =>
  199. {
  200. var filters = new Filters<Equipment>();
  201. filters.Add(LookupFactory.DefineFilter<Equipment>());
  202. if (!Security.IsAllowed<CanViewPrivateEquipment>())
  203. filters.Add(new Filter<Equipment>(x => x.Private).IsEqualTo(false));
  204. return filters.Combine();
  205. }
  206. ) { FileName = "Equipment.index"};
  207. EquipmentGroups = new EquipmentGroupModel(this,
  208. LookupFactory.DefineFilter<EquipmentGroup>);
  209. DeliveryTypes= new DeliveryTypeModel(this, () => null) { FileName = "deliverytypes.index"};
  210. Deliveries = new DeliveryModel(this, () => null);
  211. DeliveryItems = new DeliveryItemModel(this,
  212. LookupFactory.DefineFilter<DeliveryItem>
  213. );
  214. Notifications = new NotificationModel(this,
  215. () => new Filter<Notification>(x=>x.Employee.ID).IsEqualTo(App.Data.Me.ID)
  216. .And(new Filter<Notification>(x=>x.Closed).IsEqualTo(DateTime.MinValue)
  217. .Or(x=>x.Created).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-90)))
  218. );
  219. TimeSheets = new TimeSheetModel(this,
  220. () => new Filter<TimeSheet>(x=>x.Processed).IsEqualTo(DateTime.MinValue)
  221. .And(x=>x.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID));
  222. Assignments = new AssignmentModel(this,
  223. () => new Filter<Assignment>(x => x.Date).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-90))
  224. .And(x => x.Date).IsLessThanOrEqualTo(DateTime.Today.AddDays(90))
  225. );
  226. Contacts = new ContactModel(this,
  227. () => LookupFactory.DefineFilter<Contact>());
  228. Kanbans = new KanbanModel(this,
  229. () => new Filter<Kanban>(x => x.ID)
  230. .InQuery(new Filter<KanbanSubscriber>(x=>x.Employee.ID).IsEqualTo(App.Data.Me.ID), x=>x.Kanban.ID)
  231. .And(
  232. new Filter<Kanban>(x=>x.Category).IsNotEqualTo(Kanban.COMPLETE)
  233. .Or(x=>x.Completed).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-7)
  234. )
  235. )
  236. ) { FileName = "kanbans.index" };
  237. KanbanTypes = new KanbanTypeModel(this, () => null);
  238. BluetoothGates = new BluetoothGateModel(this,
  239. () => new Filter<JobTracker>(x => x.Active).IsEqualTo(true)
  240. );
  241. DigitalForms = new DigitalFormModel(this,
  242. () => new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.Data.Me.ID)
  243. .And(x => x.Form.Active).IsEqualTo(true)
  244. );
  245. KanbanForms = new KanbanFormModel(this,
  246. () => new Filter<KanbanForm>(x=>x.Parent.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID)
  247. .And(new Filter<KanbanForm>(x=>x.FormCompleted).IsEqualTo(DateTime.MinValue)
  248. .Or(x=>x.FormCompleted).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-7))
  249. )
  250. );
  251. PurchaseOrders = new PurchaseOrderModel(this,
  252. () => new Filter<PurchaseOrder>(x => x.ClosedDate).IsEqualTo(DateTime.MinValue)
  253. );
  254. ManufacturingPackets = new ManufacturingPacketModel(this,
  255. () => new Filter<ManufacturingPacket>(x => x.Archived).IsEqualTo(DateTime.MinValue)
  256. );
  257. ManufacturingFactories = new ManufacturingFactoryModel(this,
  258. () => null
  259. );
  260. }
  261. private static Filter<Job> MyJobsFilter()
  262. {
  263. return Security.IsAllowed<CanViewAllJobs>()
  264. ? new Filter<Job>(X => X.Completed).IsEqualTo(DateTime.MinValue)
  265. .And(x => x.JobStatus.Active).IsEqualTo(true)
  266. : new Filter<Job>(X => X.Completed).IsEqualTo(DateTime.MinValue)
  267. .And(x => x.JobStatus.Active).IsEqualTo(true)
  268. .And(x => x.ID).InQuery(
  269. new Filter<JobEmployee>(x => x.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID),
  270. x => x.JobLink.ID
  271. );
  272. }
  273. public void Setup()
  274. {
  275. // Clear All Transient Caches
  276. Reset();
  277. // Always load the current Employee and Security Tokens
  278. Task[] init = new Task[]
  279. {
  280. Task.Run(() => { CurrentEmployee.Refresh(true); }),
  281. Task.Run(() => { Security.CheckTokens(); })
  282. };
  283. Task.WaitAll(init);
  284. App.Bluetooth.OnScanFinished += OnBluetoothScanFinished;
  285. App.GPS.OnLocationFound += OnGPSLocationFound;
  286. App.Transport.OnOpen += OnTransportConnected;
  287. App.Transport.OnClose += OnTransportDisconnected;
  288. DigitalFormDocumentFactory.Init(
  289. new MobileDigitalFormDocumentHandler(
  290. b =>
  291. {
  292. IsBackgroundUpdateStatusActive = b;
  293. BackgroundUpdateStatusChanged?.Invoke(this, EventArgs.Empty);
  294. })
  295. );
  296. DigitalFormDocumentFactory.Run();
  297. }
  298. public bool IsBackgroundUpdateStatusActive { get; private set; }
  299. public event BackgroundUpdateStatusEvent BackgroundUpdateStatusChanged;
  300. public bool IsConnected() => App.Transport?.IsConnected() == true;
  301. public event TransportDisconnectedEvent TransportDisconnected;
  302. public event TransportConnectedEvent TransportConnected;
  303. private void OnTransportDisconnected(IRpcTransport transport, RpcTransportCloseArgs e)
  304. {
  305. DigitalFormDocumentFactory.Stop();
  306. TransportDisconnected?.Invoke(new TransportDisconnectedEventArgs());
  307. Task.Run(() =>
  308. {
  309. while (!IsConnected())
  310. App.Transport.Connect();
  311. ClientFactory.Validate(ClientFactory.SessionID);
  312. DigitalFormDocumentFactory.Run();
  313. });
  314. }
  315. private void OnTransportConnected(IRpcTransport transport, RpcTransportOpenArgs e)
  316. {
  317. TransportConnected?.Invoke(new TransportConnectedEventArgs());
  318. }
  319. private Location _lastgpslocation = new Location();
  320. private GPSTrackerLocation GetGPSTrackerUpdate(string deviceid, Location location,
  321. TimeSpan threshold, double distance)
  322. {
  323. GPSTrackerShell tracker = GPSTrackers.FirstOrDefault(x => x.DeviceID.Equals(deviceid));
  324. if (tracker != null)
  325. {
  326. if ((tracker.Timestamp < location.Timestamp.Subtract(threshold)) || (tracker.Location.DistanceTo(location, UnitOfLength.Kilometers) > distance))
  327. {
  328. GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
  329. gpsTrackerLocation.DeviceID = tracker.DeviceID;
  330. gpsTrackerLocation.Tracker.ID = tracker.ID;
  331. gpsTrackerLocation.Location = location;
  332. return gpsTrackerLocation;
  333. }
  334. }
  335. return null;
  336. }
  337. private void OnGPSLocationFound(LocationServices sender)
  338. {
  339. if (_lastgpslocation.Timestamp < DateTime.Now.Subtract(TimeSpan.FromMinutes(2)))
  340. {
  341. var devicelocation = new InABox.Core.Location()
  342. {
  343. Latitude = App.GPS.Latitude,
  344. Longitude = App.GPS.Longitude,
  345. Timestamp = App.GPS.TimeStamp,
  346. Address = App.GPS.Address
  347. };
  348. GPSTrackers.Refresh(false);
  349. var update = GetGPSTrackerUpdate(MobileUtils.GetDeviceID(), devicelocation, TimeSpan.FromMinutes(2),
  350. 0.1);
  351. if (update != null)
  352. new Client<GPSTrackerLocation>().Save(update, "Updated via Mobile Device", (o, e) => { });
  353. }
  354. GPSLocationUpdated?.Invoke(new GPSEventArgs());
  355. }
  356. private void OnBluetoothScanFinished(Bluetooth sender)
  357. {
  358. UploadTiles();
  359. BluetoothScanFinished?.Invoke(new BluetoothEventArgs());
  360. }
  361. private void UploadTiles()
  362. {
  363. try
  364. {
  365. if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))
  366. return;
  367. if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)
  368. return;
  369. var devicelocation = new InABox.Core.Location()
  370. {
  371. Latitude = App.GPS.Latitude,
  372. Longitude = App.GPS.Longitude,
  373. Timestamp = App.GPS.TimeStamp,
  374. Address = App.GPS.Address
  375. };
  376. GPSTrackers.Refresh(true);
  377. List<GPSTrackerLocation> updates = new List<GPSTrackerLocation>();
  378. foreach (String deviceid in App.Bluetooth.DetectedBlueToothMACAddresses)
  379. {
  380. var update = GetGPSTrackerUpdate(deviceid, devicelocation, TimeSpan.FromMinutes(2), 0.1);
  381. if (update != null)
  382. updates.Add(update);
  383. }
  384. if (updates.Any())
  385. new Client<GPSTrackerLocation>().Save(updates, $"Updated by Mobile {MobileUtils.GetDeviceID()}",
  386. (o, e) => { });
  387. }
  388. catch (Exception ex)
  389. {
  390. MobileLogging.Log($"UploadTiles() {ex.Message} \n {ex.StackTrace}");
  391. }
  392. }
  393. }
  394. }