MainPage.xaml.cs 68 KB

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