MainPageUtils.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Xamarin.Forms;
  7. using InABox.Core;
  8. using InABox.Configuration;
  9. using InABox.Clients;
  10. using InABox.Mobile;
  11. using Comal.Classes;
  12. using XF.Material.Forms.UI.Dialogs;
  13. using comal.timesheets.CustomControls;
  14. using comal.timesheets.StoreRequis;
  15. using PRSSecurity = InABox.Core.Security;
  16. using Plugin.LocalNotification;
  17. using comal.timesheets.Tasks;
  18. using System.IO;
  19. using static comal.timesheets.CustomControls.JobShell;
  20. using static Android.Graphics.Paint;
  21. using static InABox.Mobile.LocationServices;
  22. namespace comal.timesheets
  23. {
  24. public delegate void MainPageNotificationsChanged();
  25. public delegate void RefreshScreen();
  26. public static class MainPageUtils
  27. {
  28. public static event MainPageNotificationsChanged OnMainPageNotificationsChanged;
  29. public static event RefreshScreen OnRefreshScreen;
  30. public static Assignment CurrentAssignment = null;
  31. public static JobShell Job = new JobShell();
  32. public static int NumberOfNotifications = 0;
  33. public static string matchedDeviceName = "";
  34. public static string deviceName = "";
  35. public static bool bRecentlyUpdatedTiles = false;
  36. public static TimeSheet _timesheet = null;
  37. public static Employee _employee = null;
  38. public static CoreTable _jobs = null;
  39. public static bool firstLoad = true;
  40. public static bool recentlyAskedToUpdate = true;
  41. public static int updateCounter;
  42. public static void Init()
  43. {
  44. InitEvents();
  45. InitData();
  46. InitTimers();
  47. }
  48. private static void InitEvents()
  49. {
  50. App.GPS.OnLocationFound += LocationFound;
  51. App.GPS.OnLocationError += LocationError;
  52. App.Bluetooth.OnScanFinished += ScanFinished;
  53. App.Data.DataChanged += (s, t, e) => { OnRefreshScreen?.Invoke(); };
  54. App.Data.DataRefreshed += () => { OnRefreshScreen?.Invoke(); };
  55. }
  56. private static void InitData()
  57. {
  58. GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();
  59. GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();
  60. App.Data.Employee.ID = GlobalVariables.EmpID;
  61. App.Data.Employee.Name = GlobalVariables.EmpName;
  62. _timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  63. _employee = App.Data.Employee;
  64. _jobs = App.Data.Jobs;
  65. deviceName = MobileUtils.GetDeviceID();
  66. firstLoad = false;
  67. }
  68. private static void InitTimers()
  69. {
  70. Timer t = new Timer(RecentlyAskedToUpdateTimer, null, 600000, 600000); //user is reminded to update when opening screen after timer of 10 minutes
  71. updateCounter = 1; //user is forced to update after 3rd reminder
  72. Timer t1 = new Timer(RecentlyUpdatedTilesTimer, null, 30000, 30000);
  73. //bluetooth data is allowed to upload once every minute, notifications refreshing is piggybacked to this too
  74. }
  75. private static void RecentlyAskedToUpdateTimer(object o)
  76. {
  77. recentlyAskedToUpdate = false;
  78. }
  79. private static void RecentlyUpdatedTilesTimer(object o)
  80. {
  81. bRecentlyUpdatedTiles = false;
  82. App.Data.Refresh(true);
  83. SearchForNewNotifications();
  84. }
  85. public static Assignment CheckCurrentAssignment()
  86. {
  87. Thread.Sleep(5000);
  88. StartAssignmentTimer();
  89. CoreTable table = new Client<Assignment>().Query(
  90. new Filter<Assignment>(x => x.EmployeeLink.ID).IsEqualTo(GlobalVariables.EmpID)
  91. .And(x => x.Date).IsEqualTo(DateTime.Today.Date)
  92. .And(x => x.Actual.Finish).IsEqualTo(null),
  93. null,
  94. new SortOrder<Assignment>(x => x.Actual.Start, SortDirection.Ascending));
  95. if (!table.Rows.Any())
  96. {
  97. Job.OnJobIDChanged += OnJobIDChanged;
  98. return null;
  99. }
  100. else
  101. return table.Rows.LastOrDefault().ToObject<Assignment>();
  102. }
  103. private static void StartAssignmentTimer()
  104. {
  105. Timer t = new Timer(AssignmentTimerCallback, null, 300000, 300000);
  106. }
  107. private static void AssignmentTimerCallback(object state)
  108. {
  109. if (CurrentAssignment != null)
  110. SaveCurrentAssignment("PRS Mobile main screen - Saving assignment on 5 minute timer");
  111. }
  112. public static void SaveCurrentAssignment(string auditnote, bool complete = false)
  113. {
  114. if (!complete)
  115. CurrentAssignment.Booked.Finish = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay;
  116. else
  117. CurrentAssignment.Actual.Finish = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay;
  118. new Client<Assignment>().Save(CurrentAssignment, auditnote);
  119. }
  120. static DateTime RoundToNearestInterval(DateTime dt, TimeSpan d)
  121. {
  122. int f = 0;
  123. double m = (double)(dt.Ticks % d.Ticks) / d.Ticks;
  124. if (m >= 0.5)
  125. f = 1;
  126. return new DateTime(((dt.Ticks / d.Ticks) + f) * d.Ticks);
  127. }
  128. public static void UseCurrentAssignment(Assignment assgn)
  129. {
  130. CurrentAssignment = assgn;
  131. SaveCurrentAssignment("PRS Mobile main screen - saving assignment on re-login to App");
  132. if (CurrentAssignment.JobLink.ID != Guid.Empty)
  133. {
  134. Job.ID = CurrentAssignment.JobLink.ID;
  135. var job = new Client<Job>().Query(new Filter<Job>(x => x.ID).IsEqualTo(Job.ID)).Rows.FirstOrDefault().ToObject<Job>();
  136. Job.JobNumber = job.JobNumber;
  137. Job.Name = job.Name;
  138. Job.OnJobIDChanged += OnJobIDChanged;
  139. }
  140. }
  141. public static void OnJobIDChanged(Guid jobid)
  142. {
  143. if (CurrentAssignment == null)
  144. CreateNewAssignment(jobid);
  145. else
  146. {
  147. SaveCurrentAssignment("PRS Mobile main screen - saving assignment on job change", true);
  148. CreateNewAssignment(jobid);
  149. }
  150. }
  151. private static void CreateNewAssignment(Guid jobid)
  152. {
  153. CurrentAssignment = new Assignment { Date = DateTime.Now.Date };
  154. CurrentAssignment.EmployeeLink.ID = GlobalVariables.EmpID;
  155. CurrentAssignment.JobLink.ID = jobid;
  156. CurrentAssignment.Actual.Start = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay;
  157. CurrentAssignment.Booked.Start = CurrentAssignment.Actual.Start;
  158. CurrentAssignment.Booked.Finish = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay.Add(new TimeSpan(0, 5, 0));
  159. var job = new Client<Job>().Query(new Filter<Job>(x => x.ID).IsEqualTo(jobid)).Rows.FirstOrDefault().ToObject<Job>();
  160. CurrentAssignment.Title = "Clocking on to job " + job.Name + " (" + job.JobNumber + ") on PRS Mobile";
  161. new Client<Assignment>().Save(CurrentAssignment, "Changed job on mobile - creating new assignment");
  162. }
  163. #region Notifications
  164. public static Page DetermineCorrectPage(Plugin.LocalNotification.EventArgs.NotificationActionEventArgs e)
  165. {
  166. string data = e.Request.ReturningData;
  167. int index = data.IndexOf("$");
  168. Guid ID = Guid.Parse(data.Remove(index));
  169. string type = data.Substring(index + 1);
  170. if (type == "Comal.Classes.Kanban")
  171. return new AddEditTask(ID);
  172. else if (type == "Comal.Classes.Delivery")
  173. return new DeliveryDetails(ID);
  174. else
  175. return null;
  176. }
  177. public static async void SearchForNewNotifications()
  178. {
  179. //notifications poll reliably in the background for Anroid, unreliable for iOS due to difficulty with cross-platform plugins for notifications
  180. try
  181. {
  182. await Task.Run(() =>
  183. {
  184. if (ClientFactory.UserGuid != Guid.Empty)
  185. {
  186. CoreTable table = new Client<Notification>().Query
  187. (new Filter<Notification>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid).And(X => X.Closed).IsEqualTo(DateTime.MinValue),
  188. new Columns<Notification>(
  189. x => x.ID, //0
  190. x => x.Sender.Name, //1
  191. x => x.Title, //2
  192. x => x.Created, //3
  193. x => x.Description, //4
  194. x => x.EntityType, //5
  195. x => x.EntityID //6
  196. )
  197. );
  198. if (NumberOfNotifications == table.Rows.Count()) //no new notifications or none present at all
  199. return;
  200. else //new notifications or previous notifications have now been dismissed
  201. {
  202. NumberOfNotifications = table.Rows.Count();
  203. OnMainPageNotificationsChanged?.Invoke();
  204. CheckNotificationsPushed(table);
  205. }
  206. }
  207. });
  208. }
  209. catch { }
  210. }
  211. private static void CheckNotificationsPushed(CoreTable table)
  212. {
  213. try
  214. {
  215. if (!Application.Current.Properties.ContainsKey("LastPushedNotifications"))
  216. {
  217. Application.Current.Properties.Add("LastPushedNotifications", DateTime.Now);
  218. }
  219. DateTime lastPushed = DateTime.Parse(Application.Current.Properties["LastPushedNotifications"].ToString());
  220. List<NotificationShell> toNotify = new List<NotificationShell>();
  221. foreach (CoreRow row in table.Rows)
  222. {
  223. List<object> list = row.Values;
  224. DateTime created = DateTime.Parse(list[3].ToString());
  225. if (created > new DateTime(2022, 8, 22)) // prevent spam from buildup of old notifications before this is released
  226. {
  227. if (created > lastPushed)
  228. {
  229. if (list[1] == null) list[1] = "";
  230. if (list[2] == null) list[2] = "";
  231. if (list[3] == null) list[3] = DateTime.MinValue;
  232. if (list[4] == null) list[4] = "";
  233. if (list[5] == null) list[5] = "";
  234. if (list[6] == null) list[6] = Guid.Empty;
  235. NotificationShell shell = new NotificationShell
  236. {
  237. ID = Guid.Parse(list[0].ToString()),
  238. Sender = list[1].ToString(),
  239. Title = list[2].ToString(),
  240. Created = DateTime.Parse(list[3].ToString()),
  241. EntityType = list[5].ToString(),
  242. EntityID = Guid.Parse(list[6].ToString())
  243. };
  244. toNotify.Add(shell); //add notification to be pushed
  245. }
  246. }
  247. }
  248. if (toNotify.Count > 0)
  249. PushNotificationsAsync(toNotify);
  250. }
  251. catch { }
  252. }
  253. private static async Task PushNotificationsAsync(List<NotificationShell> shells)
  254. {
  255. try
  256. {
  257. int count = 1;
  258. foreach (NotificationShell shell in shells)
  259. {
  260. var notification = new NotificationRequest
  261. {
  262. BadgeNumber = 1,
  263. Description = shell.Title,
  264. Title = "New PRS Notification: ",
  265. ReturningData = shell.EntityID.ToString() + "$" + shell.EntityType,
  266. NotificationId = count,
  267. };
  268. count++;
  269. NotificationImage img = new NotificationImage();
  270. img.ResourceName = "icon16.png";
  271. notification.Image = img;
  272. await LocalNotificationCenter.Current.Show(notification);
  273. }
  274. Application.Current.Properties["LastPushedNotifications"] = DateTime.Now;
  275. }
  276. catch { }
  277. }
  278. #endregion
  279. private static void LocationFound(LocationServices sender)
  280. {
  281. //if (bSharedDevice)
  282. // return;
  283. if (App.Bluetooth.RecentlyScanned)
  284. UploadTiles();
  285. try
  286. {
  287. TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  288. if (timesheet != null)
  289. {
  290. if (timesheet.StartLocation.Latitude.Equals(0.0F) && timesheet.StartLocation.Longitude.Equals(0.0F))
  291. {
  292. timesheet.StartLocation.Latitude = sender.Latitude;
  293. timesheet.StartLocation.Longitude = sender.Longitude;
  294. timesheet.StartLocation.Timestamp = sender.TimeStamp;
  295. timesheet.Address = sender.Address;
  296. new Client<TimeSheet>().Save(timesheet, "Updating Timesheet with GPS Coordinates", (o, e) => { });
  297. }
  298. }
  299. if (!string.IsNullOrWhiteSpace(matchedDeviceName))
  300. {
  301. InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };
  302. curlocation.Timestamp = DateTime.Now;
  303. GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
  304. gpsTrackerLocation.DeviceID = matchedDeviceName;
  305. gpsTrackerLocation.Location.Timestamp = curlocation.Timestamp;
  306. gpsTrackerLocation.Location = curlocation;
  307. new Client<GPSTrackerLocation>().Save(gpsTrackerLocation, "Updated company device location from Timebench");
  308. }
  309. OnRefreshScreen?.Invoke();
  310. }
  311. catch { }
  312. }
  313. private static async void UploadTiles()
  314. {
  315. try
  316. {
  317. if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))
  318. return;
  319. if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)
  320. return;
  321. if (bRecentlyUpdatedTiles)
  322. return;
  323. bRecentlyUpdatedTiles = true;
  324. await Task.Run(() =>
  325. {
  326. InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };
  327. curlocation.Timestamp = DateTime.Now;
  328. List<GPSTrackerLocation> trackersToUpdate = new List<GPSTrackerLocation>();
  329. foreach (String id in App.Bluetooth.DetectedBlueToothMACAddresses)
  330. {
  331. GPSTracker tracker = GlobalVariables.GPSTrackerCache.Find(x => x.DeviceID.Equals(id));
  332. bool stale = tracker.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0));
  333. bool moved = tracker.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;
  334. if (stale || moved)
  335. {
  336. GlobalVariables.GPSTrackerCache.Remove(tracker);
  337. tracker.Location = curlocation;
  338. GlobalVariables.GPSTrackerCache.Add(tracker);
  339. //cache is updated
  340. GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
  341. gpsTrackerLocation.DeviceID = tracker.DeviceID;
  342. gpsTrackerLocation.Location.Timestamp = tracker.Location.Timestamp;
  343. gpsTrackerLocation.Location = curlocation;
  344. trackersToUpdate.Add(gpsTrackerLocation);
  345. }
  346. }
  347. if (trackersToUpdate.Any())
  348. {
  349. if (ClientFactory.UserGuid != Guid.Empty)
  350. new Client<GPSTrackerLocation>().Save(trackersToUpdate, "Updating Bluetooth Device Locations");
  351. }
  352. App.Bluetooth.DetectedBlueToothMACAddresses.Clear();
  353. }
  354. );
  355. }
  356. catch (Exception e)
  357. {
  358. }
  359. //if ((master != null) && (master.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0))))
  360. //{
  361. // GPSTrackerLocation device = new GPSTrackerLocation();
  362. // device.DeviceID = MobileUtils.GetDeviceID();
  363. // device.Location.Latitude = App.GPS.Latitude;
  364. // device.Location.Longitude = App.GPS.Longitude;
  365. // device.Location.Timestamp = DateTime.Now;
  366. // locations.Add(device);
  367. // //device.BatteryLevel = ((double)CrossBattery.Current.RemainingChargePercent);
  368. // //new Client<GPSTrackerLocation>().Save(device, "Updating Device Location"); //, SaveTrackerCallback);
  369. //}
  370. #region OLD
  371. //for (int i = 0; i < App.Bluetooth.Devices.Length; i++)
  372. //{
  373. // String id = App.Bluetooth.Devices[i];
  374. // int level = App.Bluetooth.BatteryLevels[i];
  375. // var btmaster = trackers.FirstOrDefault(x => x.DeviceID.Equals(id));
  376. // if ((btmaster != null) && (!locations.Any(x => x.DeviceID.Equals(btmaster.DeviceID))))
  377. // {
  378. // bool stale = btmaster.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0));
  379. // bool moved = btmaster.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;
  380. // if (stale || moved)
  381. // {
  382. // GPSTrackerLocation location = new GPSTrackerLocation();
  383. // location.DeviceID = id;
  384. // location.Location.Latitude = App.GPS.Latitude;
  385. // location.Location.Longitude = App.GPS.Longitude;
  386. // location.Location.Timestamp = DateTime.Now;
  387. // location.BatteryLevel = level;
  388. // locations.Add(location);
  389. // }
  390. // }
  391. // //new Client<GPSTrackerLocation>().Save(location, "Found Kontakt Device"); //, SaveTrackerCallback);
  392. //}
  393. //if (locations.Any())
  394. // new Client<GPSTrackerLocation>().Save(locations, "Updating Bluetooth Device Locations", (o, e) => { });
  395. #endregion
  396. }
  397. private static void LocationError(LocationServices sebder, Exception error)
  398. {
  399. }
  400. private static void ScanFinished(Bluetooth sender)
  401. {
  402. try
  403. {
  404. OnRefreshScreen?.Invoke();
  405. if (App.GPS.RecentlyLocated)
  406. UploadTiles();
  407. }
  408. catch { }
  409. }
  410. }
  411. }