Skip to content

Commit

Permalink
feat update training
Browse files Browse the repository at this point in the history
  • Loading branch information
sansan88 committed Oct 18, 2023
1 parent 4bbbed7 commit e8ac48c
Show file tree
Hide file tree
Showing 2 changed files with 154 additions and 105 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export class TrainingCreatePage implements OnInit {

this.trainingCopy = this.navParams.get("data");
if (this.trainingCopy.id) {
console.log(this.trainingCopy.timeFrom);
this.training = this.trainingCopy;

const startDate: Timestamp = this.trainingCopy.startDate as any;
Expand Down
258 changes: 154 additions & 104 deletions src/app/pages/training/trainings/trainings.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
ToastController,
} from "@ionic/angular";
import { User } from "@angular/fire/auth";
import { Observable, Subscription, catchError, combineLatest, concatMap, defaultIfEmpty, finalize, forkJoin, from, map, of, switchMap, take, tap, timeout} from "rxjs";
import { Observable, Subscription, catchError, combineLatest, concatMap, defaultIfEmpty, finalize, forkJoin, from, map, of, switchMap, take, tap, timeout } from "rxjs";
import { Training } from "src/app/models/training";
import { AuthService } from "src/app/services/auth.service";
import { FirebaseService } from "src/app/services/firebase.service";
Expand Down Expand Up @@ -52,15 +52,63 @@ export class TrainingsPage implements OnInit {
}

ngOnInit() {


const TIMEOUT_DURATION = 1000; // 5 seconds, adjust as needed

const teamtrainingList: Training[] = [];
this.trainingList$ = this.authService.getUser$().pipe(
take(1),
tap(() => console.log("Fetching user...")),
tap(user => this.user = user),
switchMap(user => this.fbService.getUserTeamRefs(user)),
tap(teams => console.log("Fetched teams:", teams)),
concatMap(teamsArray => from(teamsArray)),
tap(team => console.log("Processing team:", team.id)),
concatMap(team => this.trainingService.getTeamTrainingsRefs(team.id).pipe(
// timeout(TIMEOUT_DURATION),
take(1),
tap(trainings => console.log(`Fetched trainings for team ${team.id}:`, trainings)),
switchMap(trainings => {
const trainingWithAttendees$ = trainings.map(training =>
this.trainingService.getTeamTrainingsAttendeesRef(team.id, training.id).pipe(
take(1),
map(attendees => {
const userAttendee = attendees.find(att => att.id == this.user.uid);
return {
...training,
date: training.date,
teamId: team.id,
status: userAttendee ? userAttendee.status : null,
countAttendees: attendees.filter(att => att.status).length,
attendees: attendees
};
})
)
);
return forkJoin(trainingWithAttendees$);
}),
catchError(error => {
console.error(`Error fetching trainings for team ${team.id}:`, error);
return of([]); // if there's an error, emit an empty array to continue the stream
})
)),
map(trainings => trainings.sort((a, b) => a.date.toMillis() - b.date.toMillis())),
map(trainings => trainings.filter((training, index, self) =>
index === self.findIndex(t => t.id === training.id))),
tap(() => console.log("Team training fetching completed")),
) as Observable<Training[]>;

this.subscription = this.trainingList$.subscribe({
next: trainings => {
console.log("Combined training list created", trainings);
},
error: err => console.error('Error in the observable chain:', err.message)
});


const TIMEOUT_DURATION = 1000; // adjust as needed
// const teamtrainingList: Training[] = [];
const teamtrainingPastList: Training[] = [];

// CURRENT trainingS
const teamtraining$ = this.authService.getUser$().pipe(
/*const teamtraining$ = this.authService.getUser$().pipe(
take(1),
tap(() => console.log("Fetching user...")),
switchMap(user => {
Expand All @@ -77,7 +125,7 @@ export class TrainingsPage implements OnInit {
tap(trainings => console.log(`Fetched trainings for team ${team.id}:`, trainings)),
switchMap(trainings => {
// Fetch attendees for each training and combine the results
const trainingWithAttendees$ = trainings.map(training =>
const trainingWithAttendees$ = trainings.map(training =>
this.trainingService.getTeamTrainingsAttendeesRef(team.id, training.id).pipe(
take(1),
map(attendees => {
Expand All @@ -102,16 +150,16 @@ export class TrainingsPage implements OnInit {
console.error(`Error fetching trainings for team ${team.id}:`);
return of([]);
} else {
// Handle other errors, maybe rethrow or return a default object
// Handle other errors, maybe rethrow or return a default object
throw error;
}
})
)),
tap(trainings => trainings.forEach(training => teamtrainingList.push(training))),
finalize(() => console.log("Team training fetching completed"))
);
);*/

// CURRENT trainingS
// PAST trainingS
const teamtrainingPast$ = this.authService.getUser$().pipe(
take(1),
tap(() => console.log("Fetching user...")),
Expand All @@ -129,7 +177,7 @@ export class TrainingsPage implements OnInit {
tap(trainings => console.log(`Fetched trainings for team ${team.id}:`, trainings)),
switchMap(trainings => {
// Fetch attendees for each training and combine the results
const trainingWithAttendees$ = trainings.map(training =>
const trainingWithAttendees$ = trainings.map(training =>
this.trainingService.getTeamTrainingsAttendeesRef(team.id, training.id).pipe(
take(1),
map(attendees => {
Expand All @@ -144,7 +192,7 @@ export class TrainingsPage implements OnInit {
attendees: attendees
};
}),

)
);
return forkJoin(trainingWithAttendees$);
Expand All @@ -154,7 +202,7 @@ export class TrainingsPage implements OnInit {
console.error(`Error fetching trainings for team ${team.id}:`);
return of([]);
} else {
// Handle other errors, maybe rethrow or return a default object
// Handle other errors, maybe rethrow or return a default object
throw error;
}
})
Expand All @@ -164,26 +212,26 @@ export class TrainingsPage implements OnInit {
);

// Use combineLatest to get results when both observables have emitted
this.subscription = combineLatest([teamtraining$]).subscribe({
/*this.subscription = combineLatest([teamtraining$]).subscribe({
next: () => {
this.trainingList = [...teamtrainingList].sort((a, b):any => {
return a.date.toMillis() > b.date.toMillis() ;
this.trainingList = [...teamtrainingList].sort((a, b): any => {
return a.date.toMillis() > b.date.toMillis();
});
this.trainingList = this.trainingList.filter((training, index, self) =>
this.trainingList = this.trainingList.filter((training, index, self) =>
index === self.findIndex((t) => (t.id === training.id))
);
this.trainingList$ = of(this.trainingList);
console.log("Combined training list created");
},
error: err => console.error('Error in the observable chain:', err.message)
});
});*/

this.subscriptionPast = combineLatest([teamtrainingPast$]).subscribe({
next: () => {
this.trainingListPast = [...teamtrainingPastList].sort((a, b):any => {
return a.date.toMillis() < b.date.toMillis() ;
this.trainingListPast = [...teamtrainingPastList].sort((a, b): any => {
return a.date.toMillis() < b.date.toMillis();
});
this.trainingListPast = this.trainingListPast.filter((training, index, self) =>
this.trainingListPast = this.trainingListPast.filter((training, index, self) =>
index === self.findIndex((t) => (t.id === training.id))
);
this.trainingListPast$ = of(this.trainingListPast);
Expand All @@ -196,7 +244,7 @@ export class TrainingsPage implements OnInit {

ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription.unsubscribe();
}
if (this.subscriptionPast) {
this.subscriptionPast.unsubscribe();
Expand Down Expand Up @@ -262,7 +310,7 @@ export class TrainingsPage implements OnInit {

async presentToast() {
const toast = await this.toastController.create({
message: "changes has been saved",
message: "Änderung wurde gespeichert",
color: "primary",
duration: 2000,
position: "top",
Expand All @@ -274,27 +322,27 @@ export class TrainingsPage implements OnInit {
async copyTraining(slidingItem: IonItemSliding, training) {
slidingItem.closeOpened();

// const presentingElement = await this.modalCtrl.getTop();
const modal = await this.modalController.create({
component: TrainingCreatePage,
presentingElement: this.routerOutlet.nativeEl,
canDismiss: true,
showBackdrop: true,
componentProps: {
data: training,
},
});
modal.present();
const { data, role } = await modal.onWillDismiss();
if (role === "confirm") {
}
// const presentingElement = await this.modalCtrl.getTop();
const modal = await this.modalController.create({
component: TrainingCreatePage,
presentingElement: this.routerOutlet.nativeEl,
canDismiss: true,
showBackdrop: true,
componentProps: {
data: training,
},
});
modal.present();

const { data, role } = await modal.onWillDismiss();

if (role === "confirm") {
}

}


async deleteTraining(slidingItem: IonItemSliding,training) {
async deleteTraining(slidingItem: IonItemSliding, training) {
slidingItem.closeOpened();
const toast = await this.toastController.create({
message: "Delete",
Expand All @@ -306,73 +354,75 @@ export class TrainingsPage implements OnInit {
}


async openFilter(ev: Event){
async openFilter(ev: Event) {
let filterList = [];


const teams$ = this.authService.getUser$().pipe(
take(1),
switchMap(user => this.fbService.getUserTeamRefs(user).pipe(take(1))),
concatMap(teamsArray => from(teamsArray)),
tap((team:Team)=>console.log(team.id)),
concatMap(team =>
this.fbService.getTeamRef(team.id).pipe(
take(1),
defaultIfEmpty(null), // gibt null zurück, wenn kein Wert von getClubRef gesendet wird
map(result => [result]),
catchError(error => {
console.error('Error fetching TeamDetail:', error);
return of([]);
})
)
),
tap(teamList => teamList.forEach(team => filterList.push(team))),
finalize(() => console.log("Get Teams completed"))
);

this.subscription = forkJoin([teams$]).subscribe({
next: () => {
const alertInputs = [];
for (const item of filterList){
alertInputs.push({
label: item.name,
type: 'radio',
checked: item.id == this.filterValue,
value: item.id,

const teams$ = this.authService.getUser$().pipe(
take(1),
switchMap(user => this.fbService.getUserTeamRefs(user).pipe(take(1))),
concatMap(teamsArray => from(teamsArray)),
tap((team: Team) => console.log(team.id)),
concatMap(team =>
this.fbService.getTeamRef(team.id).pipe(
take(1),
defaultIfEmpty(null), // gibt null zurück, wenn kein Wert von getClubRef gesendet wird
map(result => [result]),
catchError(error => {
console.error('Error fetching TeamDetail:', error);
return of([]);
})
)
),
tap(teamList => teamList.forEach(team => filterList.push(team))),
finalize(() => console.log("Get Teams completed"))
);

this.subscription = forkJoin([teams$]).subscribe({
next: () => {
const alertInputs = [];
for (const item of filterList) {
alertInputs.push({
label: item.name,
type: 'radio',
checked: item.id == this.filterValue,
value: item.id,
});
}

this.alertCtrl.create({
header: 'News filtern',
message: 'Nach Verein oder Teams filtern.',
// subHeader: 'Nach Verein oder Teams filtern.',
inputs: alertInputs,
buttons: [
{
text: "OK",
role: "confirm",
handler: (value) => {
console.log(value)
this.filterValue = value;
this.trainingList$ = of(this.trainingList.filter((training: any) => training.teamId == value));
}
},
{
text: "abbrechen",
role: "cancel",
handler: (value) => {
console.log(value);
this.filterValue = "";
this.trainingList$ = of(this.trainingList);
}
}
],
htmlAttributes: { 'aria-label': 'alert dialog' },
}).then(alert => {
alert.present();
});
}

this.alertCtrl.create({
header: 'News filtern',
message: 'Nach Verein oder Teams filtern.',
// subHeader: 'Nach Verein oder Teams filtern.',
inputs: alertInputs,
buttons: [
{ text: "OK",
role: "confirm",
handler: (value)=>{
console.log(value)
this.filterValue = value;
this.trainingList$ = of(this.trainingList.filter((training: any) => training.teamId == value));
}
},
{ text: "abbrechen",
role: "cancel",
handler: (value)=>{
console.log(value);
this.filterValue = "";
this.trainingList$ = of(this.trainingList);
}
}
],
htmlAttributes: { 'aria-label': 'alert dialog' },
}).then(alert => {
alert.present();
});
},
error: err => console.error('Error in the observable chain:', err)
});

},
error: err => console.error('Error in the observable chain:', err)
});

}

}

0 comments on commit e8ac48c

Please sign in to comment.