DataModel.cs 23 KB

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