MainPage.xaml.cs 68 KB

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