12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using Xamarin.Forms;
- using InABox.Core;
- using InABox.Configuration;
- using InABox.Clients;
- using InABox.Mobile;
- using Comal.Classes;
- using XF.Material.Forms.UI.Dialogs;
- using comal.timesheets.CustomControls;
- using comal.timesheets.StoreRequis;
- using PRSSecurity = InABox.Core.Security;
- using Plugin.LocalNotification;
- using comal.timesheets.Tasks;
- using System.IO;
- namespace comal.timesheets
- {
- public partial class MainPage : ContentPage
- {
- #region Fields
- List<ToolEntry> toolEntries = new List<ToolEntry>();
- private TimeSheet _timesheet = null;
- private Employee _employee = null;
- private CoreTable _jobs = null;
- public bool SettingsChanged { get; private set; }
- bool bUpdatingTimesheet = false;
- bool firstLoad = true;
- bool recentlyAskedToUpdate = true;
- int updateCounter;
- public static ConnectionSettings connectionSettings = null;
- bool midnightTimerOn = false;
- DateTime oneSecondBeforeMidnight = DateTime.Today.AddSeconds(864399);
- bool clockedOffInLast5Seconds = false;
- bool bRecentlyUpdatedTiles = false;
- bool bSharedDeviceFirstLoad = true;
- bool bSharedDevice = false;
- int NumberOfNotfications = 0;
- private JobShell _job = new JobShell();
- string deviceName = "";
- string matchedDeviceName = "";
- int notCount = 1;
- Assignment currentAssignment = null;
- #endregion
- #region Constructor
- public MainPage()
- {
- InitializeComponent();
- try
- {
- App.GPS.OnLocationFound += LocationFound;
- App.GPS.OnLocationError += LocationError;
- App.Bluetooth.OnScanFinished += ScanFinished;
- App.Data.DataChanged += DataChanged;
- App.Data.DataRefreshed += DataRefreshed;
- GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();
- GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();
- App.Data.Employee.ID = GlobalVariables.EmpID;
- App.Data.Employee.Name = GlobalVariables.EmpName;
- MessagingCenter.Subscribe<App>(this, App.MessageOnResume,
- (o) =>
- {
- if (!App.GPS.RecentlyLocated)
- App.GPS.GetLocation();
- RefreshScreen();
- }
- );
- _timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
- _employee = App.Data.Employee;
- _jobs = App.Data.Jobs;
- deviceName = MobileUtils.GetDeviceID();
- LoadCacheLists();
- InitToolEntryList();
- Timer t = new Timer(RecentlyAskedToUpdateTimer, null, 600000, 600000); //user is reminded to update when opening screen after timer of 10 minutes
- updateCounter = 1; //user is forced to update after 3rd reminder
- Timer t1 = new Timer(RecentlyUpdatedTilesTimer, null, 30000, 30000);
- //bluetooth data is allowed to upload once every minute, notifications refreshing is piggybacked to this too
- InitNotificationCentre();
- firstLoad = false;
- //if (GlobalVariables.EmpID == Guid.Parse("40f6ccd9-5272-4b1a-99bf-de7542205aac"))
- //RunCustomScript();
- NotifyChanges();
- CheckCurrentAssignment();
- }
- catch (Exception e)
- {
- }
- NavigationPage.SetHasBackButton(this, false);
- }
- private void CheckCurrentAssignment()
- {
- Task.Run(() =>
- {
- Thread.Sleep(5000);
- StartAssignmentTimer();
- CoreTable table = new Client<Assignment>().Query(
- new Filter<Assignment>(x => x.EmployeeLink.ID).IsEqualTo(GlobalVariables.EmpID)
- .And(x => x.Date).IsEqualTo(DateTime.Today.Date)
- .And(x => x.Actual.Finish).IsEqualTo(null),
- null,
- new SortOrder<Assignment>(x => x.Actual.Start, SortDirection.Ascending));
- if (!table.Rows.Any())
- {
- _job.OnJobIDChanged += OnJobIDChanged;
- return;
- }
- var assgn = table.Rows.LastOrDefault().ToObject<Assignment>();
- Device.BeginInvokeOnMainThread(async () =>
- {
- string chosenOption = await DisplayActionSheet("Continue with current unfinished assignment?", "Cancel", null, "Yes", "No");
- switch(chosenOption)
- {
- case "Yes":
- currentAssignment = assgn;
- SaveCurrentAssignment("PRS Mobile main screen - saving assignment on re-login to App");
- if (currentAssignment.JobLink.ID != Guid.Empty)
- {
- _job.ID = currentAssignment.JobLink.ID;
- var job = new Client<Job>().Query(new Filter<Job>(x => x.ID).IsEqualTo(_job.ID)).Rows.FirstOrDefault().ToObject<Job>();
- _job.JobNumber = job.JobNumber;
- _job.Name = job.Name;
- RefreshJobBtn();
- _job.OnJobIDChanged += OnJobIDChanged;
- }
- break;
- default:
- _job.OnJobIDChanged += OnJobIDChanged;
- break;
- };
- });
- });
- }
- private void RunCustomScript()
- {
- }
- private void NotifyChanges()
- {
- Task.Run(() =>
- {
- string changes = NotifyMobileChanges.Notifiy();
- if (!string.IsNullOrWhiteSpace(changes))
- Device.BeginInvokeOnMainThread(() =>
- {
- DisplayAlert("Latest changes", changes, "OK");
- });
- });
- }
- #endregion
- #region OnAppearing and Display
- protected override void OnAppearing()
- {
- if (!App.IsUserLoggedIn)
- {
- Navigation.PopAsync();
- return;
- }
- //if (Application.Current.Properties.ContainsKey("IsSharedDevice"))
- //{
- // if (Application.Current.Properties["IsSharedDevice"].Equals("True"))
- // {
- // bSharedDevice = true;
- // if (!bSharedDeviceFirstLoad)
- // {
- // App.LogoutUser();
- // Navigation.PopToRootAsync();
- // }
- // else
- // {
- // bSharedDeviceFirstLoad = false;
- // clockOnButton.IsEnabled = false;
- // clockOnButton.Text = "Shared Device";
- // clockOnButton.BackgroundColor = Color.CornflowerBlue;
- // CurrentLocation.IsVisible = false;
- // jobBtn.IsVisible = false;
- // addNoteBtn.IsVisible = false;
- // Grid.SetRowSpan(flexLayoutScrollView, 3);
- // Grid.SetRow(flexLayoutScrollView, 1);
- // Timer t = new Timer(AutoLogoutUser, null, 600000, Timeout.Infinite);
- // }
- // }
- // else
- // bSharedDevice = false;
- //}
- //getting strange results from .IsAllowed
- //if (!PRSSecurity.IsAllowed<CanBypassTimeBench>())
- //{
- // clockOnButton.IsVisible = false;
- // jobBtn.IsVisible = false;
- // addNoteBtn.IsVisible = false;
- // CurrentLocation.IsVisible = false;
- // row0.Height = 0;
- // row1.Height = 0;
- // row2.Height = 0;
- // ForceLayout();
- //}
- if (!firstLoad)
- RefreshScreen();
- Task.Run(async () =>
- {
- bool isLatest = true;
- try
- {
- isLatest = await MobileUtils.AppVersion.IsUsingLatestVersion();
- }
- catch (Exception eLatest)
- {
- if (!recentlyAskedToUpdate)
- {
- Device.BeginInvokeOnMainThread(() =>
- {
- });
- recentlyAskedToUpdate = true;
- }
- string s = eLatest.Message;
- }
- if (!isLatest)
- {
- if (!recentlyAskedToUpdate)
- {
- string latestVersionNumber = await MobileUtils.AppVersion.GetLatestVersionNumber();
- if (updateCounter < 3)
- {
- Device.BeginInvokeOnMainThread(async () =>
- {
- string chosenOption = await DisplayActionSheet(String.Format("Version {0} Available. Update now?", latestVersionNumber), "You will be reminded again in 10 minutes.", null, "Yes", "No");
- switch (chosenOption)
- {
- case "No":
- break;
- case "Cancel":
- break;
- case "Yes":
- Dispatcher.BeginInvokeOnMainThread(() => { MobileUtils.AppVersion.OpenAppInStore(); });
- break;
- default:
- break;
- }
- });
- }
- else if (updateCounter >= 3)
- {
- Device.BeginInvokeOnMainThread(() =>
- {
- DisplayAlert(String.Format("Version {0} Available", latestVersionNumber), "Please update your software to the latest version.", "OK")
- .ContinueWith((Task task) =>
- {
- Dispatcher.BeginInvokeOnMainThread(() => { MobileUtils.AppVersion.OpenAppInStore(); });
- });
- });
- }
- recentlyAskedToUpdate = true;
- updateCounter++;
- }
- }
- });
- base.OnAppearing();
- }
- private void RecentlyAskedToUpdateTimer(object o)
- {
- recentlyAskedToUpdate = false;
- }
- private void AutoLogoutUser(object o)
- {
- App.LogoutUser();
- Navigation.PopToRootAsync();
- }
- private void RefreshScreen()
- {
- //if (bSharedDevice)
- // return;
- try
- {
- Device.BeginInvokeOnMainThread(() =>
- {
- homeScreenGrid.RaiseChild(CurrentLocation);
- bBusy = true;
- if (GlobalVariables.EmpID == Guid.Empty)
- {
- GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();
- GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();
- }
- clockOnButton.IsEnabled = false;
- bool PRSReady = (App.Data.Employee != null) && (App.Data.TimeSheets != null);
- bool GateReady = CheckLocation();
- CurrentLocation.Text = DisplayAddress();
- if (CurrentLocation.Text.Contains("ERROR"))
- CurrentLocation.Text = "Unknown Address";
- Title = null;
- Title = App.Data.Employee != null ? App.Data.Employee.Name : "";
- CoreRow timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault();
- clockOnButton.Text = PRSReady && GateReady ? timesheet == null ? "CLOCK ON" : "CLOCK OFF" : "PLEASE WAIT";
- clockOnButton.IsEnabled = PRSReady && GateReady;
- clockOnButton.BackgroundColor = PRSReady && GateReady ? timesheet == null ? Color.FromHex("#e6e6fa") : Color.FromHex("#15C7C1") : Color.Gainsboro;
- clockOnButton.BorderColor = PRSReady && GateReady ? timesheet == null ? Color.Black : Color.FromHex("#15C7C1") : Color.Gainsboro;
- if (clockOnButton.Text == "CLOCK OFF")
- {
- addNoteBtn.IsEnabled = true;
- if (GlobalVariables.JobsLoaded)
- jobBtn.IsEnabled = true;
- }
- else
- {
- addNoteBtn.IsEnabled = false;
- jobBtn.IsEnabled = false;
- }
- //if (firstLoad)
- // RefreshJobFromTimeSheet(timesheet);
- RefreshJobBtn();
- homeScreenGrid.RaiseChild(CurrentLocation);
- firstLoad = false;
- bBusy = false;
- });
- }
- catch (Exception e)
- {
- }
- //CurrentLocation.IsEnabled = PRSReady && GateReady;
- }
- private void RefreshJobBtn()
- {
- if (_job.ID == Guid.Empty)
- jobBtn.Text = "No Job Selected";
- else if(!string.IsNullOrWhiteSpace(_job.JobNumber))
- jobBtn.Text = "Job: " + _job.JobNumber;
- }
- private void RefreshJobFromTimeSheet(CoreRow timesheet)
- {
- Guid jobid = timesheet == null ? Guid.Empty : timesheet.Get<TimeSheet, Guid>(x => x.JobLink.ID);
- if (!jobid.Equals(Guid.Empty))
- {
- jobBtn.Text = String.Format("{0}: {1}", timesheet.Get<TimeSheet, String>(x => x.JobLink.JobNumber), timesheet.Get<TimeSheet, String>(x => x.JobLink.Name));
- _job.ID = timesheet == null ? Guid.Empty : timesheet.Get<TimeSheet, Guid>(x => x.JobLink.ID);
- _job.JobNumber = timesheet == null ? String.Empty : timesheet.Get<TimeSheet, String>(x => x.JobLink.JobNumber);
- _job.Name = timesheet == null ? String.Empty : timesheet.Get<TimeSheet, String>(x => x.JobLink.Name);
- }
- else
- {
- jobBtn.Text = "No Job Selected";
- _job = new JobShell();
- }
- }
- #endregion
- #region Clock on/off
- private void DataChanged(object sender, Type type, Exception e)
- {
- //if (bSharedDevice)
- // return;
- Device.BeginInvokeOnMainThread(() =>
- {
- if (e != null)
- {
- //DisplayAlert("Connection error with server - double check your connection", e.Message, "OK");
- }
- else
- RefreshScreen();
- });
- }
- private void DataRefreshed()
- {
- //if (bSharedDevice)
- // return;
- Device.BeginInvokeOnMainThread(() => { RefreshScreen(); });
- }
- bool bBusy = false;
- async void ClockOnOff_Clicked(object sender, System.EventArgs e)
- {
- if (bBusy)
- return;
- bBusy = true;
- string chosenOption = "Continue";
- if (clockOnButton.Text == "CLOCK OFF")
- {
- chosenOption = await DisplayActionSheet("Clock off?", "Cancel", null, "Continue", "Cancel");
- }
- switch (chosenOption)
- {
- case "Continue":
- break;
- case "Cancel":
- bBusy = false;
- return;
- break;
- default:
- bBusy = false;
- return;
- break;
- }
- if (clockOnButton.Text == "CLOCK ON" && clockedOffInLast5Seconds)
- {
- bBusy = false;
- return;
- }
- try
- {
- using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
- {
- InABox.Core.Location here = new InABox.Core.Location()
- {
- Latitude = App.GPS.Latitude,
- Longitude = App.GPS.Longitude,
- Timestamp = DateTime.Now
- };
- TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
- if (timesheet != null)
- {
- if (timesheet.ID != Guid.Empty)
- {
- if (ZeroLengthTimesheet())
- {
- bUpdatingTimesheet = true;
- new Client<TimeSheet>().Delete(timesheet, "Deleted due to zero duration timesheet");
- App.Data.TimeSheets.Rows.Clear();
- }
- else
- {
- FinishTimeSheet(timesheet, here);
- }
- }
- }
- else
- {
- Guid jobid = Guid.Empty;
- String jobnumber = "";
- String jobname = "";
- if (!App.Data.CanBypassGates)
- {
- CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
- if (row != null)
- {
- jobid = row.Get<JobTracker, Guid>(x => x.JobLink.ID);
- jobnumber = row.Get<JobTracker, String>(x => x.JobLink.JobNumber);
- jobname = row.Get<JobTracker, String>(x => x.JobLink.Name);
- }
- CreateTimeSheet(jobid, jobnumber, jobname, here, App.GPS.Address, "Clocking On");
- }
- else
- {
- if ((!App.GPS.Latitude.Equals(0.0F)) && (!App.GPS.Longitude.Equals(0.0F)))
- {
- ChooseNearbyJob(here);
- }
- }
- }
- RefreshScreen();
- }
- }
- catch (Exception e2)
- {
- }
- bBusy = false;
- }
- #endregion
- #region Bluetooth
- private async void UploadTiles()
- {
- try
- {
- if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))
- return;
- if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)
- return;
- if (bRecentlyUpdatedTiles)
- return;
- bRecentlyUpdatedTiles = true;
- await Task.Run(() =>
- {
- InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };
- curlocation.Timestamp = DateTime.Now;
- List<GPSTrackerLocation> trackersToUpdate = new List<GPSTrackerLocation>();
- foreach (String id in App.Bluetooth.DetectedBlueToothMACAddresses)
- {
- GPSTracker tracker = GlobalVariables.GPSTrackerCache.Find(x => x.DeviceID.Equals(id));
- bool stale = tracker.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0));
- bool moved = tracker.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;
- if (stale || moved)
- {
- GlobalVariables.GPSTrackerCache.Remove(tracker);
- tracker.Location = curlocation;
- GlobalVariables.GPSTrackerCache.Add(tracker);
- //cache is updated
- GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
- gpsTrackerLocation.DeviceID = tracker.DeviceID;
- gpsTrackerLocation.Location.Timestamp = tracker.Location.Timestamp;
- gpsTrackerLocation.Location = curlocation;
- trackersToUpdate.Add(gpsTrackerLocation);
- }
- }
- if (trackersToUpdate.Any())
- {
- if (ClientFactory.UserGuid != Guid.Empty)
- new Client<GPSTrackerLocation>().Save(trackersToUpdate, "Updating Bluetooth Device Locations");
- }
- App.Bluetooth.DetectedBlueToothMACAddresses.Clear();
- }
- );
- }
- catch (Exception e)
- {
- }
- //if ((master != null) && (master.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0))))
- //{
- // GPSTrackerLocation device = new GPSTrackerLocation();
- // device.DeviceID = MobileUtils.GetDeviceID();
- // device.Location.Latitude = App.GPS.Latitude;
- // device.Location.Longitude = App.GPS.Longitude;
- // device.Location.Timestamp = DateTime.Now;
- // locations.Add(device);
- // //device.BatteryLevel = ((double)CrossBattery.Current.RemainingChargePercent);
- // //new Client<GPSTrackerLocation>().Save(device, "Updating Device Location"); //, SaveTrackerCallback);
- //}
- #region OLD
- //for (int i = 0; i < App.Bluetooth.Devices.Length; i++)
- //{
- // String id = App.Bluetooth.Devices[i];
- // int level = App.Bluetooth.BatteryLevels[i];
- // var btmaster = trackers.FirstOrDefault(x => x.DeviceID.Equals(id));
- // if ((btmaster != null) && (!locations.Any(x => x.DeviceID.Equals(btmaster.DeviceID))))
- // {
- // bool stale = btmaster.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0));
- // bool moved = btmaster.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;
- // if (stale || moved)
- // {
- // GPSTrackerLocation location = new GPSTrackerLocation();
- // location.DeviceID = id;
- // location.Location.Latitude = App.GPS.Latitude;
- // location.Location.Longitude = App.GPS.Longitude;
- // location.Location.Timestamp = DateTime.Now;
- // location.BatteryLevel = level;
- // locations.Add(location);
- // }
- // }
- // //new Client<GPSTrackerLocation>().Save(location, "Found Kontakt Device"); //, SaveTrackerCallback);
- //}
- //if (locations.Any())
- // new Client<GPSTrackerLocation>().Save(locations, "Updating Bluetooth Device Locations", (o, e) => { });
- #endregion
- }
- private void RecentlyUpdatedTilesTimer(object o)
- {
- bRecentlyUpdatedTiles = false;
- App.Data.Refresh(true);
- SearchForNewNotifications();
- }
- private void LocationFound(LocationServices sender)
- {
- //if (bSharedDevice)
- // return;
- if (App.Bluetooth.RecentlyScanned)
- UploadTiles();
- try
- {
- TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
- if (timesheet != null)
- {
- if (timesheet.StartLocation.Latitude.Equals(0.0F) && timesheet.StartLocation.Longitude.Equals(0.0F))
- {
- timesheet.StartLocation.Latitude = sender.Latitude;
- timesheet.StartLocation.Longitude = sender.Longitude;
- timesheet.StartLocation.Timestamp = sender.TimeStamp;
- timesheet.Address = sender.Address;
- new Client<TimeSheet>().Save(timesheet, "Updating Timesheet with GPS Coordinates", (o, e) => { });
- }
- }
- if (!string.IsNullOrWhiteSpace(matchedDeviceName))
- {
- InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };
- curlocation.Timestamp = DateTime.Now;
- GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
- gpsTrackerLocation.DeviceID = matchedDeviceName;
- gpsTrackerLocation.Location.Timestamp = curlocation.Timestamp;
- gpsTrackerLocation.Location = curlocation;
- new Client<GPSTrackerLocation>().Save(gpsTrackerLocation, "Updated company device location from Timebench");
- }
- Device.BeginInvokeOnMainThread(() =>
- {
- RefreshScreen();
- });
- }
- catch { }
- }
- private void LocationError(LocationServices sebder, Exception error)
- {
- }
- private void ScanFinished(Bluetooth sender)
- {
- try
- {
- //if (bSharedDevice)
- // return;
- Device.BeginInvokeOnMainThread(() =>
- {
- RefreshScreen();
- //if (Button2.BackgroundColor == Color.WhiteSmoke)
- // Button2.BackgroundColor = Color.Red;
- //else
- // Button2.BackgroundColor = Color.WhiteSmoke;
- });
- if (App.GPS.RecentlyLocated)
- UploadTiles();
- }
- catch { }
- }
- #endregion
- #region Utilities
- private void OnJobIDChanged(Guid jobid)
- {
- if (currentAssignment == null)
- CreateNewAssignment(jobid);
- else
- {
- SaveCurrentAssignment("PRS Mobile main screen - saving assignment on job change", true);
- CreateNewAssignment(jobid);
- }
- }
- private void StartAssignmentTimer()
- {
- Timer t = new Timer(AssignmentTimerCallback, null, 300000, 300000);
- }
- private void AssignmentTimerCallback(object state)
- {
- if (currentAssignment != null)
- SaveCurrentAssignment("PRS MObile main screen - Saving assignment on 5 minute timer");
- }
- private void CreateNewAssignment(Guid jobid)
- {
- currentAssignment = new Assignment { Date = DateTime.Now.Date };
- currentAssignment.EmployeeLink.ID = GlobalVariables.EmpID;
- currentAssignment.JobLink.ID = jobid;
- currentAssignment.Actual.Start = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay;
- currentAssignment.Booked.Start = currentAssignment.Actual.Start;
- currentAssignment.Booked.Finish = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay.Add(new TimeSpan(0, 5, 0));
- var job = new Client<Job>().Query(new Filter<Job>(x => x.ID).IsEqualTo(jobid)).Rows.FirstOrDefault().ToObject<Job>();
- currentAssignment.Title = "Clocking on to job " + job.Name + " (" + job.JobNumber + ") on PRS Mobile";
- new Client<Assignment>().Save(currentAssignment, "Changed job on mobile - creating new assignment");
- }
- private void SaveCurrentAssignment(string auditnote, bool complete = false)
- {
- if (!complete)
- currentAssignment.Booked.Finish = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay;
- else
- currentAssignment.Actual.Finish = RoundToNearestInterval(DateTime.Now, new TimeSpan(0, 5, 0)).TimeOfDay;
- new Client<Assignment>().Save(currentAssignment, auditnote);
- }
- static DateTime RoundToNearestInterval(DateTime dt, TimeSpan d)
- {
- int f = 0;
- double m = (double)(dt.Ticks % d.Ticks) / d.Ticks;
- if (m >= 0.5)
- f = 1;
- return new DateTime(((dt.Ticks / d.Ticks) + f) * d.Ticks);
- }
- private void InitNotificationCentre()
- {
- try
- {
- LocalNotificationCenter.Current.NotificationActionTapped += (Plugin.LocalNotification.EventArgs.NotificationActionEventArgs e) =>
- {
- string data = e.Request.ReturningData;
- int index = data.IndexOf("$");
- Guid ID = Guid.Parse(data.Remove(index));
- string type = data.Substring(index + 1);
- if (type == "Comal.Classes.Kanban")
- {
- Device.BeginInvokeOnMainThread(() =>
- {
- AddEditTask page = new AddEditTask(ID);
- Navigation.PushAsync(page);
- });
- }
- else if (type == "Comal.Classes.Delivery")
- {
- Device.BeginInvokeOnMainThread(() =>
- {
- DeliveryDetails page = new DeliveryDetails(ID);
- Navigation.PushAsync(page);
- });
- }
- };
- }
- catch { }
- }
- private async void SearchForNewNotifications()
- {
- //notifications poll reliably in the background for Anroid, unreliable for iOS due to difficulty with cross-platform plugins for notifications
- try
- {
- await Task.Run(() =>
- {
- if (ClientFactory.UserGuid != Guid.Empty)
- {
- CoreTable table = new Client<Notification>().Query
- (new Filter<Notification>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid).And(X => X.Closed).IsEqualTo(DateTime.MinValue),
- new Columns<Notification>(
- x => x.ID, //0
- x => x.Sender.Name, //1
- x => x.Title, //2
- x => x.Created, //3
- x => x.Description, //4
- x => x.EntityType, //5
- x => x.EntityID //6
- )
- );
- if (NumberOfNotfications == table.Rows.Count()) //no new notifications or none present at all
- return;
- else //new notifications or previous notifications have now been dismissed
- {
- NumberOfNotfications = table.Rows.Count();
- RefreshOnNotificationsChange();
- CheckNotificationsPushed(table);
- }
- }
- });
- }
- catch { }
- }
- private void RefreshOnNotificationsChange()
- {
- try
- {
- int index = toolEntries.FindIndex(x => x.Text.Equals("Notifications"));
- toolEntries.RemoveAt(index);
- string notificationsString = "";
- if (NumberOfNotfications != 0)
- {
- notificationsString = NumberOfNotfications.ToString();
- }
- ToolEntry Notifications = new ToolEntry(notificationsString)
- {
- Text = "Notifications",
- Image = "notifications"
- };
- Notifications.OnTapped += (async (object sender, EventArgs e) =>
- {
- using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
- {
- NotificationList notificationList = new NotificationList();
- notificationList.NotificationsClosed += (n) =>
- {
- NumberOfNotfications = n;
- RefreshOnNotificationsChange();
- };
- Navigation.PushAsync(notificationList);
- }
- });
- toolEntries.Insert(index, Notifications);
- Device.BeginInvokeOnMainThread(() =>
- {
- flexLayout.Children.RemoveAt(index);
- flexLayout.Children.Insert(index, toolEntries[index]);
- });
- }
- catch { }
- }
- private void CheckNotificationsPushed(CoreTable table)
- {
- try
- {
- if (!Application.Current.Properties.ContainsKey("LastPushedNotifications"))
- {
- Application.Current.Properties.Add("LastPushedNotifications", DateTime.Now);
- }
- DateTime lastPushed = DateTime.Parse(Application.Current.Properties["LastPushedNotifications"].ToString());
- List<NotificationShell> toNotify = new List<NotificationShell>();
- foreach (CoreRow row in table.Rows)
- {
- List<object> list = row.Values;
- DateTime created = DateTime.Parse(list[3].ToString());
- if (created > new DateTime(2022, 8, 22)) // prevent spam from buildup of old notifications before this is released
- {
- if (created > lastPushed)
- {
- if (list[1] == null) list[1] = "";
- if (list[2] == null) list[2] = "";
- if (list[3] == null) list[3] = DateTime.MinValue;
- if (list[4] == null) list[4] = "";
- if (list[5] == null) list[5] = "";
- if (list[6] == null) list[6] = Guid.Empty;
- NotificationShell shell = new NotificationShell
- {
- ID = Guid.Parse(list[0].ToString()),
- Sender = list[1].ToString(),
- Title = list[2].ToString(),
- Created = DateTime.Parse(list[3].ToString()),
- EntityType = list[5].ToString(),
- EntityID = Guid.Parse(list[6].ToString())
- };
- toNotify.Add(shell); //add notification to be pushed
- }
- }
- }
- if (toNotify.Count > 0)
- PushNotificationsAsync(toNotify);
- }
- catch { }
- }
- private async Task PushNotificationsAsync(List<NotificationShell> shells)
- {
- try
- {
- int count = 1;
- foreach (NotificationShell shell in shells)
- {
- var notification = new NotificationRequest
- {
- BadgeNumber = 1,
- Description = shell.Title,
- Title = "New PRS Notification: ",
- ReturningData = shell.EntityID.ToString() + "$" + shell.EntityType,
- NotificationId = count,
- };
- count++;
- NotificationImage img = new NotificationImage();
- img.ResourceName = "icon16.png";
- notification.Image = img;
- await LocalNotificationCenter.Current.Show(notification);
- //if (Device.RuntimePlatform.Equals(Device.iOS))
- //{
- // var content = new UNMutableNotificationContent();
- // content.Title = "New PRS Notification: ";
- // content.Subtitle = shell.Title;
- // content.Body = "";
- // content.Badge = 1;
- // var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
- // var requestID = "request";
- // var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
- // UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
- // {
- // if (err != null)
- // {
- // Do something with error...
- // }
- // });
- //}
- }
- Application.Current.Properties["LastPushedNotifications"] = DateTime.Now;
- }
- catch { }
- }
- private void StartMidnightTimeSheetTimer()
- {
- midnightTimerOn = true;
- int msUntilMidnight = (int)(oneSecondBeforeMidnight - DateTime.Now).TotalMilliseconds;
- Timer midnightTimer = new Timer(MidnightTimerCallback, null, msUntilMidnight, Timeout.Infinite);
- }
- private void MidnightTimerCallback(object o)
- {
- try
- {
- //if (bSharedDevice)
- // return;
- if (midnightTimerOn)
- {
- if (clockOnButton.Text == "CLOCK OFF")
- {
- InABox.Core.Location here = new InABox.Core.Location()
- {
- Latitude = App.GPS.Latitude,
- Longitude = App.GPS.Longitude,
- Timestamp = DateTime.Now
- };
- TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
- if (timesheet != null)
- {
- if (timesheet.ID != Guid.Empty)
- {
- if (ZeroLengthTimesheet())
- {
- bUpdatingTimesheet = true;
- new Client<TimeSheet>().Delete(timesheet, "Deleted due to zero duration timesheet");
- App.Data.TimeSheets.Rows.Clear();
- }
- else
- {
- timesheet.Finish = new TimeSpan(23, 59, 59);
- timesheet.FinishLocation = here;
- bUpdatingTimesheet = true;
- new Client<TimeSheet>().Save(timesheet, "Auto Close timesheet at Midnight");
- App.Data.TimeSheets.Rows.Clear();
- Guid jobid = Guid.Empty;
- String jobnumber = "";
- String jobname = "";
- if (!App.Data.CanBypassGates)
- {
- CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
- if (row != null)
- {
- jobid = row.Get<JobTracker, Guid>(x => x.JobLink.ID);
- jobnumber = row.Get<JobTracker, String>(x => x.JobLink.JobNumber);
- jobname = row.Get<JobTracker, String>(x => x.JobLink.Name);
- }
- CreateTimeSheet(jobid, jobnumber, jobname, here, App.GPS.Address, "Clocking On");
- }
- else
- {
- if ((!App.GPS.Latitude.Equals(0.0F)) && (!App.GPS.Longitude.Equals(0.0F)))
- {
- ChooseNearbyJob(here);
- }
- }
- }
- }
- }
- }
- }
- }
- catch { }
- }
- private void FinishTimeSheet(TimeSheet timesheet, InABox.Core.Location here)
- {
- try
- {
- TimeSpan tod = DateTime.Now - DateTime.Today;
- timesheet.Finish = new TimeSpan(tod.Hours, tod.Minutes, 0);
- timesheet.FinishLocation = here;
- bUpdatingTimesheet = true;
- new Client<TimeSheet>().Save(timesheet, "Clocking Off");
- App.Data.TimeSheets.Rows.Clear();
- midnightTimerOn = false;
- Timer last60Seconds = new Timer(Last60SecondsTimerCallBack, null, 5000, Timeout.Infinite);
- clockedOffInLast5Seconds = true;
- if (currentAssignment != null)
- {
- SaveCurrentAssignment("PRS Mobile - clocking off", true);
- currentAssignment = null;
- }
- }
- catch { }
- }
- private void Last60SecondsTimerCallBack(object o)
- {
- clockedOffInLast5Seconds = false;
- }
- private async void ChooseNearbyJob(InABox.Core.Location here)
- {
- try
- {
- JobShell selectedJob = new JobShell();
- Dictionary<string, JobShell> nearbyJobs = new Dictionary<string, JobShell>();
- foreach (CoreRow row in App.Data.Jobs.Rows)
- {
- 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) };
- double distance = here.DistanceTo(jobLocation, UnitOfLength.Kilometers);
- if (distance < 1.0F)
- {
- JobShell jobShell = new JobShell();
- jobShell.ID = row.Get<Job, Guid>(X => X.ID);
- jobShell.JobNumber = row.Get<Job, String>(x => x.JobNumber);
- jobShell.Name = row.Get<Job, String>(x => x.Name);
- jobShell.DisplayName = jobShell.JobNumber + " " + jobShell.Name;
- nearbyJobs.Add(jobShell.DisplayName, jobShell);
- }
- }
- if (nearbyJobs.Count > 1)
- {
- string[] array = nearbyJobs.Keys.ToArray();
- string chosenOption = await DisplayActionSheet("Choose job site", "Cancel", null, array);
- if (string.IsNullOrEmpty(chosenOption) || chosenOption.Equals("Cancel"))
- {
- CreateTimeSheet(selectedJob.ID, selectedJob.JobNumber, selectedJob.Name, here, App.GPS.Address, "Clocking On");
- return;
- }
- else
- {
- selectedJob = nearbyJobs[chosenOption];
- }
- }
- else if (nearbyJobs.Count == 1)
- {
- selectedJob = nearbyJobs.Values.First();
- }
- CreateTimeSheet(selectedJob.ID, selectedJob.JobNumber, selectedJob.Name, here, App.GPS.Address, "Clocking On");
- }
- catch { }
- }
- void AddNote_Tapped(System.Object sender, System.EventArgs e)
- {
- try
- {
- TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
- if (timesheet == null)
- return;
- var notepage = new NotePage(timesheet);
- Navigation.PushAsync(notepage);
- }
- catch { }
- }
- private void JobBtn_Tapped(object sender, EventArgs e)
- {
- try
- {
- JobSelectionPage jobSelectionPage = new JobSelectionPage();
- jobSelectionPage.OnItemSelected += (() =>
- {
- _job.ID = jobSelectionPage.Job.ID;
- _job.JobNumber = jobSelectionPage.Job.JobNumber;
- _job.Name = jobSelectionPage.Job.Name;
- RefreshScreen();
- JobPage_OnItemSelected(jobSelectionPage.Job);
- });
- Navigation.PushAsync(jobSelectionPage);
- }
- catch { }
- }
- private void JobPage_OnItemSelected(JobShell job)
- {
- //try
- //{
- // TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();
- // if (timesheet == null)
- // return;
- // String auditmessage = String.Format("Changed Selected Job to: {0}: {1}", timesheet.JobLink.JobNumber, timesheet.JobLink.Name);
- // if (ZeroLengthTimesheet())
- // {
- // timesheet.JobLink.ID = job.ID;
- // timesheet.JobLink.JobNumber = job.JobNumber;
- // timesheet.JobLink.Name = job.Name;
- // bUpdatingTimesheet = true;
- // new Client<TimeSheet>().Save(timesheet, auditmessage);
- // Device.BeginInvokeOnMainThread(() =>
- // {
- // if (timesheet.JobLink.ID != Guid.Empty)
- // {
- // jobBtn.Text = "(" + timesheet.JobLink.JobNumber + ") " + timesheet.JobLink.Name;
- // }
- // else
- // {
- // jobBtn.Text = "No Job Selected";
- // }
- // });
- // }
- // else
- // {
- // InABox.Core.Location here = new InABox.Core.Location()
- // {
- // Latitude = App.GPS.Latitude,
- // Longitude = App.GPS.Longitude,
- // Timestamp = DateTime.Now
- // };
- // TimeSpan tod = DateTime.Now - DateTime.Today;
- // timesheet.Finish = new TimeSpan(tod.Hours, tod.Minutes, 0);
- // timesheet.FinishLocation = here;
- // new Client<TimeSheet>().Save(timesheet, "Changing Job");
- // CreateTimeSheet(
- // job.ID,
- // job.JobNumber,
- // job.Name,
- // here,
- // App.GPS.Address,
- // auditmessage
- // );
- // }
- // RefreshScreen();
- //}
- //catch { }
- }
- private bool CheckTimeSheetAgainstGates(TimeSheet timesheet)
- {
- DateTime now = DateTime.Now;
- //var timesheet = CurrentTimeSheet();
- //Can't confirm if there is no timesheet
- if (timesheet == null)
- return false;
- // Can't confirm if there are no devices
- if (App.Bluetooth.Devices.Length == 0)
- return false;
- if (App.Data.Gates == null)
- return false;
- long tsTicks = timesheet.Date.Add(timesheet.Start).Ticks;
- long btTicks = App.Bluetooth.TimeStamp.Ticks;
- if (Math.Abs(tsTicks - btTicks) > new TimeSpan(0, 2, 0).Ticks)
- return false;
- CoreRow firstgate = null;
- List<String> gates = new List<string>();
- // Scan every located d
- foreach (var device in App.Bluetooth.Devices)
- {
- CoreRow gate = App.Data.Gates?.Rows.FirstOrDefault(r => r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID) == device);
- if (gate != null)
- {
- if ((gate.Get<JobTracker, bool>(x => x.IsJobSite) == true) && (firstgate == null))
- firstgate = gate;
- gates.Add(gate.Get<JobTracker, String>(x => x.Gate));
- }
- }
- if (gates.Any())
- {
- timesheet.Gate = String.Join(", ", gates.OrderBy(x => x));
- if (firstgate != null)
- {
- timesheet.JobLink.ID = firstgate.Get<JobTracker, Guid>(x => x.JobLink.ID);
- timesheet.JobLink.JobNumber = firstgate.Get<JobTracker, String>(x => x.JobLink.JobNumber);
- timesheet.JobLink.Name = firstgate.Get<JobTracker, String>(x => x.JobLink.Name);
- }
- return true;
- //new Client<TimeSheet>().Save(timesheet, "Confirmed Gate Entry by Bluetooth Tracker", (o, e) => { });
- }
- return false;
- }
- private bool ZeroLengthTimesheet()
- {
- try
- {
- if (App.Data.TimeSheets == null)
- return true;
- CoreRow row = App.Data.TimeSheets.Rows.FirstOrDefault();
- if (row == null)
- return true;
- String notes = row.Get<TimeSheet, String>(x => x.Notes);
- if (!String.IsNullOrWhiteSpace(notes))
- return false;
- DateTime date = row.Get<TimeSheet, DateTime>(x => x.Date);
- TimeSpan start = row.Get<TimeSheet, TimeSpan>(x => x.Start);
- if (date.Equals(DateTime.Today))
- {
- TimeSpan tod = DateTime.Now - DateTime.Today;
- var diff = (tod - start).TotalSeconds;
- if (Math.Abs(diff) < 120.0F)
- return true;
- }
- }
- catch { }
- return false;
- }
- private async void CreateTimeSheet(Guid jobid, string jobnumber, String jobname, InABox.Core.Location location, String address, String auditmessage)
- {
- try
- {
- var timesheet = new TimeSheet();
- using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
- {
- timesheet.EmployeeLink.ID = App.Data.Employee.ID;
- timesheet.Date = DateTime.Today;
- TimeSpan tod = DateTime.Now - DateTime.Today;
- tod = new TimeSpan(tod.Hours, tod.Minutes, 0);
- timesheet.Start = tod;
- timesheet.StartLocation = location;
- timesheet.JobLink.ID = jobid;
- timesheet.JobLink.JobNumber = jobnumber;
- timesheet.JobLink.Name = jobname;
- timesheet.Address = address;
- timesheet.SoftwareVersion = MobileUtils.AppVersion.InstalledVersionNumber + GlobalVariables.DeviceString;
- //if (ClientFactory.IsAllowed<AllowTimeSheetRollover>()) CheckTimeSheetAgainstGates(timesheet);
- bUpdatingTimesheet = true;
- new Client<TimeSheet>().Save(timesheet, auditmessage);
- if (timesheet.ID == Guid.Empty)
- {
- DisplayAlert("Error creating new timesheet", "Please check your connection and try again", "OK");
- return;
- }
- StartMidnightTimeSheetTimer();
- // Don't Save Completed Timesheets!
- App.Data.TimeSheets.Rows.Clear();
- if (timesheet.Finish.Ticks == 0L)
- {
- CoreRow row = App.Data.TimeSheets.NewRow();
- App.Data.TimeSheets.LoadRow(row, timesheet);
- App.Data.TimeSheets.Rows.Add(row);
- }
- }
- Device.BeginInvokeOnMainThread(() =>
- {
- if (timesheet.JobLink.ID != Guid.Empty)
- {
- jobBtn.Text = "(" + timesheet.JobLink.JobNumber + ") " + timesheet.JobLink.Name;
- }
- else
- {
- jobBtn.Text = "No Job Selected";
- }
- });
- }
- catch { }
- }
- private bool CheckLocation()
- {
- try
- {
- if (App.Data.CanBypassGates)
- {
- if (App.GPS.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 5, 0)))
- return true;
- else
- return false;
- }
- if (App.Data.Gates == null)
- return false;
- if (App.Bluetooth.TimeStamp < DateTime.Now.Subtract(new TimeSpan(0, 2, 0)))
- return false;
- if (!App.Bluetooth.Devices.Any())
- return false;
- return App.Data.Gates.Rows.Any(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
- }
- catch
- {
- return true;
- }
- }
- private String DisplayAddress()
- {
- try
- {
- bool PRSReady = App.Data.Employee != null; // && (TimeSheet != null); // && (Activities != null);
- if (!PRSReady)
- return "Retrieving Data";
- if (App.Data.CanBypassGates)
- {
- if (App.GPS.TimeStamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0)))
- {
- App.GPS.GetLocation(true);
- return "Searching for GPS";
- }
- else
- return App.GPS.Address;
- }
- else
- {
- // Hmm.. this can/should be simplified
- // if in range of a gate
- // Show Gate Description
- // else
- // "Looking for Gate"
- if ((App.Data.Gates != null) && (App.Bluetooth.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 2, 0))))
- {
- CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));
- if (row != null)
- return row.Get<JobTracker, String>(x => x.Gate);
- //else if ((CurrentTimeSheet() != null) && (!GPS.TimeStamp.IsEmpty()))
- // return GPS.Address;
- else
- return "Looking for Gate";
- }
- //else if ((CurrentTimeSheet() != null) && (GPS.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 2, 0))))
- // return GPS.Address;
- else
- return "Looking for Gate";
- }
- }
- catch
- {
- return "Address error";
- }
- }
- #region Background Loading
- private async Task LoadCacheLists()
- {
- GlobalVariables.ProductsLoaded = false;
- GlobalVariables.JobsLoaded = false;
- GlobalVariables.GetXamarinWidth();
- await CacheLoader.LoadJobs();
- LoadEmployeeShells();
- LoadProducts();
- LoadCompanyDevices();
- LoadBlueToothAddresses();
- //LoadHRToDos(); to be uncommented when ready for roll out
- }
- private void LoadCompanyDevices()
- {
- Task.Run(() =>
- {
- if (!string.IsNullOrWhiteSpace(deviceName) && deviceName != "unknown")
- {
- List<Equipment> companyDevices = new List<Equipment>();
- CoreTable table = new Client<Equipment>().Query
- (
- new Filter<Equipment>(x => x.GroupLink.Code).IsEqualTo("DEVICE"),
- new Columns<Equipment>(
- x => x.TrackerLink.DeviceID
- )
- );
- if (table.Rows.Any())
- {
- foreach (CoreRow row in table.Rows)
- {
- List<object> list = row.Values;
- if (list[0].ToString().Equals(deviceName))
- {
- matchedDeviceName = deviceName;
- }
- }
- }
- }
- });
- }
- private async void LoadEmployeeShells()
- {
- await Task.Run(() =>
- {
- List<EmployeeShell> employeeShells = new List<EmployeeShell>();
- List<EmployeeShell> teamEmployeeShells = new List<EmployeeShell>();
- MultiQuery query = new MultiQuery();
- query.Add<Employee>(
- LookupFactory.DefineFilter<Employee>(),
- new Columns<Employee>(x => x.ID)
- .Add(x => x.Code)
- .Add(x => x.Name),
- LookupFactory.DefineSort<Employee>()
- );
- query.Add<Team>(
- LookupFactory.DefineFilter<Team>(),
- new Columns<Team>(x => x.Name),
- new SortOrder<Team>(x => x.Name)
- );
- query.Add<EmployeeTeam>(
- LookupFactory.DefineFilter<EmployeeTeam>(),
- new Columns<EmployeeTeam>(x => x.EmployeeLink.ID)
- .Add(x => x.EmployeeLink.Code)
- .Add(x => x.EmployeeLink.Name)
- .Add(x => x.TeamLink.Name),
- new SortOrder<EmployeeTeam>(x => x.EmployeeLink.Name)
- );
- query.Query();
- CoreTable emps = query.Get<Employee>();
- foreach (var row in emps.Rows)
- {
- employeeShells.Add(
- new EmployeeShell()
- {
- ID = row.Get<Employee, Guid>(x => x.ID),
- Code = row.Get<Employee, String>(x => x.Code),
- Name = row.Get<Employee, String>(x => x.Name),
- TeamName = "All Staff"
- }
- );
- }
- GlobalVariables.TeamNames = query.Get<Team>().Rows.Select(r => r.Get<Team, String>(c => c.Name)).ToList();
- CoreTable members = query.Get<EmployeeTeam>();
- foreach (var row in members.Rows)
- {
- teamEmployeeShells.Add(
- new EmployeeShell()
- {
- ID = row.Get<EmployeeTeam, Guid>(x => x.EmployeeLink.ID),
- Code = row.Get<EmployeeTeam, String>(x => x.EmployeeLink.Code),
- Name = row.Get<EmployeeTeam, String>(x => x.EmployeeLink.Name),
- TeamName = row.Get<EmployeeTeam, String>(x => x.TeamLink.Name)
- }
- );
- }
- GlobalVariables.EmployeeShells = employeeShells;
- GlobalVariables.TeamEmployeeShells = teamEmployeeShells;
- });
- }
- private async void LoadHRToDos()
- {
- try
- {
- await Task.Run(() =>
- {
- Thread.Sleep(10000);
- if (GlobalVariables.UpdateHRItemsNeedingAttention())
- {
- string message = "You have HR Items needing attention. Open My HR now?";
- Device.BeginInvokeOnMainThread(async () =>
- {
- string chosenOption = await DisplayActionSheet(message, "Cancel", null, "Yes", "No");
- switch (chosenOption)
- {
- case "Cancel":
- break;
- case "No":
- break;
- default:
- break;
- case "Yes":
- MyHRHome myHRHome = new MyHRHome();
- Navigation.PushAsync(myHRHome);
- break;
- }
- });
- }
- });
- }
- catch { }
- }
- private async void LoadProducts()
- {
- try
- {
- await Task.Run(() =>
- {
- ProductsLoader productsLoader = new ProductsLoader();
- //if (ClientFactory.IsAllowed<CanViewStoresRequisitions>())
- //{
- //}
- });
- }
- catch { }
- }
- private async void LoadBlueToothAddresses()
- {
- try
- {
- //if (bSharedDevice)
- // return;
- await Task.Run(() =>
- {
- GlobalVariables.GPSTrackerCache = new List<GPSTracker>();
- CoreTable table = new Client<GPSTracker>().Query(new Filter<GPSTracker>(x => x.Type.Description).Contains("Kontakt"));
- foreach (CoreRow row in table.Rows)
- {
- GPSTracker tracker = row.ToObject<GPSTracker>();
- GlobalVariables.GPSTrackerCache.Add(tracker);
- App.Bluetooth.KnownBlueToothMACAddresses.Add(tracker.DeviceID);
- }
- });
- }
- catch { }
- }
- #endregion
- #endregion
- #region Modules
- public async void InitToolEntryList()
- {
- try
- {
- await Task.Run(() =>
- {
- //Assignments
- ToolEntry Assignments = new ToolEntry
- {
- Text = "Assignments",
- Image = "calendar"
- };
- Assignments.IsVisible = PRSSecurity.CanView<Assignment>();
- Assignments.OnTapped += ((object sender, EventArgs e) =>
- {
- var assignment_form = new AssignmentList();
- Navigation.PushAsync(assignment_form);
- });
- toolEntries.Add(Assignments);
- //Deliveries
- ToolEntry Deliveries = new ToolEntry
- {
- Text = "Deliveries",
- Image = "deliveries"
- };
- Deliveries.IsVisible = PRSSecurity.CanView<Delivery>();
- Deliveries.OnTapped += ((object sender, EventArgs e) =>
- {
- var delivery_form = new DeliveryList();
- Navigation.PushAsync(delivery_form);
- });
- toolEntries.Add(Deliveries);
- //Digital Forms
- ToolEntry Forms = new ToolEntry
- {
- Text = "Forms",
- Image = "forms"
- };
- Forms.IsVisible = PRSSecurity.CanView<DigitalForm>();
- Forms.OnTapped += ((object sender, EventArgs e) =>
- {
- var qaFormPicker = new DigitalFormsPicker();
- Navigation.PushAsync(qaFormPicker);
- });
- toolEntries.Add(Forms);
- //Equipment
- ToolEntry Equipment = new ToolEntry
- {
- Text = "Equipment",
- Image = "digger"
- };
- Equipment.IsVisible = PRSSecurity.CanView<Equipment>();
- Equipment.OnTapped += (async (object sender, EventArgs e) =>
- {
- using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))
- {
- var equipment = new EquipmentModule();
- Navigation.PushAsync(equipment);
- }
- });
- toolEntries.Add(Equipment);
- //InOut
- ToolEntry InOut = new ToolEntry
- {
- Text = "In/Out",
- Image = "inout"
- };
- InOut.IsVisible = PRSSecurity.IsAllowed<CanViewInOutBoard>();
- InOut.OnTapped += ((object sender, EventArgs e) =>
- {
- var staff_form = new StaffStatusPage();
- Navigation.PushAsync(staff_form);
- });
- toolEntries.Add(InOut);
- //Manufacturing
- ToolEntry Manufacturing = new ToolEntry
- {
- Text = "Manufacturing",
- Image = "manufacturingg"
- };
- if (Device.RuntimePlatform.Equals(Device.iOS))
- {
- Manufacturing.Image = "Image";
- }
- Manufacturing.IsVisible = PRSSecurity.IsAllowed<CanViewManufacturingOnMobile>();
- Manufacturing.OnTapped += ((object sender, EventArgs e) =>
- {
- ManufacturingScreen manufacturingScreen = new ManufacturingScreen();
- Navigation.PushAsync(manufacturingScreen);
- });
- toolEntries.Add(Manufacturing);
- //My HR
- ToolEntry MyHR = new ToolEntry
- {
- Text = "My HR",
- Image = "myhr"
- };
- MyHR.OnTapped += ((object sender, EventArgs e) =>
- {
- MyHRHome myHRHome = new MyHRHome();
- Navigation.PushAsync(myHRHome);
- });
- toolEntries.Add(MyHR);
- //Notifications
- ToolEntry Notifications = new ToolEntry()
- {
- Text = "Notifications",
- Image = "notifications"
- };
- Notifications.OnTapped += (object sender, EventArgs e) =>
- {
- NotificationList notificationList = new NotificationList();
- notificationList.NotificationsClosed += (n) =>
- {
- NumberOfNotfications = n;
- RefreshOnNotificationsChange();
- };
- Navigation.PushAsync(notificationList);
- };
- toolEntries.Add(Notifications);
- ToolEntry Products = new ToolEntry()
- {
- Text = "Products",
- Image = "products"
- };
- Products.OnTapped += ((object sender, EventArgs e) =>
- {
- if (GlobalVariables.ProductsLoaded)
- {
- ProductList products = new ProductList(GlobalVariables.ProductShells);
- Navigation.PushAsync(products);
- }
- else
- {
- ProductList products = new ProductList();
- Navigation.PushAsync(products);
- }
- });
- toolEntries.Add(Products);
- //Purchase Orders
- ToolEntry PurchaseOrders = new ToolEntry()
- {
- Text = "Purchase Orders",
- Image = "shoppingcart"
- };
- PurchaseOrders.IsVisible = PRSSecurity.CanView<PurchaseOrder>();
- PurchaseOrders.OnTapped += ((object sender, EventArgs e) =>
- {
- PurchaseOrderModule page = new PurchaseOrderModule();
- Navigation.PushAsync(page);
- });
- toolEntries.Add(PurchaseOrders);
- //Scanner
- ToolEntry Scanner = new ToolEntry
- {
- Text = "Scanner",
- Image = "scanner"
- };
- Scanner.OnTapped += ((object sender, EventArgs e) =>
- {
- ScannerPage scannerPage = new ScannerPage();
- Navigation.PushAsync(scannerPage);
- });
- toolEntries.Add(Scanner);
- //Site
- ToolEntry Site = new ToolEntry
- {
- Text = "Site",
- Image = "construction"
- };
- Site.OnTapped += ((object sender, EventArgs e) =>
- {
- Site site = new Site(new Job { ID = _job.ID, Name = _job.Name, JobNumber = _job.JobNumber });
- Navigation.PushAsync(site);
- //if (_job.ID == Guid.Empty)
- //{
- // JobSelectionPage jobSelectionPage = new JobSelectionPage(true);
- // jobSelectionPage.OnItemSelected += (async () =>
- // {
- // if (jobSelectionPage.Job.ID != Guid.Empty)
- // {
- // Job selectedJob = new Job();
- // selectedJob.ID = jobSelectionPage.Job.ID;
- // selectedJob.JobNumber = jobSelectionPage.Job.JobNumber;
- // selectedJob.Name = jobSelectionPage.Job.Name;
- // Site site = new Site(selectedJob);
- // var previousPage = Navigation.NavigationStack.LastOrDefault();
- // await Navigation.PushAsync(site);
- // Navigation.RemovePage(previousPage);
- // }
- // });
- // Navigation.PushAsync(jobSelectionPage);
- //}
- });
- toolEntries.Add(Site);
- //Store Requis
- ToolEntry StoreRequis = new ToolEntry
- {
- Text = "Store Requis",
- Image = "storerequis"
- };
- StoreRequis.IsVisible = PRSSecurity.CanView<Requisition>();
- StoreRequis.OnTapped += ((object sender, EventArgs e) =>
- {
- var storeRequisList = new StoreRequiList();
- Navigation.PushAsync(storeRequisList);
- });
- toolEntries.Add(StoreRequis);
- //Tasks
- ToolEntry Tasks = new ToolEntry
- {
- Text = "Tasks",
- Image = "tasks"
- };
- Tasks.IsVisible = PRSSecurity.IsAllowed<CanViewTasks>();
- Tasks.OnTapped += ((object sender, EventArgs e) =>
- {
- var tasksForm = new TasksList();
- Navigation.PushAsync(tasksForm);
- });
- toolEntries.Add(Tasks);
- //Warehousing
- ToolEntry Warehousing = new ToolEntry
- {
- Text = "Warehousing",
- Image = "newwarehousing"
- };
- Warehousing.IsVisible = PRSSecurity.CanView<StockWarehouse>();
- Warehousing.OnTapped += ((object sender, EventArgs e) =>
- {
- Warehousing2 locations = new Warehousing2();
- Navigation.PushAsync(locations);
- });
- toolEntries.Add(Warehousing);
- AddChildren();
- });
- }
- catch { }
- }
- private void AddChildren()
- {
- Device.BeginInvokeOnMainThread(() =>
- {
- foreach (ToolEntry toolEntry in toolEntries)
- {
- toolEntry.Margin = new Thickness(5, 0, 5, 0);
- flexLayout.Children.Add(toolEntry);
- }
- SearchForNewNotifications();
- AddBlanks();
- });
- }
- private void AddBlanks()
- {
- for (int x = 0; x < 6; x++)
- {
- ToolEntry toolEntry = new ToolEntry(true);
- toolEntry.Margin = new Thickness(5, 0, 5, 0);
- flexLayout.Children.Add(toolEntry);
- }
- }
- private void Settings_Tapped(object sender, EventArgs e)
- {
- try
- {
- Settings settingsform = new Settings();
- settingsform.Disappearing += (object sender2, EventArgs e2) =>
- {
- settingsform = (Settings)sender2;
- if (settingsform.SettingsChanged)
- Navigation.PopModalAsync();
- };
- Navigation.PushAsync(settingsform);
- }
- catch { }
- }
- #endregion
- }
- }
|