MainPage.xaml.cs 66 KB

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