Commit 34248d79 authored by RenanMontenegro3's avatar RenanMontenegro3

fix: concerta o erro na atualização automatica de páginas + download de exel em aceite-navios

parent b186fd8c
......@@ -26,6 +26,7 @@ import { throwError } from 'rxjs';
import { MatCardActions } from '@angular/material/card';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../../environments/.env';
import { ReloadService } from '../../../services/reload.service';
@Component({
selector: 'app-aceite-edit',
standalone: true,
......@@ -68,7 +69,7 @@ export class AceiteEditComponent implements OnInit {
private _bercoService: BercosService,
private cdr: ChangeDetectorRef,
private httpClient: HttpClient,
private _reloadService: ReloadService
) {
this.empForm = this._fb.group({
......@@ -534,6 +535,8 @@ selectedCategoriaNome: string = '';
next: () => {
this._dialogRef.close(true);
this.toastService.success('Aceite editado com sucesso');
this._reloadService.reloadRoute('navio')
this._reloadService.reloadRoute('aceite')
},
error: (err: any) => {
console.error(err);
......@@ -544,6 +547,8 @@ selectedCategoriaNome: string = '';
next: () => {
this._dialogRef.close(true);
this.toastService.success('Aceite editado com sucesso');
this._reloadService.reloadRoute('navio')
this._reloadService.reloadRoute('aceite')
},
error: (err: any) => {
console.error(err);
......
......@@ -27,6 +27,8 @@ import { JwtDecoderService } from '../../../jwt-decoder.service';
import { AuthService } from '../../../auth.service';
import { jwtDecode } from 'jwt-decode';
import { CsvService } from '../../../csv.service';
import { ReloadService } from '../../../services/reload.service';
import { Router } from '@angular/router';
interface AceiteData {
id: number;
imo: number;
......@@ -88,9 +90,20 @@ export class AceitesComponent implements OnInit {
private jwtDecoderService: JwtDecoderService,
private authService: AuthService,
private cdr: ChangeDetectorRef,
private _csvService: CsvService
private _csvService: CsvService,
private _reloadService: ReloadService,
private _router: Router
) { }
reload() {
if (this._reloadService.reload) {
this._router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this._router.navigate(['aceite']);
this._reloadService.reload = false;
});
}
}
ngOnInit(): void {
this.validationToken();
......@@ -429,8 +442,7 @@ export class AceitesComponent implements OnInit {
this._coreService.openSnackBar(err.error.title);
},
});
this.cdr.detectChanges();
this.reload();
}
openEditForm(data: any) {
......
......@@ -17,6 +17,7 @@ import { MatDialogModule } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { BercosComponent } from '../bercos/bercos.component';
import { BercosService } from '../../../services/bercos/bercos.service';
import { ReloadService } from '../../../services/reload.service';
@Component({
selector: 'app-berco-add',
......@@ -51,6 +52,7 @@ export class BercoAddComponent implements OnInit {
private _dialogRef: MatDialogRef<BercoAddComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private toastService: ToastrService,
private _reloadService: ReloadService
) {
this.bercoForm = this._fb.group({
nome: ['', Validators.required],
......@@ -91,6 +93,8 @@ export class BercoAddComponent implements OnInit {
this._bercoService.addEmployee(this.bercoForm.value).subscribe({
next: (val: any) => {
this.toastService.success('Berço adicionado com sucesso');
this._reloadService.reloadRoute('navio');
this._reloadService.reloadRoute('berco');
this._dialogRef.close(true);
},
error: (err: any) => {
......@@ -99,4 +103,4 @@ export class BercoAddComponent implements OnInit {
});
}
}
}
\ No newline at end of file
}
......@@ -15,6 +15,7 @@ import { MatDialogModule } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { BercosComponent } from '../bercos/bercos.component';
import { BercosService } from '../../../services/bercos/bercos.service';
import { ReloadService } from '../../../services/reload.service';
@Component({
selector: 'app-berco-edit',
......@@ -30,7 +31,7 @@ import { BercosService } from '../../../services/bercos/bercos.service';
MatDatepickerModule,
MatSelectModule,
MatRadioModule,
MatIconModule,
MatIconModule,
MatSnackBarModule,
BercosComponent,
],
......@@ -46,6 +47,7 @@ export class BercoEditComponent implements OnInit {
private _dialogRef: MatDialogRef<BercoEditComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private toastService: ToastrService,
private _reloadService: ReloadService
) {
this.bercoForm = this._fb.group({
nome: ['', Validators.required],
......@@ -92,6 +94,8 @@ export class BercoEditComponent implements OnInit {
this._bercoService.updateEmployee(this.data.id, this.bercoForm.value).subscribe({
next: (val: any) => {
this.toastService.success('Detalhes do berço atualizados!');
this._reloadService.reloadRoute('navio');
this._reloadService.reloadRoute('berco');
this._dialogRef.close(true);
},
error: (err: any) => {
......@@ -101,4 +105,4 @@ export class BercoEditComponent implements OnInit {
}
}
}
}
\ No newline at end of file
}
......@@ -16,6 +16,7 @@ import { MatDialogModule } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { NgxCurrencyDirective } from 'ngx-currency';
import { BlackListService } from '../../../services/Blacklists/black-list.service';
import { ReloadService } from '../../../services/reload.service';
@Component({
selector: 'app-black-list-add',
standalone: true,
......@@ -33,7 +34,7 @@ import { BlackListService } from '../../../services/Blacklists/black-list.servic
MatIconModule,
MatSnackBarModule,
NgxCurrencyDirective,
],
],
templateUrl: './black-list-add.component.html',
styleUrl: './black-list-add.component.scss'
})
......@@ -50,7 +51,8 @@ export class BlackListAddComponent implements OnInit {
private _empService: BlackListService,
@Inject(MAT_DIALOG_DATA) public data: any,
private _dialogRef: MatDialogRef<BlackListAddComponent>,
private toastService: ToastrService
private toastService: ToastrService,
private _reladService: ReloadService
) {
this.empForm = this._fb.group({
imo: [this.data?.imo || '', Validators.required],
......@@ -419,12 +421,12 @@ export class BlackListAddComponent implements OnInit {
if (input.files && input.files.length > 0) {
const file = input.files[0];
const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
if (!allowedTypes.includes(file.type)) {
this.toastService.error('Apenas arquivos PDF ou Word são permitidos.');
return;
}
this.selectedFile = file;
this.fileName = file.name;
const reader = new FileReader();
......
......@@ -29,7 +29,10 @@ import { BlackListEdit } from '../black-list-edit/black-list-edit.component';
import { BlackListService } from '../../../services/Blacklists/black-list.service';
import { VisualizacaoBlackListComponent } from '../visualizacao-black-list/visualizacao-black-list.component';
import { CsvService } from '../../../csv.service';
import { ReloadService
} from '../../../services/reload.service';
import { Router } from '@angular/router';
interface NavioData {
id: number;
imo: number;
......@@ -99,9 +102,21 @@ export class BlackListComponent {
private authService: AuthService,
private _coreService: CoreService,
private cdr: ChangeDetectorRef,
private _csvService: CsvService // Injetando o serviço CSV'
private _csvService: CsvService, // Injetando o serviço CSV'
private _reloadService: ReloadService,
private _router: Router
) { }
reload() {
if (this._reloadService.reload) {
this._router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this._router.navigate(['black-list']);
this._reloadService.reload = false;
});
}
}
ngOnInit(): void {
this.validationToken();
}
......@@ -171,6 +186,7 @@ export class BlackListComponent {
this._coreService.openSnackBar(err.error.title);
},
});
this.reload();
}
openEditForm(data: any) {
......@@ -180,8 +196,6 @@ export class BlackListComponent {
disableClose: true, // Impede que o diálogo feche ao clicar fora
width: '600px', // Define a largura do diálogo
});
this.cdr.detectChanges();
}
addBlackList(data: any) {
......@@ -191,8 +205,7 @@ export class BlackListComponent {
disableClose: true, // Impede que o diálogo feche ao clicar fora
width: '600px', // Define a largura do diálogo
});
this.cdr.detectChanges();
this.reload();
}
openAddEmpForm() {
......@@ -201,7 +214,6 @@ export class BlackListComponent {
disableClose: true, // Impede que o diálogo feche ao clicar fora
width: '600px', // Define a largura do diálogo}));
})
this.cdr.detectChanges();
}
......@@ -211,7 +223,6 @@ export class BlackListComponent {
autoFocus: true, // Foca no primeiro campo interativo do formulário
width: '800px', // Define a largura do diálogo
});
this.cdr.detectChanges();
}
......
......@@ -17,6 +17,7 @@ import { NaviosComponent } from '../navios/navios.component';
import { ToastrService } from 'ngx-toastr';
import { NgxCurrencyDirective } from 'ngx-currency';
import { BercosService } from '../../../services/bercos/bercos.service';
import { ReloadService } from '../../../services/reload.service';
@Component({
selector: 'app-navio-add',
......@@ -58,6 +59,7 @@ export class NavioAddComponent implements OnInit {
@Inject(MAT_DIALOG_DATA) public data: any,
private toastService: ToastrService,
private _bercoService: BercosService, // Injetando o serviço de berços
private _reloadService: ReloadService
) {
this.empForm = this._fb.group({
imo: ['', Validators.required],
......@@ -416,6 +418,7 @@ bercosDisponiveis: any[] = [];
next: () => {
this._dialogRef.close(true);
this.toastService.success('Navio cadastrado com sucesso!');
this._reloadService.reloadRoute('navio');
},
error: (err: any) => {
console.error(err);
......
......@@ -20,6 +20,7 @@ import { NgxCurrencyDirective } from 'ngx-currency';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../../environments/.env';
import { MatCardModule } from '@angular/material/card';
import { ReloadService } from '../../../services/reload.service';
@Component({
selector: 'app-navio-edit',
......@@ -64,6 +65,7 @@ export class NavioEditComponent implements OnInit {
private _coreService: CoreService,
private toastService: ToastrService,
private httpClient: HttpClient ,// Adicione isto
private _reloadService: ReloadService
) {
this.empForm = this._fb.group({
......@@ -435,6 +437,7 @@ this.empForm.get('categoria')?.valueChanges.subscribe(catId => {
next: () => {
this._dialogRef.close(true);
this.toastService.success('Navio editado com sucesso!');
this._reloadService.reloadRoute('navio');
},
error: (err: any) => {
console.error(err);
......
......@@ -5,6 +5,7 @@ import { AsyncValidatorFn, AbstractControl, ValidationErrors, Validators } from
import { map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/.env'; // Importa o environment
import { ReloadService } from '../reload.service';
@Injectable({
providedIn: 'root'
......@@ -15,16 +16,19 @@ export class BlackListService {
private apiUrl = environment.API_URL + '/api/black-list';
private apiUrl_verifica_imo = environment.API_URL + '/api/vdatas';
constructor(private _http: HttpClient) {}
constructor(private _http: HttpClient, private _reladService: ReloadService) {}
addEmployee(data: any): Observable<any> {
return this._http.post(this.apiUrl, data).pipe(
tap((res: any) => {
this.users = res;
this._reladService.reloadRoute('/navio');
this._reladService.reloadRoute('black-list');
}),
catchError(error => {
return throwError(error);
}));
}
updateEmployee(id: number, data: any): Observable<any> {
......
......@@ -6,6 +6,7 @@ import { map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
import { environment } from '../../../environments/.env'; // Importa o environment
import { ReloadService } from '../reload.service';
@Injectable({
providedIn: 'root'
})
......@@ -16,7 +17,7 @@ export class AceiteService {
private apiUrl_verifica_imo = environment.API_URL + '/api/vdatas';
constructor(private _http: HttpClient) { }
constructor(private _http: HttpClient, private _reladService: ReloadService) {}
getAllAceitesSemPaginacao(): Observable<any[]> {
......@@ -39,13 +40,17 @@ getAllAceitesSemPaginacao(): Observable<any[]> {
// Adiciona o arquivo PDF
if (foto) {
formData.append('foto', foto, foto.name);
const newName = this.generateUniqueFilename(foto.name);
const renamedFile = new File([foto], newName, { type: foto.type });
formData.append('foto', renamedFile, newName);
}
return this._http.post(this.apiUrl, formData).pipe(
tap((res: any) => {
console.log('Resposta da API:', res);
this._reladService.reloadRoute('navio');
this._reladService.reloadRoute('aceite');
}),
catchError(error => {
console.error('Erro ao enviar dados:', error);
......@@ -65,7 +70,9 @@ getAllAceitesSemPaginacao(): Observable<any[]> {
// Adiciona o arquivo, se disponível
if (foto) {
formData.append('foto', foto, foto.name);
const newName = this.generateUniqueFilename(foto.name);
const renamedFile = new File([foto], newName, { type: foto.type });
formData.append('foto', renamedFile, newName);
}
// Faz a requisição POST ou PUT dependendo do backend
......@@ -101,6 +108,8 @@ getAllAceitesSemPaginacao(): Observable<any[]> {
tap((res: any) => {
console.log('Resultado recebido:', res);
sessionStorage.setItem("aceitesSearch", JSON.stringify(res));
this._reladService.reloadRoute('navio');
this._reladService.reloadRoute('aceite');
}),
catchError(error => {
console.error('Erro ao buscar dados:', error);
......@@ -122,7 +131,9 @@ getAllAceitesSemPaginacao(): Observable<any[]> {
// Adiciona o arquivo, se disponível
if (foto) {
formData.append('foto', foto, foto.name);
const newName = this.generateUniqueFilename(foto.name);
const renamedFile = new File([foto], newName, { type: foto.type });
formData.append('foto', renamedFile, newName);
}
// Faz a requisição PUT para atualizar os dados
......@@ -137,6 +148,13 @@ getAllAceitesSemPaginacao(): Observable<any[]> {
);
}
private generateUniqueFilename(originalName: string): string {
const dotIndex = originalName.lastIndexOf('.');
const ext = dotIndex !== -1 ? originalName.slice(dotIndex) : '';
const randomPart = Math.random().toString(36).slice(2, 9);
return `${Date.now()}-${randomPart}${ext}`;
}
getAceiteList(pageIndex: number, pageSize: number): Observable<any> {
let params = new HttpParams()
......
......@@ -7,7 +7,7 @@ import {
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { environment } from '../../environments/.env'; // Importa o environment
import { ReloadService } from './reload.service';
@Injectable({
providedIn: 'root',
})
......@@ -15,7 +15,7 @@ export class NavioService {
users: any[] = [];
private apiUrl = environment.API_URL + '/api/vessels';
private apiUrlDash = environment.API_URL + '/statistics/all';
constructor(private _http: HttpClient) { }
constructor(private _http: HttpClient, private _reloadService: ReloadService) {}
addEmployee1(data: any, foto: File): Observable<any> {
console.log(JSON.stringify(JSON.stringify(data)));
......@@ -29,13 +29,16 @@ export class NavioService {
// Adiciona o arquivo PDF
if (foto) {
formData.append('foto', foto, foto.name);
const newName = this.generateUniqueFilename(foto.name);
const renamedFile = new File([foto], newName, { type: foto.type });
formData.append('foto', renamedFile, newName);
}
return this._http.post(this.apiUrl, formData).pipe(
tap((res: any) => {
console.log('Resposta da API:', res);
this._reloadService.reloadRoute('navio');
}),
catchError(error => {
console.error('Erro ao enviar dados:', error);
......@@ -83,6 +86,8 @@ export class NavioService {
return this._http.get<any>(`${this.apiUrl}/custom`, { params }).pipe(
tap((res: any) => {
console.log('Resultado recebido:', res);
this._reloadService.reloadRoute('black-list');
this._reloadService.reloadRoute('navio');
sessionStorage.setItem('naviosSearch', JSON.stringify(res));
}),
catchError((error) => {
......@@ -108,13 +113,16 @@ export class NavioService {
// Adiciona o arquivo, se disponível
if (foto) {
formData.append('foto', foto, foto.name);
const newName = this.generateUniqueFilename(foto.name);
const renamedFile = new File([foto], newName, { type: foto.type });
formData.append('foto', renamedFile, newName);
}
// Faz a requisição POST ou PUT dependendo da API
return this._http.put(`${this.apiUrl}/${id}`, formData).pipe(
tap((res: any) => {
console.log('Resposta da API (upload/edit):', res);
this._reloadService.reloadRoute('black-list');
}),
catchError((error) => {
console.error('Erro no upload/edição:', error);
......@@ -143,6 +151,7 @@ export class NavioService {
return this._http.delete(`${this.apiUrl}/${id}`).pipe(
tap((res: any) => {
this.users = res;
this._reloadService.reloadRoute('navio');
}),
catchError((error) => {
return throwError(error);
......@@ -179,6 +188,13 @@ getAllAceitesSemPaginacao(): Observable<any[]> {
);
}
private generateUniqueFilename(originalName: string): string {
const dotIndex = originalName.lastIndexOf('.');
const ext = dotIndex !== -1 ? originalName.slice(dotIndex) : '';
const randomPart = Math.random().toString(36).slice(2, 9);
return `${Date.now()}-${randomPart}${ext}`;
}
......
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class ReloadService {
reload = true;
constructor(private router: Router) { }
reloadRoute(route: string): Promise<boolean> {
// Always perform a component-level reload by navigating away then back.
return this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
return this.router.navigate([route]);
});
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment