Changeset b738035


Ignore:
Timestamp:
01/24/22 21:08:32 (3 years ago)
Author:
Ema <ema_spirova@…>
Branches:
master
Children:
76712b2
Parents:
bdd6491
Message:

signup/login server errors on front and remove location from planner

Files:
13 added
3 deleted
37 edited
1 moved

Legend:

Unmodified
Added
Removed
  • trip-planner-front/src/app/_models/city.ts

    rbdd6491 rb738035  
    77    constructor(){
    88        this.id = 1;
    9         this.name= 'City name';
    10         this.description= 'City description';
     9        this.name= '';
     10        this.description= '';
    1111    }
    1212}
  • trip-planner-front/src/app/_services/location.service.ts

    rbdd6491 rb738035  
    2323    postLocationToPlanner(plannerLocationDto : PlannerLocationDto) : Observable<Location>{
    2424        let url = "http://localhost:8080/api/add-location";
    25         return this.httpClient.put<Location>(url, plannerLocationDto);
     25        return this.httpClient.post<Location>(url, plannerLocationDto);
    2626    }
    2727
  • trip-planner-front/src/app/_services/planner.service.ts

    rbdd6491 rb738035  
    33import { Observable } from "rxjs";
    44import { PlannerDto } from "../_models/dto/plannerDto";
     5import { PlannerLocationDto } from "../_models/dto/plannerLocationDto";
    56import { Planner } from "../_models/planner";
    67
     
    1516        'Content-Type': 'application/json'
    1617    });
    17 
    1818
    1919    constructor(private httpClient: HttpClient) {
     
    3030    postInitialPlanner(plannerDto: PlannerDto): Observable<Planner> {
    3131        let url = "http://localhost:8080/api/planner/new";
    32         return this.httpClient.post<Planner>(url, plannerDto);
     32        return this.httpClient.post<Planner>(url, plannerDto, {headers: this.httpHeaders});
    3333    }
    3434
     
    4747        return this.httpClient.delete<Planner>(url, { headers: this.httpHeaders });
    4848    }
     49
     50    deleteLocationFromPlanner(plannerLocationDto : PlannerLocationDto) {
     51        let url = "http://localhost:8080/api/delete-location";
     52        const options = {
     53            body: {
     54                "plannerId": plannerLocationDto.plannerId,
     55                "locationId": plannerLocationDto.locationId
     56            }
     57        }
     58        return this.httpClient.request('delete', url, options);
     59    }
     60 
     61
    4962}
  • trip-planner-front/src/app/_services/user.service.ts

    rbdd6491 rb738035  
    4343    let user = sessionStorage.getItem("username");
    4444    let token = sessionStorage.getItem("token");
    45     console.log(user);
    46     console.log(token);
    47     console.log(!(user === null));
    4845    return !(user === null);
    4946  }
    5047
     48  getAllUsernames() {
     49    let url = "http://localhost:8080/api/users/usernames";
     50    return this.httpClient.get<string[]>(url);
     51  }
     52
     53  getPassword(loginRequest : LoginRequest){
     54    let url="http://localhost:8080/api/users/password";
     55    const options = {
     56     
     57      body: {
     58          "username": loginRequest.username
     59         
     60      }
     61  }
     62    return this.httpClient.request('get', url, options);
     63  }
     64
    5165}
  • trip-planner-front/src/app/app-routing.module.ts

    rbdd6491 rb738035  
    11import { NgModule } from '@angular/core';
    22import { RouterModule, Routes } from '@angular/router';
    3 import { AuthGuard } from './auth/auth.guard';
     3import { ExploreComponent } from './explore/explore.component';
    44import { HomepageComponent } from './homepage/homepage.component';
    55import { LoginComponent } from './homepage/login/login.component';
     
    1717  {path: '', component: HomepageComponent},
    1818  {path: '', component:LoginComponent},
    19   {path: 'location', component: LocationDetailsComponent}
     19  {path: 'location', component: LocationDetailsComponent},
     20  {path: 'explore', component: ExploreComponent}
    2021];
    2122
  • trip-planner-front/src/app/app.module.ts

    rbdd6491 rb738035  
    44import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
    55import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    6 import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
     6import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    77import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    88import { CategoryService } from './_services/cateogry.service';
     
    2626import { MatAutocompleteModule } from '@angular/material/autocomplete';
    2727import { EditPlannerComponent } from './planner/edit-planner/edit-planner.component';
    28 import { DetailPlannerComponent } from './planner/detail-planner/detail-planner.component';
    2928import { AddLocationToPlannerPanelComponent } from './location/add-location-to-planner-panel/add-location-to-planner-panel.component';
    3029import { HomepageComponent } from './homepage/homepage.component';
     
    4948import { AuthGuard } from './auth/auth.guard';
    5049import { AuthInterceptor } from './auth/auth.interceptor';
    51 
     50import { ExploreComponent } from './explore/explore.component';
     51import {AutoCompleteModule} from 'primeng/autocomplete';
     52import { ExploreResultComponent } from './explore/explore-result/explore-result.component';
     53import {RatingModule} from 'primeng/rating';
     54import { CustomValidators } from './providers/CustomValidators';
    5255
    5356@NgModule({
     
    5962    LocationsFormComponent,
    6063    EditPlannerComponent,
    61     DetailPlannerComponent,
    6264    AddLocationToPlannerPanelComponent,
    6365    HomepageComponent,
    6466    LocationDetailsComponent,
    6567    RegisterComponent,
    66     LoginComponent
     68    LoginComponent,
     69    ExploreComponent,
     70    ExploreResultComponent
    6771  ],
    6872  imports: [
     
    104108    FormsModule,
    105109    PaginatorModule,
    106     CardModule
     110    CardModule,
     111    AutoCompleteModule,
     112    RatingModule
    107113  ],
    108114
  • trip-planner-front/src/app/create-initial-planner/create-initial-planner.component.ts

    rbdd6491 rb738035  
    1919
    2020  ngOnInit(): void {
    21     this.plannerDto = new Planner();
     21    this.plannerDto = new PlannerDto();
    2222  }
    2323
  • trip-planner-front/src/app/homepage/homepage.component.html

    rbdd6491 rb738035  
    1010
    1111<body>
    12 
     12  <p-toast></p-toast>
    1313  <header>
    1414    <nav class="navbar navbar-expand-sm bg-light">
  • trip-planner-front/src/app/homepage/homepage.component.ts

    rbdd6491 rb738035  
    11import { HttpErrorResponse } from '@angular/common/http';
     2import { identifierModuleUrl } from '@angular/compiler';
    23import { Component, OnInit } from '@angular/core';
    34import { Router } from '@angular/router';
     5import { MessageService } from 'primeng/api';
    46import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
    57import { LoginRequest } from '../_models/dto/loginRequest';
     
    2022
    2123   imageURI = 'https://i.pinimg.com/736x/a1/1a/57/a11a572a1ec4e07039bbd04661a3b035.jpg';
    22    myLogo = 'http://www.logo-designer.co/wp-content/uploads/2020/02/2020-tripadvisor-new-logo-design-by-mother-design-4.png';
    2324   responsiveOptions;
    2425   locations: Location[];
     
    2728
    2829   constructor(private locationService: LocationService, private dialogService: DialogService, private userService: UserService,
    29       private router: Router) {
     30      private router: Router, private messageService: MessageService) {
    3031      this.responsiveOptions = [
    3132         {
     
    6162         }
    6263      );
    63 
    6464   }
    6565
     
    8282      },
    8383         err => {
    84 
     84            console.log("oops");
    8585         });
    8686   }
  • trip-planner-front/src/app/homepage/login/login.component.html

    rbdd6491 rb738035  
    1 <div class="p-col-12 p-md-4">
    2     <div class="p-inputgroup">
    3         <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
    4         <input type="text" pInputText placeholder="Email address (Username)"
    5              [(ngModel)]="loginRequest.username" name="username">
     1<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
     2    integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
     3
     4
     5
     6<div class="readersack">
     7    <div class="container">
     8        <div class="row">
     9            <div class="col-md-6 offset-md-3">
     10                <form [formGroup]="form" #myform="ngForm" (ngSubmit)="onFormLogIn(loginRequest)">
     11                    <div class="form-group">
     12
     13                        <label>Username (email)</label>
     14                        <input formControlName="username" id="username" type="text" class="form-control"
     15                            [(ngModel)]="loginRequest.username"
     16                            [ngClass]="{ 'is-invalid': myform.submitted && (form.get('username')?.errors?.['required']
     17                        || form.get('username')?.errors?.['validateUser'])}" />
     18                        <div *ngIf="form.get('username')?.hasError('required') && myform.submitted"
     19                            class="invalid-feedback">
     20                            Username is required
     21                        </div>
     22                        <div *ngIf="form.get('username')?.hasError('validateUser') && myform.submitted"
     23                            class="invalid-feedback">
     24                            Invalid username
     25                        </div>
     26
     27                        <label>Password</label>
     28                        <input formControlName="password" id="password" type="password" class="form-control"
     29                            [(ngModel)]="loginRequest.password" [ngClass]="{ 'is-invalid': myform.submitted && form.get('password')?.errors?.['required']}" />
     30                        <div *ngIf="form.get('password')?.hasError('required') && myform.submitted"
     31                            class="invalid-feedback">
     32                            Password is required</div>
     33                       
     34
     35                        <div class="p-col-12 p-md-4">
     36                            <button type="submit" pButton pRipple class="p-button-secondary">Submit</button>
     37                        </div>
     38                    </div>
     39                </form>
     40            </div>
     41        </div>
    642    </div>
    743</div>
    8 <div class="p-col-12 p-md-4">
    9     <div class="p-inputgroup">
    10         <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
    11         <input type="password" pInputText placeholder="Password" name="password" [(ngModel)]="loginRequest.password">
    12     </div>
    13 </div>
    14 
    15 <div class="p-col-12 p-md-4">
    16     <button pButton pRipple label="Log in" class="p-button-secondary" type="submit"
    17         (click)="onFormLogIn(loginRequest)"></button>
    18 </div>
  • trip-planner-front/src/app/homepage/login/login.component.ts

    rbdd6491 rb738035  
    11import { Component, OnInit } from '@angular/core';
    2 import { Router } from '@angular/router';
     2import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
    33import { DynamicDialogRef } from 'primeng/dynamicdialog';
    44import { LoginRequest } from 'src/app/_models/dto/loginRequest';
     5import { PlannerLocationDto } from 'src/app/_models/dto/plannerLocationDto';
     6import { UserDto } from 'src/app/_models/dto/userDto';
     7import { UsernameDto } from 'src/app/_models/dto/usernameDto';
    58import { UserService } from 'src/app/_services/user.service';
    69
     
    1215export class LoginComponent implements OnInit {
    1316
     17  form: FormGroup;
     18  loginRequest: LoginRequest;
     19  usernames: string[];
    1420
    15   loginRequest : LoginRequest;
     21  constructor(private ref: DynamicDialogRef, private userService: UserService, formBuilder: FormBuilder) {
     22    this.loginRequest = new LoginRequest();
     23    this.usernames = [];
    1624
    17   constructor(private ref: DynamicDialogRef, private router: Router, private userService : UserService) {
    18     this.loginRequest = new LoginRequest();
    19    
     25    this.form = formBuilder.group({
     26      username: new FormControl('', [Validators.required]),
     27      password: new FormControl('', [Validators.required, Validators.minLength(6)]),
     28    },
     29      {
     30        validators: [
     31          this.validateUser('username')
     32        ]
     33      }
     34    );
    2035  }
    2136
    2237  ngOnInit(): void {
     38
    2339  }
    2440
    25   onFormLogIn(loginRequest){
    26     this.ref.close(loginRequest);
    27    
     41  onFormLogIn(loginRequest) {
     42    const { valid } = this.form;
     43    if (valid) {
     44      this.ref.close(loginRequest);
     45    }
     46  }
     47
     48  validateUser(username: string) {
     49    return (formGroup: FormGroup) => {
     50      const control = formGroup.controls[username];
     51
     52      if (control.errors && !control.errors.validateUser) {
     53        return;
     54      }
     55
     56      this.userService.getAllUsernames().subscribe(
     57        data => {
     58          this.usernames = data;
     59          for (let i = 0; i < this.usernames.length; i++) {
     60            if (control.value === this.usernames[i]) {
     61              control.setErrors(null);
     62             
     63              break;
     64            } else {
     65              control.setErrors({ validateUser: true });
     66            }
     67
     68          }
     69        }
     70      );
     71      return null;
     72 
     73    };
     74
    2875  }
    2976}
  • trip-planner-front/src/app/homepage/register/register.component.html

    rbdd6491 rb738035  
    22    integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    33
    4 <div class="p-grid p-fluid">
    5     <div class="p-col-12 p-md-4">
    6         <div class="p-inputgroup">
    7             <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
    8             <input type="text" pInputText placeholder="Full name" [(ngModel)]="user.fullName" name="fullName"
    9                 class="form-control">
    104
     5<div class="readersack">
     6    <div class="container">
     7        <div class="row">
     8            <div class="col-md-6 offset-md-3">
     9                <form [formGroup]="form" #myform="ngForm" (ngSubmit)="onFormSubmitSignUp(user)">
     10                    <div class="form-group">
     11                        <label>Full name</label>
     12                        <input formControlName="fullName" id="fullName" type="text" class="form-control"
     13                            [(ngModel)]="user.fullName"
     14                            [ngClass]="{ 'is-invalid': myform.submitted && form.get('fullName')?.errors?.['required']}" />
     15                        <div *ngIf="myform.submitted && form.get('fullName')?.errors" class="invalid-feedback">
     16                            <div *ngIf="form.get('fullName')?.hasError('required') && myform.submitted">
     17                                Full Name is required
     18                            </div>
     19                        </div>
     20
     21                        <label>Username (email)</label>
     22                        <input formControlName="username" id="username" type="text" class="form-control"
     23                            [(ngModel)]="user.username"
     24                            [ngClass]="{ 'is-invalid': myform.submitted && (form.get('username')?.errors?.['required'] ||
     25                            form.get('username')?.errors?.['email'] || form.get('username')?.hasError('validateUsername'))}" />
     26                        <div *ngIf="form.get('username')?.hasError('required') && myform.submitted"
     27                            class="invalid-feedback">
     28                            Username is required</div>
     29                        <div *ngIf="form.get('username')?.hasError('email') && myform.submitted"
     30                            class="invalid-feedback">
     31                            Please enter valid email.</div>
     32                        <div *ngIf="form.get('username')?.hasError('validateUsername') && myform.submitted"
     33                            class="invalid-feedback">
     34                            Username already exists</div>
     35
     36
     37
     38                        <label>Password</label>
     39                        <input formControlName="password" id="password" type="password" class="form-control"
     40                            [(ngModel)]="user.password" [ngClass]="{ 'is-invalid': myform.submitted && (form.get('password')?.errors?.['required'] ||
     41                            form.get('password')?.errors?.['minlength'])}" />
     42                        <div *ngIf="form.get('password')?.hasError('required') && myform.submitted"
     43                            class="invalid-feedback">
     44                            Password is required</div>
     45                        <div *ngIf="form.get('password')?.errors?.['minlength'] && myform.submitted"
     46                            class="invalid-feedback">
     47                            Password must be at least 6 characters long.
     48                        </div>
     49
     50                        <label>Confirm password</label>
     51                        <input formControlName="confirmPassword" id="confirmPassword" type="password"
     52                            class="form-control" [(ngModel)]="user.confirmPassword"
     53                            [ngClass]="{ 'is-invalid': myform.submitted && (form.get('confirmPassword')?.errors?.['required'] ||
     54                            form.get('confirmPassword')?.errors?.['minlength'] || form.get('confirmPassword')?.errors?.['mustMatch'])}" />
     55                        <div *ngIf="form.get('confirmPassword')?.hasError('required') && myform.submitted"
     56                            class="invalid-feedback">
     57                            Confirm Password is required</div>
     58                        <div *ngIf="form.get('confirmPassword')?.errors?.['minlength'] && myform.submitted"
     59                            class="invalid-feedback">
     60                            Confirm Password must be at least 6 characters long.
     61                        </div>
     62                        <div *ngIf="form.get('confirmPassword')?.errors?.['mustMatch'] && myform.submitted"
     63                            class="invalid-feedback">Password and confirm password must match
     64                        </div>
     65
     66                        <div class="p-col-12 p-md-4">
     67                            <button type="submit" pButton pRipple class="p-button-secondary">Submit</button>
     68                        </div>
     69                    </div>
     70                </form>
     71            </div>
    1172        </div>
    1273    </div>
    13 
    14     <div class="p-col-12 p-md-4">
    15         <div class="p-inputgroup">
    16             <span class="p-inputgroup-addon"><i class="pi pi-user"></i></span>
    17             <input type="text" pInputText placeholder="Email address (Username)" [(ngModel)]="user.username"
    18                 name="username">
    19         </div>
    20     </div>
    21 
    22     <div class="p-col-12 p-md-4">
    23         <div class="p-inputgroup">
    24             <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
    25             <input type="password" pInputText placeholder="Password" [(ngModel)]="user.password" name="password">
    26         </div>
    27     </div>
    28 
    29     <div class="p-col-12 p-md-4">
    30         <div class="p-inputgroup">
    31             <span class="p-inputgroup-addon"><i class="pi pi-password"></i></span>
    32             <input type="password" pInputText placeholder="Repeat password" [(ngModel)]="user.confirmPassword"
    33                 name="confirmPassword">
    34         </div>
    35     </div>
    36 
    37     <div class="p-col-12 p-md-4">
    38         <button pButton pRipple label="Submit" class="p-button-secondary" type="button"
    39             (click)="onFormSubmitSignUp(user)"></button>
    40     </div>
    4174</div>
    42 
    43 
  • trip-planner-front/src/app/homepage/register/register.component.ts

    rbdd6491 rb738035  
    11import { Component, OnInit } from '@angular/core';
    2 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
     2import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
    33import { DynamicDialogRef } from 'primeng/dynamicdialog';
     4import { CustomValidators } from 'src/app/providers/CustomValidators';
    45import { UserDto } from 'src/app/_models/dto/userDto';
     6import { UserService } from 'src/app/_services/user.service';
    57
    68@Component({
     
    1214
    1315  user: UserDto;
    14   myForm: FormGroup;
     16  form: FormGroup;
     17  usernames: string[];
    1518
    16   constructor(private ref: DynamicDialogRef, private fb: FormBuilder) {
     19
     20  constructor(private ref: DynamicDialogRef,
     21    formBuilder: FormBuilder, private userService: UserService) {
    1722    this.user = new UserDto();
    18     this.myForm = fb.group({
    19       title: fb.control('initial value', Validators.required)
     23    this.usernames = [];
     24
     25    this.form = formBuilder.group({
     26      fullName: new FormControl('', [Validators.required, Validators.minLength(3)]),
     27      username: new FormControl('', [Validators.required, Validators.email]),
     28      password: new FormControl('', [Validators.required, Validators.minLength(6)]),
     29      confirmPassword: new FormControl('', [Validators.required, Validators.minLength(6)])
     30    }, {
     31      validators: [
     32        CustomValidators.mustMatch('password', 'confirmPassword'),
     33        this.validateUsername('username')
     34      ]
    2035    });
    2136  }
    2237
    2338  ngOnInit(): void {
    24     this.myForm = this.fb.group({
    25       fullName: this.fb.control('', Validators.required),
    26       username: this.fb.control('', Validators.required),
    27       password: this.fb.control('', Validators.required),
    28       confirmPassword: this.fb.control('', Validators.required)
    29     });
    3039  }
    3140
    3241  onFormSubmitSignUp(user) {
    33     this.ref.close(user);
    34     //window.location.reload();
     42    const { valid } = this.form;
     43    if (valid) {
     44      this.ref.close(user);
     45    }
     46  }
     47
     48  validateUsername(username: string) {
     49    return (formGroup: FormGroup) => {
     50      const control = formGroup.controls[username];
     51
     52      if (control.errors && !control.errors.validateUsername) {
     53        return;
     54      }
     55
     56      this.userService.getAllUsernames().subscribe(
     57        data => {
     58          this.usernames = data;
     59          for (let i = 0; i < this.usernames.length; i++) {
     60            if (control.value === this.usernames[i]) {
     61              control.setErrors({ validateUsername: true });
     62              break;
     63            } else {
     64              control.setErrors(null);
     65            }
     66          }
     67        }
     68      );
     69      return null;
     70    };
    3571
    3672  }
  • trip-planner-front/src/app/location/add-location-to-planner-panel/add-location-to-planner-panel.component.html

    rbdd6491 rb738035  
    77        </tr>
    88    </ng-template>
    9     <ng-template pTemplate="body" let-planner let-data>
     9    <ng-template pTemplate="body" let-planner>
    1010        <tr>
    1111            <td>{{planner.name}}</td>
  • trip-planner-front/src/app/location/add-location-to-planner-panel/add-location-to-planner-panel.component.ts

    rbdd6491 rb738035  
    11import { Component, OnInit } from '@angular/core';
    2 import { ActivatedRoute } from '@angular/router';
    32import { Planner } from 'src/app/_models/planner';
    43import { PlannerService } from 'src/app/_services/planner.service';
    54import { DynamicDialogRef } from 'primeng/dynamicdialog';
    6 import { LocationService } from 'src/app/_services/location.service';
    75
    86
     
    1715  planners: Planner[];
    1816 
    19   constructor(private plannerService: PlannerService,
    20     private route: ActivatedRoute, private ref: DynamicDialogRef, private locationService : LocationService) {
     17  constructor(private plannerService: PlannerService, private ref: DynamicDialogRef) {
    2118    this.planners = [];
    2219  }
     
    2926      }
    3027    );
    31 
    3228  }
    3329
  • trip-planner-front/src/app/location/location-details/location-details.component.html

    rbdd6491 rb738035  
    1818            </ng-template>
    1919        </p-galleria>
     20        <br>
     21        <p-rating></p-rating>
    2022    </div>
    2123</div>
  • trip-planner-front/src/app/location/location-details/location-details.component.ts

    rbdd6491 rb738035  
    1 import { Component, OnInit, ViewEncapsulation } from '@angular/core';
     1import { Component, OnInit } from '@angular/core';
    22import { ActivatedRoute, Router } from '@angular/router';
    33import { Images } from 'src/app/_models/images';
  • trip-planner-front/src/app/location/location.component.css

    rbdd6491 rb738035  
     1img{
     2    width: 150px;
     3    height: 120px;
     4    display: block;
     5}
  • trip-planner-front/src/app/location/location.component.html

    rbdd6491 rb738035  
    99    <tr>
    1010      <th scope="col">#</th>
     11      <th scope="col">Photo</th>
    1112      <th scope="col">Location name</th>
    1213      <th scope="col"> Add to my planner</th>
     
    1718    <tr *ngFor="let location of listLocations">
    1819      <td>{{location.id}}</td>
     20      <td><img src="data:image/png;base64,{{location.photo}}" /></td>
    1921      <td>{{location.name}}</td>
    2022      <td><button type="button" (click)="show(location)" pButton icon="pi pi-info-circle"
    2123          label="Add to my planner"></button></td>
    2224      <td><button type="button" color="primary" pButton icon="pi pi-info-circle"
    23           (click)="onClickSeeDetails(location.id)" label="See details"></button></td>
     25          (click)="onClickSeeDetails(location.id)" label="See details"></button>
     26      </td>
    2427    </tr>
    2528  </tbody>
  • trip-planner-front/src/app/location/location.component.ts

    rbdd6491 rb738035  
    9393
    9494    this.ref.onClose.subscribe((planner: Planner) => {
    95       if(planner){
    96       this.plannerLocationDto.locationId = location.id;
    97       this.plannerLocationDto.plannerId = planner.id;
    98       console.log("LOC ID: " + this.plannerLocationDto.locationId);
    99       console.log("PLANNER ID: " + this.plannerLocationDto.plannerId);
     95      if (planner) {
     96        this.plannerLocationDto.locationId = location.id;
     97        this.plannerLocationDto.plannerId = planner.id;
     98        console.log("LOC ID: " + this.plannerLocationDto.locationId);
     99        console.log("PLANNER ID: " + this.plannerLocationDto.plannerId);
    100100
    101       this.locationService.getAllLocationIdsForPlanner(planner.id).subscribe(
    102         lid => {
    103           if (lid.length == 0) {
    104             this.locationService.postLocationToPlanner(this.plannerLocationDto).subscribe(
    105               data => {
    106                 console.log(data);
    107               }
    108             );
    109             this.messageService.add({ severity: 'success', summary: 'Location ' + location.name + ' has been added to planner: ', detail: planner.name });
    110 
    111           } else if (lid.length > 0) {
    112             if (lid.indexOf(this.plannerLocationDto.locationId) !== -1) {
    113               console.log("LOKACIJATA VEKE JA IMA VO PLANEROT");
    114               this.messageService.add({ severity: 'error', summary: 'Location ' + location.name + ' already exists in the planner.' });
    115             } else {
     101        this.locationService.getAllLocationIdsForPlanner(planner.id).subscribe(
     102          lid => {
     103            if (lid.length == 0) {
    116104              this.locationService.postLocationToPlanner(this.plannerLocationDto).subscribe(
    117105                data => {
     
    120108              );
    121109              this.messageService.add({ severity: 'success', summary: 'Location ' + location.name + ' has been added to planner: ', detail: planner.name });
     110
     111            } else if (lid.length > 0) {
     112              if (lid.indexOf(this.plannerLocationDto.locationId) !== -1) {
     113                console.log("LOKACIJATA VEKE JA IMA VO PLANEROT");
     114                this.messageService.add({ severity: 'error', summary: 'Location ' + location.name + ' already exists in the planner.' });
     115              } else {
     116                this.locationService.postLocationToPlanner(this.plannerLocationDto).subscribe(
     117                  data => {
     118                    console.log(data);
     119                  }
     120                );
     121                this.messageService.add({ severity: 'success', summary: 'Location ' + location.name + ' has been added to planner: ', detail: planner.name });
     122              }
     123
    122124            }
    123 
    124125          }
    125         }
    126       );
     126        );
    127127      }
    128128    });
    129  
     129
    130130  }
    131131
  • trip-planner-front/src/app/planner/edit-planner/edit-planner.component.html

    rbdd6491 rb738035  
    3838                                </td>
    3939                                <td>
    40                                     <button pButton pRipple type="button" icon="pi pi-times" class="p-button-rounded p-button-danger p-button-text"></button>
     40                                    <button pButton pRipple type="button" icon="pi pi-times" class="p-button-rounded p-button-danger p-button-text" (click)="onClickRemoveLocation(planner, location)"></button>
    4141                                </td>
    4242                            </tr>
  • trip-planner-front/src/app/planner/edit-planner/edit-planner.component.ts

    rbdd6491 rb738035  
    33import { ActivatedRoute, Router } from '@angular/router';
    44import { PlannerDto } from 'src/app/_models/dto/plannerDto';
     5import { PlannerLocationDto } from 'src/app/_models/dto/plannerLocationDto';
    56import { Location } from 'src/app/_models/location';
    67import { Planner } from 'src/app/_models/planner';
     
    2122  id: number;
    2223  locations: Location[];
    23 
     24  plannerLocationDto: PlannerLocationDto;
    2425
    2526  constructor(private router: Router, private route: ActivatedRoute, private fb: FormBuilder, private plannerService: PlannerService,
     
    3334    this.id = 1;
    3435    this.locations = [];
     36    this.plannerLocationDto = new PlannerLocationDto();
    3537  }
    3638
     
    6466  }
    6567
    66   private updatePlanner() {
     68  updatePlanner() {
    6769    this.plannerService.updatePlanner(this.id, this.form.value)
    6870      .pipe()
     
    8183  }
    8284
    83   onClickRemoveLocation(id : number){
    84    
     85  onClickRemoveLocation(planner: Planner, location: Location) {
     86    planner.id = this.id;
     87
     88    this.plannerLocationDto.plannerId = planner.id;
     89    this.plannerLocationDto.locationId = location.id;
     90    console.log(this.plannerLocationDto.plannerId);
     91    console.log(this.plannerLocationDto.locationId);
     92    this.plannerService.deleteLocationFromPlanner(this.plannerLocationDto).subscribe(
     93      data => {
     94        console.log("deleted")
     95      }
     96    );
     97    window.location.reload();
    8598  }
    8699}
  • trip-planner-front/src/app/planner/planner.component.ts

    rbdd6491 rb738035  
    7272        this.messageService.add({ severity: 'success', summary: 'The planner: ' + plannerDto.name + ' has been created.' });
    7373      }
    74      
     74
    7575    });
    7676
  • trip-planner/src/main/java/finki/diplomska/tripplanner/repository/jpa/JpaLocationRepository.java

    rbdd6491 rb738035  
    109109    List<Location> getVillages();
    110110
     111    @Query(value = "SELECT * FROM locations AS l WHERE l.id_city = :cityId", nativeQuery = true)
     112    List<Location> getLocationsForCity(@Param("cityId") Long cityId);
    111113}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/repository/jpa/JpaPlannerRepository.java

    rbdd6491 rb738035  
    1616        List<Planner> getPlannersByUser(@Param("username") String username );
    1717
    18         @Query(value = "delete from planners_contain WHERE planners_contain.id_location = :locationId", nativeQuery = true)
    19         void deleteLocationFromPlanner(@Param("locationId") Long locationId);
     18        @Query(value = "DELETE planners_contain " +
     19                "FROM planners_contain " +
     20                "JOIN planners ON planners_contain.id_planner = planners.id_planner " +
     21                "JOIN locations ON planners_contain.id_location = locations.id_location " +
     22                "WHERE planners_contain.id_planner = :plannerId AND planners_contain.id_location = :locationId", nativeQuery = true)
     23        void deleteLocationFromPlanner(@Param("plannerId") Long plannerId, @Param("locationId") Long locationId);
    2024}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/repository/jpa/JpaUserRepository.java

    rbdd6491 rb738035  
    22
    33import finki.diplomska.tripplanner.models.User;
     4import org.springframework.data.jpa.repository.Query;
    45import org.springframework.data.repository.CrudRepository;
     6import org.springframework.data.repository.query.Param;
    57import org.springframework.stereotype.Repository;
     8
     9import java.util.List;
     10import java.util.Optional;
    611
    712@Repository
     
    914    User findByUsername(String username);
    1015    User getById(Long id);
     16
     17    @Query(value = "SELECT u.username FROM users AS u", nativeQuery = true)
     18    List<String> getAllUsernames();
     19
     20    @Query(value = "SELECT u.password FROM users AS u WHERE u.username LIKE :username ", nativeQuery = true)
     21    Optional<String> getPassword(@Param("username") String username);
     22
    1123}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/security/SecurityConfig.java

    rbdd6491 rb738035  
    7878                .antMatchers("/api/weekend").permitAll()
    7979                .antMatchers("/api/villages").permitAll()
     80                .antMatchers("/api/cities").permitAll()
    8081                .anyRequest().authenticated();
    8182        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/LocationService.java

    rbdd6491 rb738035  
    2525    List<Location> getVillages();
    2626    List<Long> getAllLocationIdsForPlanner(Long plannerId);
     27    List<Location> getLocationsForCity(Long cityId);
    2728}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/PlannerService.java

    rbdd6491 rb738035  
    44import finki.diplomska.tripplanner.models.Planner;
    55import finki.diplomska.tripplanner.models.dto.PlannerDto;
     6import finki.diplomska.tripplanner.models.dto.PlannerLocationDto;
     7import org.springframework.http.ResponseEntity;
    68
    79import java.util.List;
     
    1820        Optional<Planner> newPlanner(PlannerDto plannerDto, String username);
    1921        void deletePlannerById(Long id);
    20         void deleteLocationFromPlanner(Long locationId);
     22        ResponseEntity deleteLocationFromPlanner(PlannerLocationDto plannerLocationDto);
    2123}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/UserService.java

    rbdd6491 rb738035  
    44import finki.diplomska.tripplanner.models.dto.UserDto;
    55
     6import java.util.List;
    67import java.util.Optional;
    78
     
    1011
    1112    User saveUser (User user);
    12 
     13    List<String> getAllUsernames();
     14    Optional<String> getPassword(UserDto userDto);
     15    Optional<User> findById(Long id);
    1316}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/impl/LocationServiceImpl.java

    rbdd6491 rb738035  
    183183        return this.locationRepository.getAllLocationIdsForPlanner(plannerId);
    184184    }
     185
     186    @Override
     187    public List<Location> getLocationsForCity(Long cityId) {
     188        return this.locationRepository.getLocationsForCity(cityId);
     189    }
    185190}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/impl/PlannerServiceImpl.java

    rbdd6491 rb738035  
    55import finki.diplomska.tripplanner.models.User;
    66import finki.diplomska.tripplanner.models.dto.PlannerDto;
     7import finki.diplomska.tripplanner.models.dto.PlannerLocationDto;
    78import finki.diplomska.tripplanner.models.exceptions.LocationNotFoundException;
    89import finki.diplomska.tripplanner.models.exceptions.PlannerNotFoundException;
     
    1112import finki.diplomska.tripplanner.repository.jpa.JpaUserRepository;
    1213import finki.diplomska.tripplanner.service.PlannerService;
     14import org.springframework.http.ResponseEntity;
    1315import org.springframework.stereotype.Service;
    1416
     
    6769
    6870    @Override
    69     public void deleteLocationFromPlanner(Long locationId) {
    70         this.plannerRepository.deleteLocationFromPlanner(locationId);
     71    public ResponseEntity deleteLocationFromPlanner(PlannerLocationDto plannerLocationDto) {
     72        plannerRepository.deleteLocationFromPlanner(plannerLocationDto.getPlannerId(), plannerLocationDto.getLocationId());
     73        return null;
    7174    }
    7275
  • trip-planner/src/main/java/finki/diplomska/tripplanner/service/impl/UserServiceImpl.java

    rbdd6491 rb738035  
    77import finki.diplomska.tripplanner.service.UserService;
    88import org.springframework.beans.factory.annotation.Autowired;
     9import org.springframework.http.ResponseEntity;
    910import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    1011import org.springframework.stereotype.Service;
    1112
     13import java.util.List;
    1214import java.util.Optional;
    1315
     
    3436            throw new UsernameAlreadyExistsException("Username '"+newUser.getUsername()+ "' already exists");
    3537        }
     38    }
    3639
     40    @Override
     41    public List<String> getAllUsernames() {
     42        return this.userRepository.getAllUsernames();
     43    }
     44
     45    @Override
     46    public Optional<String> getPassword(UserDto userDto) {
     47         this.userRepository.getPassword(userDto.getUsername());
     48         return null;
     49    }
     50
     51    @Override
     52    public Optional<User> findById(Long id) {
     53        return this.userRepository.findById(id);
    3754    }
    3855
  • trip-planner/src/main/java/finki/diplomska/tripplanner/web/rest/LocationRestController.java

    rbdd6491 rb738035  
    4545
    4646    @GetMapping(value = "/region/locations")
    47     public List<Location> getAllLocationsFromRegion(@RequestParam(required = false) Long regionId,
    48                                                     @RequestParam(required = false)  Long companionId,
    49                                                     @RequestParam(required = false) Long lengthOfStay,
    50                                                     @RequestParam(required = false) String categoryIds){
     47    public List<Location> getAllLocationsFromRegion(@RequestParam Long regionId,
     48                                                    @RequestParam  Long companionId,
     49                                                    @RequestParam Long lengthOfStay,
     50                                                    @RequestParam String categoryIds){
    5151        return this.locationService.findLocationsFromRegionForm(regionId, companionId,lengthOfStay, categoryIds);
    5252    }
    5353
    54     @PutMapping(value = "/add-location")
     54    @PostMapping(value = "/add-location")
    5555    public Location addLocationToPlanner(@RequestBody PlannerLocationDto plannerLocationDto){
    5656        return this.locationService.addLocationToPlanner(plannerLocationDto);
  • trip-planner/src/main/java/finki/diplomska/tripplanner/web/rest/PlannerRestController.java

    rbdd6491 rb738035  
    55import finki.diplomska.tripplanner.models.User;
    66import finki.diplomska.tripplanner.models.dto.PlannerDto;
     7import finki.diplomska.tripplanner.models.dto.PlannerLocationDto;
    78import finki.diplomska.tripplanner.service.LocationService;
    89import finki.diplomska.tripplanner.service.PlannerService;
     
    9293    }
    9394
    94 
    95     @DeleteMapping(value = "/delete-from-planner")
    96     public ResponseEntity deleteLocationFromPlanner(@PathVariable Long locationId){
    97         this.plannerService.deleteLocationFromPlanner(locationId);
    98         return this.locationService.findById(locationId)
    99                 .map(location -> ResponseEntity.ok().body(location))
    100                 .orElseGet(()-> ResponseEntity.notFound().build());
     95    @DeleteMapping(value = "/delete-location")
     96    public ResponseEntity deleteLocationFromPlanner(@RequestBody PlannerLocationDto plannerLocationDto){
     97       return  this.plannerService.deleteLocationFromPlanner(plannerLocationDto);
    10198    }
    10299}
  • trip-planner/src/main/java/finki/diplomska/tripplanner/web/rest/UserController.java

    rbdd6491 rb738035  
    1919import org.springframework.web.bind.annotation.*;
    2020import org.springframework.security.core.Authentication;
     21
    2122import javax.validation.Valid;
     23import java.util.List;
     24import java.util.Optional;
    2225
    2326@RestController
     
    5255                )
    5356        );
    54 
    5557        SecurityContextHolder.getContext().setAuthentication(authentication);
    5658        String jwt = SecurityConstants.TOKEN_PREFIX +  tokenProvider.generateToken(authentication);
    57 
    5859        return ResponseEntity.ok(new JWTLoginSucessReponse(true, jwt));
    5960    }
     
    6566        ResponseEntity<?> errorMap = mapValidationErrorService.MapValidationService(result);
    6667        if(errorMap != null)return errorMap;
     68        User newUser = userService.saveUser(user);
     69        return  new ResponseEntity<User>(newUser, HttpStatus.CREATED);
     70    }
    6771
    68         User newUser = userService.saveUser(user);
     72    @GetMapping(value = "/usernames")
     73    public List<String> getAllUsernames (){
     74        return this.userService.getAllUsernames();
     75    }
    6976
    70         return  new ResponseEntity<User>(newUser, HttpStatus.CREATED);
     77    @GetMapping(value = "/password")
     78    public Optional<String> getPassword(@RequestBody UserDto userDto){
    7179
     80        return this.userService.getPassword(userDto);
    7281    }
     82
    7383}
  • trip-planner/src/test/api.http

    rbdd6491 rb738035  
    9494
    9595###
    96 DELETE http://localhost:8080/api/delete/19
     96DELETE http://localhost:8080/api/delete-location
    9797Content-Type: application/json
     98
     99{"plannerId": 23, "locationId": 3}
     100
     101###
     102GET http://localhost:8080/api/users/usernames
     103Content-Type: application/json
     104
     105###
     106GET http://localhost:8080/api/users/password
     107Content-Type: application/json
     108
     109{"username": "ema@test.com"}
Note: See TracChangeset for help on using the changeset viewer.