MainPage.xaml.cs 71 KB

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