DataModel.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 TransportConnectedEventArgs : EventArgs
  21. {
  22. }
  23. public delegate void TransportConnectedEvent(TransportConnectedEventArgs args);
  24. public class TransportDisconnectedEventArgs : EventArgs
  25. {
  26. }
  27. public delegate void TransportDisconnectedEvent(TransportDisconnectedEventArgs args);
  28. public class DataModel : IModelHost
  29. {
  30. public event GPSLocationUpdatedEvent GPSLocationUpdated;
  31. public event BluetoothScanFinishedEvent BluetoothScanFinished;
  32. /// <summary>
  33. /// All Active Employees of the Company
  34. /// </summary>
  35. public EmployeeModel Employees { get; private set; }
  36. /// <summary>
  37. /// EmployeeDetails for Currently Logged in User
  38. /// </summary>
  39. public EmployeeDetailModel Me { get; private set; }
  40. /// <summary>
  41. /// All Employee Teams for the Company
  42. /// Should this be just teams I am a part of, or all available teams
  43. /// Need to implement a Security Token to differentiate
  44. /// </summary>
  45. public EmployeeTeamModel EmployeeTeams { get; private set; }
  46. /// <summary>
  47. /// All Available Contacts - used in Deliveries
  48. /// </summary>
  49. public ContactModel Contacts { get; private set; }
  50. /// <summary>
  51. /// All Defined Bluetooth-enabled Gates
  52. /// </summary>
  53. public BluetoothGateModel BluetoothGates { get; private set; }
  54. /// <summary>
  55. /// Unprocessed Timesheets for Currently Logged in User
  56. /// </summary>
  57. public TimeSheetModel TimeSheets { get; private set; }
  58. /// <summary>
  59. /// List of All active Jobs
  60. /// </summary>
  61. public JobLookupModel JobLookups { get; private set; }
  62. /// <summary>
  63. /// List of Jobs that Currently Logged in User has access To
  64. /// </summary>
  65. public JobModel Jobs { get; private set; }
  66. /// <summary>
  67. /// List of Assignments for ??? need to specify this.
  68. /// Can I see other people's assignments? (Security Token)
  69. /// How far back / forward can I look.
  70. /// This smells Transient, or maybe split into lookups (for all)
  71. /// and shells (for mine)
  72. /// Possibly need a back/forward window as well?
  73. /// </summary>
  74. public AssignmentModel Assignments { get; private set; }
  75. /// <summary>
  76. /// Master Product Catalogue for the company
  77. /// This should be split into Lookups and Shells
  78. /// </summary>
  79. public ProductModel Products { get; private set; }
  80. /// <summary>
  81. /// Master Product Groups List (Lookup?)
  82. /// </summary>
  83. public ProductGroupLookupModel ProductGroupsLookup { get; private set; }
  84. /// <summary>
  85. /// All GPS Tracker Devices registered by the company
  86. /// </summary>
  87. public GPSTrackerModel GPSTrackers { get; private set; }
  88. /// <summary>
  89. /// Master Equipment Register
  90. /// </summary>
  91. public EquipmentModel Equipment { get; private set; }
  92. /// <summary>
  93. /// Master List of Equipment Groups
  94. /// </summary>
  95. public EquipmentGroupModel EquipmentGroups { get; private set; }
  96. /// <summary>
  97. /// List of all Deliveries made in the last 90 days
  98. /// hmmm.. should be configurable?
  99. /// </summary>
  100. public DeliveryModel Deliveries { get; private set; }
  101. /// <summary>
  102. /// My Notifications (open only?)
  103. /// </summary>
  104. public NotificationModel Notifications { get; private set; }
  105. /// <summary>
  106. /// All Open Kanbans
  107. /// </summary>
  108. public KanbanLookupModel KanbanLookups { get; private set; }
  109. /// <summary>
  110. /// All Tasks I am subscribed to
  111. /// </summary>
  112. public KanbanModel Kanbans { get; private set; }
  113. /// <summary>
  114. /// All Kanban Types
  115. /// </summary>
  116. public KanbanTypeModel KanbanTypes { get; private set; }
  117. /// <summary>
  118. /// Available Form Library - this includes all "Applies To" values
  119. /// You can filter to a specific type by using the "Search" function
  120. /// </summary>
  121. public DigitalFormModel DigitalForms { get; private set; }
  122. // The list of open task-kased forms for the current user
  123. // Specifically for us in the "Forms" module
  124. // This overlaps the "Task" module a fair amount, but it provides
  125. // an alternative paradigm for tasks
  126. public KanbanFormModel KanbanForms { get; private set; }
  127. /// <summary>
  128. /// List of Employees, along with Clock on / off status
  129. /// </summary>
  130. public InOutModel InOut { get; private set; }
  131. /// <summary>
  132. /// List of all available Document Set Tags
  133. /// </summary>
  134. public JobDocumentSetTagModel DocumentSetTags { get; private set; }
  135. /// <summary>
  136. /// List of available Delivery Barcodes
  137. /// </summary>
  138. public DeliveryItemLookupModel DeliveryItems { get; private set; }
  139. public DataModel()
  140. {
  141. Me = new EmployeeDetailModel(this,
  142. () => new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  143. );
  144. Employees = new EmployeeModel(this,
  145. () => LookupFactory.DefineFilter<Employee>());
  146. EmployeeTeams = new EmployeeTeamModel(this,
  147. () => new Filter<EmployeeTeam>(x => x.EmployeeLink.ID)
  148. .InQuery(LookupFactory.DefineFilter<Employee>(), x => x.ID)
  149. );
  150. InOut = new InOutModel(this,
  151. () => LookupFactory.DefineFilter<Employee>()
  152. .And(x=>x.ID).IsNotEqualTo(App.Data.Me.ID));
  153. Jobs = new JobModel(this, MyJobsFilter);
  154. JobLookups = new JobLookupModel(this,
  155. () => LookupFactory.DefineFilter<Job>());
  156. Products = new ProductModel(this,
  157. () => LookupFactory.DefineFilter<Product>());
  158. ProductGroupsLookup = new ProductGroupLookupModel(this,
  159. () => LookupFactory.DefineFilter<ProductGroup>());
  160. GPSTrackers = new GPSTrackerModel(this,
  161. () => LookupFactory.DefineFilter<GPSTracker>());
  162. Equipment = new EquipmentModel(this,
  163. () =>
  164. {
  165. var filter = LookupFactory.DefineFilter<Equipment>();
  166. var privfilter = new Filter<Equipment>(x => x.Private).IsEqualTo(false);
  167. if (InABox.Core.Security.IsAllowed<CanViewPrivateEquipment>())
  168. return filter;
  169. return filter != null
  170. ? filter.And(privfilter)
  171. : privfilter;
  172. },
  173. "equipment.index");
  174. EquipmentGroups = new EquipmentGroupModel(this,
  175. () => LookupFactory.DefineFilter<EquipmentGroup>());
  176. Deliveries = new DeliveryModel(this,
  177. () => new Filter<Delivery>(x => x.Completed).IsEqualTo(DateTime.MinValue)
  178. .Or(x => x.Completed).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-90))
  179. );
  180. DeliveryItems = new DeliveryItemLookupModel(this,
  181. () => LookupFactory.DefineFilter<DeliveryItem>()
  182. );
  183. Notifications = new NotificationModel(this,
  184. () => new Filter<Notification>(x=>x.Closed).IsEqualTo(DateTime.MinValue)
  185. .And(x=>x.Employee.ID).IsEqualTo(App.Data.Me.ID)
  186. );
  187. TimeSheets = new TimeSheetModel(this,
  188. () => new Filter<TimeSheet>(x=>x.Processed).IsEqualTo(DateTime.MinValue)
  189. .And(x=>x.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID));
  190. Assignments = new AssignmentModel(this,
  191. () => new Filter<Assignment>(x => x.Date).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-90))
  192. .And(x => x.Date).IsLessThanOrEqualTo(DateTime.Today.AddDays(90))
  193. );
  194. Contacts = new ContactModel(this,
  195. () => LookupFactory.DefineFilter<Contact>());
  196. Kanbans = new KanbanModel(this,
  197. () => new Filter<Kanban>(x => x.ID).InQuery(
  198. new Filter<KanbanSubscriber>(x=>x.Employee.ID).IsEqualTo(App.Data.Me.ID), x=>x.Kanban.ID)
  199. );
  200. KanbanLookups = new KanbanLookupModel(this,
  201. () => new Filter<Kanban>(x => x.Completed).IsEqualTo(DateTime.MinValue));
  202. KanbanTypes = new KanbanTypeModel(this, () => null);
  203. BluetoothGates = new BluetoothGateModel(this,
  204. () => new Filter<JobTracker>(x => x.Active).IsEqualTo(true)
  205. );
  206. DigitalForms = new DigitalFormModel(this,
  207. () => new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.Data.Me.ID)
  208. .And(x => x.Form.Active).IsEqualTo(true)
  209. .And(x => x.Form.Secure).IsEqualTo(false)
  210. );
  211. KanbanForms = new KanbanFormModel(this,
  212. () => new Filter<KanbanForm>(x=>x.Parent.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID)
  213. .And(x=>x.FormCompleted).IsEqualTo(DateTime.MinValue)
  214. );
  215. DocumentSetTags = new JobDocumentSetTagModel(this,
  216. () => null
  217. );
  218. }
  219. private static Filter<Job> MyJobsFilter()
  220. {
  221. return InABox.Core.Security.IsAllowed<CanViewAllJobs>()
  222. ? new Filter<Job>(X => X.Completed).IsEqualTo(DateTime.MinValue)
  223. .And(x => x.JobStatus.Active).IsEqualTo(true)
  224. : new Filter<Job>(X => X.Completed).IsEqualTo(DateTime.MinValue)
  225. .And(x => x.JobStatus.Active).IsEqualTo(true)
  226. .And(x => x.ID).InQuery(
  227. new Filter<JobEmployee>(x => x.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID),
  228. x => x.JobLink.ID
  229. );
  230. }
  231. public void Setup()
  232. {
  233. _connected = true;
  234. InABox.Core.Security.CheckTokens();
  235. Me.Refresh(true);
  236. Task[] _setuptasks = new Task[]
  237. {
  238. Task.Run(() => Employees.Refresh(true)),
  239. Task.Run(() => TimeSheets.Refresh(true)),
  240. Task.Run(() => GPSTrackers.Refresh(true)),
  241. Task.Run(() => BluetoothGates.Refresh(true)),
  242. Task.Run(() => Notifications.Refresh(true)),
  243. Task.Run(() => Kanbans.Refresh(true))
  244. };
  245. Task.WaitAll(_setuptasks);
  246. App.Bluetooth.OnScanFinished += OnBluetoothScanFinished;
  247. App.GPS.OnLocationFound += OnGPSLocationFound;
  248. App.Transport.OnOpen += OnTransportConnected;
  249. App.Transport.OnClose += OnTransportDisconnected;
  250. }
  251. public bool IsConnected() => _connected;
  252. private bool _connected;
  253. public event TransportDisconnectedEvent TransportDisconnected;
  254. public event TransportConnectedEvent TransportConnected;
  255. private void OnTransportDisconnected(IRpcTransport transport, RpcTransportCloseArgs e)
  256. {
  257. _connected = false;
  258. TransportDisconnected?.Invoke(new TransportDisconnectedEventArgs());
  259. Task.Run(() =>
  260. {
  261. while (!_connected)
  262. App.Transport.Connect();
  263. var status = ClientFactory.Validate(ClientFactory.SessionID);
  264. });
  265. }
  266. private void OnTransportConnected(IRpcTransport transport, RpcTransportOpenArgs e)
  267. {
  268. _connected = true;
  269. TransportConnected?.Invoke(new TransportConnectedEventArgs());
  270. }
  271. private GPSTrackerLocation GetGPSTrackerUpdate(string deviceid, InABox.Core.Location location,
  272. TimeSpan threshold, double distance)
  273. {
  274. GPSTrackerShell tracker = GPSTrackers.FirstOrDefault(x => x.DeviceID.Equals(deviceid));
  275. if (tracker != null)
  276. {
  277. if ((tracker.Timestamp < location.Timestamp.Subtract(threshold)) || (tracker.Location.DistanceTo(location, UnitOfLength.Kilometers) > distance))
  278. {
  279. GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
  280. gpsTrackerLocation.DeviceID = tracker.DeviceID;
  281. gpsTrackerLocation.Tracker.ID = tracker.ID;
  282. gpsTrackerLocation.Location = location;
  283. return gpsTrackerLocation;
  284. }
  285. }
  286. return null;
  287. }
  288. private InABox.Core.Location _lastgpslocation = new InABox.Core.Location();
  289. private void OnGPSLocationFound(LocationServices sender)
  290. {
  291. if (_lastgpslocation.Timestamp < DateTime.Now.Subtract(TimeSpan.FromMinutes(2)))
  292. {
  293. var devicelocation = new InABox.Core.Location()
  294. {
  295. Latitude = App.GPS.Latitude,
  296. Longitude = App.GPS.Longitude,
  297. Timestamp = App.GPS.TimeStamp,
  298. Address = App.GPS.Address
  299. };
  300. GPSTrackers.Refresh(false);
  301. var update = GetGPSTrackerUpdate(MobileUtils.GetDeviceID(), devicelocation, TimeSpan.FromMinutes(2), 0.1);
  302. if (update != null)
  303. new Client<GPSTrackerLocation>().Save(update, "Updated via Mobile Device", (o, e) => { });
  304. }
  305. GPSLocationUpdated?.Invoke(new GPSEventArgs());
  306. }
  307. private void OnBluetoothScanFinished(Bluetooth sender)
  308. {
  309. UploadTiles();
  310. BluetoothScanFinished?.Invoke(new BluetoothEventArgs());
  311. }
  312. private void UploadTiles()
  313. {
  314. try
  315. {
  316. if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))
  317. return;
  318. if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)
  319. return;
  320. var devicelocation = new InABox.Core.Location()
  321. {
  322. Latitude = App.GPS.Latitude,
  323. Longitude = App.GPS.Longitude,
  324. Timestamp = App.GPS.TimeStamp,
  325. Address = App.GPS.Address
  326. };
  327. GPSTrackers.Refresh(true);
  328. List<GPSTrackerLocation> updates = new List<GPSTrackerLocation>();
  329. foreach (String deviceid in App.Bluetooth.DetectedBlueToothMACAddresses)
  330. {
  331. var update = GetGPSTrackerUpdate(deviceid, devicelocation, TimeSpan.FromMinutes(2), 0.1);
  332. if (update != null)
  333. updates.Add(update);
  334. }
  335. if (updates.Any())
  336. new Client<GPSTrackerLocation>().Save(updates, $"Updated by Mobile {MobileUtils.GetDeviceID()}",
  337. (o, e) => { });
  338. }
  339. catch (Exception ex)
  340. {
  341. MobileLogging.Log($"UploadTiles() {ex.Message} \n {ex.StackTrace}");
  342. }
  343. }
  344. public int EmployeeFormsToDo { get; set; }
  345. public int QualificationsNeedingAttention { get; set; }
  346. public bool UpdateHRItemsNeedingAttention()
  347. {
  348. try
  349. {
  350. EmployeeFormsToDo = 0;
  351. QualificationsNeedingAttention = 0;
  352. CoreTable table = new Client<EmployeeQualification>().Query(
  353. new Filter<EmployeeQualification>(x => x.Employee.ID).IsEqualTo(Me.ID),
  354. new Columns<EmployeeQualification>(
  355. x => x.ID, //0
  356. x => x.Expiry, //1
  357. x => x.FrontPhoto.ID //2
  358. )
  359. );
  360. if (table.Rows.Any())
  361. {
  362. List<Guid> IDs = new List<Guid>();
  363. foreach (CoreRow row in table.Rows)
  364. {
  365. List<object> list = row.Values;
  366. if (list[0] == null) { list[0] = Guid.Empty; } //0
  367. if (list[1] == null) { list[1] = DateTime.MinValue; } //1
  368. if (list[2] == null) { list[2] = Guid.Empty; } //2
  369. if (DateTime.Parse(list[1].ToString()) <= DateTime.Today.AddDays(30))
  370. {
  371. if (!Guid.Parse(list[2].ToString()).Equals(Guid.Empty))
  372. {
  373. CoreTable innerTable = new Client<Document>().Query(
  374. new Filter<Document>(x => x.ID).IsEqualTo(Guid.Parse(list[2].ToString())),
  375. new Columns<Document>(x => x.Created)
  376. );
  377. CoreRow innerRow = innerTable.Rows.First();
  378. List<object> innerList = innerRow.Values;
  379. if (DateTime.Parse(innerList[0].ToString()) < DateTime.Today.AddDays(-7)) //if photo was added more than 7 days ago, added to list needing attention
  380. {
  381. if (!IDs.Contains(Guid.Parse(list[0].ToString())))
  382. IDs.Add(Guid.Parse(list[0].ToString()));
  383. }
  384. }
  385. else
  386. {
  387. if (!IDs.Contains(Guid.Parse(list[0].ToString())))
  388. IDs.Add(Guid.Parse(list[0].ToString()));
  389. }
  390. }
  391. if (Guid.Parse(list[2].ToString()).Equals(Guid.Empty))
  392. {
  393. if (!IDs.Contains(Guid.Parse(list[0].ToString())))
  394. IDs.Add(Guid.Parse(list[0].ToString()));
  395. }
  396. }
  397. QualificationsNeedingAttention = IDs.Count;
  398. }
  399. CoreTable table1 = new Client<EmployeeForm>().Query(
  400. new Filter<EmployeeForm>(x => x.Parent.ID).IsEqualTo(Me.ID).And
  401. (x => x.FormCompleted).IsEqualTo(DateTime.MinValue),
  402. new Columns<EmployeeForm>(x => x.FormCompleted)
  403. );
  404. if (table1.Rows.Any())
  405. {
  406. EmployeeFormsToDo = table1.Rows.Count;
  407. }
  408. if (QualificationsNeedingAttention > 0 || EmployeeFormsToDo > 0)
  409. {
  410. return true;
  411. }
  412. else
  413. return false;
  414. }
  415. catch
  416. {
  417. return false;
  418. }
  419. }
  420. public void CheckEmployeeFormsToDo()
  421. {
  422. try
  423. {
  424. CoreTable table1 = new Client<EmployeeForm>().Query(
  425. new Filter<EmployeeForm>(x => x.Parent.ID).IsEqualTo(Me.ID).And
  426. (x => x.FormCompleted).IsEqualTo(DateTime.MinValue),
  427. new Columns<EmployeeForm>(x => x.FormCompleted)
  428. );
  429. if (table1.Rows.Any())
  430. {
  431. EmployeeFormsToDo = table1.Rows.Count;
  432. }
  433. else
  434. {
  435. EmployeeFormsToDo = 0;
  436. }
  437. }
  438. catch
  439. {
  440. }
  441. }
  442. }
  443. }