Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4기 - 한승원] SpringBoot Part3 Weekly Mission 제출합니다. #831

Open
wants to merge 9 commits into
base: seungwon/w1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ group = 'co.programmers'
version = '0.0.1-SNAPSHOT'

java {
sourceCompatibility = '11'
sourceCompatibility = 17
}

repositories {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
package co.programmers.voucher_management;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import co.programmers.voucher_management.voucher.dto.VoucherResponseDTO;
import co.programmers.voucher_management.voucher.service.VoucherService;

@Controller
public class ApplicationController {
@GetMapping("home")
public String inquiryVoucherOf(){
public String inquiryVoucherOf() {
return "home";
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package co.programmers.voucher_management;

import static co.programmers.voucher_management.exception.ErrorCode.*;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
Expand Down Expand Up @@ -50,14 +52,9 @@ private void executeCommand(String userInput) {
outputView.print(menuDescription);
String commandNum = inputView.input();
switch (userInput) {
case "1":
voucherController.executeVoucherMenu(commandNum);
break;
case "2":
customerController.executeCustomerMenu(commandNum);
break;
default:
throw new InvalidDataException("Unsupported menu");
case "1" -> voucherController.executeVoucherMenu(commandNum);
case "2" -> customerController.executeCustomerMenu(commandNum);
default -> throw new InvalidDataException(INVALID_MENU);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package co.programmers.voucher_management;

import java.time.LocalDate;
import java.util.List;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import co.programmers.voucher_management.voucher.dto.VoucherRequestDTO;
import co.programmers.voucher_management.voucher.dto.VoucherResponseDTO;
import co.programmers.voucher_management.voucher.service.VoucherService;

@RequestMapping("/api/v1/vouchers")
@RestController
public class VoucherApiController {
private final VoucherService voucherService;

public VoucherApiController(VoucherService voucherService) {
this.voucherService = voucherService;
}

@GetMapping
public ResponseEntity<List<VoucherResponseDTO>> find(
@RequestParam(required = false) String type,
@RequestParam(required = false, defaultValue = "-1") Long id
) {
if (id > 0) {
return findById(id);
}
if (type != null) {
return findByType(type);
}
return findAll();
}
Comment on lines +30 to +42

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

동적 쿼리를 구현하시려고 노력한 흔적이 보이네요
이미 아실 수도 있지만 QueryDSL을 사용하면 동적쿼리를 쉽게 처리할 수 있습니다.
좀더 검색에 대한 니즈가 강해서 고도화할 필요가 있으면 엘라스틱 서치를 사용하게 될꺼구요


public ResponseEntity<List<VoucherResponseDTO>> findAll() {
List<VoucherResponseDTO> response = voucherService.inquiryVoucherOf();
return ResponseEntity.ok(response);
}

private ResponseEntity<List<VoucherResponseDTO>> findById(@PathVariable long id) {
VoucherResponseDTO response = voucherService.findById(id);
return ResponseEntity.ok(List.of(response));
}
Comment on lines +49 to +52

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ResponseEntity를 사용해서 응답을 제어하는 부분이 딱히 없다면 List 그대로 반환해도 동일한 코드가 될것 같네요


private ResponseEntity<List<VoucherResponseDTO>> findByType(@RequestParam String discountType) {
List<VoucherResponseDTO> response = voucherService.findByType(discountType);
return ResponseEntity.ok(response);
}

@GetMapping(params = {"startDate", "endDate"})
public ResponseEntity<List<VoucherResponseDTO>> findByDate(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
List<VoucherResponseDTO> response = voucherService.findByDate(startDate, endDate);
return ResponseEntity.ok(response);
}

@PostMapping

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리소스 경로에 대한 Rest API 컨벤션을 잘지켜주시고 계시네요

public ResponseEntity<VoucherResponseDTO> create(@RequestBody VoucherRequestDTO voucherRequestDTO) {
VoucherResponseDTO response = voucherService.create(voucherRequestDTO);
return ResponseEntity.ok(response);
}

@DeleteMapping("/{id}")
public ResponseEntity deleteById(@PathVariable long id) {
voucherService.deleteById(id);
return ResponseEntity.ok("");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,8 @@

import java.util.List;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -23,7 +17,6 @@
@RequestMapping("/vouchers")
@Controller
public class VoucherViewController {
private static final Logger logger = LoggerFactory.getLogger(VoucherViewController.class);
private final VoucherService voucherService;

public VoucherViewController(VoucherService voucherService) {
Expand Down Expand Up @@ -54,23 +47,13 @@ public String deleteById(@PathVariable long id, Model model) {
@GetMapping("/new")
public String create(Model model) {
model.addAttribute("voucher", new VoucherRequestDTO());
return "vouchers-new"; //html
//viewResolver
return "vouchers-new";
}

@PostMapping("/new")
public String create(@Validated @NotEmpty @NotNull @ModelAttribute("voucher") VoucherRequestDTO voucherRequestDTO) {
// ,BindingResult bindingResult,
// RedirectAttributes redirectAttributes) {
// if (bindingResult.hasErrors()) {
// return "vouchers/saveVoucher";
// }

// VoucherResponseDTO voucherResponseDTO =
public String create(@ModelAttribute("voucher") VoucherRequestDTO voucherRequestDTO) {
voucherService.create(voucherRequestDTO);
// long createdVoucherId = voucherResponseDTO.getId();
// redirectAttributes.addAttribute("voucherId", createdVoucherId);
return "redirect:/vouchers"; //경로
return "redirect:/vouchers";

}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package co.programmers.voucher_management.common;

import static co.programmers.voucher_management.exception.ErrorCode.*;

import java.util.Arrays;

import co.programmers.voucher_management.exception.InvalidDataException;
Expand Down Expand Up @@ -28,7 +30,7 @@ public static String of(String expression) {
return Arrays.stream(MenuDescription.values())
.filter(m -> m.expression.equals(expression))
.findAny()
.orElseThrow(() -> new InvalidDataException("Unsupported menu"))
.orElseThrow(() -> new InvalidDataException(INVALID_MENU))
.description();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import co.programmers.voucher_management.customer.entity.Customer;
import co.programmers.voucher_management.customer.service.CustomerService;
import co.programmers.voucher_management.exception.ErrorCode;
import co.programmers.voucher_management.exception.InvalidDataException;
import co.programmers.voucher_management.view.InputView;
import co.programmers.voucher_management.view.OutputView;
Expand All @@ -23,15 +24,10 @@ public CustomerController(CustomerService customerService, OutputView outputView
}

public void executeCustomerMenu(String commandNum) {
switch (commandNum){
case "1":
inquiryBlackList();
break;
case "2":
inquiryCustomerByVoucher();
break;
default:
throw new InvalidDataException("Unsupported command");
switch (commandNum) {
case "1" -> inquiryBlackList();
case "2" -> inquiryCustomerByVoucher();
default -> throw new InvalidDataException(ErrorCode.INVALID_COMMAND);
}
}

Expand All @@ -40,7 +36,7 @@ public void inquiryBlackList() {
customerService.inquireByRating(rating);
}

public void inquiryCustomerByVoucher(){
public void inquiryCustomerByVoucher() {
String requestMessageFormat = "Input {0} >> ";
outputView.print(MessageFormat.format(requestMessageFormat, "ID of a voucher"));
long voucherId = Long.parseLong(inputView.input());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package co.programmers.voucher_management.customer.entity;

import static co.programmers.voucher_management.exception.ErrorCode.*;

import java.util.regex.Pattern;

import co.programmers.voucher_management.exception.InvalidDataException;
Expand All @@ -20,7 +22,6 @@ public class Customer {
public Customer(long id, String name, Rating rating, String phoneNumber) {
validatePhoneNumber(phoneNumber);
validateName(name);
// validateRating(rating);

this.id = id;
this.name = name;
Expand All @@ -32,14 +33,14 @@ public Customer(long id, String name, Rating rating, String phoneNumber) {
private void validateName(String name) {
if (!NAME_FORMAT.matcher(name)
.matches()) {
throw new InvalidDataException();
throw new InvalidDataException(INVALID_NAME);
}
}

private void validatePhoneNumber(String phoneNumber) {
if (!PHONE_NUM_FORMAT.matcher(phoneNumber)
.matches()) {
throw new InvalidDataException();
throw new InvalidDataException(INVALID_PHONE_NUMBER);
}
}

Expand All @@ -56,6 +57,6 @@ public String toString() {

public enum Rating {
NORMAL,
BLACKLIST;
BLACKLIST
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

public enum Status {
NORMAL,
DELETED;
DELETED
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package co.programmers.voucher_management.customer.repository;

import static co.programmers.voucher_management.customer.entity.Customer.*;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
Expand All @@ -11,7 +13,6 @@
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import static co.programmers.voucher_management.customer.entity.Customer.Rating;
import co.programmers.voucher_management.customer.entity.Customer;

@Repository
Expand All @@ -38,8 +39,10 @@ private Customer mapToCustomer(ResultSet resultSet) {
long id = resultSet.getLong("id");
String name = resultSet.getString("name");
String phoneNumber = resultSet.getString("phone_number");

String ratingExpression = resultSet.getString("rating");
Rating rating = Rating.valueOf(ratingExpression);

return Customer.builder()
.id(id)
.name(name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,15 @@
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;

import com.opencsv.CSVReader;

import co.programmers.voucher_management.customer.entity.Status;
import co.programmers.voucher_management.customer.entity.Customer;
import co.programmers.voucher_management.customer.entity.Status;

@Repository
@Profile("file")
Expand All @@ -35,10 +34,11 @@ public List<Customer> findByRating(String ratingToFind) {
try (Reader reader = Files.newBufferedReader(path);
CSVReader csvReader = new CSVReader(reader)) {
List<String[]> customers = csvReader.readAll();

return customers.stream()
.filter(fileLine -> ratingToFind.equals(fileLine[ratingIndex]))
.map(this::mapToCustomer)
.collect(Collectors.toList());
.toList();
} catch (IOException ioException) {
throw new RuntimeException("file reading failed");
}
Expand All @@ -59,10 +59,12 @@ public Optional<Customer> findById(long customerId) {
String[] line;
try (Reader reader = Files.newBufferedReader(path);
CSVReader csvReader = new CSVReader(reader)) {

while ((line = csvReader.readNext()) != null) {
long id = Long.parseLong(line[CustomerProperty.ID.index]);
String status = line[CustomerProperty.STATUS.index];
String normalStatus = String.valueOf(Status.NORMAL);

if ((customerId == id) && (status.equals(normalStatus))) {
return Optional.of(mapToCustomer(line));
}
Expand All @@ -82,13 +84,13 @@ public enum CustomerProperty {

final int index;

public int index() {
return index;
}

CustomerProperty(int index) {
this.index = index;
}

public int index() {
return index;
}

}
}
Loading