Skip to content

Commit

Permalink
Merge pull request fga-eps-mds#16 from fga-eps-mds/ajustesPosR2
Browse files Browse the repository at this point in the history
Alterações sugeridas pós entrega da R2
  • Loading branch information
GabrielRoger07 authored Aug 26, 2024
2 parents 5a9ef97 + 6e22bdd commit 19a154c
Show file tree
Hide file tree
Showing 14 changed files with 625 additions and 72 deletions.
5 changes: 3 additions & 2 deletions src/app/pages/catalog/catalog.component.css
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}


.checkbox-container {
margin: 1em 12em 0 12em;
display: flex;
align-items: center;
margin-left: 0.625em; /* Adiciona algum espaço entre o campo de pesquisa e a checkbox */
justify-content:space-around;
}


Expand Down
18 changes: 11 additions & 7 deletions src/app/pages/catalog/catalog.component.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
<div class="center flex flex-col justify-center content-start flex-wrap gap-y-8 w-full max-w-3xl">
<div>
<input [(ngModel)]="filterTitle" (ngModelChange)="filterVideos()" placeholder="Pesquise um vídeo" class="CampoFiltro"/>
<label *ngIf="isAuthenticated" class="checkbox-container">
<input type="checkbox" [(ngModel)]="filterWatchLater" (change)="onFilterWatchLaterChange()" class="custom-checkbox"/>
Assistir mais tarde
</label>
<label *ngIf="isAuthenticated" class="checkbox-container">
<input type="checkbox" [(ngModel)]="filterFavorite" (change)="onFilterFavoriteVideosChange()" class="custom-checkbox"/> Listar Favoritos
</label>
<div class="checkbox-container">
<label *ngIf="isAuthenticated"class="first-container">
<input type="checkbox" [(ngModel)]="filterWatchLater" (change)="onFilterWatchLaterChange()" class="custom-checkbox"/>
Assistir mais tarde
</label>

<label *ngIf="isAuthenticated">
<input type="checkbox" [(ngModel)]="filterFavorite" (change)="onFilterFavoriteVideosChange()" class="custom-checkbox"/>
Listar Favoritos
</label>
</div>
</div>
<div *ngIf="filterTitle.length===0 && !filterFavorite && !filterWatchLater">
<div class="flex flex-col gap-2">
Expand Down
16 changes: 8 additions & 8 deletions src/app/pages/catalog/catalog.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,16 @@ export class CatalogComponent implements OnInit {
if (this.isAuthenticated) {
this.videoService.getFavoriteVideos(this.userId).subscribe({
next: (data) => {

// Verifique se `videoList` existe e é um array
if (data && Array.isArray(data.videoList)) {
const favorite_videos_ids = data.videoList.map((item: any) => String(item.video_id)); // Converta IDs para string

this.favoriteVideos = this.unbTvVideos.filter(video => favorite_videos_ids.includes(String(video.id))); // Converta IDs para string
} else {
console.warn('A estrutura da resposta da API não está conforme o esperado:', data);
}

this.filterVideos(); // Atualize a filtragem após carregar os vídeos de "favoritos"
},
error: (error) => {
Expand All @@ -111,16 +111,16 @@ export class CatalogComponent implements OnInit {
if (this.isAuthenticated) {
this.videoService.getWatchLaterVideos(this.userId).subscribe({
next: (data) => {

// Verifique se `videoList` existe e é um array
if (data && Array.isArray(data.videoList)) {
const watchLaterVideoIds = data.videoList.map((item: any) => String(item.video_id)); // Converta IDs para string

this.watchLaterVideos = this.unbTvVideos.filter(video => watchLaterVideoIds.includes(String(video.id))); // Converta IDs para string
} else {
console.warn('A estrutura da resposta da API não está conforme o esperado:', data);
}

this.filterVideos(); // Atualize a filtragem após carregar os vídeos de "assistir mais tarde"
},
error: (error) => {
Expand All @@ -137,7 +137,7 @@ export class CatalogComponent implements OnInit {
this.filterVideos();
}
}


filterVideosByChannel(videos: IVideo[]): void {
videos.forEach((video) => {
Expand All @@ -156,7 +156,7 @@ export class CatalogComponent implements OnInit {
const matchesDescription = this.filterTitle ? video.description?.toLowerCase().includes(this.filterTitle.toLowerCase()) : true;
const matchesKeywords = this.filterTitle ? video.keywords?.toLowerCase().includes(this.filterTitle.toLowerCase()) : true;
const matchesCatalog = this.filterTitle ? video.catalog?.toLowerCase().includes(this.filterTitle.toLowerCase()) : true;

return isWatchLater && isFavorite && (matchesTitle || matchesDescription || matchesKeywords || matchesCatalog);
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/category-table/category-table.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,4 @@ <h1>Dados - Categorias</h1>
</table>
</div>
</main>
</div>
</div>
7 changes: 2 additions & 5 deletions src/app/pages/category-table/category-table.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,10 @@ describe('CategoryTableComponent', () => {
it('should call findAll on ngOnInit', () => {
spyOn(component, 'findAll');
component.ngOnInit();

expect(component.findAll).toHaveBeenCalled();
component.categories.forEach(category => {
if (category === "Todas"){
expect(component.selectedCategories[category]).toBeTrue()
}else{
expect(component.selectedCategories[category]).toBeFalse()
}
expect(component.selectedCategories[category]).toBeTrue();
});
});

Expand Down
38 changes: 26 additions & 12 deletions src/app/pages/category-table/category-table.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export class CategoryTableComponent {
"Séries Especiais",
"UnBTV",
"Variedades"

];
filteredAggregatedVideos: any[] = [];
selectedCategories: { [key: string]: boolean } = {};
Expand All @@ -44,13 +45,15 @@ export class CategoryTableComponent {
private authService: AuthService,
private confirmationService: ConfirmationService
) {};

ngOnInit(): void{
this.categories.forEach(category => this.selectedCategories[category] = false);
this.selectedCategories["Todas"] = true;
this.categories.forEach(category => {
this.selectedCategories[category] = true;
});
this.findAll();
}

findAll(): void {
this.videoService.findAll().subscribe({
next: (data) => {
Expand Down Expand Up @@ -107,7 +110,7 @@ export class CategoryTableComponent {

this.aggregatedVideos = Array.from(categoryMap.entries()).map(([category, data]) => ({
category,
videoCount: data.count,
videoCount: data.count,
totalViews: data.views,
viewsPerVideo: data.count > 0 ? data.views/data.count : 0
}));
Expand Down Expand Up @@ -141,17 +144,28 @@ export class CategoryTableComponent {
this.sortAscending = true;
}
this.sortAggregatedVideos();
}
}

filterCategories(): void {
const selectedCategories = Object.keys(this.selectedCategories).filter(category => this.selectedCategories[category]);
if (selectedCategories.includes("Todas")) {
this.filteredAggregatedVideos = this.aggregatedVideos;
}else if(selectedCategories.length === 0){
this.categories.forEach(category => {
this.selectedCategories[category] = true;
});
this.filteredAggregatedVideos = this.aggregatedVideos;
} else if (
!selectedCategories.includes("Todas") &&
this.selectedCategories["Todas"] === false &&
selectedCategories.length === 8
) {
this.categories.forEach(category => {
this.selectedCategories[category] = false;
});
this.filteredAggregatedVideos = [];
} else if(selectedCategories.length === 0){
this.filteredAggregatedVideos = [];
}
else{
this.filteredAggregatedVideos = this.aggregatedVideos.filter(video => selectedCategories.includes(video.category));
} else{
this.filteredAggregatedVideos = this.aggregatedVideos.filter(video => selectedCategories.includes(video.category));
}
this.sortAggregatedVideos();
}
Expand Down Expand Up @@ -182,7 +196,7 @@ export class CategoryTableComponent {
];

ws['!cols'] = columnWidths;
XLSX.utils.book_append_sheet(wb, ws,'Sheet1');
XLSX.utils.book_append_sheet(wb, ws,'Sheet1');
XLSX.writeFile(wb, this.fileName);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
font-family: Helvetic, sans-serif;
}

.containerCard, .containerLegenda, .containerGraficos {
font-size: 12px;
}

.containerPrincipal {
display: flex;
min-height: 100vh;
Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/suggest-agenda/suggest-agenda.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ <h1>Sugestão de Pautas</h1>
class="input first button"
name="email-contato"
formControlName="emailContato"
placeholder="@example.xxx"
placeholder="[email protected]"
/>
<input
inputmask
Expand Down
22 changes: 20 additions & 2 deletions src/app/pages/suggest-agenda/suggest-agenda.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { FormBuilder, FormControl, ReactiveFormsModule } from '@angular/forms';
import { of, throwError } from 'rxjs';
import { EmailService } from 'src/app/services/email.service';
import { SuggestAgendaComponent } from './suggest-agenda.component';
Expand Down Expand Up @@ -113,7 +113,7 @@ describe('SuggestAgendaComponent', () => {
form.setValue({
descricao: 'Descrição',
responsavel: 'Usuário Teste',
telefoneResponsavel: '(99) 99999-9999',
telefoneResponsavel: 999999999,
tema: '',
quando: '',
local: '',
Expand All @@ -123,4 +123,22 @@ describe('SuggestAgendaComponent', () => {
component.sendSuggestAgenda();
expect(alertSpy).toHaveBeenCalledWith('error', 'Erro', 'Serviços válidos: Youtube, Google Drive, Microsoft Stream, Streamable e Vimeo.');
});

it('should handle invalid phone number error', () => {
fixture.detectChanges();
const alertSpy = spyOn(alertService, 'showMessage');
const form = component.suggestAgendaForm;
form.setValue({
descricao: 'Descrição',
responsavel: 'Usuário Teste',
telefoneResponsavel: 99999-9999,
tema: '',
quando: '',
local: '',
emailContato: '[email protected]',
urlVideo: 'https://www.youtube.com/watch?v=bX-8WWmW06Q'
});
component.sendSuggestAgenda();
expect(alertSpy).toHaveBeenCalledWith('error', 'Erro', 'Telefone inválido.');
});
});
17 changes: 15 additions & 2 deletions src/app/pages/suggest-agenda/suggest-agenda.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,24 @@ export class SuggestAgendaComponent implements OnInit {
quando: [''],
local: [''],
responsavel: ['', [Validators.required]],
telefoneResponsavel: ['', [Validators.required]],
telefoneResponsavel: ['', [this.validacaoTelefone()]],
emailContato: ['', [Validators.pattern('^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$')]],
urlVideo: ['', [this.validacaoUrl()]]
},
);
}

validacaoTelefone(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
if (control.value == '') {
return null;
}
const padrao_telefone = /^\d{8,15}$/;
const valido = padrao_telefone.test(control.value);
return valido ? null : { telefone_invalido: { value: control.value } };
}
}

validacaoUrl(): ValidatorFn{
return (control:AbstractControl):{[key: string]:any}| null => {
if(control.value == ''){
Expand Down Expand Up @@ -71,7 +82,9 @@ export class SuggestAgendaComponent implements OnInit {
this.isSendingEmail = false;
});
} else {
if(this.suggestAgendaForm.controls['urlVideo'].errors?.['url_invalida']){
if(this.suggestAgendaForm.controls['telefoneResponsavel'].errors?.['telefone_invalido']){
this.alertService.showMessage("error", "Erro", "Telefone inválido.");
} else if(this.suggestAgendaForm.controls['urlVideo'].errors?.['url_invalida']){
this.alertService.showMessage("error", "Erro", "Serviços válidos: Youtube, Google Drive, Microsoft Stream, Streamable e Vimeo.");
}else{
this.alertService.showMessage("info", "Alerta", "Preencha todos os campos corretamente!");
Expand Down
30 changes: 15 additions & 15 deletions src/app/pages/video-viewer/video-viewer.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class VideoViewerComponent implements OnInit {
this.checkRecord();
this.findAll();
}

checkRecord(): Promise<void> {
return new Promise((resolve, reject) => {
this.videoService.checkRecord(this.userId.toString()).subscribe({
Expand All @@ -91,15 +91,6 @@ export class VideoViewerComponent implements OnInit {
this.filteredVideos = this.unbTvVideos.filter(video => video.id !== undefined && keys.includes(video.id));
}

filterVideosByChannel(videos: IVideo[]): void {
videos.forEach((video) => {
const channel = video?.channels;
if (channel && channel[0].id === this.unbTvChannelId) {
this.unbTvVideos.push(video);
}
});
}

findAll(): void {
this.videoService.findAll().subscribe({
next: (data) => {
Expand All @@ -118,9 +109,9 @@ export class VideoViewerComponent implements OnInit {
this.program = this.videoService.findProgramName(this.catalog, this.categoryVideo, this.idVideo);

this.videosByCategory = this.videoService.filterVideosByCategory(this.unbTvVideos, this.categoryVideo);
//console.log("vídeos da categoria do atual: ", this.videosByCategory)
console.log("vídeos da categoria do atual: ", this.videosByCategory)
this.filterVideosByRecord();
//console.log("videos assistidos: ", this.filteredVideos)
console.log("videos assistidos: ", this.filteredVideos)
this.idNextVideo = this.videoService.recommendVideo(this.videosByCategory, this.catalog, this.categoryVideo, this.filteredVideos, this.program);
//Se o id for diferente de -1, o usuário ainda não viu todos os vídeos da categoria atual
if(this.idNextVideo != -1){
Expand All @@ -134,15 +125,24 @@ export class VideoViewerComponent implements OnInit {
}else{
this.titleNextVideo = "Não há vídeo para ser recomendado"
}
//console.log("id do próximo vídeo: ", this.idNextVideo)
//console.log("título do próximo vídeo: ", this.titleNextVideo)
console.log("id do próximo vídeo: ", this.idNextVideo)
console.log("título do próximo vídeo: ", this.titleNextVideo)
},
error: (error) => {
console.log(error);
}
});
}

filterVideosByChannel(videos: IVideo[]): void {
videos.forEach((video) => {
const channel = video?.channels;
if (channel && channel[0].id === this.unbTvChannelId) {
this.unbTvVideos.push(video);
}
});
}

nextVideo(): void {
if(this.idNextVideo != -1){
this.router.navigate([`/video/${this.idNextVideo}`]).then(() => {
Expand Down Expand Up @@ -301,4 +301,4 @@ export class VideoViewerComponent implements OnInit {
console.warn('A API de compartilhamento não é suportada neste navegador.');
}
}
}
}
6 changes: 1 addition & 5 deletions src/app/pages/video-views/video-views.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,7 @@ describe('VideoViewsComponent', () => {
expect(component.findAll).toHaveBeenCalled();
expect(component.filteredVideos).toEqual(component.unbTvVideos);
component.categories.forEach(category => {
if (category === "Todas"){
expect(component.selectedCategories[category]).toBeTrue()
}else{
expect(component.selectedCategories[category]).toBeFalse()
}
expect(component.selectedCategories[category]).toBeTrue()
});
});

Expand Down
Loading

0 comments on commit 19a154c

Please sign in to comment.