diff --git a/api/src/loadshedding.rs b/api/src/loadshedding.rs index 9b0abeba..f1afbe90 100644 --- a/api/src/loadshedding.rs +++ b/api/src/loadshedding.rs @@ -222,6 +222,7 @@ pub struct LoadSheddingStage { #[serde(skip_serializing, skip_deserializing)] db: Option, stage: i32, + pub update: Option } #[derive(Debug, Deserialize, Clone)] @@ -670,6 +671,7 @@ impl LoadsheddingData { end_time: self.end.0.timestamp(), db: None, stage: self.stage, + update: Some(true) } } } @@ -759,7 +761,7 @@ impl MunicipalityEntity { // filter schedules to relevant ones for schedule in unfiltered_schedules { let keep = schedule.is_within_timeslot(&time_to_search); - println!("{:?}", time_to_search.hour()); + //println!("{:?}", time_to_search.hour()); if keep { schedules.push(schedule); } @@ -867,10 +869,10 @@ impl SuburbEntity { .unwrap() .with_minute(0) .unwrap(); - println!("{:?}", time_now.timestamp()); + //println!("{:?}", time_now.timestamp()); let mut response: Vec = Vec::new(); let day_in_future = - get_date_time(Some((Local::now() + chrono::Duration::days(1)).timestamp())); + get_date_time(Some((get_date_time(time) + chrono::Duration::days(1)).timestamp())); let (group, mut all_stages, schedule) = match self .collect_information(&time_now.timestamp(), connection, db_functions) @@ -882,7 +884,7 @@ impl SuburbEntity { all_stages.reverse(); let mut time_to_search = time_now; - println!("{:?}", time_to_search.timestamp()); + //println!("{:?}", time_to_search.timestamp()); while time_to_search < day_in_future { let day = time_to_search.day() as i32; let time_slots: Vec = schedule @@ -1116,30 +1118,32 @@ impl SuburbEntity { impl LoadSheddingStage { pub async fn set_stage(&mut self) { // get the next thing from db - let con = &self.db.as_ref().unwrap().database("production"); - let now = get_date_time(None).timestamp(); - let query = doc! { - "startTime" : { - "$lte" : now - } - }; - let filter = doc! { - "startTime" : -1 - }; - let find_options = FindOneOptions::builder().sort(filter).build(); - let new_status: LoadSheddingStage = con - .collection("stage_log") - .find_one(query, find_options) - .await - .unwrap() - .unwrap(); - println!("self is: {:?}", self); - println!("new is: {:?}", new_status); - self.end_time = new_status.end_time; - self.start_time = new_status.start_time; - self.stage = new_status.stage; - println!("self is after operation: {:?}", self); - //println!("{:?}", self); + if let Some(client) = &self.db.as_ref() { + let con = client.database("production"); + let now = get_date_time(None).timestamp(); + let query = doc! { + "startTime" : { + "$lte" : now + } + }; + let filter = doc! { + "startTime" : -1 + }; + let find_options = FindOneOptions::builder().sort(filter).build(); + let new_status: LoadSheddingStage = con + .collection("stage_log") + .find_one(query, find_options) + .await + .unwrap() + .unwrap(); + println!("self is: {:?}", self); + println!("new is: {:?}", new_status); + self.end_time = new_status.end_time; + self.start_time = new_status.start_time; + self.stage = new_status.stage; + println!("self is after operation: {:?}", self); + //println!("{:?}", self); + } } pub async fn request_stage_data_update(&mut self) -> Result { @@ -1165,7 +1169,7 @@ impl LoadSheddingStage { if let Some(client) = &self.db.as_ref() { let db_con = &client.database("production"); let query = doc! { - "start_time" : -1 + "startTime" : -1 }; let find_options = FindOneOptions::builder().sort(query).build(); @@ -1183,6 +1187,7 @@ impl LoadSheddingStage { start_time: 0, end_time: 0, db: None, + update: Some(true) }, }; let latest_in_db = result.start_time; @@ -1225,7 +1230,11 @@ impl LoadSheddingStage { mongodb::options::UpdateModifications::Document(doc! { "$set" : {"stage" : new_data.stage} }); - let _ = db_data.update(update, db_con).await; + if let Some(update_value) = db_data.update { + if update_value { + let _ = db_data.update(update, db_con).await; + } + } } } // else if no match @@ -1280,6 +1289,7 @@ impl Fairing for StageUpdater { start_time: 0, end_time: 0, db: None, + update: Some(true) })); let rocket = rocket.manage(Some(stage_info)); Ok(rocket) @@ -1343,7 +1353,7 @@ impl<'de> Deserialize<'de> for SASTDateTime { // hack for now because library is not being co-operative let convert_to_sast = dt.timestamp() - 2*3600; let sast = get_date_time(Some(convert_to_sast)); - println!("{:?}", sast); + //println!("{:?}", sast); Ok(SASTDateTime(sast)) } } diff --git a/api/src/tests.rs b/api/src/tests.rs index b58bcdd2..24da71cf 100644 --- a/api/src/tests.rs +++ b/api/src/tests.rs @@ -181,7 +181,6 @@ async fn test_getstats() { assert_eq!(result,expected_output); } -/* #[rocket::async_test] async fn test_ai_endpoint() { let client = Client::tracked(build_rocket().await) @@ -204,7 +203,6 @@ async fn test_ai_endpoint() { assert!(body.success); } -*/ #[rocket::async_test] async fn test_loadshedding_helpers() { @@ -653,7 +651,7 @@ const TEST_SUBURB_DATA: &'static str = r#"{ }"#; const TEST_GETSTATS_EXPECTED_RESULT: &'static str = "{\"totalTime\":{\"on\":2520,\"off\":7560},\"perDayTimes\":{\"Sun\":{\"on\":360,\"off\":1080},\"Mon\":{\"on\":360,\"off\":1080},\"Sat\":{\"on\":360,\"off\":1080},\"Tue\":{\"on\":360,\"off\":1080},\"Thu\":{\"on\":360,\"off\":1080},\"Fri\":{\"on\":360,\"off\":1080},\"Wed\":{\"on\":360,\"off\":1080}},\"suburb\":{\"_id\":{\"$oid\":\"64b6b9b30d09aa7756061b30\"},\"municipality\":{\"$oid\":\"64b6b9b30d09aa7756061a47\"},\"name\":\"MUCKLENEUK\",\"geometry\":[1]}}"; -const TEST_GETSCHEDULE_EXPECTED_RESULT: &'static str = "{\"timesOff\":[{\"start\":1694743200,\"end\":1694665800},{\"start\":1694750400,\"end\":1694673000},{\"start\":1694757600,\"end\":1694680200},{\"start\":1694764800,\"end\":1694687400},{\"start\":1694772000,\"end\":1694694600},{\"start\":1694779200,\"end\":1694701800},{\"start\":1694786400,\"end\":1694709000},{\"start\":1694793600,\"end\":1694716200},{\"start\":1694800800,\"end\":1694723400},{\"start\":1694728800,\"end\":1694737800},{\"start\":1694822400,\"end\":1694745000},{\"start\":1694829600,\"end\":1694752200},{\"start\":1694836800,\"end\":1694759400},{\"start\":1694844000,\"end\":1694766600},{\"start\":1694851200,\"end\":1694773800},{\"start\":1694858400,\"end\":1694781000},{\"start\":1694865600,\"end\":1694788200},{\"start\":1694872800,\"end\":1694795400},{\"start\":1694880000,\"end\":1694802600},{\"start\":1694887200,\"end\":1694809800},{\"start\":1694815200,\"end\":1694824200},{\"start\":1694916000,\"end\":1694838600},{\"start\":1694923200,\"end\":1694845800},{\"start\":1695038400,\"end\":1694961000},{\"start\":1694973600,\"end\":1694982600},{\"start\":1695002400,\"end\":1695011400},{\"start\":1695096000,\"end\":1695018600},{\"start\":1695031200,\"end\":1695040200},{\"start\":1695124800,\"end\":1695047400},{\"start\":1695132000,\"end\":1695054600},{\"start\":1695060000,\"end\":1695069000},{\"start\":1695074400,\"end\":1695083400},{\"start\":1695088800,\"end\":1695097800},{\"start\":1695211200,\"end\":1695133800},{\"start\":1695218400,\"end\":1695141000},{\"start\":1695146400,\"end\":1695155400},{\"start\":1695261600,\"end\":1695270600},{\"start\":1695384000,\"end\":1695306600},{\"start\":1695391200,\"end\":1695313800},{\"start\":1695319200,\"end\":1695328200},{\"start\":1695333600,\"end\":1695342600},{\"start\":1695348000,\"end\":1695357000},{\"start\":1695441600,\"end\":1695364200},{\"start\":1695448800,\"end\":1695371400},{\"start\":1695376800,\"end\":1695385800},{\"start\":1695470400,\"end\":1695393000}]}"; +const TEST_GETSCHEDULE_EXPECTED_RESULT: &'static str = "{\"timesOff\":[{\"start\":1694743200,\"end\":1694665800},{\"start\":1694750400,\"end\":1694673000},{\"start\":1694757600,\"end\":1694680200},{\"start\":1694764800,\"end\":1694687400},{\"start\":1694772000,\"end\":1694694600},{\"start\":1694779200,\"end\":1694701800},{\"start\":1694786400,\"end\":1694709000},{\"start\":1694793600,\"end\":1694716200},{\"start\":1694800800,\"end\":1694723400},{\"start\":1694728800,\"end\":1694737800},{\"start\":1694822400,\"end\":1694745000},{\"start\":1694829600,\"end\":1694752200}]}"; const POLYGON_DATA: &'static str = r#"{ "_id": { "$oid": "64b6b9b30d09aa7756061a47" }, "name": "tshwane", diff --git a/app/WhereIsThePower/src/app/report/report.spec.ts b/app/WhereIsThePower/src/app/report/report.spec.ts deleted file mode 100644 index b169b38a..00000000 --- a/app/WhereIsThePower/src/app/report/report.spec.ts +++ /dev/null @@ -1,100 +0,0 @@ -@@ -1, 99 + 0, 0 @@ -// Import necessary modules and dependencies for testing -import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; -import { ReportPage } from './report.page'; -import { ReportService } from './report.service'; -import { AuthService } from '../authentication/auth.service'; -import { Router } from '@angular/router'; -import { of } from 'rxjs'; - -// Create mock services -const mockReportService = { - reportIssue: (reportType: string) => { - // Simulate a successful response with a status and a message - return of({ status: 'success', message: ' Report submitted successfully' }); - }, -}; - - -const mockAuthService = { - isUserLoggedIn: () => Promise.resolve(true), // Change to false for testing non-logged-in state -}; - -const mockRouter = { - navigate: jasmine.createSpy('navigate'), -}; - -describe('ReportPage', () => { - let component: ReportPage; - let fixture: ComponentFixture; - let authService: AuthService; - - beforeEach(async () => { - await TestBed.configureTestingModule({ - declarations: [ReportPage], - providers: [ - { provide: ReportService, useValue: mockReportService }, - { provide: AuthService, useValue: mockAuthService }, - { provide: Router, useValue: mockRouter }, - ], - }).compileComponents(); - }); - - beforeEach(() => { - fixture = TestBed.createComponent(ReportPage); - component = fixture.componentInstance; - authService = TestBed.inject(AuthService); // Inject AuthService - - fixture.detectChanges(); - }); - - it('should create', () => { - expect(component).toBeTruthy(); - }); - - it('should set "isLoggedIn" to true when the user is logged in', async () => { - await component.ionViewWillEnter(); - expect(component.isLoggedIn).toBe(true); - }); - - it('should navigate to "/tabs/tab-navigate" after reporting an issue', () => { - const reportType = 'SubstationBlew'; - component.report(reportType); - expect(mockRouter.navigate).toHaveBeenCalledWith(['/tabs/tab-navigate']); - }); - - it('should navigate to "/tabs/tab-profile" when "Go to Profile" button is clicked for non-logged-in users', () => { - authService.isUserLoggedIn = () => Promise.resolve(false); // Mock non-logged-in state - fixture.detectChanges(); - const navigateSpy = spyOn(component['router'], 'navigate'); // Access private router property - const button = fixture.nativeElement.querySelector('ion-button'); - button.click(); - fixture.detectChanges(); - expect(navigateSpy).toHaveBeenCalledWith(['/tabs/tab-profile']); - }); - - it('should display the "Reporting is only available to registered users." message for non-logged-in users', () => { - authService.isUserLoggedIn = () => Promise.resolve(false); // Mock non-logged-in state - fixture.detectChanges(); - const message = fixture.nativeElement.querySelector('h3'); - expect(message.textContent).toContain('Reporting is only available to registered users.'); - }); - - it('should display report options for logged-in users', () => { - authService.isUserLoggedIn = () => Promise.resolve(true); // Mock logged-in state - fixture.detectChanges(); - const reportOptions = fixture.nativeElement.querySelectorAll('ion-col'); - expect(reportOptions.length).toBeGreaterThan(0); - }); - - it('should report "SubstationBlew" when the corresponding card is clicked', fakeAsync(() => { - authService.isUserLoggedIn = () => Promise.resolve(true); // Mock logged-in state - fixture.detectChanges(); - const reportType = 'SubstationBlew'; - const reportSpy = spyOn(mockReportService, 'reportIssue').and.returnValue(of({})); - const card = fixture.nativeElement.querySelector('ion-card'); - card.click(); - tick(); - expect(reportSpy).toHaveBeenCalledWith(reportType); - })); -}); diff --git a/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.scss b/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.scss index cd471de2..0e0143ab 100644 --- a/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.scss +++ b/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.scss @@ -99,4 +99,10 @@ ion-list { :host ::ng-deep .mapboxgl-popup-content h4 ion-icon { padding-right: 8px; /* Adjust the margin as needed */ -} \ No newline at end of file +} + +.report-icon { + position: absolute; + z-index: 9999; /* Set a high z-index value */ + /* Add any other styling as needed */ +} diff --git a/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.ts b/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.ts index 568f96e3..f2937322 100644 --- a/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.ts +++ b/app/WhereIsThePower/src/app/shared/map-modal/map-modal.component.ts @@ -70,6 +70,8 @@ export class MapModalComponent implements OnInit, AfterViewInit { currentSuburbSchedule: any; modifiedAddress: string = ""; isPlaceSaved: boolean = false; + currentPopup: string | null = null; + isReportMarker: boolean = false; @ViewChild('myModal') myModal: any; // Reference to the ion-modal element modalResult: any; // To store the selected result data @@ -192,10 +194,12 @@ export class MapModalComponent implements OnInit, AfterViewInit { customIcon.style.backgroundPosition = 'center'; customIcon.style.borderRadius = '50%'; customIcon.style.padding = '8px'; + customIcon.style.pointerEvents = 'none'; + customIcon.setAttribute('class', 'report-icon'); const formattedReportType = reportType.replace(/([A-Z])/g, ' $1'); - const reportMarker = new mapboxgl.Marker({ + new mapboxgl.Marker({ element: customIcon, }) .setLngLat([lon, lat]) @@ -207,15 +211,30 @@ export class MapModalComponent implements OnInit, AfterViewInit { ${formattedReportType} -

Reported at 14:00

+

Reported at ${this.formatTime(new Date())}

` ) ) .addTo(this.map); + customIcon.addEventListener('click', this.handleReportIconClick.bind(this)); - this.closePopup(); + console.log("this.popup", this.popup); + // Close the other popup if it's open + } + + formatTime(date: any) { + const hours = date.getHours().toString().padStart(2, '0'); + const minutes = date.getMinutes().toString().padStart(2, '0'); + return `${hours}:${minutes}`; + } + + // Define a separate function to handle the click event + handleReportIconClick() { + console.log("Report Icon Clicked"); + this.isReportMarker = true; } + populatePolygons() { this.map.on('load', () => { // Add a data source containing GeoJSON data. @@ -259,10 +278,14 @@ export class MapModalComponent implements OnInit, AfterViewInit { // Listen for the click event on the map this.map.on('click', 'polygons-layer', (e: any) => { + setTimeout(() => { + this.isReportMarker = false; + }, 20); + const clickedFeature = e.features[0]; //console.log(e); - if (clickedFeature) { + if (clickedFeature && this.isReportMarker == false) { let suburbId = clickedFeature.id; console.log("Suburb ID =" + suburbId) // Get the properties of the clicked feature (suburb information) @@ -274,36 +297,36 @@ export class MapModalComponent implements OnInit, AfterViewInit { this.mapSuburbsService.fetchTimeForPolygon(suburbId).subscribe( (response: any) => { // Handle the response here - - + + console.log('Time response:', response); console.log("success", response.success); - if(response.success === true) - { - const timesOff = response.result.timesOff; // Assuming "response" holds your API response - if (timesOff && timesOff.length > 0) { - const formattedTimes = timesOff.map((time: any) => { - const start = new Date(time.start * 1000); // Convert seconds to milliseconds - const end = new Date(time.end * 1000); // Convert seconds to milliseconds - - const startHours = start.getHours().toString().padStart(2, '0'); - const startMinutes = start.getMinutes().toString().padStart(2, '0'); - - const endHours = end.getHours().toString().padStart(2, '0'); - const endMinutes = end.getMinutes().toString().padStart(2, '0'); - - this.currentSuburbSchedule = `${startHours}:${startMinutes} - ${endHours}:${endMinutes}`; - - }); - - console.log('Formatted Time Ranges:', formattedTimes); - } else { - console.log('No time ranges available.'); - this.currentSuburbSchedule = "unavailable"; - } - const showSchedule = suburbInfo?.PowerStatus !== 'on'; - const popupContent = ` + if (response.success === true) { + const timesOff = response.result.timesOff; // Assuming "response" holds your API response + if (timesOff && timesOff.length > 0) { + const formattedTimes = timesOff.map((time: any) => { + const start = new Date(time.start * 1000); // Convert seconds to milliseconds + const end = new Date(time.end * 1000); // Convert seconds to milliseconds + + const startHours = start.getHours().toString().padStart(2, '0'); + const startMinutes = start.getMinutes().toString().padStart(2, '0'); + + const endHours = end.getHours().toString().padStart(2, '0'); + const endMinutes = end.getMinutes().toString().padStart(2, '0'); + + this.currentSuburbSchedule = `${startHours}:${startMinutes} - ${endHours}:${endMinutes}`; + + }); + + console.log('Formatted Time Ranges:', formattedTimes); + } else { + console.log('No time ranges available.'); + this.currentSuburbSchedule = "unavailable"; + } + + const showSchedule = suburbInfo?.PowerStatus !== 'on'; + const popupContent = ` ${suburbInfo?.SP_NAME} @@ -314,11 +337,14 @@ export class MapModalComponent implements OnInit, AfterViewInit { `; - // Create a new popup and set its HTML content - this.popup = new mapboxgl.Popup() - .setLngLat(e.lngLat) - .setHTML(popupContent) - .addTo(this.map); + // Create a new popup and set its HTML content + this.popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(popupContent) + .addTo(this.map); + + this.currentPopup = popupContent; + } }, (error) => { diff --git a/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.html b/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.html index 84a9de19..a6df0c94 100644 --- a/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.html +++ b/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.html @@ -17,31 +17,47 @@ alt="Traffic Jam Illustration" class="ion-padding" > - + + +
+ Account +
+
+ + + Login to my account + + + + Sign up for an account + + + +
+ User Manual +
+
+ + + + + Mobile + + + + + Desktop + - - - - - - Login to my account - - - - Sign up for an account - - - - - + Terms of Service - + @@ -53,25 +69,44 @@

Welcome {{user?.firstName}} !

- + +
+ Settings +
+
Light Dark - - Logout + + Logout -
+ +
+ User Manual +
+
+ + + + + Mobile + + + + + Desktop +
diff --git a/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.ts b/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.ts index 4cdc67f7..a214d888 100644 --- a/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.ts +++ b/app/WhereIsThePower/src/app/tab-profile/tab-profile.page.ts @@ -21,7 +21,7 @@ export class TabProfilePage implements OnInit { isLoggedIn: boolean = false; constructor(private authService: AuthService, - private modalController: ModalController) { } + private modalController: ModalController) { } ngOnInit() { //this.isLoggedIn = this.authService.isLoggedin; @@ -96,4 +96,23 @@ export class TabProfilePage implements OnInit { toggleTheme(systemTheme: string) { document.body.setAttribute('witp-color-theme', systemTheme); } + + downloadUserManual(type: string) { + // Determine the URL of the user manual based on the 'type' + let userManualURL = ''; + + if (type === 'mobile') { + userManualURL = 'assets/pdf/user-manual-mobile.pdf'; + } else if (type === 'desktop') { + userManualURL = 'assets/pdf/user-manual-desktop.pdf'; + } + // Add more 'if' conditions for other user manual types if needed + + // Trigger the download + const link = document.createElement('a'); + link.href = userManualURL; + link.target = '_blank'; // Open the link in a new tab (optional) + link.download = `user-manual-${type}.pdf`; // Specify the filename + link.click(); + } } diff --git a/app/WhereIsThePower/src/assets/pdf/user-manual-desktop.pdf b/app/WhereIsThePower/src/assets/pdf/user-manual-desktop.pdf new file mode 100644 index 00000000..274c0424 Binary files /dev/null and b/app/WhereIsThePower/src/assets/pdf/user-manual-desktop.pdf differ diff --git a/app/WhereIsThePower/src/assets/pdf/user-manual-mobile.pdf b/app/WhereIsThePower/src/assets/pdf/user-manual-mobile.pdf new file mode 100644 index 00000000..85a1d50d Binary files /dev/null and b/app/WhereIsThePower/src/assets/pdf/user-manual-mobile.pdf differ diff --git a/app/WhereIsThePower/src/environments/environment.ts b/app/WhereIsThePower/src/environments/environment.ts index 16253b1f..d23824c7 100644 --- a/app/WhereIsThePower/src/environments/environment.ts +++ b/app/WhereIsThePower/src/environments/environment.ts @@ -1,4 +1,4 @@ export const environment = { production: false, - MapboxApiKey: 'HelloAPIKey' + MapboxApiKey: 'pk.eyJ1IjoidTE4MDA0ODc0IiwiYSI6ImNsajMzdWh5ZzAwcHAzZXMxc3lveXJmNDgifQ.7P_tuuiC4M_Q1_H5ZF1rTA' };