MainPage.xaml.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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. namespace comal.timesheets
  20. {
  21. public partial class MainPage : ContentPage
  22. {
  23. #region Fields
  24. List<ToolEntry> toolEntries = new List<ToolEntry>();
  25. private TimeSheet _timesheet = null;
  26. private Employee _employee = null;
  27. private CoreTable _jobs = null;
  28. public bool SettingsChanged { get; private set; }
  29. bool bUpdatingTimesheet = false;
  30. bool firstLoad = true;
  31. bool recentlyAskedToUpdate = true;
  32. int updateCounter;
  33. public static ConnectionSettings connectionSettings = null;
  34. bool midnightTimerOn = false;
  35. DateTime oneSecondBeforeMidnight = DateTime.Today.AddSeconds(864399);
  36. bool clockedOffInLast5Seconds = false;
  37. bool bRecentlyUpdatedTiles = false;
  38. bool bSharedDeviceFirstLoad = true;
  39. bool bSharedDevice = false;
  40. int NumberOfNotfications = 0;
  41. private Job _job = new Job();
  42. string deviceName = "";
  43. string matchedDeviceName = "";
  44. int notCount = 1;
  45. #endregion
  46. #region Constructor
  47. public MainPage()
  48. {
  49. InitializeComponent();
  50. try
  51. {
  52. App.GPS.OnLocationFound += LocationFound;
  53. App.GPS.OnLocationError += LocationError;
  54. App.Bluetooth.OnScanFinished += ScanFinished;
  55. App.Data.DataChanged += DataChanged;
  56. App.Data.DataRefreshed += DataRefreshed;
  57. GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();
  58. GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();
  59. MessagingCenter.Subscribe<App>(this, App.MessageOnResume,
  60. (o) =>
  61. {
  62. if (!App.GPS.RecentlyLocated)
  63. App.GPS.GetLocation();
  64. RefreshScreen();
  65. }
  66. );
  67. _timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  68. _employee = App.Data.Employee;
  69. _jobs = App.Data.Jobs;
  70. deviceName = MobileUtils.GetDeviceID();
  71. LoadCacheLists();
  72. InitToolEntryList();
  73. Timer t = new Timer(RecentlyAskedToUpdateTimer, null, 600000, 600000); //user is reminded to update when opening screen after timer of 10 minutes
  74. updateCounter = 1; //user is forced to update after 3rd reminder
  75. Timer t1 = new Timer(RecentlyUpdatedTilesTimer, null, 30000, 30000);
  76. //bluetooth data is allowed to upload once every minute, notifications refreshing is piggybacked to this too
  77. InitNotificationCentre();
  78. firstLoad = false;
  79. //if (GlobalVariables.EmpID == Guid.Parse("40f6ccd9-5272-4b1a-99bf-de7542205aac"))
  80. //RunCustomScript();
  81. NotifyChanges();
  82. }
  83. catch (Exception e)
  84. {
  85. }
  86. NavigationPage.SetHasBackButton(this, false);
  87. }
  88. private void RunCustomScript()
  89. {
  90. }
  91. private void NotifyChanges()
  92. {
  93. Task.Run(() =>
  94. {
  95. string changes = NotifyMobileChanges.Notifiy();
  96. if (!string.IsNullOrWhiteSpace(changes))
  97. Device.BeginInvokeOnMainThread(() =>
  98. {
  99. DisplayAlert("Latest changes", changes, "OK");
  100. });
  101. });
  102. }
  103. #endregion
  104. #region OnAppearing and Display
  105. protected override void OnAppearing()
  106. {
  107. if (!App.IsUserLoggedIn)
  108. {
  109. Navigation.PopAsync();
  110. return;
  111. }
  112. //if (Application.Current.Properties.ContainsKey("IsSharedDevice"))
  113. //{
  114. // if (Application.Current.Properties["IsSharedDevice"].Equals("True"))
  115. // {
  116. // bSharedDevice = true;
  117. // if (!bSharedDeviceFirstLoad)
  118. // {
  119. // App.LogoutUser();
  120. // Navigation.PopToRootAsync();
  121. // }
  122. // else
  123. // {
  124. // bSharedDeviceFirstLoad = false;
  125. // clockOnButton.IsEnabled = false;
  126. // clockOnButton.Text = "Shared Device";
  127. // clockOnButton.BackgroundColor = Color.CornflowerBlue;
  128. // CurrentLocation.IsVisible = false;
  129. // jobBtn.IsVisible = false;
  130. // addNoteBtn.IsVisible = false;
  131. // Grid.SetRowSpan(flexLayoutScrollView, 3);
  132. // Grid.SetRow(flexLayoutScrollView, 1);
  133. // Timer t = new Timer(AutoLogoutUser, null, 600000, Timeout.Infinite);
  134. // }
  135. // }
  136. // else
  137. // bSharedDevice = false;
  138. //}
  139. //getting strange results from .IsAllowed
  140. //if (!PRSSecurity.IsAllowed<CanBypassTimeBench>())
  141. //{
  142. // clockOnButton.IsVisible = false;
  143. // jobBtn.IsVisible = false;
  144. // addNoteBtn.IsVisible = false;
  145. // CurrentLocation.IsVisible = false;
  146. // row0.Height = 0;
  147. // row1.Height = 0;
  148. // row2.Height = 0;
  149. // ForceLayout();
  150. //}
  151. if (!firstLoad)
  152. RefreshScreen();
  153. Task.Run(async () =>
  154. {
  155. bool isLatest = true;
  156. try
  157. {
  158. isLatest = await MobileUtils.AppVersion.IsUsingLatestVersion();
  159. }
  160. catch (Exception eLatest)
  161. {
  162. if (!recentlyAskedToUpdate)
  163. {
  164. Device.BeginInvokeOnMainThread(() =>
  165. {
  166. });
  167. recentlyAskedToUpdate = true;
  168. }
  169. string s = eLatest.Message;
  170. }
  171. if (!isLatest)
  172. {
  173. if (!recentlyAskedToUpdate)
  174. {
  175. string latestVersionNumber = await MobileUtils.AppVersion.GetLatestVersionNumber();
  176. if (updateCounter < 3)
  177. {
  178. Device.BeginInvokeOnMainThread(async () =>
  179. {
  180. string chosenOption = await DisplayActionSheet(String.Format("Version {0} Available. Update now?", latestVersionNumber), "You will be reminded again in 10 minutes.", null, "Yes", "No");
  181. switch (chosenOption)
  182. {
  183. case "No":
  184. break;
  185. case "Cancel":
  186. break;
  187. case "Yes":
  188. Dispatcher.BeginInvokeOnMainThread(() => { MobileUtils.AppVersion.OpenAppInStore(); });
  189. break;
  190. default:
  191. break;
  192. }
  193. });
  194. }
  195. else if (updateCounter >= 3)
  196. {
  197. Device.BeginInvokeOnMainThread(() =>
  198. {
  199. DisplayAlert(String.Format("Version {0} Available", latestVersionNumber), "Please update your software to the latest version.", "OK")
  200. .ContinueWith((Task task) =>
  201. {
  202. Dispatcher.BeginInvokeOnMainThread(() => { MobileUtils.AppVersion.OpenAppInStore(); });
  203. });
  204. });
  205. }
  206. recentlyAskedToUpdate = true;
  207. updateCounter++;
  208. }
  209. }
  210. });
  211. base.OnAppearing();
  212. }
  213. private void RecentlyAskedToUpdateTimer(object o)
  214. {
  215. recentlyAskedToUpdate = false;
  216. }
  217. private void AutoLogoutUser(object o)
  218. {
  219. App.LogoutUser();
  220. Navigation.PopToRootAsync();
  221. }
  222. private void RefreshScreen()
  223. {
  224. //if (bSharedDevice)
  225. // return;
  226. try
  227. {
  228. Device.BeginInvokeOnMainThread(() =>
  229. {
  230. homeScreenGrid.RaiseChild(CurrentLocation);
  231. bBusy = true;
  232. if (GlobalVariables.EmpID == Guid.Empty)
  233. {
  234. GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();
  235. GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();
  236. }
  237. clockOnButton.IsEnabled = false;
  238. bool PRSReady = (App.Data.Employee != null) && (App.Data.TimeSheets != null);
  239. bool GateReady = CheckLocation();
  240. CurrentLocation.Text = DisplayAddress();
  241. if (CurrentLocation.Text.Contains("ERROR"))
  242. CurrentLocation.Text = "Unknown Address";
  243. Title = null;
  244. Title = App.Data.Employee != null ? App.Data.Employee.Name : "";
  245. CoreRow timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault();
  246. clockOnButton.Text = PRSReady && GateReady ? timesheet == null ? "CLOCK ON" : "CLOCK OFF" : "PLEASE WAIT";
  247. clockOnButton.IsEnabled = PRSReady && GateReady;
  248. clockOnButton.BackgroundColor = PRSReady && GateReady ? timesheet == null ? Color.FromHex("#e6e6fa") : Color.FromHex("#15C7C1") : Color.Gainsboro;
  249. clockOnButton.BorderColor = PRSReady && GateReady ? timesheet == null ? Color.Black : Color.FromHex("#15C7C1") : Color.Gainsboro;
  250. if (clockOnButton.Text == "CLOCK OFF")
  251. {
  252. addNoteBtn.IsEnabled = true;
  253. if (GlobalVariables.JobsLoaded)
  254. jobBtn.IsEnabled = true;
  255. }
  256. else
  257. {
  258. addNoteBtn.IsEnabled = false;
  259. jobBtn.IsEnabled = false;
  260. }
  261. if (firstLoad)
  262. RefreshJobFromTimeSheet(timesheet);
  263. homeScreenGrid.RaiseChild(CurrentLocation);
  264. firstLoad = false;
  265. bBusy = false;
  266. });
  267. }
  268. catch (Exception e)
  269. {
  270. }
  271. //CurrentLocation.IsEnabled = PRSReady && GateReady;
  272. }
  273. private void RefreshJobFromTimeSheet(CoreRow timesheet)
  274. {
  275. Guid jobid = timesheet == null ? Guid.Empty : timesheet.Get<TimeSheet, Guid>(x => x.JobLink.ID);
  276. if (!jobid.Equals(Guid.Empty))
  277. {
  278. jobBtn.Text = String.Format("{0}: {1}", timesheet.Get<TimeSheet, String>(x => x.JobLink.JobNumber), timesheet.Get<TimeSheet, String>(x => x.JobLink.Name));
  279. _job.ID = timesheet == null ? Guid.Empty : timesheet.Get<TimeSheet, Guid>(x => x.JobLink.ID);
  280. _job.JobNumber = timesheet == null ? String.Empty : timesheet.Get<TimeSheet, String>(x => x.JobLink.JobNumber);
  281. _job.Name = timesheet == null ? String.Empty : timesheet.Get<TimeSheet, String>(x => x.JobLink.Name);
  282. }
  283. else
  284. {
  285. jobBtn.Text = "No Job Selected";
  286. _job = new Job();
  287. }
  288. }
  289. #endregion
  290. #region Clock on/off
  291. private void DataChanged(object sender, Type type, Exception e)
  292. {
  293. //if (bSharedDevice)
  294. // return;
  295. Device.BeginInvokeOnMainThread(() =>
  296. {
  297. if (e != null)
  298. {
  299. //DisplayAlert("Connection error with server - double check your connection", e.Message, "OK");
  300. }
  301. else
  302. RefreshScreen();
  303. });
  304. }
  305. private void DataRefreshed()
  306. {
  307. //if (bSharedDevice)
  308. // return;
  309. Device.BeginInvokeOnMainThread(() => { RefreshScreen(); });
  310. }
  311. bool bBusy = false;
  312. async void ClockOnOff_Clicked(object sender, System.EventArgs e)
  313. {
  314. if (bBusy)
  315. return;
  316. bBusy = true;
  317. string chosenOption = "Continue";
  318. if (clockOnButton.Text == "CLOCK OFF")
  319. {
  320. chosenOption = await DisplayActionSheet("Clock off?", "Cancel", null, "Continue", "Cancel");
  321. }
  322. switch (chosenOption)
  323. {
  324. case "Continue":
  325. break;
  326. case "Cancel":
  327. bBusy = false;
  328. return;
  329. break;
  330. default:
  331. bBusy = false;
  332. return;
  333. break;
  334. }
  335. if (clockOnButton.Text == "CLOCK ON" && clockedOffInLast5Seconds)
  336. {
  337. bBusy = false;
  338. return;
  339. }
  340. try
  341. {
  342. using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
  343. {
  344. InABox.Core.Location here = new InABox.Core.Location()
  345. {
  346. Latitude = App.GPS.Latitude,
  347. Longitude = App.GPS.Longitude,
  348. Timestamp = DateTime.Now
  349. };
  350. TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  351. if (timesheet != null)
  352. {
  353. if (timesheet.ID != Guid.Empty)
  354. {
  355. if (ZeroLengthTimesheet())
  356. {
  357. bUpdatingTimesheet = true;
  358. new Client<TimeSheet>().Delete(timesheet, "Deleted due to zero duration timesheet");
  359. App.Data.TimeSheets.Rows.Clear();
  360. }
  361. else
  362. {
  363. FinishTimeSheet(timesheet, here);
  364. }
  365. }
  366. }
  367. else
  368. {
  369. Guid jobid = Guid.Empty;
  370. String jobnumber = "";
  371. String jobname = "";
  372. if (!App.Data.CanBypassGates)
  373. {
  374. CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
  375. if (row != null)
  376. {
  377. jobid = row.Get<JobTracker, Guid>(x => x.JobLink.ID);
  378. jobnumber = row.Get<JobTracker, String>(x => x.JobLink.JobNumber);
  379. jobname = row.Get<JobTracker, String>(x => x.JobLink.Name);
  380. }
  381. CreateTimeSheet(jobid, jobnumber, jobname, here, App.GPS.Address, "Clocking On");
  382. }
  383. else
  384. {
  385. if ((!App.GPS.Latitude.Equals(0.0F)) && (!App.GPS.Longitude.Equals(0.0F)))
  386. {
  387. ChooseNearbyJob(here);
  388. }
  389. }
  390. }
  391. RefreshScreen();
  392. }
  393. }
  394. catch (Exception e2)
  395. {
  396. }
  397. bBusy = false;
  398. }
  399. #endregion
  400. #region Bluetooth
  401. private async void UploadTiles()
  402. {
  403. try
  404. {
  405. if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))
  406. return;
  407. if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)
  408. return;
  409. if (bRecentlyUpdatedTiles)
  410. return;
  411. bRecentlyUpdatedTiles = true;
  412. await Task.Run(() =>
  413. {
  414. InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };
  415. curlocation.Timestamp = DateTime.Now;
  416. List<GPSTrackerLocation> trackersToUpdate = new List<GPSTrackerLocation>();
  417. foreach (String id in App.Bluetooth.DetectedBlueToothMACAddresses)
  418. {
  419. GPSTracker tracker = GlobalVariables.GPSTrackerCache.Find(x => x.DeviceID.Equals(id));
  420. bool stale = tracker.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0));
  421. bool moved = tracker.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;
  422. if (stale || moved)
  423. {
  424. GlobalVariables.GPSTrackerCache.Remove(tracker);
  425. tracker.Location = curlocation;
  426. GlobalVariables.GPSTrackerCache.Add(tracker);
  427. //cache is updated
  428. GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
  429. gpsTrackerLocation.DeviceID = tracker.DeviceID;
  430. gpsTrackerLocation.Location.Timestamp = tracker.Location.Timestamp;
  431. gpsTrackerLocation.Location = curlocation;
  432. trackersToUpdate.Add(gpsTrackerLocation);
  433. }
  434. }
  435. if (trackersToUpdate.Any())
  436. {
  437. if (ClientFactory.UserGuid != Guid.Empty)
  438. new Client<GPSTrackerLocation>().Save(trackersToUpdate, "Updating Bluetooth Device Locations");
  439. }
  440. App.Bluetooth.DetectedBlueToothMACAddresses.Clear();
  441. }
  442. );
  443. }
  444. catch (Exception e)
  445. {
  446. }
  447. //if ((master != null) && (master.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0))))
  448. //{
  449. // GPSTrackerLocation device = new GPSTrackerLocation();
  450. // device.DeviceID = MobileUtils.GetDeviceID();
  451. // device.Location.Latitude = App.GPS.Latitude;
  452. // device.Location.Longitude = App.GPS.Longitude;
  453. // device.Location.Timestamp = DateTime.Now;
  454. // locations.Add(device);
  455. // //device.BatteryLevel = ((double)CrossBattery.Current.RemainingChargePercent);
  456. // //new Client<GPSTrackerLocation>().Save(device, "Updating Device Location"); //, SaveTrackerCallback);
  457. //}
  458. #region OLD
  459. //for (int i = 0; i < App.Bluetooth.Devices.Length; i++)
  460. //{
  461. // String id = App.Bluetooth.Devices[i];
  462. // int level = App.Bluetooth.BatteryLevels[i];
  463. // var btmaster = trackers.FirstOrDefault(x => x.DeviceID.Equals(id));
  464. // if ((btmaster != null) && (!locations.Any(x => x.DeviceID.Equals(btmaster.DeviceID))))
  465. // {
  466. // bool stale = btmaster.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0));
  467. // bool moved = btmaster.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;
  468. // if (stale || moved)
  469. // {
  470. // GPSTrackerLocation location = new GPSTrackerLocation();
  471. // location.DeviceID = id;
  472. // location.Location.Latitude = App.GPS.Latitude;
  473. // location.Location.Longitude = App.GPS.Longitude;
  474. // location.Location.Timestamp = DateTime.Now;
  475. // location.BatteryLevel = level;
  476. // locations.Add(location);
  477. // }
  478. // }
  479. // //new Client<GPSTrackerLocation>().Save(location, "Found Kontakt Device"); //, SaveTrackerCallback);
  480. //}
  481. //if (locations.Any())
  482. // new Client<GPSTrackerLocation>().Save(locations, "Updating Bluetooth Device Locations", (o, e) => { });
  483. #endregion
  484. }
  485. private void RecentlyUpdatedTilesTimer(object o)
  486. {
  487. bRecentlyUpdatedTiles = false;
  488. App.Data.Refresh(true);
  489. SearchForNewNotifications();
  490. }
  491. private void LocationFound(LocationServices sender)
  492. {
  493. //if (bSharedDevice)
  494. // return;
  495. if (App.Bluetooth.RecentlyScanned)
  496. UploadTiles();
  497. try
  498. {
  499. TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  500. if (timesheet != null)
  501. {
  502. if (timesheet.StartLocation.Latitude.Equals(0.0F) && timesheet.StartLocation.Longitude.Equals(0.0F))
  503. {
  504. timesheet.StartLocation.Latitude = sender.Latitude;
  505. timesheet.StartLocation.Longitude = sender.Longitude;
  506. timesheet.StartLocation.Timestamp = sender.TimeStamp;
  507. timesheet.Address = sender.Address;
  508. new Client<TimeSheet>().Save(timesheet, "Updating Timesheet with GPS Coordinates", (o, e) => { });
  509. }
  510. }
  511. if (!string.IsNullOrWhiteSpace(matchedDeviceName))
  512. {
  513. InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };
  514. curlocation.Timestamp = DateTime.Now;
  515. GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
  516. gpsTrackerLocation.DeviceID = matchedDeviceName;
  517. gpsTrackerLocation.Location.Timestamp = curlocation.Timestamp;
  518. gpsTrackerLocation.Location = curlocation;
  519. new Client<GPSTrackerLocation>().Save(gpsTrackerLocation, "Updated company device location from Timebench");
  520. }
  521. Device.BeginInvokeOnMainThread(() =>
  522. {
  523. RefreshScreen();
  524. });
  525. }
  526. catch { }
  527. }
  528. private void LocationError(LocationServices sebder, Exception error)
  529. {
  530. }
  531. private void ScanFinished(Bluetooth sender)
  532. {
  533. try
  534. {
  535. //if (bSharedDevice)
  536. // return;
  537. Device.BeginInvokeOnMainThread(() =>
  538. {
  539. RefreshScreen();
  540. //if (Button2.BackgroundColor == Color.WhiteSmoke)
  541. // Button2.BackgroundColor = Color.Red;
  542. //else
  543. // Button2.BackgroundColor = Color.WhiteSmoke;
  544. });
  545. if (App.GPS.RecentlyLocated)
  546. UploadTiles();
  547. }
  548. catch { }
  549. }
  550. #endregion
  551. #region Utilities
  552. private void InitNotificationCentre()
  553. {
  554. try
  555. {
  556. LocalNotificationCenter.Current.NotificationActionTapped += (Plugin.LocalNotification.EventArgs.NotificationActionEventArgs e) =>
  557. {
  558. string data = e.Request.ReturningData;
  559. int index = data.IndexOf("$");
  560. Guid ID = Guid.Parse(data.Remove(index));
  561. string type = data.Substring(index + 1);
  562. if (type == "Comal.Classes.Kanban")
  563. {
  564. Device.BeginInvokeOnMainThread(() =>
  565. {
  566. AddEditTask page = new AddEditTask(ID);
  567. Navigation.PushAsync(page);
  568. });
  569. }
  570. else if (type == "Comal.Classes.Delivery")
  571. {
  572. Device.BeginInvokeOnMainThread(() =>
  573. {
  574. DeliveryDetails page = new DeliveryDetails(ID);
  575. Navigation.PushAsync(page);
  576. });
  577. }
  578. };
  579. }
  580. catch { }
  581. }
  582. private async void SearchForNewNotifications()
  583. {
  584. //notifications poll reliably in the background for Anroid, unreliable for iOS due to difficulty with cross-platform plugins for notifications
  585. try
  586. {
  587. await Task.Run(() =>
  588. {
  589. if (ClientFactory.UserGuid != Guid.Empty)
  590. {
  591. CoreTable table = new Client<Notification>().Query
  592. (new Filter<Notification>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid).And(X => X.Closed).IsEqualTo(DateTime.MinValue),
  593. new Columns<Notification>(
  594. x => x.ID, //0
  595. x => x.Sender.Name, //1
  596. x => x.Title, //2
  597. x => x.Created, //3
  598. x => x.Description, //4
  599. x => x.EntityType, //5
  600. x => x.EntityID //6
  601. )
  602. );
  603. if (NumberOfNotfications == table.Rows.Count()) //no new notifications or none present at all
  604. return;
  605. else //new notifications or previous notifications have now been dismissed
  606. {
  607. NumberOfNotfications = table.Rows.Count();
  608. RefreshOnNotificationsChange();
  609. CheckNotificationsPushed(table);
  610. }
  611. }
  612. });
  613. }
  614. catch { }
  615. }
  616. private void RefreshOnNotificationsChange()
  617. {
  618. try
  619. {
  620. int index = toolEntries.FindIndex(x => x.Text.Equals("Notifications"));
  621. toolEntries.RemoveAt(index);
  622. string notificationsString = "";
  623. if (NumberOfNotfications != 0)
  624. {
  625. notificationsString = NumberOfNotfications.ToString();
  626. }
  627. ToolEntry Notifications = new ToolEntry(notificationsString)
  628. {
  629. Text = "Notifications",
  630. Image = "notifications"
  631. };
  632. Notifications.OnTapped += (async (object sender, EventArgs e) =>
  633. {
  634. using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
  635. {
  636. NotificationList notificationList = new NotificationList();
  637. notificationList.NotificationsClosed += (n) =>
  638. {
  639. NumberOfNotfications = n;
  640. RefreshOnNotificationsChange();
  641. };
  642. Navigation.PushAsync(notificationList);
  643. }
  644. });
  645. toolEntries.Insert(index, Notifications);
  646. Device.BeginInvokeOnMainThread(() =>
  647. {
  648. flexLayout.Children.RemoveAt(index);
  649. flexLayout.Children.Insert(index, toolEntries[index]);
  650. });
  651. }
  652. catch { }
  653. }
  654. private void CheckNotificationsPushed(CoreTable table)
  655. {
  656. try
  657. {
  658. if (!Application.Current.Properties.ContainsKey("LastPushedNotifications"))
  659. {
  660. Application.Current.Properties.Add("LastPushedNotifications", DateTime.Now);
  661. }
  662. DateTime lastPushed = DateTime.Parse(Application.Current.Properties["LastPushedNotifications"].ToString());
  663. List<NotificationShell> toNotify = new List<NotificationShell>();
  664. foreach (CoreRow row in table.Rows)
  665. {
  666. List<object> list = row.Values;
  667. DateTime created = DateTime.Parse(list[3].ToString());
  668. if (created > new DateTime(2022, 8, 22)) // prevent spam from buildup of old notifications before this is released
  669. {
  670. if (created > lastPushed)
  671. {
  672. if (list[1] == null) list[1] = "";
  673. if (list[2] == null) list[2] = "";
  674. if (list[3] == null) list[3] = DateTime.MinValue;
  675. if (list[4] == null) list[4] = "";
  676. if (list[5] == null) list[5] = "";
  677. if (list[6] == null) list[6] = Guid.Empty;
  678. NotificationShell shell = new NotificationShell
  679. {
  680. ID = Guid.Parse(list[0].ToString()),
  681. Sender = list[1].ToString(),
  682. Title = list[2].ToString(),
  683. Created = DateTime.Parse(list[3].ToString()),
  684. EntityType = list[5].ToString(),
  685. EntityID = Guid.Parse(list[6].ToString())
  686. };
  687. toNotify.Add(shell); //add notification to be pushed
  688. }
  689. }
  690. }
  691. if (toNotify.Count > 0)
  692. PushNotificationsAsync(toNotify);
  693. }
  694. catch { }
  695. }
  696. private async Task PushNotificationsAsync(List<NotificationShell> shells)
  697. {
  698. try
  699. {
  700. int count = 1;
  701. foreach (NotificationShell shell in shells)
  702. {
  703. var notification = new NotificationRequest
  704. {
  705. BadgeNumber = 1,
  706. Description = shell.Title,
  707. Title = "New PRS Notification: ",
  708. ReturningData = shell.EntityID.ToString() + "$" + shell.EntityType,
  709. NotificationId = count,
  710. };
  711. count++;
  712. NotificationImage img = new NotificationImage();
  713. img.ResourceName = "icon16.png";
  714. notification.Image = img;
  715. await LocalNotificationCenter.Current.Show(notification);
  716. //if (Device.RuntimePlatform.Equals(Device.iOS))
  717. //{
  718. // var content = new UNMutableNotificationContent();
  719. // content.Title = "New PRS Notification: ";
  720. // content.Subtitle = shell.Title;
  721. // content.Body = "";
  722. // content.Badge = 1;
  723. // var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
  724. // var requestID = "request";
  725. // var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
  726. // UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
  727. // {
  728. // if (err != null)
  729. // {
  730. // Do something with error...
  731. // }
  732. // });
  733. //}
  734. }
  735. Application.Current.Properties["LastPushedNotifications"] = DateTime.Now;
  736. }
  737. catch { }
  738. }
  739. private void StartMidnightTimeSheetTimer()
  740. {
  741. midnightTimerOn = true;
  742. int msUntilMidnight = (int)(oneSecondBeforeMidnight - DateTime.Now).TotalMilliseconds;
  743. Timer midnightTimer = new Timer(MidnightTimerCallback, null, msUntilMidnight, Timeout.Infinite);
  744. }
  745. private void MidnightTimerCallback(object o)
  746. {
  747. try
  748. {
  749. //if (bSharedDevice)
  750. // return;
  751. if (midnightTimerOn)
  752. {
  753. if (clockOnButton.Text == "CLOCK OFF")
  754. {
  755. InABox.Core.Location here = new InABox.Core.Location()
  756. {
  757. Latitude = App.GPS.Latitude,
  758. Longitude = App.GPS.Longitude,
  759. Timestamp = DateTime.Now
  760. };
  761. TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  762. if (timesheet != null)
  763. {
  764. if (timesheet.ID != Guid.Empty)
  765. {
  766. if (ZeroLengthTimesheet())
  767. {
  768. bUpdatingTimesheet = true;
  769. new Client<TimeSheet>().Delete(timesheet, "Deleted due to zero duration timesheet");
  770. App.Data.TimeSheets.Rows.Clear();
  771. }
  772. else
  773. {
  774. timesheet.Finish = new TimeSpan(23, 59, 59);
  775. timesheet.FinishLocation = here;
  776. bUpdatingTimesheet = true;
  777. new Client<TimeSheet>().Save(timesheet, "Auto Close timesheet at Midnight");
  778. App.Data.TimeSheets.Rows.Clear();
  779. Guid jobid = Guid.Empty;
  780. String jobnumber = "";
  781. String jobname = "";
  782. if (!App.Data.CanBypassGates)
  783. {
  784. CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
  785. if (row != null)
  786. {
  787. jobid = row.Get<JobTracker, Guid>(x => x.JobLink.ID);
  788. jobnumber = row.Get<JobTracker, String>(x => x.JobLink.JobNumber);
  789. jobname = row.Get<JobTracker, String>(x => x.JobLink.Name);
  790. }
  791. CreateTimeSheet(jobid, jobnumber, jobname, here, App.GPS.Address, "Clocking On");
  792. }
  793. else
  794. {
  795. if ((!App.GPS.Latitude.Equals(0.0F)) && (!App.GPS.Longitude.Equals(0.0F)))
  796. {
  797. ChooseNearbyJob(here);
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. }
  805. }
  806. catch { }
  807. }
  808. private void FinishTimeSheet(TimeSheet timesheet, InABox.Core.Location here)
  809. {
  810. try
  811. {
  812. TimeSpan tod = DateTime.Now - DateTime.Today;
  813. timesheet.Finish = new TimeSpan(tod.Hours, tod.Minutes, 0);
  814. timesheet.FinishLocation = here;
  815. bUpdatingTimesheet = true;
  816. new Client<TimeSheet>().Save(timesheet, "Clocking Off");
  817. App.Data.TimeSheets.Rows.Clear();
  818. midnightTimerOn = false;
  819. Timer last60Seconds = new Timer(Last60SecondsTimerCallBack, null, 5000, Timeout.Infinite);
  820. clockedOffInLast5Seconds = true;
  821. }
  822. catch { }
  823. }
  824. private void Last60SecondsTimerCallBack(object o)
  825. {
  826. clockedOffInLast5Seconds = false;
  827. }
  828. private async void ChooseNearbyJob(InABox.Core.Location here)
  829. {
  830. try
  831. {
  832. JobShell selectedJob = new JobShell();
  833. Dictionary<string, JobShell> nearbyJobs = new Dictionary<string, JobShell>();
  834. foreach (CoreRow row in App.Data.Jobs.Rows)
  835. {
  836. InABox.Core.Location jobLocation = new InABox.Core.Location() { Latitude = row.Get<Job, double>(X => X.SiteAddress.Location.Latitude), Longitude = row.Get<Job, double>(X => X.SiteAddress.Location.Longitude) };
  837. double distance = here.DistanceTo(jobLocation, UnitOfLength.Kilometers);
  838. if (distance < 1.0F)
  839. {
  840. JobShell jobShell = new JobShell();
  841. jobShell.ID = row.Get<Job, Guid>(X => X.ID);
  842. jobShell.JobNumber = row.Get<Job, String>(x => x.JobNumber);
  843. jobShell.Name = row.Get<Job, String>(x => x.Name);
  844. jobShell.DisplayName = jobShell.JobNumber + " " + jobShell.Name;
  845. nearbyJobs.Add(jobShell.DisplayName, jobShell);
  846. }
  847. }
  848. if (nearbyJobs.Count > 1)
  849. {
  850. string[] array = nearbyJobs.Keys.ToArray();
  851. string chosenOption = await DisplayActionSheet("Choose job site", "Cancel", null, array);
  852. if (string.IsNullOrEmpty(chosenOption) || chosenOption.Equals("Cancel"))
  853. {
  854. CreateTimeSheet(selectedJob.ID, selectedJob.JobNumber, selectedJob.Name, here, App.GPS.Address, "Clocking On");
  855. return;
  856. }
  857. else
  858. {
  859. selectedJob = nearbyJobs[chosenOption];
  860. }
  861. }
  862. else if (nearbyJobs.Count == 1)
  863. {
  864. selectedJob = nearbyJobs.Values.First();
  865. }
  866. CreateTimeSheet(selectedJob.ID, selectedJob.JobNumber, selectedJob.Name, here, App.GPS.Address, "Clocking On");
  867. }
  868. catch { }
  869. }
  870. void AddNote_Tapped(System.Object sender, System.EventArgs e)
  871. {
  872. try
  873. {
  874. TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  875. if (timesheet == null)
  876. return;
  877. var notepage = new NotePage(timesheet);
  878. Navigation.PushAsync(notepage);
  879. }
  880. catch { }
  881. }
  882. private void JobBtn_Tapped(object sender, EventArgs e)
  883. {
  884. try
  885. {
  886. JobSelectionPage jobSelectionPage = new JobSelectionPage();
  887. jobSelectionPage.OnItemSelected += (() =>
  888. {
  889. _job.ID = jobSelectionPage.Job.ID;
  890. _job.JobNumber = jobSelectionPage.Job.JobNumber;
  891. _job.Name = jobSelectionPage.Job.Name;
  892. JobPage_OnItemSelected(jobSelectionPage.Job);
  893. });
  894. Navigation.PushAsync(jobSelectionPage);
  895. }
  896. catch { }
  897. }
  898. private void JobPage_OnItemSelected(JobShell job)
  899. {
  900. try
  901. {
  902. TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
  903. if (timesheet == null)
  904. return;
  905. String auditmessage = String.Format("Changed Selected Job to: {0}: {1}", timesheet.JobLink.JobNumber, timesheet.JobLink.Name);
  906. if (ZeroLengthTimesheet())
  907. {
  908. timesheet.JobLink.ID = job.ID;
  909. timesheet.JobLink.JobNumber = job.JobNumber;
  910. timesheet.JobLink.Name = job.Name;
  911. bUpdatingTimesheet = true;
  912. new Client<TimeSheet>().Save(timesheet, auditmessage);
  913. Device.BeginInvokeOnMainThread(() =>
  914. {
  915. if (timesheet.JobLink.ID != Guid.Empty)
  916. {
  917. jobBtn.Text = "(" + timesheet.JobLink.JobNumber + ") " + timesheet.JobLink.Name;
  918. }
  919. else
  920. {
  921. jobBtn.Text = "No Job Selected";
  922. }
  923. });
  924. }
  925. else
  926. {
  927. InABox.Core.Location here = new InABox.Core.Location()
  928. {
  929. Latitude = App.GPS.Latitude,
  930. Longitude = App.GPS.Longitude,
  931. Timestamp = DateTime.Now
  932. };
  933. TimeSpan tod = DateTime.Now - DateTime.Today;
  934. timesheet.Finish = new TimeSpan(tod.Hours, tod.Minutes, 0);
  935. timesheet.FinishLocation = here;
  936. new Client<TimeSheet>().Save(timesheet, "Changing Job");
  937. CreateTimeSheet(
  938. job.ID,
  939. job.JobNumber,
  940. job.Name,
  941. here,
  942. App.GPS.Address,
  943. auditmessage
  944. );
  945. }
  946. RefreshScreen();
  947. }
  948. catch { }
  949. }
  950. private bool CheckTimeSheetAgainstGates(TimeSheet timesheet)
  951. {
  952. DateTime now = DateTime.Now;
  953. //var timesheet = CurrentTimeSheet();
  954. //Can't confirm if there is no timesheet
  955. if (timesheet == null)
  956. return false;
  957. // Can't confirm if there are no devices
  958. if (App.Bluetooth.Devices.Length == 0)
  959. return false;
  960. if (App.Data.Gates == null)
  961. return false;
  962. long tsTicks = timesheet.Date.Add(timesheet.Start).Ticks;
  963. long btTicks = App.Bluetooth.TimeStamp.Ticks;
  964. if (Math.Abs(tsTicks - btTicks) > new TimeSpan(0, 2, 0).Ticks)
  965. return false;
  966. CoreRow firstgate = null;
  967. List<String> gates = new List<string>();
  968. // Scan every located d
  969. foreach (var device in App.Bluetooth.Devices)
  970. {
  971. CoreRow gate = App.Data.Gates?.Rows.FirstOrDefault(r => r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID) == device);
  972. if (gate != null)
  973. {
  974. if ((gate.Get<JobTracker, bool>(x => x.IsJobSite) == true) && (firstgate == null))
  975. firstgate = gate;
  976. gates.Add(gate.Get<JobTracker, String>(x => x.Gate));
  977. }
  978. }
  979. if (gates.Any())
  980. {
  981. timesheet.Gate = String.Join(", ", gates.OrderBy(x => x));
  982. if (firstgate != null)
  983. {
  984. timesheet.JobLink.ID = firstgate.Get<JobTracker, Guid>(x => x.JobLink.ID);
  985. timesheet.JobLink.JobNumber = firstgate.Get<JobTracker, String>(x => x.JobLink.JobNumber);
  986. timesheet.JobLink.Name = firstgate.Get<JobTracker, String>(x => x.JobLink.Name);
  987. }
  988. return true;
  989. //new Client<TimeSheet>().Save(timesheet, "Confirmed Gate Entry by Bluetooth Tracker", (o, e) => { });
  990. }
  991. return false;
  992. }
  993. private bool ZeroLengthTimesheet()
  994. {
  995. try
  996. {
  997. if (App.Data.TimeSheets == null)
  998. return true;
  999. CoreRow row = App.Data.TimeSheets.Rows.FirstOrDefault();
  1000. if (row == null)
  1001. return true;
  1002. String notes = row.Get<TimeSheet, String>(x => x.Notes);
  1003. if (!String.IsNullOrWhiteSpace(notes))
  1004. return false;
  1005. DateTime date = row.Get<TimeSheet, DateTime>(x => x.Date);
  1006. TimeSpan start = row.Get<TimeSheet, TimeSpan>(x => x.Start);
  1007. if (date.Equals(DateTime.Today))
  1008. {
  1009. TimeSpan tod = DateTime.Now - DateTime.Today;
  1010. var diff = (tod - start).TotalSeconds;
  1011. if (Math.Abs(diff) < 120.0F)
  1012. return true;
  1013. }
  1014. }
  1015. catch { }
  1016. return false;
  1017. }
  1018. private async void CreateTimeSheet(Guid jobid, string jobnumber, String jobname, InABox.Core.Location location, String address, String auditmessage)
  1019. {
  1020. try
  1021. {
  1022. var timesheet = new TimeSheet();
  1023. using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
  1024. {
  1025. timesheet.EmployeeLink.ID = App.Data.Employee.ID;
  1026. timesheet.Date = DateTime.Today;
  1027. TimeSpan tod = DateTime.Now - DateTime.Today;
  1028. tod = new TimeSpan(tod.Hours, tod.Minutes, 0);
  1029. timesheet.Start = tod;
  1030. timesheet.StartLocation = location;
  1031. timesheet.JobLink.ID = jobid;
  1032. timesheet.JobLink.JobNumber = jobnumber;
  1033. timesheet.JobLink.Name = jobname;
  1034. timesheet.Address = address;
  1035. timesheet.SoftwareVersion = MobileUtils.AppVersion.InstalledVersionNumber + GlobalVariables.DeviceString;
  1036. //if (ClientFactory.IsAllowed<AllowTimeSheetRollover>()) CheckTimeSheetAgainstGates(timesheet);
  1037. bUpdatingTimesheet = true;
  1038. new Client<TimeSheet>().Save(timesheet, auditmessage);
  1039. if (timesheet.ID == Guid.Empty)
  1040. {
  1041. DisplayAlert("Error creating new timesheet", "Please check your connection and try again", "OK");
  1042. return;
  1043. }
  1044. StartMidnightTimeSheetTimer();
  1045. // Don't Save Completed Timesheets!
  1046. App.Data.TimeSheets.Rows.Clear();
  1047. if (timesheet.Finish.Ticks == 0L)
  1048. {
  1049. CoreRow row = App.Data.TimeSheets.NewRow();
  1050. App.Data.TimeSheets.LoadRow(row, timesheet);
  1051. App.Data.TimeSheets.Rows.Add(row);
  1052. }
  1053. }
  1054. Device.BeginInvokeOnMainThread(() =>
  1055. {
  1056. if (timesheet.JobLink.ID != Guid.Empty)
  1057. {
  1058. jobBtn.Text = "(" + timesheet.JobLink.JobNumber + ") " + timesheet.JobLink.Name;
  1059. }
  1060. else
  1061. {
  1062. jobBtn.Text = "No Job Selected";
  1063. }
  1064. });
  1065. }
  1066. catch { }
  1067. }
  1068. private bool CheckLocation()
  1069. {
  1070. try
  1071. {
  1072. if (App.Data.CanBypassGates)
  1073. {
  1074. if (App.GPS.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 5, 0)))
  1075. return true;
  1076. else
  1077. return false;
  1078. }
  1079. if (App.Data.Gates == null)
  1080. return false;
  1081. if (App.Bluetooth.TimeStamp < DateTime.Now.Subtract(new TimeSpan(0, 2, 0)))
  1082. return false;
  1083. if (!App.Bluetooth.Devices.Any())
  1084. return false;
  1085. return App.Data.Gates.Rows.Any(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
  1086. }
  1087. catch
  1088. {
  1089. return true;
  1090. }
  1091. }
  1092. private String DisplayAddress()
  1093. {
  1094. try
  1095. {
  1096. bool PRSReady = App.Data.Employee != null; // && (TimeSheet != null); // && (Activities != null);
  1097. if (!PRSReady)
  1098. return "Retrieving Data";
  1099. if (App.Data.CanBypassGates)
  1100. {
  1101. if (App.GPS.TimeStamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0)))
  1102. {
  1103. App.GPS.GetLocation(true);
  1104. return "Searching for GPS";
  1105. }
  1106. else
  1107. return App.GPS.Address;
  1108. }
  1109. else
  1110. {
  1111. // Hmm.. this can/should be simplified
  1112. // if in range of a gate
  1113. // Show Gate Description
  1114. // else
  1115. // "Looking for Gate"
  1116. if ((App.Data.Gates != null) && (App.Bluetooth.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 2, 0))))
  1117. {
  1118. CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
  1119. if (row != null)
  1120. return row.Get<JobTracker, String>(x => x.Gate);
  1121. //else if ((CurrentTimeSheet() != null) && (!GPS.TimeStamp.IsEmpty()))
  1122. // return GPS.Address;
  1123. else
  1124. return "Looking for Gate";
  1125. }
  1126. //else if ((CurrentTimeSheet() != null) && (GPS.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 2, 0))))
  1127. // return GPS.Address;
  1128. else
  1129. return "Looking for Gate";
  1130. }
  1131. }
  1132. catch
  1133. {
  1134. return "Address error";
  1135. }
  1136. }
  1137. #region Background Loading
  1138. private async Task LoadCacheLists()
  1139. {
  1140. GlobalVariables.ProductsLoaded = false;
  1141. GlobalVariables.JobsLoaded = false;
  1142. GlobalVariables.GetXamarinWidth();
  1143. await CacheLoader.LoadJobs();
  1144. LoadEmployeeShells();
  1145. LoadProducts();
  1146. LoadCompanyDevices();
  1147. LoadBlueToothAddresses();
  1148. //LoadHRToDos(); to be uncommented when ready for roll out
  1149. }
  1150. private void LoadCompanyDevices()
  1151. {
  1152. Task.Run(() =>
  1153. {
  1154. if (!string.IsNullOrWhiteSpace(deviceName) && deviceName != "unknown")
  1155. {
  1156. List<Equipment> companyDevices = new List<Equipment>();
  1157. CoreTable table = new Client<Equipment>().Query
  1158. (
  1159. new Filter<Equipment>(x => x.GroupLink.Code).IsEqualTo("DEVICE"),
  1160. new Columns<Equipment>(
  1161. x => x.TrackerLink.DeviceID
  1162. )
  1163. );
  1164. if (table.Rows.Any())
  1165. {
  1166. foreach (CoreRow row in table.Rows)
  1167. {
  1168. List<object> list = row.Values;
  1169. if (list[0].ToString().Equals(deviceName))
  1170. {
  1171. matchedDeviceName = deviceName;
  1172. }
  1173. }
  1174. }
  1175. }
  1176. });
  1177. }
  1178. private async void LoadEmployeeShells()
  1179. {
  1180. await Task.Run(() =>
  1181. {
  1182. List<EmployeeShell> employeeShells = new List<EmployeeShell>();
  1183. List<EmployeeShell> teamEmployeeShells = new List<EmployeeShell>();
  1184. MultiQuery query = new MultiQuery();
  1185. query.Add<Employee>(
  1186. LookupFactory.DefineFilter<Employee>(),
  1187. new Columns<Employee>(x => x.ID)
  1188. .Add(x => x.Code)
  1189. .Add(x => x.Name),
  1190. LookupFactory.DefineSort<Employee>()
  1191. );
  1192. query.Add<Team>(
  1193. LookupFactory.DefineFilter<Team>(),
  1194. new Columns<Team>(x => x.Name),
  1195. new SortOrder<Team>(x => x.Name)
  1196. );
  1197. query.Add<EmployeeTeam>(
  1198. LookupFactory.DefineFilter<EmployeeTeam>(),
  1199. new Columns<EmployeeTeam>(x => x.EmployeeLink.ID)
  1200. .Add(x => x.EmployeeLink.Code)
  1201. .Add(x => x.EmployeeLink.Name)
  1202. .Add(x => x.TeamLink.Name),
  1203. new SortOrder<EmployeeTeam>(x => x.EmployeeLink.Name)
  1204. );
  1205. query.Query();
  1206. CoreTable emps = query.Get<Employee>();
  1207. foreach (var row in emps.Rows)
  1208. {
  1209. employeeShells.Add(
  1210. new EmployeeShell()
  1211. {
  1212. ID = row.Get<Employee, Guid>(x => x.ID),
  1213. Code = row.Get<Employee, String>(x => x.Code),
  1214. Name = row.Get<Employee, String>(x => x.Name),
  1215. TeamName = "All Staff"
  1216. }
  1217. );
  1218. }
  1219. GlobalVariables.TeamNames = query.Get<Team>().Rows.Select(r => r.Get<Team, String>(c => c.Name)).ToList();
  1220. CoreTable members = query.Get<EmployeeTeam>();
  1221. foreach (var row in members.Rows)
  1222. {
  1223. teamEmployeeShells.Add(
  1224. new EmployeeShell()
  1225. {
  1226. ID = row.Get<EmployeeTeam, Guid>(x => x.EmployeeLink.ID),
  1227. Code = row.Get<EmployeeTeam, String>(x => x.EmployeeLink.Code),
  1228. Name = row.Get<EmployeeTeam, String>(x => x.EmployeeLink.Name),
  1229. TeamName = row.Get<EmployeeTeam, String>(x => x.TeamLink.Name)
  1230. }
  1231. );
  1232. }
  1233. GlobalVariables.EmployeeShells = employeeShells;
  1234. GlobalVariables.TeamEmployeeShells = teamEmployeeShells;
  1235. });
  1236. }
  1237. private async void LoadHRToDos()
  1238. {
  1239. try
  1240. {
  1241. await Task.Run(() =>
  1242. {
  1243. Thread.Sleep(10000);
  1244. if (GlobalVariables.UpdateHRItemsNeedingAttention())
  1245. {
  1246. string message = "You have HR Items needing attention. Open My HR now?";
  1247. Device.BeginInvokeOnMainThread(async () =>
  1248. {
  1249. string chosenOption = await DisplayActionSheet(message, "Cancel", null, "Yes", "No");
  1250. switch (chosenOption)
  1251. {
  1252. case "Cancel":
  1253. break;
  1254. case "No":
  1255. break;
  1256. default:
  1257. break;
  1258. case "Yes":
  1259. MyHRHome myHRHome = new MyHRHome();
  1260. Navigation.PushAsync(myHRHome);
  1261. break;
  1262. }
  1263. });
  1264. }
  1265. });
  1266. }
  1267. catch { }
  1268. }
  1269. private async void LoadProducts()
  1270. {
  1271. try
  1272. {
  1273. await Task.Run(() =>
  1274. {
  1275. ProductsLoader productsLoader = new ProductsLoader();
  1276. //if (ClientFactory.IsAllowed<CanViewStoresRequisitions>())
  1277. //{
  1278. //}
  1279. });
  1280. }
  1281. catch { }
  1282. }
  1283. private async void LoadBlueToothAddresses()
  1284. {
  1285. try
  1286. {
  1287. //if (bSharedDevice)
  1288. // return;
  1289. await Task.Run(() =>
  1290. {
  1291. GlobalVariables.GPSTrackerCache = new List<GPSTracker>();
  1292. CoreTable table = new Client<GPSTracker>().Query(new Filter<GPSTracker>(x => x.Type.Description).Contains("Kontakt"));
  1293. foreach (CoreRow row in table.Rows)
  1294. {
  1295. GPSTracker tracker = row.ToObject<GPSTracker>();
  1296. GlobalVariables.GPSTrackerCache.Add(tracker);
  1297. App.Bluetooth.KnownBlueToothMACAddresses.Add(tracker.DeviceID);
  1298. }
  1299. });
  1300. }
  1301. catch { }
  1302. }
  1303. #endregion
  1304. #endregion
  1305. #region Modules
  1306. public async void InitToolEntryList()
  1307. {
  1308. try
  1309. {
  1310. await Task.Run(() =>
  1311. {
  1312. //Assignments
  1313. ToolEntry Assignments = new ToolEntry
  1314. {
  1315. Text = "Assignments",
  1316. Image = "calendar"
  1317. };
  1318. Assignments.IsVisible = PRSSecurity.CanView<Assignment>();
  1319. Assignments.OnTapped += ((object sender, EventArgs e) =>
  1320. {
  1321. var assignment_form = new AssignmentList();
  1322. Navigation.PushAsync(assignment_form);
  1323. });
  1324. toolEntries.Add(Assignments);
  1325. //Deliveries
  1326. ToolEntry Deliveries = new ToolEntry
  1327. {
  1328. Text = "Deliveries",
  1329. Image = "deliveries"
  1330. };
  1331. Deliveries.IsVisible = PRSSecurity.CanView<Delivery>();
  1332. Deliveries.OnTapped += ((object sender, EventArgs e) =>
  1333. {
  1334. var delivery_form = new DeliveryList();
  1335. Navigation.PushAsync(delivery_form);
  1336. });
  1337. toolEntries.Add(Deliveries);
  1338. //Digital Forms
  1339. ToolEntry Forms = new ToolEntry
  1340. {
  1341. Text = "Forms",
  1342. Image = "forms"
  1343. };
  1344. Forms.IsVisible = PRSSecurity.CanView<DigitalForm>();
  1345. Forms.OnTapped += ((object sender, EventArgs e) =>
  1346. {
  1347. var qaFormPicker = new DigitalFormsPicker();
  1348. Navigation.PushAsync(qaFormPicker);
  1349. });
  1350. toolEntries.Add(Forms);
  1351. //Equipment
  1352. ToolEntry Equipment = new ToolEntry
  1353. {
  1354. Text = "Equipment",
  1355. Image = "digger"
  1356. };
  1357. Equipment.IsVisible = PRSSecurity.CanView<Equipment>();
  1358. Equipment.OnTapped += (async (object sender, EventArgs e) =>
  1359. {
  1360. using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
  1361. {
  1362. var equipment = new EquipmentModule();
  1363. Navigation.PushAsync(equipment);
  1364. }
  1365. });
  1366. toolEntries.Add(Equipment);
  1367. //InOut
  1368. ToolEntry InOut = new ToolEntry
  1369. {
  1370. Text = "In/Out",
  1371. Image = "inout"
  1372. };
  1373. InOut.IsVisible = PRSSecurity.IsAllowed<CanViewInOutBoard>();
  1374. InOut.OnTapped += ((object sender, EventArgs e) =>
  1375. {
  1376. var staff_form = new StaffStatusPage();
  1377. Navigation.PushAsync(staff_form);
  1378. });
  1379. toolEntries.Add(InOut);
  1380. //Manufacturing
  1381. ToolEntry Manufacturing = new ToolEntry
  1382. {
  1383. Text = "Manufacturing",
  1384. Image = "manufacturingg"
  1385. };
  1386. if (Device.RuntimePlatform.Equals(Device.iOS))
  1387. {
  1388. Manufacturing.Image = "Image";
  1389. }
  1390. Manufacturing.IsVisible = PRSSecurity.IsAllowed<CanViewManufacturingOnMobile>();
  1391. Manufacturing.OnTapped += ((object sender, EventArgs e) =>
  1392. {
  1393. ManufacturingScreen manufacturingScreen = new ManufacturingScreen();
  1394. Navigation.PushAsync(manufacturingScreen);
  1395. });
  1396. toolEntries.Add(Manufacturing);
  1397. //My HR
  1398. ToolEntry MyHR = new ToolEntry
  1399. {
  1400. Text = "My HR",
  1401. Image = "myhr"
  1402. };
  1403. MyHR.OnTapped += ((object sender, EventArgs e) =>
  1404. {
  1405. MyHRHome myHRHome = new MyHRHome();
  1406. Navigation.PushAsync(myHRHome);
  1407. });
  1408. toolEntries.Add(MyHR);
  1409. //Notifications
  1410. ToolEntry Notifications = new ToolEntry()
  1411. {
  1412. Text = "Notifications",
  1413. Image = "notifications"
  1414. };
  1415. Notifications.OnTapped += (object sender, EventArgs e) =>
  1416. {
  1417. NotificationList notificationList = new NotificationList();
  1418. notificationList.NotificationsClosed += (n) =>
  1419. {
  1420. NumberOfNotfications = n;
  1421. RefreshOnNotificationsChange();
  1422. };
  1423. Navigation.PushAsync(notificationList);
  1424. };
  1425. toolEntries.Add(Notifications);
  1426. ToolEntry Products = new ToolEntry()
  1427. {
  1428. Text = "Products",
  1429. Image = "products"
  1430. };
  1431. Products.OnTapped += ((object sender, EventArgs e) =>
  1432. {
  1433. if (GlobalVariables.ProductsLoaded)
  1434. {
  1435. ProductList products = new ProductList(GlobalVariables.ProductShells);
  1436. Navigation.PushAsync(products);
  1437. }
  1438. else
  1439. {
  1440. ProductList products = new ProductList();
  1441. Navigation.PushAsync(products);
  1442. }
  1443. });
  1444. toolEntries.Add(Products);
  1445. //Purchase Orders
  1446. ToolEntry PurchaseOrders = new ToolEntry()
  1447. {
  1448. Text = "Purchase Orders",
  1449. Image = "shoppingcart"
  1450. };
  1451. PurchaseOrders.IsVisible = PRSSecurity.CanView<PurchaseOrder>();
  1452. PurchaseOrders.OnTapped += ((object sender, EventArgs e) =>
  1453. {
  1454. PurchaseOrderModule page = new PurchaseOrderModule();
  1455. Navigation.PushAsync(page);
  1456. });
  1457. toolEntries.Add(PurchaseOrders);
  1458. //Scanner
  1459. ToolEntry Scanner = new ToolEntry
  1460. {
  1461. Text = "Scanner",
  1462. Image = "scanner"
  1463. };
  1464. Scanner.OnTapped += ((object sender, EventArgs e) =>
  1465. {
  1466. ScannerPage scannerPage = new ScannerPage();
  1467. Navigation.PushAsync(scannerPage);
  1468. });
  1469. toolEntries.Add(Scanner);
  1470. //Site
  1471. ToolEntry Site = new ToolEntry
  1472. {
  1473. Text = "Site",
  1474. Image = "construction"
  1475. };
  1476. Site.OnTapped += ((object sender, EventArgs e) =>
  1477. {
  1478. Site site = new Site(_job);
  1479. Navigation.PushAsync(site);
  1480. //if (_job.ID == Guid.Empty)
  1481. //{
  1482. // JobSelectionPage jobSelectionPage = new JobSelectionPage(true);
  1483. // jobSelectionPage.OnItemSelected += (async () =>
  1484. // {
  1485. // if (jobSelectionPage.Job.ID != Guid.Empty)
  1486. // {
  1487. // Job selectedJob = new Job();
  1488. // selectedJob.ID = jobSelectionPage.Job.ID;
  1489. // selectedJob.JobNumber = jobSelectionPage.Job.JobNumber;
  1490. // selectedJob.Name = jobSelectionPage.Job.Name;
  1491. // Site site = new Site(selectedJob);
  1492. // var previousPage = Navigation.NavigationStack.LastOrDefault();
  1493. // await Navigation.PushAsync(site);
  1494. // Navigation.RemovePage(previousPage);
  1495. // }
  1496. // });
  1497. // Navigation.PushAsync(jobSelectionPage);
  1498. //}
  1499. });
  1500. toolEntries.Add(Site);
  1501. //Store Requis
  1502. ToolEntry StoreRequis = new ToolEntry
  1503. {
  1504. Text = "Store Requis",
  1505. Image = "storerequis"
  1506. };
  1507. StoreRequis.IsVisible = PRSSecurity.CanView<Requisition>();
  1508. StoreRequis.OnTapped += ((object sender, EventArgs e) =>
  1509. {
  1510. var storeRequisList = new StoreRequiList();
  1511. Navigation.PushAsync(storeRequisList);
  1512. });
  1513. toolEntries.Add(StoreRequis);
  1514. //Tasks
  1515. ToolEntry Tasks = new ToolEntry
  1516. {
  1517. Text = "Tasks",
  1518. Image = "tasks"
  1519. };
  1520. Tasks.IsVisible = PRSSecurity.IsAllowed<CanViewTasks>();
  1521. Tasks.OnTapped += ((object sender, EventArgs e) =>
  1522. {
  1523. var tasksForm = new TasksList();
  1524. Navigation.PushAsync(tasksForm);
  1525. });
  1526. toolEntries.Add(Tasks);
  1527. //Warehousing
  1528. ToolEntry Warehousing = new ToolEntry
  1529. {
  1530. Text = "Warehousing",
  1531. Image = "newwarehousing"
  1532. };
  1533. Warehousing.IsVisible = PRSSecurity.CanView<StockWarehouse>();
  1534. Warehousing.OnTapped += ((object sender, EventArgs e) =>
  1535. {
  1536. Warehousing2 locations = new Warehousing2();
  1537. Navigation.PushAsync(locations);
  1538. });
  1539. toolEntries.Add(Warehousing);
  1540. AddChildren();
  1541. });
  1542. }
  1543. catch { }
  1544. }
  1545. private void AddChildren()
  1546. {
  1547. Device.BeginInvokeOnMainThread(() =>
  1548. {
  1549. foreach (ToolEntry toolEntry in toolEntries)
  1550. {
  1551. toolEntry.Margin = new Thickness(5, 0, 5, 0);
  1552. flexLayout.Children.Add(toolEntry);
  1553. }
  1554. SearchForNewNotifications();
  1555. AddBlanks();
  1556. });
  1557. }
  1558. private void AddBlanks()
  1559. {
  1560. for (int x = 0; x < 6; x++)
  1561. {
  1562. ToolEntry toolEntry = new ToolEntry(true);
  1563. toolEntry.Margin = new Thickness(5, 0, 5, 0);
  1564. flexLayout.Children.Add(toolEntry);
  1565. }
  1566. }
  1567. private void Settings_Tapped(object sender, EventArgs e)
  1568. {
  1569. try
  1570. {
  1571. Settings settingsform = new Settings();
  1572. settingsform.Disappearing += (object sender2, EventArgs e2) =>
  1573. {
  1574. settingsform = (Settings)sender2;
  1575. if (settingsform.SettingsChanged)
  1576. Navigation.PopModalAsync();
  1577. };
  1578. Navigation.PushAsync(settingsform);
  1579. }
  1580. catch { }
  1581. }
  1582. #endregion
  1583. }
  1584. }