MainPage.xaml.cs 74 KB

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