<repo_name>jscubillos5/Prueba-NUVU<file_sep>/FRONTEND/src/classes/Person/Person.spect.ts
import { Person } from 'src/classes/Person/Person';

describe('Person', () => {
    it('should create an instance', () => {
        expect(new Person()).toBeTruthy();
    });
});
<file_sep>/FRONTEND/src/services/Person.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, pipe } from 'rxjs';
import { Person } from 'src/classes/Person/Person';
import { retry, catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class PersonService {

    private personURL: string;

    httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    }

    constructor(private http: HttpClient) {
        console.log(HttpHeaders);
        console.log(Observable);
        console.log(pipe);
        var mainHost = 'http://localhost:';
        var port = '8081';
        var mainURL = '/Person/';
        this.personURL = mainHost + port + mainURL;
    }

    public getPersons(): Observable<Person[]> {
        var endpoint = 'get-persons';
        return this.http.get<Person[]>(this.personURL + endpoint);
    }

    public addPerson(person: Person) {
        var endpoint = 'add-person';
        var url = this.personURL + endpoint;
        console.log("addPerson url: " + url + " person: " + JSON.stringify(person));
        return this.http.post<Person>(url, JSON.stringify(person), this.httpOptions)
            .pipe(
                retry(1),
                catchError(this.handleError)
            )
    }

    public deletePerson(id: number) {
        var endpoint = 'delete-person';
        var param = '?id=';
        var url = this.personURL + endpoint + param + + id.toString();
        console.log("deletePerson url: " + url);
        return this.http.post<Person>(url, null, this.httpOptions)
            .pipe(
                retry(1),
                catchError(this.handleError)
            )
    }

    private handleError(error: HttpErrorResponse): any {
        if (error.status == 406) {
            console.error(error.message);
            alert("The person has already been added or removed, please review");
        } else if (error.status == 409) {
            console.error(error.message);
            alert("Server error, please contact customer service");
        }
        return throwError(
            'Something bad happened; please try again later.');
    }
}<file_sep>/FRONTEND/src/app/person/person.component.ts
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { PersonService } from 'src/services/Person.service';
import { Person } from 'src/classes/Person/Person';


@Component({
  selector: 'app-person-form',
  templateUrl: './person.component.html',
  styleUrls: ['./person.component.css']
})
export class PersonComponent {

  person: Person;
  persons: Person[];

  constructor(private route: ActivatedRoute,
    private router: Router,
    private personService: PersonService) {
    this.person = new Person();
    this.persons = [];
  }

  ngOnInit() {
    this.refreshPerson()
  }

  refreshPerson() {
    this.personService.getPersons()
      .subscribe(data => {
        console.log(data)
        this.persons = data;
      })

  }

  clearformPerson() {
    this.person = new Person();
  }

  addPerson(): void {
    const idDefault = 0;
    this.person.id = idDefault;
    this.personService.addPerson(this.person).subscribe(data => {
      console.log(data)
      this.refreshPerson();
    });
    this.clearformPerson();
  }

  deletePerson(id: number, name: string): void {
    if (confirm("Are you sure to delete: " + name)) {
      this.personService.deletePerson(id).subscribe(data => {
        console.log(data)
        this.refreshPerson();
      });
    }
  }
}
<file_sep>/BACK/src/main/java/com/nuvu/dao/CreditCardDao.java
package com.nuvu.dao;

import com.nuvu.model.CreditCard;
import com.nuvu.repositories.CreditCardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

@Component
public class CreditCardDao {

    @Autowired
    CreditCardRepository creditCardRepository;

    public CreditCard getCreditCard(Long id) {
        return creditCardRepository.findById(id).orElse(null);
    }

    public CreditCard getCreditCardByNumber(int number) {
        return creditCardRepository.findByNumber(number);
    }

    public List<CreditCard> getCreditCardByPerson(Long idPerson) {
        List<CreditCard> results = new ArrayList<>();
        for (CreditCard creditCard : creditCardRepository.findAll()) {
            if (creditCard.getIdPerson() == idPerson) {
                results.add(creditCard);
            }
        }
        return results;
    }

    public void addCreditCard(CreditCard creditCard) {
        creditCardRepository.save(creditCard);
    }

    public void deleteCreditCard(Long id) {
        creditCardRepository.deleteById(id);
    }
}
<file_sep>/BACK/src/main/java/com/nuvu/model/Person.java
package com.nuvu.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String identification;
    private String name;
    private String email;
    private Date dateRegister;

    public Person(long id, String identification, String name, String email, Date dateRegister) {
        this.id = id;
        this.identification = identification;
        this.name = name;
        this.email = email;
        this.dateRegister = dateRegister;
    }

    public Person() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getIdentification() {
        return identification;
    }

    public void setIdentification(String identification) {
        this.identification = identification;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getDateRegister() {
        return dateRegister;
    }

    public void setDateRegister(Date dateRegister) {
        this.dateRegister = dateRegister;
    }
}
<file_sep>/BACK/src/main/java/com/nuvu/dto/PersonDto.java
package com.nuvu.dto;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

public class PersonDto {

    private long id;
    private String identification;
    private String name;
    private String email;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getIdentification() {
        return identification;
    }

    public void setIdentification(String identification) {
        this.identification = identification;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
<file_sep>/BACK/src/main/java/com/nuvu/repositories/CreditCardRepository.java
package com.nuvu.repositories;

import com.nuvu.model.CreditCard;
import org.springframework.data.repository.CrudRepository;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

public interface CreditCardRepository extends CrudRepository<CreditCard, Long> {

    CreditCard findByNumber(int number);
}
<file_sep>/BACK/src/main/java/com/nuvu/controllers/CreditCardController.java
package com.nuvu.controllers;

import com.nuvu.dto.CreditCardDto;
import com.nuvu.model.CreditCard;
import com.nuvu.service.CreditCardService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

@RestController
@RequestMapping(path = "/CreditCard/")
@CrossOrigin(origins = "http://localhost:4200")
public class CreditCardController {

    @Autowired
    CreditCardService creditCardService;

    @ApiOperation(value = "Permite identificar si el controlador de tarjetas de credito esta arriba")
    @RequestMapping("home")
    public String home() {
        return "Home Credit Card";
    }

    @ApiOperation(value = "Retorna la lista de tarjetas de credito asociadas a una persona")
    @GetMapping(
            path = "get-credit-cards",
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public @ResponseBody
    HttpEntity<List<CreditCard>> getCreditCardByPerson(@Valid @RequestParam("idPerson") Long idPerson) {
        return creditCardService.getCreditCardByPerson(idPerson);
    }

    @ApiOperation(value = "Permite registrar una tarjeta de credito en el sistema")
    @PostMapping(
            path = "add-credit-card",
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public @ResponseBody
    HttpEntity<CreditCard> addCreditCard(@RequestBody CreditCardDto creditCardDto) {
        return creditCardService.addCreditCard(creditCardDto);
    }

    @ApiOperation(value = "Permite eliminar una tarjeta de credito en el sistema")
    @PostMapping(
            path = "delete-credit-card",
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public @ResponseBody
    HttpEntity<Long> deleteCreditCard(@Valid @RequestParam("id") Long id) {
        return creditCardService.deleteCreditCard(id);
    }
}
<file_sep>/FRONTEND/src/services/CreditCard.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, pipe } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { CreditCard } from 'src/classes/CreditCard/CreditCard';

@Injectable()
export class CreditCardService {

    private creditCardURL: string;

    httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    }

    constructor(private http: HttpClient) {
        console.log(HttpHeaders);
        console.log(Observable);
        console.log(pipe);
        var mainHost = 'http://localhost:';
        var port = '8081';
        var mainURL = '/CreditCard/';
        this.creditCardURL = mainHost + port + mainURL;
    }

    public getCreditCardByPerson(idPerson: number): Observable<CreditCard[]> {
        var endpoint = 'get-credit-cards';
        var param = '?idPerson=';
        var url = this.creditCardURL + endpoint + param + + idPerson.toString();
        console.log("getCreditCardByPerson url: " + url);        
        return this.http.get<CreditCard[]>(url);
    }

    public addcreditCard(creditCard: CreditCard) {
        var endpoint = 'add-credit-card';
        var url = this.creditCardURL + endpoint;
        console.log("addcreditCard url: " + url + " creditCard: " + JSON.stringify(creditCard));
        return this.http.post<CreditCard>(url, JSON.stringify(creditCard), this.httpOptions)
            .pipe(
                retry(1),
                catchError(this.handleError)
            )
    }

    public deletecreditCard(id: number) {
        var endpoint = 'delete-credit-card';
        var param = '?id=';
        var url = this.creditCardURL + endpoint + param + + id.toString();
        console.log("deletecreditCard url: " + url);
        return this.http.post<CreditCard>(url, null, this.httpOptions)
            .pipe(
                retry(1),
                catchError(this.handleError)
            )
    }

    private handleError(error: HttpErrorResponse): any {
        if (error.status == 406) {
            console.error(error.message);
            alert("The credit card has already been added or removed, please review");
        } else if (error.status == 409) {
            console.error(error.message);
            alert("Server error, please contact customer service");
        }
        return throwError(
            'Something bad happened; please try again later.');
    }
}<file_sep>/BACK/src/main/java/com/nuvu/model/CreditCard.java
package com.nuvu.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

@Entity
public class CreditCard {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private int number;
    private Date validUntil;
    private int cvc;
    private long idPerson;

    public CreditCard() {
    }

    public CreditCard(long id, int number, Date validUntil, int cvc, long idPerson) {
        this.id = id;
        this.number = number;
        this.validUntil = validUntil;
        this.cvc = cvc;
        this.idPerson = idPerson;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public Date getValidUntil() {
        return validUntil;
    }

    public void setValidUntil(Date validUntil) {
        this.validUntil = validUntil;
    }

    public int getCvc() {
        return cvc;
    }

    public void setCvc(int cvc) {
        this.cvc = cvc;
    }

    public long getIdPerson() {
        return idPerson;
    }

    public void setIdPerson(long idPerson) {
        this.idPerson = idPerson;
    }
}
<file_sep>/FRONTEND/src/app/credit-card/credit-card.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CreditCard } from 'src/classes/CreditCard/CreditCard';
import { Person } from 'src/classes/Person/Person';
import { CreditCardService } from 'src/services/CreditCard.service';
import { PersonService } from 'src/services/Person.service';

@Component({
  selector: 'app-credit-card',
  templateUrl: './credit-card.component.html',
  styleUrls: ['./credit-card.component.css']
})
export class CreditCardComponent implements OnInit {

  creditCard: CreditCard;
  persons: Person[];
  creditCards: CreditCard[];

  constructor(private route: ActivatedRoute,
    private router: Router,
    private creditCardService: CreditCardService,
    private personService: PersonService) {
    this.creditCard = new CreditCard();
    this.persons = [];
    this.creditCards = [];
  }

  ngOnInit() {
    this.refreshCreditCard()
  }

  refreshCreditCard() {
    this.creditCards = [];
    this.personService.getPersons().subscribe(data => {
      console.log(data)
      this.persons = data;
      this.persons.forEach((value) => {
        console.log("value.id: " + value.id + " value.identification: " + value.identification)
        this.loadCreditCards(value.id);
      });
    });
  }

  loadCreditCards(idPerson: number) {
    this.creditCardService.getCreditCardByPerson(idPerson)
      .subscribe(data => {
        console.log(data)
        if (data.length > 0) {
          data.forEach((value) => {
            this.creditCards.push(value);
          });
        }
      });
  }

  clearformcreditCard() {
    this.creditCard = new CreditCard();
  }

  addCreditCard(): void {
    const idDefault = 0;
    const maxValuenumber = 9999999999;
    const maxValueCVC = 999;
    this.creditCard.id = idDefault;
    if (this.creditCard.number > maxValuenumber) {
      alert("The number of a credit card cannot be greater than 10 numbers");
    }
    else if (this.creditCard.cvc > maxValueCVC) {
      alert("The CVC of a credit card cannot be greater than 3 numbers");
    }
    else {
      this.creditCardService.addcreditCard(this.creditCard).subscribe(data => {
        console.log(data)
        this.refreshCreditCard();
      });
      this.clearformcreditCard();
    }
  }

  deleteCreditCard(id: number, number: number): void {
    if (confirm("Are you sure to delete: " + number)) {
      this.creditCardService.deletecreditCard(id).subscribe(data => {
        console.log(data)
        this.refreshCreditCard();
      });
    }
  }

}
<file_sep>/BACK/src/main/java/com/nuvu/BasicApplication.java
package com.nuvu;

import com.nuvu.model.CreditCard;
import com.nuvu.model.Person;
import com.nuvu.repositories.CreditCardRepository;
import com.nuvu.repositories.PersonRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import java.text.SimpleDateFormat;
import java.util.Date;

@SpringBootApplication
@ComponentScan()
public class BasicApplication {

    public static void main(String[] args) {
        SpringApplication.run(BasicApplication.class, args);
    }

    @Bean
    CommandLineRunner initPersonRepository(PersonRepository personRepository) {
        return args -> {
            Person person = new Person(1, "1018458060", "<NAME>", "CUBILLOS2093HOTMAIL.COM", new Date());
            personRepository.save(person);
        };
    }

    @Bean
    CommandLineRunner initCreditCardRepository(CreditCardRepository creditCardRepository) {
        return args -> {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date validUntil = sdf.parse("01/01/2022");
            CreditCard creditCard = new CreditCard(1, 45526877, validUntil, 209, 1);
            creditCardRepository.save(creditCard);
        };
    }
}
<file_sep>/FRONTEND/src/classes/CreditCard/CreditCard.ts
export class CreditCard {
    id!: number;
    number!: number;
    validUntil!: Date;    
    cvc!: number;
    idPerson!: number;
}<file_sep>/BACK/src/main/java/com/nuvu/repositories/PersonRepository.java
package com.nuvu.repositories;

import com.nuvu.model.Person;
import org.springframework.data.repository.CrudRepository;

/**
 * @author <NAME>
 * @since 2020-04-16
 */

public interface PersonRepository extends CrudRepository<Person, Long> {

    Person findByIdentification(String identification);
}
