MainPage.xaml.cs 66 KB

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