code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,27 @@ +package subway.command; + +public enum LineCommand implements Command { + REGISTER("1", "๋…ธ์„  ๋“ฑ๋ก"), + REMOVE("2", "๋…ธ์„  ์‚ญ์ œ"), + RETRIEVE("3", "๋…ธ์„  ์กฐํšŒ"), + BACK("B", "๋Œ์•„๊ฐ€๊ธฐ"); + + private final String command; + private final String description; + + LineCommand(String command, String description) { + this.command = command; + this.description = description; + } + + @Override + public String getCommand() { + return command; + } + + @Override + public String getDescription() { + return description; + } + +}
Java
view ๊ฐ์ฒด์˜ ์ถœ๋ ฅ์„ ํ™•์ธํ•ด๋ณด๋‹ˆ ์—ฌ๊ธฐ์„œ ์ƒ์„ฑํ•œ ๋ฌธ์ž์—ด์„ ๊ทธ๋Œ€๋กœ ๋ฐ›์•„์„œ ์ถœ๋ ฅํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ๋„๋ฉ”์ธ์ด UI ์ƒ์„ฑ ๋กœ์ง์—๋„ ๊ด€์—ฌํ•˜๊ณ  ์žˆ๋Š” ์„ค๊ณ„๊ฐ€ ์•„๋‹๊นŒ์š”?
@@ -0,0 +1,78 @@ +package subway.config; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import subway.domain.Line; +import subway.domain.Station; +import subway.exception.ReaderException; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.utils.LineFieldsDto; +import subway.utils.LineParser; +import subway.utils.StationFieldsDto; +import subway.utils.StationParser; + +public class SubwayFileInitializer { + private final StationParser stationParser; + private final LineParser lineParser; + private final StationRepository stationRepository; + private final LineRepository lineRepository; + + public SubwayFileInitializer(StationParser stationParser, LineParser lineParser, + StationRepository stationRepository, LineRepository lineRepository) { + this.stationParser = stationParser; + this.lineParser = lineParser; + this.stationRepository = stationRepository; + this.lineRepository = lineRepository; + } + + public void init() { + try { + initStations(); + initLines(); + } catch (IOException e) { + throw new ReaderException(); + } catch (IllegalArgumentException error) { + throw new IllegalArgumentException(error.getMessage()); + } + } + + private void initStations() throws IOException { + while (true) { + StationFieldsDto stationFieldsDto = stationParser.nextStation(); + if (stationFieldsDto == null) { + break; + } + + stationRepository.add(new Station(stationFieldsDto.stationName())); + } + } + + private void initLines() throws IOException { + while (true) { + LineFieldsDto lineFieldsDto = lineParser.nextLine(); + if (lineFieldsDto == null) { + break; + } + + List<Station> stations = new ArrayList<>(); + for (String stationName : lineFieldsDto.stationNames()) { + Station station = stationRepository.findByName(stationName); + if (station == null) { + throw new IllegalArgumentException(); + } + + stations.add(station); + } + + Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast()); + lineRepository.add(line); + for (int i = 1; i < stations.size() - 1; i++) { + Station station = stations.get(i); + lineRepository.addStation(line, station, i); + } + } + } + +}
Java
๋‹ค์‹œ ์ƒˆ๋กœ์šด ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๊ธฐ ๋ณด๋‹ค๋Š” `throw error` ์ด๋Ÿฐ์‹์œผ๋กœ ๊ธฐ์กด ์˜ˆ์™ธ๋ฅผ ๊ทธ๋Œ€๋กœ ๋„˜๊ธฐ๋Š” ๊ฒƒ์ด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,78 @@ +package subway.config; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import subway.domain.Line; +import subway.domain.Station; +import subway.exception.ReaderException; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.utils.LineFieldsDto; +import subway.utils.LineParser; +import subway.utils.StationFieldsDto; +import subway.utils.StationParser; + +public class SubwayFileInitializer { + private final StationParser stationParser; + private final LineParser lineParser; + private final StationRepository stationRepository; + private final LineRepository lineRepository; + + public SubwayFileInitializer(StationParser stationParser, LineParser lineParser, + StationRepository stationRepository, LineRepository lineRepository) { + this.stationParser = stationParser; + this.lineParser = lineParser; + this.stationRepository = stationRepository; + this.lineRepository = lineRepository; + } + + public void init() { + try { + initStations(); + initLines(); + } catch (IOException e) { + throw new ReaderException(); + } catch (IllegalArgumentException error) { + throw new IllegalArgumentException(error.getMessage()); + } + } + + private void initStations() throws IOException { + while (true) { + StationFieldsDto stationFieldsDto = stationParser.nextStation(); + if (stationFieldsDto == null) { + break; + } + + stationRepository.add(new Station(stationFieldsDto.stationName())); + } + } + + private void initLines() throws IOException { + while (true) { + LineFieldsDto lineFieldsDto = lineParser.nextLine(); + if (lineFieldsDto == null) { + break; + } + + List<Station> stations = new ArrayList<>(); + for (String stationName : lineFieldsDto.stationNames()) { + Station station = stationRepository.findByName(stationName); + if (station == null) { + throw new IllegalArgumentException(); + } + + stations.add(station); + } + + Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast()); + lineRepository.add(line); + for (int i = 1; i < stations.size() - 1; i++) { + Station station = stations.get(i); + lineRepository.addStation(line, station, i); + } + } + } + +}
Java
Optional์„ ์ด์šฉํ•œ๋‹ค๋ฉด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,78 @@ +package subway.config; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import subway.domain.Line; +import subway.domain.Station; +import subway.exception.ReaderException; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.utils.LineFieldsDto; +import subway.utils.LineParser; +import subway.utils.StationFieldsDto; +import subway.utils.StationParser; + +public class SubwayFileInitializer { + private final StationParser stationParser; + private final LineParser lineParser; + private final StationRepository stationRepository; + private final LineRepository lineRepository; + + public SubwayFileInitializer(StationParser stationParser, LineParser lineParser, + StationRepository stationRepository, LineRepository lineRepository) { + this.stationParser = stationParser; + this.lineParser = lineParser; + this.stationRepository = stationRepository; + this.lineRepository = lineRepository; + } + + public void init() { + try { + initStations(); + initLines(); + } catch (IOException e) { + throw new ReaderException(); + } catch (IllegalArgumentException error) { + throw new IllegalArgumentException(error.getMessage()); + } + } + + private void initStations() throws IOException { + while (true) { + StationFieldsDto stationFieldsDto = stationParser.nextStation(); + if (stationFieldsDto == null) { + break; + } + + stationRepository.add(new Station(stationFieldsDto.stationName())); + } + } + + private void initLines() throws IOException { + while (true) { + LineFieldsDto lineFieldsDto = lineParser.nextLine(); + if (lineFieldsDto == null) { + break; + } + + List<Station> stations = new ArrayList<>(); + for (String stationName : lineFieldsDto.stationNames()) { + Station station = stationRepository.findByName(stationName); + if (station == null) { + throw new IllegalArgumentException(); + } + + stations.add(station); + } + + Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast()); + lineRepository.add(line); + for (int i = 1; i < stations.size() - 1; i++) { + Station station = stations.get(i); + lineRepository.addStation(line, station, i); + } + } + } + +}
Java
Stream์„ ์ด์šฉํ•˜์—ฌ indent๋ฅผ ์ค„์—ฌ๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,49 @@ +package subway.controller.handler; + +import subway.command.Command; +import subway.command.SectionCommand; +import subway.controller.retryInputUtil.SectionRetryInput; +import subway.dto.SectionRegisterDto.SectionRegisterInputDto; +import subway.dto.SectionRemoveDto.SectionRemoveInputDto; +import subway.service.SectionService; +import subway.view.OutputView; + +public class SectionHandler implements Handler { + private final SectionService sectionService; + + public SectionHandler(SectionService sectionService) { + this.sectionService = sectionService; + } + + @Override + public void handle() { + OutputView.printSectionManageMenu(); + SectionCommand sectionCommand = Command.findCommand(SectionRetryInput.getCommand(), + SectionCommand.values()); + + if (sectionCommand == SectionCommand.REGISTER) { + registerSection(); + } + if (sectionCommand == SectionCommand.REMOVE) { + removeSection(); + } + if (sectionCommand == SectionCommand.BACK) { + // nothing to do. + } + + } + + private void registerSection() { + String lineName = SectionRetryInput.getLineName(); + String stationName = SectionRetryInput.getStationName(); + int orderNumber = SectionRetryInput.getOrderNumber(); + sectionService.register(new SectionRegisterInputDto(lineName, stationName, orderNumber)); + } + + private void removeSection() { + String lineName = SectionRetryInput.getRemoveLineName(); + String stationName = SectionRetryInput.getRemoveStationName(); + sectionService.remove(new SectionRemoveInputDto(lineName, stationName)); + OutputView.printSectionRemovedMessage(); + } +}
Java
์ด ์กฐ๊ฑด๋ฌธ์„ ๊ตณ์ด ์ž‘์„ฑํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ์ €๋Š” BACK์ผ ๊ฒฝ์šฐ, ์•„๋ฌด ๊ธฐ๋Šฅ๋„ ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ ์กฐ๊ฑด๋ฌธ์œผ๋กœ ๋ถ„๋ฆฌํ•˜์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -1,15 +1,45 @@ package subway.domain; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import subway.validator.LineValidator; + public class Line { private String name; + private List<Station> stations; - public Line(String name) { + public Line(String name, Station startStation, Station endStation) { + LineValidator.validate(name, startStation, endStation); this.name = name; + this.stations = new ArrayList<>(List.of(startStation, endStation)); + } + + public void addStation(Station station) { + stations.add(station); + } + + public void addStation(Station station, int index) { + stations.add(index, station); + } + + public void removeStation(Station station) { + stations.remove(station); + } + + public List<Station> getStations() { + return stations; + } + + public int getStationCount() { + return stations.size(); + } + + public List<String> getStationNames() { + return stations.stream().map(Station::getName).collect(Collectors.toList()); } public String getName() { return name; } - - // ์ถ”๊ฐ€ ๊ธฐ๋Šฅ ๊ตฌํ˜„ }
Java
๋ถˆ๋ณ€ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,67 @@ +package subway.controller; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import subway.command.Command; +import subway.command.MainCommand; +import subway.controller.handler.Handler; +import subway.controller.handler.LineHandler; +import subway.controller.handler.SectionHandler; +import subway.controller.handler.StationHandler; +import subway.controller.retryInputUtil.RetryInputUtil; +import subway.dto.LineDto; +import subway.service.LineService; +import subway.service.SectionService; +import subway.service.StationService; +import subway.view.OutputView; + +public class SubwayController { + private final LineService lineService; + private final Map<MainCommand, Handler> commandHandlers; + + public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) { + this.lineService = lineService; + + this.commandHandlers = new HashMap<>(); + this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService)); + this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService)); + this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService)); + } + + public void run() { + int state = 0; + + while (state == 0) { + try { + OutputView.printMainMenu(); + MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values()); + + state = mainLogic(mainCommand); + } catch (IllegalArgumentException error) { + OutputView.printError(error.getMessage()); + } + } + } + + private int mainLogic(MainCommand mainCommand) { + if (mainCommand == MainCommand.QUIT) { + return 1; + } + + if (this.commandHandlers.containsKey(mainCommand)) { + this.commandHandlers.get(mainCommand).handle(); + } + if (mainCommand == MainCommand.LINE_PRINT) { + printLineMap(); + } + + return 0; + } + + private void printLineMap() { + List<LineDto> lines = lineService.retrieve().lines(); + OutputView.printLineMap(lines); + } + +}
Java
ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! C๋ฅผ ๋งŽ์ด ํ•ด์„œ ๊ทธ๋Ÿฐ์ง€ ์Šต๊ด€์ ์œผ๋กœ int๋ฅผ ์‚ฌ์šฉํ–ˆ๋„ค์š”! boolean์œผ๋กœ ํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,54 @@ +package subway.controller.handler; + +import java.util.List; +import subway.command.Command; +import subway.command.StationCommand; +import subway.controller.retryInputUtil.StationRetryInput; +import subway.dto.StationDto; +import subway.dto.StationRegisterDto.StationRegisterInputDto; +import subway.dto.StationRemoveDto.StationRemoveInputDto; +import subway.service.StationService; +import subway.view.OutputView; + +public class StationHandler implements Handler { + private final StationService stationService; + + public StationHandler(StationService stationService) { + this.stationService = stationService; + } + + @Override + public void handle() { + OutputView.printStationManageMenu(); + StationCommand stationCommand = Command.findCommand(StationRetryInput.getCommand(), StationCommand.values()); + + if (stationCommand == StationCommand.REGISTER) { + registerStation(); + } + if (stationCommand == StationCommand.REMOVE) { + removeStation(); + } + if (stationCommand == StationCommand.RETRIEVE) { + retrieveStation(); + } + if (stationCommand == StationCommand.BACK) { + // nothing to do. + } + } + + private void registerStation() { + String stationName = StationRetryInput.getStationName(); + stationService.register(new StationRegisterInputDto(stationName)); + } + + private void removeStation() { + String stationName = StationRetryInput.getRemoveStationName(); + stationService.remove(new StationRemoveInputDto(stationName)); + OutputView.printStationRemovedMessage(); + } + + private void retrieveStation() { + List<StationDto> stations = stationService.retrieve().stations(); + OutputView.printStations(stations); + } +}
Java
๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. BACK๋ถ€๋ถ„์€ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— ๊ตณ์ด ์ž‘์„ฑํ•˜์ง€ ์•Š์•„๋„ ํ๋ฆ„์ƒ ๋ฌธ์ œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ ์•„๋ฌด๋Ÿฐ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜์ง€ ์•Š๋”๋ผ๋„ "์•„๋ฌด๊ฒƒ๋„ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๋Š”๋‹ค"๋ผ๋Š” ๋ฉ”์‹œ์ง€๋ฅผ ์ฃผ๊ณ  ์‹ถ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‚จ๊ฒจ๋‘์—ˆ์Šต๋‹ˆ๋‹ค. ๋ช…์‹œ์ ์œผ๋กœ "BACK์ด๋ผ๋Š” ๋ช…๋ น์ด ์žˆ๋Š”๋ฐ ์•„๋ฌด๊ฒƒ๋„ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๊ณ  ์ข…๋ฃŒํ• ๊ฑฐ์•ผ"๋ผ๋Š” ๋ฉ”์‹œ์ง€๋ฅผ ์ฃผ๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,52 @@ +package subway.config; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import subway.controller.SubwayController; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.SectionService; +import subway.service.StationService; +import subway.utils.CsvReader; +import subway.utils.LineParser; +import subway.utils.StationParser; + +public class DependencyInjector { + public SubwayController createSubwayController() { + StationRepository stationRepository = new StationRepository(); + LineRepository lineRepository = new LineRepository(); + + StationService stationService = new StationService(stationRepository); + SectionService sectionService = new SectionService(lineRepository, stationRepository); + LineService lineService = new LineService(lineRepository, stationRepository); + + SubwayFileInitializer subwayFileInitializer = createSubwayFileInitializer(stationRepository, lineRepository, + stationService, sectionService); + subwayFileInitializer.init(); + + return new SubwayController(stationService, lineService, sectionService); + } + + public SubwayFileInitializer createSubwayFileInitializer(StationRepository stationRepository, + LineRepository lineRepository, + StationService stationService, + SectionService sectionService) { + StationParser stationParser = new StationParser( + new CsvReader(this.createBufferedReader(Configuration.STATION_FILE_NAME.getString()), + false)); + LineParser lineParser = new LineParser( + new CsvReader(this.createBufferedReader(Configuration.LINE_FILE_NAME.getString()), false)); + + return new SubwayFileInitializer( + stationParser, lineParser, stationRepository, lineRepository + ); + } + + + private BufferedReader createBufferedReader(String fileName) { + return new BufferedReader(new InputStreamReader( + DependencyInjector.class.getClassLoader().getResourceAsStream(fileName) + )); + } +}
Java
์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๋งŒ๋“ ๋‹ค๋Š”๊ฒŒ static์œผ๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์„ ๋ง์”€ํ•˜์‹œ๋Š”๊ฑด๊ฐ€์š”??
@@ -0,0 +1,16 @@ +package subway.command; + +public interface Command { + static <T extends Command> T findCommand(String input, T[] commands) { + for (T command : commands) { + if (command.getCommand().equals(input)) { + return command; + } + } + throw new IllegalArgumentException("์„ ํƒํ•  ์ˆ˜ ์—†๋Š” ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค."); + } + + String getCommand(); + + String getDescription(); +}
Java
์ด์œ ๋Š”... ์—†์Šต๋‹ˆ๋‹ค. ์ตœ๋Œ€ํ•œ ๋น ๋ฅด๊ฒŒ ๊ฐœ๋ฐœํ•˜๋Š” ๊ฒƒ์„ ๋ชฉํ‘œ๋กœ ํ•ด์„œ ๋””ํ…Œ์ผํ•œ ๋ถ€๋ถ„์€ ๊ฐ€์ ธ๊ฐ€์ง€ ๋ชปํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ใ… ใ… 
@@ -1,7 +1,65 @@ package store; +import static store.constant.Constant.ERROR_PREFIX; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import store.constant.YesOrNo; +import store.controller.PurchaseController; +import store.dto.StockResponse; +import store.entity.Product; +import store.entity.Promotion; +import store.entity.Stock; +import store.service.CartService; +import store.service.StockService; +import store.util.parse.PromotionParser; +import store.util.parse.ProductParser; +import store.view.InputView; +import store.view.OutputView; + public class Application { + private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md"; + private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md"; + private static final String FILE_ERROR_MESSAGE = ERROR_PREFIX + "ํŒŒ์ผ์„ ์ฝ๋Š”๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."; + public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + List<Product> items = getInitProducts(); + Stock stock = new Stock(items); + StockService stockService = new StockService(stock); + initializeApplication(stock, stockService); + } + + private static void initializeApplication(Stock stock, StockService stockService) { + YesOrNo continueShopping = YesOrNo.YES; + while (continueShopping == YesOrNo.YES) { + CartService cartService = new CartService(stock); + PurchaseController purchaseController = new PurchaseController(cartService, stockService); + List<StockResponse> stockResult = purchaseController.getStock(); + OutputView.printStartMessage(stockResult); + purchaseController.purchase(); + continueShopping = InputView.askForAdditionalPurchase(); + } + } + + private static List<Product> getInitProducts() { + List<String> products = readFile(PRODUCT_FILE_PATH); + List<String> promotions = readFile(PROMOTION_FILE_PATH); + Map<String, Promotion> parsePromotions = PromotionParser.parse(promotions); + List<Product> items = ProductParser.parse(products, parsePromotions); + return items; + } + + private static List<String> readFile(String filePath) { + try { + Path path = Paths.get(filePath); + return Files.readAllLines(path); + } catch (IOException e) { + throw new UncheckedIOException(FILE_ERROR_MESSAGE, e); + } } }
Java
์—ฌ๊ธฐ์„œ ์ถ”๊ฐ€๊ตฌ๋งค์— ๋Œ€ํ•œ ์‘๋‹ต์œผ๋กœ 'Y'๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ๋งค ๋ฐ˜๋ณต๋งˆ๋‹ค CarService์™€ PurchaseController๊ฐ€ ์ƒˆ๋กœ ์ƒ์„ฑ๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,5 @@ +package store.constant; + +public class Constant { + public static final String ERROR_PREFIX = "[ERROR] "; +}
Java
`ERROR_PREFIX` ๊ฐ™์ด ๋ฐ˜๋ณต๋˜๋Š” ๋ถ€๋ถ„์„ ์ƒ์ˆ˜๋กœ ์ •์˜ํ•ด์ฃผ์‹ ๊ฒŒ ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,7 @@ +package store.entity; + +import java.time.LocalDate; + +public interface DateProvider { + LocalDate now(); +}
Java
๋‚ ์งœ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•ด์ฃผ๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋”ฐ๋กœ ์ƒ์„ฑํ•˜์‹  ์ด์œ ๋ฅผ ์•Œ ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,11 @@ +package store.entity; + +public class Membership { + private static final int discountPercent = 30; + private static final int maxDiscountAmount = 8000; + + public int discount(Cart nonDiscountedCart) { + int discountAmount = nonDiscountedCart.getTotalPrice() * discountPercent / 100; + return Math.min(discountAmount, maxDiscountAmount); + } +}
Java
`Math.min()`์„ ์‚ฌ์šฉํ•ด์„œ ํ• ์ธ์ตœ๋Œ€์น˜๊ฐ€ ์ดˆ๊ณผ๋˜์ง€ ์•Š๋„๋ก ๊น”๋”ํ•˜๊ฒŒ ์ž˜ ๊ตฌํ˜„ํ•ด์ฃผ์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,57 @@ +package store.entity; + +import java.time.LocalDate; +import java.util.Objects; + +public class Promotion { + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean isPromotionValid(LocalDate currentDate) { + return !currentDate.isBefore(startDate) && !currentDate.isAfter(endDate); + } + + public boolean isInsufficientPromotion(Integer value) { + return value % (buy + get) >= buy; + } + + public Integer getInsufficientPromotionQuantity(Integer value) { + return (buy + get) - value % (buy + get); + } + + public Integer getCycle() { + return buy + get; + } + + public String getName() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Promotion promotion = (Promotion) o; + return buy == promotion.buy && + get == promotion.get && + Objects.equals(name, promotion.name) && + Objects.equals(startDate, promotion.startDate) && + Objects.equals(endDate, promotion.endDate); + } + + @Override + public int hashCode() { + return Objects.hash(name, buy, get, startDate, endDate); + } +}
Java
๊ฐœ์ธ์ ์ธ ์ƒ๊ฐ์œผ๋กœ ์•ž์— !์—ฐ์‚ฐ์ž๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๋ฉด ์ฝ”๋“œ๋ฅผ ์ฝ๋Š” ๋„์ค‘ ํ•œ๋ฒˆ ๋” ์ƒ๊ฐ์„ ํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. `currentDate.isAfter(startDate) && currentDate.isBefore(endDate);`๊ณผ ๊ฐ™์€ ๋ฐฉ๋ฒ•๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,61 @@ +package store.entity; + +import static store.constant.Constant.ERROR_PREFIX; + +import java.util.List; +import java.util.Map; + +public class Stock { + private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private final List<Product> stock; + + public Stock(List<Product> stock) { + this.stock = stock; + } + + public Product findByName(String name) { + return stock.stream() + .filter(product -> product.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE)); + } + + public void validateAll(Map<String, Integer> items) { + items.forEach(this::validate); + } + + public void update(Map<Product, Integer> cartItem) { + cartItem.forEach((product, quantity) -> { + Product stockProduct = findByName(product.getName()); + if (product.isPromotionEligible()) { + stockProduct.reducePromotionQuantity(quantity); + } else { + stockProduct.reduceQuantity(quantity); + } + }); + } + + private void validate(String productName, Integer quantity) { + if (!isValidName(productName)) { + throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE); + } + if (!isStockAvailable(productName, quantity)) { + throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE); + } + } + + private boolean isValidName(String name) { + return stock.stream().anyMatch(product -> product.getName().equals(name)); + } + + private boolean isStockAvailable(String productName, Integer quantity) { + Product product = findByName(productName); + return product.isStockAvailable(quantity); + } + + public List<Product> getStock() { + return stock.stream().toList(); + } +}
Java
else๋ฌธ ์‚ฌ์šฉ์€ ๊ฐ€๊ธ‰์ ์ด๋ฉด ์ง€์–‘ํ•ด์ฃผ์‹œ๋Š” ๊ฒŒ ์ข‹๋‹ค๊ณ  ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,40 @@ +package store.util.parse; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.entity.DateProvider; +import store.entity.Product; +import store.entity.Promotion; +import store.entity.RealDateProvider; + +public class ProductParser { + private static final DateProvider dateProvider = new RealDateProvider(); + + public static List<Product> parse(List<String> products, Map<String, Promotion> promotions) { + List<Product> stockProduct = new ArrayList<>(); + for (int i = 1; i < products.size(); i++) { // ํ—ค๋” ๋ถ€๋ถ„ ์ œ์™ธ + String[] fields = products.get(i).split(","); + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + Promotion promotion = promotions.get(fields[3]); + addOrUpdateProduct(stockProduct, fields[0], price, quantity, promotion); + } + return stockProduct; + } + + private static void addOrUpdateProduct(List<Product> products, String name, int price, int quantity, + Promotion promotion) { + findProduct(products, name).ifPresentOrElse( + existingProduct -> existingProduct.addQuantity(quantity, promotion), + () -> products.add(new Product(name, price, quantity, promotion, dateProvider)) + ); + } + + private static Optional<Product> findProduct(List<Product> products, String name) { + return products.stream() + .filter(p -> p.getName().equals(name)) + .findFirst(); + } +}
Java
๋ณดํ†ต ์ปฌ๋ ‰์…˜์ด๋‚˜ ๋ฐฐ์—ด์„ ์ˆœํšŒํ•  ๋•Œ ์ธ๋ฑ์Šค๊ฐ€ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋Š” ๊ฑธ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์‹œ์ž‘์ธ๋ฑ์Šค๊ฐ€ ์™œ 1์ธ์ง€ ์ƒ์ˆ˜๋กœ ํ‘œํ˜„ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹จ ์ƒ๊ฐ์ด ๋“ญ๋‹ˆ๋‹ค!
@@ -0,0 +1,30 @@ +package store.util.parse; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import store.entity.Promotion; + +public class PromotionParser { + private static final String SEPARATOR = ","; + private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + public static Map<String, Promotion> parse(List<String> promotions) { + return promotions.stream() + .skip(1) // ์ฒซ ๋ฒˆ์งธ ํ—ค๋” ๋ถ€๋ถ„ ์ œ์™ธ + .map(PromotionParser::parsePromotionLine) + .collect(Collectors.toMap(Promotion::getName, promotion -> promotion)); + } + + private static Promotion parsePromotionLine(String promotion) { + String[] fields = promotion.split(SEPARATOR); + String name = fields[0]; + int buy = Integer.parseInt(fields[1]); + int get = Integer.parseInt(fields[2]); + LocalDate startDate = LocalDate.parse(fields[3], dateTimeFormatter); + LocalDate endDate = LocalDate.parse(fields[4], dateTimeFormatter); + return new Promotion(name, buy, get, startDate, endDate); + } +}
Java
์ฒซ ๋ฒˆ์งธ ํ—ค๋”๋ฅผ ์ œ์™ธํ•œ๋‹ค๋Š” ์ฃผ์„ ๋Œ€์‹  1์ด ๊ฐ€์ง€๋Š” ์˜๋ฏธ๋ฅผ ์ƒ์ˆ˜๋กœ ์ •์˜ํ•ด์ฃผ์…”๋„ ๊ดœ์ฐฎ์•˜์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,7 @@ +package store.entity; + +import java.time.LocalDate; + +public interface DateProvider { + LocalDate now(); +}
Java
ํ…Œ์ŠคํŠธ ํ• ๋•Œ ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์˜ค๋Š˜ ๋‚ ์งœ๋กœ ํ…Œ์ŠคํŠธ๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,57 @@ +package store.entity; + +import java.time.LocalDate; +import java.util.Objects; + +public class Promotion { + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean isPromotionValid(LocalDate currentDate) { + return !currentDate.isBefore(startDate) && !currentDate.isAfter(endDate); + } + + public boolean isInsufficientPromotion(Integer value) { + return value % (buy + get) >= buy; + } + + public Integer getInsufficientPromotionQuantity(Integer value) { + return (buy + get) - value % (buy + get); + } + + public Integer getCycle() { + return buy + get; + } + + public String getName() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Promotion promotion = (Promotion) o; + return buy == promotion.buy && + get == promotion.get && + Objects.equals(name, promotion.name) && + Objects.equals(startDate, promotion.startDate) && + Objects.equals(endDate, promotion.endDate); + } + + @Override + public int hashCode() { + return Objects.hash(name, buy, get, startDate, endDate); + } +}
Java
๊ทธ๋ ‡๋„ค์š”! ์ข‹์€ ์˜๊ฒฌ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,61 @@ +package store.entity; + +import static store.constant.Constant.ERROR_PREFIX; + +import java.util.List; +import java.util.Map; + +public class Stock { + private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private final List<Product> stock; + + public Stock(List<Product> stock) { + this.stock = stock; + } + + public Product findByName(String name) { + return stock.stream() + .filter(product -> product.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE)); + } + + public void validateAll(Map<String, Integer> items) { + items.forEach(this::validate); + } + + public void update(Map<Product, Integer> cartItem) { + cartItem.forEach((product, quantity) -> { + Product stockProduct = findByName(product.getName()); + if (product.isPromotionEligible()) { + stockProduct.reducePromotionQuantity(quantity); + } else { + stockProduct.reduceQuantity(quantity); + } + }); + } + + private void validate(String productName, Integer quantity) { + if (!isValidName(productName)) { + throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE); + } + if (!isStockAvailable(productName, quantity)) { + throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE); + } + } + + private boolean isValidName(String name) { + return stock.stream().anyMatch(product -> product.getName().equals(name)); + } + + private boolean isStockAvailable(String productName, Integer quantity) { + Product product = findByName(productName); + return product.isStockAvailable(quantity); + } + + public List<Product> getStock() { + return stock.stream().toList(); + } +}
Java
ํ—ˆ๊ฑฑ.. ์ด๊ฑธ ๋ชป๋ดค๋„ค์š”..
@@ -0,0 +1,40 @@ +package store.util.parse; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.entity.DateProvider; +import store.entity.Product; +import store.entity.Promotion; +import store.entity.RealDateProvider; + +public class ProductParser { + private static final DateProvider dateProvider = new RealDateProvider(); + + public static List<Product> parse(List<String> products, Map<String, Promotion> promotions) { + List<Product> stockProduct = new ArrayList<>(); + for (int i = 1; i < products.size(); i++) { // ํ—ค๋” ๋ถ€๋ถ„ ์ œ์™ธ + String[] fields = products.get(i).split(","); + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + Promotion promotion = promotions.get(fields[3]); + addOrUpdateProduct(stockProduct, fields[0], price, quantity, promotion); + } + return stockProduct; + } + + private static void addOrUpdateProduct(List<Product> products, String name, int price, int quantity, + Promotion promotion) { + findProduct(products, name).ifPresentOrElse( + existingProduct -> existingProduct.addQuantity(quantity, promotion), + () -> products.add(new Product(name, price, quantity, promotion, dateProvider)) + ); + } + + private static Optional<Product> findProduct(List<Product> products, String name) { + return products.stream() + .filter(p -> p.getName().equals(name)) + .findFirst(); + } +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,7 @@ +package store.entity; + +import java.time.LocalDate; + +public interface DateProvider { + LocalDate now(); +}
Java
> ํ…Œ์ŠคํŠธ ํ• ๋•Œ ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์˜ค๋Š˜ ๋‚ ์งœ๋กœ ํ…Œ์ŠคํŠธ๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค! ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด ์ œ๊ฐ€ ์ž˜ ์ดํ•ด๋ฅผ ํ•˜์ง€ ๋ชปํ•˜์˜€๋Š”๋ฐ, ๊ฐ„๋‹จํ•œ ์˜ˆ์‹œ๋ฅผ ๋ง์”€ํ•ด์ฃผ์‹ค ์ˆ˜ ์žˆ์„๊นŒ์š”??
@@ -1,7 +1,65 @@ package store; +import static store.constant.Constant.ERROR_PREFIX; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import store.constant.YesOrNo; +import store.controller.PurchaseController; +import store.dto.StockResponse; +import store.entity.Product; +import store.entity.Promotion; +import store.entity.Stock; +import store.service.CartService; +import store.service.StockService; +import store.util.parse.PromotionParser; +import store.util.parse.ProductParser; +import store.view.InputView; +import store.view.OutputView; + public class Application { + private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md"; + private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md"; + private static final String FILE_ERROR_MESSAGE = ERROR_PREFIX + "ํŒŒ์ผ์„ ์ฝ๋Š”๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."; + public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + List<Product> items = getInitProducts(); + Stock stock = new Stock(items); + StockService stockService = new StockService(stock); + initializeApplication(stock, stockService); + } + + private static void initializeApplication(Stock stock, StockService stockService) { + YesOrNo continueShopping = YesOrNo.YES; + while (continueShopping == YesOrNo.YES) { + CartService cartService = new CartService(stock); + PurchaseController purchaseController = new PurchaseController(cartService, stockService); + List<StockResponse> stockResult = purchaseController.getStock(); + OutputView.printStartMessage(stockResult); + purchaseController.purchase(); + continueShopping = InputView.askForAdditionalPurchase(); + } + } + + private static List<Product> getInitProducts() { + List<String> products = readFile(PRODUCT_FILE_PATH); + List<String> promotions = readFile(PROMOTION_FILE_PATH); + Map<String, Promotion> parsePromotions = PromotionParser.parse(promotions); + List<Product> items = ProductParser.parse(products, parsePromotions); + return items; + } + + private static List<String> readFile(String filePath) { + try { + Path path = Paths.get(filePath); + return Files.readAllLines(path); + } catch (IOException e) { + throw new UncheckedIOException(FILE_ERROR_MESSAGE, e); + } } }
Java
์ €๋„ ๋™์˜ํ•ฉ๋‹ˆ๋‹ค! ์ •์  ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ ์ด์šฉํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,65 @@ +package store.controller; + +import java.util.List; +import java.util.Map; +import store.dto.ProductItem; +import store.dto.StockResponse; +import store.service.CartService; +import store.service.StockService; +import store.util.RetryHandler; +import store.util.parse.PurchaseItemParser; +import store.view.InputView; +import store.view.OutputView; + +public class PurchaseController { + private final CartService cartService; + private final StockService stockService; + + public PurchaseController(CartService cartService, StockService stockService) { + this.cartService = cartService; + this.stockService = stockService; + } + + public List<StockResponse> getStock() { + return stockService.getStock(); + } + + public void purchase() { + inputPurchaseItem(); + inputAdditionalPromotionItem(); + inputPromotionStock(); + OutputView.printReceipt(cartService.pay(inputMembership())); + } + + private void inputPromotionStock() { + RetryHandler.handleWithRetry(() -> { + List<ProductItem> nonPromotionItems = cartService.getNonPromotion(); + if (!nonPromotionItems.isEmpty()) { + List<ProductItem> removeNonPromotionItems = InputView.askForNonPromotionItems(nonPromotionItems); + cartService.removeNonPromotionItems(removeNonPromotionItems); + } + }); + } + + private void inputPurchaseItem() { + RetryHandler.handleWithRetry(() -> { + String items = InputView.readItem(); + Map<String, Integer> parseItems = PurchaseItemParser.parse(items); + cartService.purchase(parseItems); + }); + } + + private void inputAdditionalPromotionItem() { + RetryHandler.handleWithRetry(() -> { + List<ProductItem> additionalItems = cartService.getPromotionAdditionalItems(); + if (!additionalItems.isEmpty()) { + List<ProductItem> items = InputView.askForPromotionItems(additionalItems); + cartService.addPromotionItems(items); + } + }); + } + + private boolean inputMembership() { + return RetryHandler.handleWithRetry(() -> InputView.askForMembership()); + } +}
Java
์ „์ฒด์ ์œผ๋กœ ์ฝ”๋“œ์˜ indent๊ฐ€ ๊นŠ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”! ๋ฏธ์…˜ ์š”๊ตฌ์‚ฌํ•ญ์—๋Š” indent๋ฅผ 2๊นŒ์ง€ ํ—ˆ์šฉํ•œ๋‹ค๊ณ  ๋ดค๋Š”๋ฐ ์ด์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,4 @@ +package store.dto; + +public record ProductItem(String productName, int quantity) { +}
Java
๋ ˆ์ฝ”๋“œ ํ™œ์šฉ๐Ÿ‘
@@ -0,0 +1,24 @@ +package store.dto; + +import store.entity.Product; + +public record StockResponse(String name, int price, String quantity, String promotionQuantity, String promotionName) { + private static final String NONE_STOCK = "์žฌ๊ณ  ์—†์Œ"; + private static final String QUANTITY_UNIT = "๊ฐœ"; + + public static StockResponse from(Product product) { + String promotionName = ""; + if (product.getPromotion() != null) { + promotionName = product.getPromotion().getName(); + } + return new StockResponse(product.getName(), product.getPrice(), formatQuantity(product.getQuantity()), + formatQuantity(product.getPromotionQuantity()), promotionName); + } + + private static String formatQuantity(int quantity) { + if (quantity == 0) { + return NONE_STOCK; + } + return quantity + QUANTITY_UNIT; + } +}
Java
๋นˆ ๋ฌธ์ž์—ด๋กœ ์ดˆ๊ธฐํ™”ํ•œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,117 @@ +package store.entity; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import store.dto.FinalPaymentProduct; +import store.dto.ProductItem; +import store.dto.ProductItemWithPrice; + +public class Cart { + private final Map<Product, Integer> cartItem; + + public Cart() { + this.cartItem = new LinkedHashMap<>(); + } + + public void addProduct(Product product, int quantity) { + cartItem.put(product, cartItem.getOrDefault(product, 0) + quantity); + } + + public void addPromotionItems(Product product, int additionalQuantity) { + cartItem.put(product, cartItem.get(product) + additionalQuantity); + } + + public void removeNonPromotionItems(Product product, int quantity) { + cartItem.put(product, cartItem.get(product) - quantity); + } + + public List<ProductItem> getInsufficientPromotionItems() { + List<ProductItem> insufficientPromotionItems = new ArrayList<>(); + for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) { + Product product = cart.getKey(); + if (product.isInsufficientPromotion(cart.getValue())) { + int insufficientQuantity = product.getInsufficientPromotionQuantity(cart.getValue()); + insufficientPromotionItems.add(new ProductItem(product.getName(), insufficientQuantity)); + } + } + return insufficientPromotionItems; + } + + public List<ProductItem> getNonPromotionItems() { + List<ProductItem> nonPromotionItems = new ArrayList<>(); + for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) { + Product product = cart.getKey(); + if (product.isInSufficientPromotionStock(cart.getValue())) { + int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(cart.getValue()); + nonPromotionItems.add(new ProductItem(product.getName(), nonPromotionQuantity)); + } + } + return nonPromotionItems; + } + + public Map<Product, Integer> getPromotionItems() { + Map<Product, Integer> promotionItems = new LinkedHashMap<>(); + for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) { + Product product = entry.getKey(); + if (product.isPromotionEligible()) { + promotionItems.put(product, entry.getValue()); + } + } + return promotionItems; + } + + public FinalPaymentProduct getFinalPaymentItems() { + Cart discountedCart = new Cart(); + Cart nonDiscountedCart = new Cart(); + for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) { + if (isEligibleForPromotion(entry.getKey())) { + processPromotionProduct(entry.getKey(), entry.getValue(), discountedCart, nonDiscountedCart); + } else { + nonDiscountedCart.addProduct(entry.getKey(), entry.getValue()); + } + } + return new FinalPaymentProduct(discountedCart, nonDiscountedCart); + } + + public int getTotalPrice() { + return cartItem.entrySet().stream() + .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue()) + .sum(); + } + + public List<ProductItemWithPrice> getCartItemsWithPrice() { + return cartItem.entrySet().stream() + .map(entry -> new ProductItemWithPrice(entry.getKey().getName(), entry.getValue(), + entry.getKey().getPrice())) + .toList(); + } + + public List<ProductItem> getCartItems() { + return cartItem.entrySet().stream() + .map(entry -> new ProductItem(entry.getKey().getName(), entry.getValue())) + .toList(); + } + + private boolean isEligibleForPromotion(Product product) { + return product.getPromotion() != null && product.isPromotionEligible(); + } + + private void processPromotionProduct(Product product, Integer orderedQuantity, Cart discountedCart, + Cart nonDiscountedCart) { + int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(orderedQuantity); + int promotionCount = orderedQuantity - nonPromotionQuantity; + int promotableQuantity = product.calculateEligiblePromotionQuantity(promotionCount); + if (promotableQuantity > 0) { + discountedCart.addProduct(product, promotableQuantity); + } + if (nonPromotionQuantity > 0) { + nonDiscountedCart.addProduct(product, nonPromotionQuantity); + } + } + + public Map<Product, Integer> getCartItem() { + return cartItem; + } +}
Java
Cart ํด๋ž˜์Šค์—์„œ ์ƒ์„ฑ์ž ์˜์กด์„ฑ ์ฃผ์ž…์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋œ ๊ณ„๊ธฐ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,61 @@ +package store.entity; + +import static store.constant.Constant.ERROR_PREFIX; + +import java.util.List; +import java.util.Map; + +public class Stock { + private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private final List<Product> stock; + + public Stock(List<Product> stock) { + this.stock = stock; + } + + public Product findByName(String name) { + return stock.stream() + .filter(product -> product.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE)); + } + + public void validateAll(Map<String, Integer> items) { + items.forEach(this::validate); + } + + public void update(Map<Product, Integer> cartItem) { + cartItem.forEach((product, quantity) -> { + Product stockProduct = findByName(product.getName()); + if (product.isPromotionEligible()) { + stockProduct.reducePromotionQuantity(quantity); + } else { + stockProduct.reduceQuantity(quantity); + } + }); + } + + private void validate(String productName, Integer quantity) { + if (!isValidName(productName)) { + throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE); + } + if (!isStockAvailable(productName, quantity)) { + throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE); + } + } + + private boolean isValidName(String name) { + return stock.stream().anyMatch(product -> product.getName().equals(name)); + } + + private boolean isStockAvailable(String productName, Integer quantity) { + Product product = findByName(productName); + return product.isStockAvailable(quantity); + } + + public List<Product> getStock() { + return stock.stream().toList(); + } +}
Java
์˜ˆ์™ธ๋ฅผ `isValidName`๋ฉ”์„œ๋“œ์™€ `isStockAvailable`๋ฉ”์„œ๋“œ์—์„œ ๋˜์ง€๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,93 @@ +package store.view; + +import java.util.List; +import store.dto.ProductItem; +import store.dto.ProductItemWithPrice; +import store.dto.Receipt; +import store.dto.StockResponse; + +public class OutputView { + private static final String START_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\nํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค.\n"; + private static final String PROMOTION_IN_STOCK_FORMAT = "- %s %,d์› %s %s"; + private static final String REGULAR_IN_STOCK_FORMAT = "- %s %,d์› %s"; + private static final String RECEIPT_HEADER = "==============W ํŽธ์˜์ ================"; + private static final String RECEIPT_ITEM_HEADER = String.format("%-17s %-9s %-1s", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + private static final String NAME_QUANTITY_PRICE = "%-17s %-9d %,d"; + private static final String RECEIPT_PROMOTION_HEADER = "=============์ฆ ์ •==============="; + private static final String NAME_QUANTITY_ONLY = "%-17s %d"; + private static final String RECEIPT_FOOTER = "===================================="; + private static final String NAME_AMOUNT_ONLY = "%-27s -%,d"; + private static final String NAME_AMOUNT_FINAL_AMOUNT = "%-27s %,d"; + private static final String TOTAL_AMOUNT_LABEL = "์ด๊ตฌ๋งค์•ก"; + private static final String EVENT_DISCOUNT_LABEL = "ํ–‰์‚ฌํ• ์ธ"; + private static final String MEMBERSHIP_DISCOUNT_LABEL = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + private static final String FINAL_PAYMENT_LABEL = "๋‚ด์‹ค๋ˆ"; + + public static void printStartMessage(List<StockResponse> stock) { + System.out.println(START_MESSAGE); + for (StockResponse stockResponse : stock) { + if (!stockResponse.promotionName().isBlank()) { + printStockWithPromotion(stockResponse); + continue; + } + printStockWithoutPromotion(stockResponse); + } + System.out.println(); + } + + public static void printErrorMessage(String errorMessage) { + System.out.println(errorMessage); + } + + private static void printStockWithPromotion(StockResponse stockResponse) { + System.out.println( + String.format(PROMOTION_IN_STOCK_FORMAT, stockResponse.name(), stockResponse.price(), + stockResponse.promotionQuantity(), + stockResponse.promotionName())); + System.out.println(String.format(REGULAR_IN_STOCK_FORMAT, stockResponse.name(), stockResponse.price(), + stockResponse.quantity())); + } + + private static void printStockWithoutPromotion(StockResponse stockResponse) { + System.out.println(String.format(REGULAR_IN_STOCK_FORMAT, stockResponse.name(), stockResponse.price(), + stockResponse.quantity())); + } + + public static void printReceipt(Receipt receipt) { + System.out.println(RECEIPT_HEADER); + printPurchaseProduct(receipt); + printPresent(receipt); + printAmount(receipt); + } + + private static void printPurchaseProduct(Receipt receipt) { + System.out.println(RECEIPT_ITEM_HEADER); + for (ProductItemWithPrice productItem: receipt.purchaseProducts()) { + System.out.println(String.format(NAME_QUANTITY_PRICE, + productItem.productName(), + productItem.quantity(), + productItem.quantity() * productItem.price() + )); + } + } + + private static void printPresent(Receipt receipt) { + List<ProductItem> discountedItems = receipt.promotionDiscountedItems(); + if (!discountedItems.isEmpty()) { + System.out.println(RECEIPT_PROMOTION_HEADER); + discountedItems.forEach( + item -> System.out.println(String.format(NAME_QUANTITY_ONLY, item.productName(), item.quantity()))); + } + System.out.println(RECEIPT_FOOTER); + } + + private static void printAmount(Receipt receipt) { + System.out.printf(NAME_QUANTITY_PRICE + "\n", TOTAL_AMOUNT_LABEL, + receipt.purchaseProducts().stream().mapToInt(productItem -> productItem.quantity()).sum(), + receipt.amount().totalAmount()); + System.out.printf(NAME_AMOUNT_ONLY + "\n", EVENT_DISCOUNT_LABEL, receipt.amount().promotionDiscountAmount()); + System.out.printf(NAME_AMOUNT_ONLY + "\n", MEMBERSHIP_DISCOUNT_LABEL, + receipt.amount().membershipDiscountAmount()); + System.out.printf(NAME_AMOUNT_FINAL_AMOUNT + "\n", FINAL_PAYMENT_LABEL, receipt.amount().finalAmount()); + } +}
Java
DTO์™€ ์ปฌ๋ ‰์…˜ ์‚ฌ์šฉํ•ด์„œ ์ถœ๋ ฅ์„ ๊น”๋”ํ•˜๊ฒŒ ํ•˜์…จ๋„ค์š”! ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค!!
@@ -0,0 +1,65 @@ +package store.controller; + +import java.util.List; +import java.util.Map; +import store.dto.ProductItem; +import store.dto.StockResponse; +import store.service.CartService; +import store.service.StockService; +import store.util.RetryHandler; +import store.util.parse.PurchaseItemParser; +import store.view.InputView; +import store.view.OutputView; + +public class PurchaseController { + private final CartService cartService; + private final StockService stockService; + + public PurchaseController(CartService cartService, StockService stockService) { + this.cartService = cartService; + this.stockService = stockService; + } + + public List<StockResponse> getStock() { + return stockService.getStock(); + } + + public void purchase() { + inputPurchaseItem(); + inputAdditionalPromotionItem(); + inputPromotionStock(); + OutputView.printReceipt(cartService.pay(inputMembership())); + } + + private void inputPromotionStock() { + RetryHandler.handleWithRetry(() -> { + List<ProductItem> nonPromotionItems = cartService.getNonPromotion(); + if (!nonPromotionItems.isEmpty()) { + List<ProductItem> removeNonPromotionItems = InputView.askForNonPromotionItems(nonPromotionItems); + cartService.removeNonPromotionItems(removeNonPromotionItems); + } + }); + } + + private void inputPurchaseItem() { + RetryHandler.handleWithRetry(() -> { + String items = InputView.readItem(); + Map<String, Integer> parseItems = PurchaseItemParser.parse(items); + cartService.purchase(parseItems); + }); + } + + private void inputAdditionalPromotionItem() { + RetryHandler.handleWithRetry(() -> { + List<ProductItem> additionalItems = cartService.getPromotionAdditionalItems(); + if (!additionalItems.isEmpty()) { + List<ProductItem> items = InputView.askForPromotionItems(additionalItems); + cartService.addPromotionItems(items); + } + }); + } + + private boolean inputMembership() { + return RetryHandler.handleWithRetry(() -> InputView.askForMembership()); + } +}
Java
์ € ์ฝ”๋“œ๋Š” indent๊ฐ€ 2 ์•„๋‹Œ๊ฐ€์š”?!
@@ -0,0 +1,24 @@ +package store.dto; + +import store.entity.Product; + +public record StockResponse(String name, int price, String quantity, String promotionQuantity, String promotionName) { + private static final String NONE_STOCK = "์žฌ๊ณ  ์—†์Œ"; + private static final String QUANTITY_UNIT = "๊ฐœ"; + + public static StockResponse from(Product product) { + String promotionName = ""; + if (product.getPromotion() != null) { + promotionName = product.getPromotion().getName(); + } + return new StockResponse(product.getName(), product.getPrice(), formatQuantity(product.getQuantity()), + formatQuantity(product.getPromotionQuantity()), promotionName); + } + + private static String formatQuantity(int quantity) { + if (quantity == 0) { + return NONE_STOCK; + } + return quantity + QUANTITY_UNIT; + } +}
Java
OutputView ์—์„œ ํ•ด๋‹น promotionName์˜ ์ƒํƒœ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ํฌ๋งท์„ ์ ์šฉ์‹œํ‚ค๋ ค๊ณ  ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,117 @@ +package store.entity; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import store.dto.FinalPaymentProduct; +import store.dto.ProductItem; +import store.dto.ProductItemWithPrice; + +public class Cart { + private final Map<Product, Integer> cartItem; + + public Cart() { + this.cartItem = new LinkedHashMap<>(); + } + + public void addProduct(Product product, int quantity) { + cartItem.put(product, cartItem.getOrDefault(product, 0) + quantity); + } + + public void addPromotionItems(Product product, int additionalQuantity) { + cartItem.put(product, cartItem.get(product) + additionalQuantity); + } + + public void removeNonPromotionItems(Product product, int quantity) { + cartItem.put(product, cartItem.get(product) - quantity); + } + + public List<ProductItem> getInsufficientPromotionItems() { + List<ProductItem> insufficientPromotionItems = new ArrayList<>(); + for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) { + Product product = cart.getKey(); + if (product.isInsufficientPromotion(cart.getValue())) { + int insufficientQuantity = product.getInsufficientPromotionQuantity(cart.getValue()); + insufficientPromotionItems.add(new ProductItem(product.getName(), insufficientQuantity)); + } + } + return insufficientPromotionItems; + } + + public List<ProductItem> getNonPromotionItems() { + List<ProductItem> nonPromotionItems = new ArrayList<>(); + for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) { + Product product = cart.getKey(); + if (product.isInSufficientPromotionStock(cart.getValue())) { + int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(cart.getValue()); + nonPromotionItems.add(new ProductItem(product.getName(), nonPromotionQuantity)); + } + } + return nonPromotionItems; + } + + public Map<Product, Integer> getPromotionItems() { + Map<Product, Integer> promotionItems = new LinkedHashMap<>(); + for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) { + Product product = entry.getKey(); + if (product.isPromotionEligible()) { + promotionItems.put(product, entry.getValue()); + } + } + return promotionItems; + } + + public FinalPaymentProduct getFinalPaymentItems() { + Cart discountedCart = new Cart(); + Cart nonDiscountedCart = new Cart(); + for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) { + if (isEligibleForPromotion(entry.getKey())) { + processPromotionProduct(entry.getKey(), entry.getValue(), discountedCart, nonDiscountedCart); + } else { + nonDiscountedCart.addProduct(entry.getKey(), entry.getValue()); + } + } + return new FinalPaymentProduct(discountedCart, nonDiscountedCart); + } + + public int getTotalPrice() { + return cartItem.entrySet().stream() + .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue()) + .sum(); + } + + public List<ProductItemWithPrice> getCartItemsWithPrice() { + return cartItem.entrySet().stream() + .map(entry -> new ProductItemWithPrice(entry.getKey().getName(), entry.getValue(), + entry.getKey().getPrice())) + .toList(); + } + + public List<ProductItem> getCartItems() { + return cartItem.entrySet().stream() + .map(entry -> new ProductItem(entry.getKey().getName(), entry.getValue())) + .toList(); + } + + private boolean isEligibleForPromotion(Product product) { + return product.getPromotion() != null && product.isPromotionEligible(); + } + + private void processPromotionProduct(Product product, Integer orderedQuantity, Cart discountedCart, + Cart nonDiscountedCart) { + int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(orderedQuantity); + int promotionCount = orderedQuantity - nonPromotionQuantity; + int promotableQuantity = product.calculateEligiblePromotionQuantity(promotionCount); + if (promotableQuantity > 0) { + discountedCart.addProduct(product, promotableQuantity); + } + if (nonPromotionQuantity > 0) { + nonDiscountedCart.addProduct(product, nonPromotionQuantity); + } + } + + public Map<Product, Integer> getCartItem() { + return cartItem; + } +}
Java
์ƒ์„ฑ์ž์— ์•„๋ฌด๊ฒƒ๋„ ๋ฐ›์ง€ ์•Š์•„์„œ ์˜์กด์„ฑ ์ฃผ์ž…์€ ์•„๋‹ˆ์ง€ ์•Š๋‚˜์š”?!
@@ -0,0 +1,7 @@ +package store.entity; + +import java.time.LocalDate; + +public interface DateProvider { + LocalDate now(); +}
Java
ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์—์„œ ์‹ค์ œ ์˜ค๋Š˜๋‚ ์งœ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” now()๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ๋˜๋ฉด ํ…Œ์ŠคํŠธ์ฝ”๋“œ๊ฐ€ ํ•ด๋‹น ๋‚ ์งœ์— ์˜์กดํ•˜์ง€ ์•Š์„๊นŒ์š”??
@@ -0,0 +1,61 @@ +package store.entity; + +import static store.constant.Constant.ERROR_PREFIX; + +import java.util.List; +import java.util.Map; + +public class Stock { + private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private final List<Product> stock; + + public Stock(List<Product> stock) { + this.stock = stock; + } + + public Product findByName(String name) { + return stock.stream() + .filter(product -> product.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE)); + } + + public void validateAll(Map<String, Integer> items) { + items.forEach(this::validate); + } + + public void update(Map<Product, Integer> cartItem) { + cartItem.forEach((product, quantity) -> { + Product stockProduct = findByName(product.getName()); + if (product.isPromotionEligible()) { + stockProduct.reducePromotionQuantity(quantity); + } else { + stockProduct.reduceQuantity(quantity); + } + }); + } + + private void validate(String productName, Integer quantity) { + if (!isValidName(productName)) { + throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE); + } + if (!isStockAvailable(productName, quantity)) { + throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE); + } + } + + private boolean isValidName(String name) { + return stock.stream().anyMatch(product -> product.getName().equals(name)); + } + + private boolean isStockAvailable(String productName, Integer quantity) { + Product product = findByName(productName); + return product.isStockAvailable(quantity); + } + + public List<Product> getStock() { + return stock.stream().toList(); + } +}
Java
๊ทธ๋ž˜๋„ ๋ ๊ฒƒ๊ฐ™๋„ค์š”!
@@ -1,7 +1,65 @@ package store; +import static store.constant.Constant.ERROR_PREFIX; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import store.constant.YesOrNo; +import store.controller.PurchaseController; +import store.dto.StockResponse; +import store.entity.Product; +import store.entity.Promotion; +import store.entity.Stock; +import store.service.CartService; +import store.service.StockService; +import store.util.parse.PromotionParser; +import store.util.parse.ProductParser; +import store.view.InputView; +import store.view.OutputView; + public class Application { + private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md"; + private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md"; + private static final String FILE_ERROR_MESSAGE = ERROR_PREFIX + "ํŒŒ์ผ์„ ์ฝ๋Š”๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."; + public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + List<Product> items = getInitProducts(); + Stock stock = new Stock(items); + StockService stockService = new StockService(stock); + initializeApplication(stock, stockService); + } + + private static void initializeApplication(Stock stock, StockService stockService) { + YesOrNo continueShopping = YesOrNo.YES; + while (continueShopping == YesOrNo.YES) { + CartService cartService = new CartService(stock); + PurchaseController purchaseController = new PurchaseController(cartService, stockService); + List<StockResponse> stockResult = purchaseController.getStock(); + OutputView.printStartMessage(stockResult); + purchaseController.purchase(); + continueShopping = InputView.askForAdditionalPurchase(); + } + } + + private static List<Product> getInitProducts() { + List<String> products = readFile(PRODUCT_FILE_PATH); + List<String> promotions = readFile(PROMOTION_FILE_PATH); + Map<String, Promotion> parsePromotions = PromotionParser.parse(promotions); + List<Product> items = ProductParser.parse(products, parsePromotions); + return items; + } + + private static List<String> readFile(String filePath) { + try { + Path path = Paths.get(filePath); + return Files.readAllLines(path); + } catch (IOException e) { + throw new UncheckedIOException(FILE_ERROR_MESSAGE, e); + } } }
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
๋ฉค๋ฒ„์‹ญ์„ ์ ์šฉํ•œ๋‹ค๋Š” ๊ด€์ ์ด ์•„๋‹ˆ๋ผ, has ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฉค๋ฒ„์‹ญ์ด ์žˆ๋‹ค๋ฉด ๋ฐ˜๋“œ์‹œ ์ ์šฉํ•œ๋‹ค๋Š” ๊ด€์ ์ด ์ƒ๋‹นํžˆ ์ง๊ด€์ ์ด๊ณ  ์ดํ•ด๊ฐ€ ์ž˜ ๋˜๋„ค์š”. ๊ทธ๋ ‡์ง€๋งŒ ์ถœ๋ ฅ๋˜๋Š” ๋ฌธ์žฅ์ด `๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)`์ธ๋ฐ ์ถ”์ƒํ™”ํ•ด์„œ ํ‘œํ˜„ํ•ด๋„ ๋˜๋Š” ๊ฑธ๊นŒ์š”?
@@ -0,0 +1,29 @@ +package store.exception.store; + +public enum StoreErrorStatus { + + INSUFFICIENT_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + NON_EXIST_PRODUCT("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + DUPLICATE_GENERAL_PRODUCT("์ƒํ’ˆ์ด ์ค‘๋ณต๋˜์—ˆ์Šต๋‹ˆ๋‹ค."), + DUPLICATE_PROMOTION_PRODUCT("ํ•˜๋‚˜์˜ ์ƒํ’ˆ์— ๋‘๊ฐœ์˜ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + + INVALID_PROMOTION_BUY_AMOUNT("๊ตฌ๋งค ๊ฐœ์ˆ˜๋Š” 0 ์ดํ•˜๊ฐ€ ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_PROMOTION_GIVE_AMOUNT("์ถ”๊ฐ€ ์ฆ์ •์€ ํ•˜๋‚˜๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."), + NON_EXIST_PROMOTION("์กด์žฌํ•˜์ง€ ์•Š๋Š” ํ”„๋กœ๋ชจ์…˜์ด ์žˆ์Šต๋‹ˆ๋‹ค."), + DUPLICATE_PROMOTION_NAME("ํ”„๋กœ๋ชจ์…˜์˜ ์ด๋ฆ„์€ ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + + INVALID_PRODUCT_PRICE("๊ฐ€๊ฒฉ์€ 0 ์ดํ•˜๊ฐ€ ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_PRODUCT_STOCK("์žฌ๊ณ ๋Š” ์Œ์ˆ˜๊ฐ€ ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + + PRODUCT_PRICE_INCONSISTENT("์ผ๋ฐ˜ ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์˜ ๊ฐ€๊ฒฉ์€ ๋™์ผํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค."); + + private final String message; + + StoreErrorStatus(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
๋ฐ˜์„ฑํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ์˜ˆ์™ธ ๋ฆฌ์ŠคํŠธ๋„ค์š”... ๋Œ€๋‹จํ•˜์‹ญ๋‹ˆ๋‹ค.
@@ -0,0 +1,92 @@ +package store.model.order; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.Map; +import java.util.stream.Collectors; +import store.model.store.StoreRoom; +import store.model.store.product.Product; + +public class Payment { + private final PurchaseOrder purchaseOrder; + private final StoreRoom storeRoom; + private final boolean hasMembership; + + private Payment(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) { + this.purchaseOrder = purchaseOrder; + this.storeRoom = storeRoom; + this.hasMembership = hasMembership; + } + + public static Payment from(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) { + return new Payment(purchaseOrder, storeRoom, hasMembership); + } + + public long calculateActualPrice() { + long promotionalDiscount = calculatePromotionalDiscount(); + long membershipDiscount = calculateMembershipDiscount(); + long totalPrice = calculateTotalPrice(); + return totalPrice - (promotionalDiscount + membershipDiscount); + } + + public long calculatePromotionalDiscount() { + return extractPromotionalProducts().entrySet().stream() + .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue()) + .sum(); + } + + public long calculateMembershipDiscount() { + if (!hasMembership) { + return 0; + } + long promotionAppliedPrice = extractPromotionalProducts().entrySet().stream() + .mapToLong(entry -> { + Product product = storeRoom.getPromotionProducts().findNullableProductByName(entry.getKey()); + return (long) product.getPrice() * entry.getValue() * product.getPromotionUnit(); + }).sum(); + long membershipDiscount = (long) ((calculateTotalPrice() - promotionAppliedPrice) * 0.3); + return Math.min(8000L, membershipDiscount); + } + + public long calculateTotalPrice() { + return purchaseOrder.getPurchaseOrder().entrySet().stream() + .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue()) + .sum(); + } + + public long calculateProductPrice(String productName) { + int buyAmount = purchaseOrder.getPurchaseOrder().get(productName); + int productPrice = storeRoom.getProductPrice(productName); + return (long) buyAmount * productPrice; + } + + public long calculateTotalBuyAmount() { + return purchaseOrder.getPurchaseOrder().values().stream() + .mapToLong(Long::valueOf) + .sum(); + } + + private int calculateGiveawayAmount(String productName, int quantity) { + Product product = storeRoom.getPromotionProducts().findNullableProductByName(productName); + if (product != null + && product.isPromotionPeriod(DateTimes.now()) + && product.getStock() >= product.getPromotionUnit()) { + int promotionalQuantity = quantity - storeRoom.getNonPromotionalQuantity(productName, quantity); + return promotionalQuantity / product.getPromotionUnit(); + } + return 0; + } + + public Map<String, Integer> extractPromotionalProducts() { + return purchaseOrder.getPurchaseOrder().entrySet().stream() + .map(entry -> Map.entry( + entry.getKey(), + calculateGiveawayAmount(entry.getKey(), entry.getValue()) + )) + .filter(entry -> entry.getValue() > 0) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + public PurchaseOrder getPurchaseOrder() { + return purchaseOrder; + } +}
Java
ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ 2๊ฐœ ์ด์ƒ์ด๋ผ๋ฉด of ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋‚˜์š”? ๊ตณ์ด ์‹ ๊ฒฝ์“ฐ์ง€ ์•Š๋Š” ๋ถ€๋ถ„์ด์‹ค๊นŒ์š”?
@@ -0,0 +1,94 @@ +package store.model.store.product; + +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE; +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK; + +import java.time.LocalDateTime; +import store.exception.store.StoreException; +import store.model.store.promotion.Promotion; + +public class Product { + private final String name; + private final int price; + private int stock; + private final Promotion promotion; + + private Product(String name, int price, int stock, Promotion promotion) { + validatePrice(price); + validateStock(stock); + this.name = name; + this.price = price; + this.stock = stock; + this.promotion = promotion; + } + + public static Product of(String name, int price, int stock, Promotion promotion) { + return new Product(name, price, stock, promotion); + } + + public static Product createEmptyGeneralProduct(Product product) { + return new Product(product.name, product.price, 0, null); + } + + public void decreaseStock(int amount) { + stock -= amount; + } + + public boolean isNameEquals(Product product) { + return this.name.equals(product.name); + } + + public boolean isNameEquals(String name) { + return this.name.equals(name); + } + + public boolean isPromotionPeriod(LocalDateTime now) { + if (this.promotion == null) { + return false; + } + return promotion.isPeriod(now); + } + + public boolean isGeneralProduct() { + return promotion == null; + } + + public boolean isPromotionProduct() { + return promotion != null; + } + + private void validatePrice(int price) { + if (price <= 0) { + throw new StoreException(INVALID_PRODUCT_PRICE); + } + } + + private void validateStock(int stock) { + if (stock < 0) { + throw new StoreException(INVALID_PRODUCT_STOCK); + } + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public String getPromotionName() { + if (promotion == null) { + return ""; + } + return promotion.getName(); + } + + public int getPromotionUnit() { + return promotion.getUnit(); + } +}
Java
์ด ๋ถ€๋ถ„์ด ์ €๋ž‘ ๋‹ค๋ฅด๋„ค์š”! ์ €๋Š” Product์— ์žฌ๊ณ ๋ฅผ ํฌํ•จ์‹œํ‚ค์ง€ ์•Š๊ณ  ์žฌ๊ณ ๋Š” repository์—์„œ ๊ฐ€์ ธ์˜ค๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค. product๊ฐ€ ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ๊ฐ€์ ธ๋„ ๊ดœ์ฐฎ์€์ง€ ์—ฌ์ญค๋ณด๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,61 @@ +package store.model.store.promotion; + +import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_BUY_AMOUNT; +import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_GIVE_AMOUNT; + +import java.time.LocalDateTime; +import store.exception.store.StoreException; + +public class Promotion { + private final String name; + private final int buyAmount; + private final int giveAmount; + private final LocalDateTime startAt; + private final LocalDateTime endAt; + + private Promotion(String name, int buyAmount, int giveAmount, LocalDateTime startAt, LocalDateTime endAt) { + validateBuyAmount(buyAmount); + validateGiveAmount(giveAmount); + this.name = name; + this.buyAmount = buyAmount; + this.giveAmount = giveAmount; + this.startAt = startAt; + this.endAt = endAt; + } + + public static Promotion of(String name, + int buyAmount, + int giveAmount, + LocalDateTime startAt, + LocalDateTime endAt) { + return new Promotion(name, buyAmount, giveAmount, startAt, endAt); + } + + public boolean isNameEquals(String name) { + return this.name.equals(name); + } + + public boolean isPeriod(LocalDateTime now) { + return startAt.isBefore(now) && endAt.isAfter(now); + } + + private void validateBuyAmount(int buyAmount) { + if (buyAmount < 1) { + throw new StoreException(INVALID_PROMOTION_BUY_AMOUNT); + } + } + + private void validateGiveAmount(int giveAmount) { + if (giveAmount != 1) { + throw new StoreException(INVALID_PROMOTION_GIVE_AMOUNT); + } + } + + public String getName() { + return name; + } + + public int getUnit() { + return buyAmount + giveAmount; + } +}
Java
LocalDate๊ฐ€ ์•„๋‹Œ LocalDateTime์„ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,20 @@ +package store.util.reader; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RepeatableReader { + public static <T> T handle(Supplier<String> viewMethod, + Function<String, T> converter, + Consumer<String> errorHandler) { + while (true) { + try { + String userInput = viewMethod.get(); + return converter.apply(userInput); + } catch (IllegalArgumentException e) { + errorHandler.accept(e.getMessage()); + } + } + } +}
Java
ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ๋˜๊ฒŒ ์ž˜ํ•˜์‹œ๋„ค์š”.
@@ -0,0 +1,10 @@ +package store.view; + +public class ErrorView { + + private static final String ERROR_PREFIX = "[ERROR] "; + + public void errorPage(String message) { + System.out.println(ERROR_PREFIX + message); + } +}
Java
ErrorView๋Š” ์ฒ˜์Œ ๋ณด๋Š”๋ฐ, ์ž˜ ๋งŒ๋“œ์‹  ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,44 @@ +package store.util.reader; + +import static store.exception.reader.FileReadErrorStatus.INVALID_FILE_PATH; +import static store.exception.reader.FileReadErrorStatus.UNEXPECTED_IO_ERROR; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import store.exception.reader.FileReadException; + +public class StoreFileReader { + private static final String DELIMITER = ","; + + public static List<List<String>> readFile(String fileName) { + validateFileReadable(fileName); + Path path = Paths.get(fileName); + try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { + return reader.lines().skip(1) + .filter(line -> line != null && !line.trim().isEmpty()) + .map(StoreFileReader::parseLine) + .toList(); + } catch (IOException e) { + throw new FileReadException(UNEXPECTED_IO_ERROR); + } + } + + private static List<String> parseLine(String line) { + return List.of(line.split(DELIMITER)); + } + + public static void validateFileReadable(String fileName) { + if (fileName == null || fileName.trim().isEmpty()) { + throw new FileReadException(INVALID_FILE_PATH); + } + Path path = Paths.get(fileName); + if (!(Files.exists(path) && Files.isReadable(path))) { + throw new FileReadException(INVALID_FILE_PATH); + } + } +}
Java
`String.isBlank`๋ฉ”์„œ๋“œ๋„ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,130 @@ +package store.view.formatter; + +import store.model.order.Payment; +import store.model.store.StoreRoom; +import store.model.store.product.Product; +import store.model.store.product.Products; + +public class OutputFormatter { + private static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\nํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + private static final String PRODUCT_PREFIX = "- "; + private static final String SOLD_OUT = "์žฌ๊ณ  ์—†์Œ"; + private static final String RECEIPT_START_MESSAGE = "==============W ํŽธ์˜์ ================"; + private static final String RECEIPT_COLUMN_MESSAGE = "์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก"; + private static final String RECEIPT_PURCHASE_MESSAGE_FORMAT = "%s\t\t%,d \t%,d"; + private static final String RECEIPT_GIVEAWAY_MESSAGE = "=============์ฆ\t์ •==============="; + private static final String RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT = "%s\t\t%,d"; + private static final String RECEIPT_LINE_SEPARATOR = "===================================="; + private static final String RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT = "์ด๊ตฌ๋งค์•ก\t\t%,d\t%,d"; + private static final String RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT = "ํ–‰์‚ฌํ• ์ธ\t\t\t-%,d"; + private static final String RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT = "๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%,d"; + private static final String RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT = "๋‚ด์‹ค๋ˆ\t\t\t%,d"; + private static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator(); + + private OutputFormatter() { + } + + public static String buildStoreStock(StoreRoom storeRoom) { + StringBuilder sb = new StringBuilder(); + sb.append(WELCOME_MESSAGE).append(SYSTEM_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR); + + String menus = buildProducts(storeRoom.getGeneralProducts(), storeRoom.getPromotionProducts()); + sb.append(menus); + return sb.toString(); + } + + public static String buildReceipt(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(buildReceiptHeader()) + .append(buildPurchaseItems(payment)) + .append(buildGiveawayIems(payment)) + .append(buildReceiptSummary(payment)); + return sb.toString(); + } + + private static String buildProducts(Products generalProducts, Products promotionProducts) { + StringBuilder sb = new StringBuilder(); + for (Product product : generalProducts.getProducts()) { + if (promotionProducts.contains(product.getName())) { + sb.append(buildProductMessage(promotionProducts.findNullableProductByName(product.getName()))); + } + sb.append(buildProductMessage(product)); + } + return sb.toString(); + } + + private static String buildProductMessage(Product product) { + StringBuilder sb = new StringBuilder(); + sb.append(PRODUCT_PREFIX) + .append(product.getName()).append(" ") + .append(String.format("%,d์›", product.getPrice())).append(" ") + .append(buildProductStock(product.getStock())).append(" ") + .append(product.getPromotionName()).append(SYSTEM_LINE_SEPARATOR); + return sb.toString(); + } + + private static String buildProductStock(int stock) { + if (stock == 0) { + return SOLD_OUT; + } + return String.format("%,d๊ฐœ", stock); + } + + private static String buildReceiptHeader() { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_START_MESSAGE).append(SYSTEM_LINE_SEPARATOR) + .append(RECEIPT_COLUMN_MESSAGE).append(SYSTEM_LINE_SEPARATOR); + return sb.toString(); + } + + private static String buildPurchaseItems(Payment payment) { + StringBuilder sb = new StringBuilder(); + payment.getPurchaseOrder().getPurchaseOrder().forEach((name, quantity) -> + sb.append(String.format(RECEIPT_PURCHASE_MESSAGE_FORMAT, + name, quantity, payment.calculateProductPrice(name))) + .append(SYSTEM_LINE_SEPARATOR) + ); + return sb.toString(); + } + + private static String buildGiveawayIems(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_GIVEAWAY_MESSAGE).append(SYSTEM_LINE_SEPARATOR); + + payment.extractPromotionalProducts().forEach((name, quantity) -> + sb.append(String.format(RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT, name, quantity)) + .append(SYSTEM_LINE_SEPARATOR) + ); + return sb.toString(); + } + + private static String buildReceiptSummary(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR) + .append(buildTotalPrice(payment)) + .append(buildDiscounts(payment)) + .append(buildFinalPrice(payment)); + return sb.toString(); + } + + private static String buildTotalPrice(Payment payment) { + return String.format(RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT, + payment.calculateTotalBuyAmount(), payment.calculateTotalPrice()) + + SYSTEM_LINE_SEPARATOR; + } + + private static String buildDiscounts(Payment payment) { + return String.format(RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT, + payment.calculatePromotionalDiscount()) + + SYSTEM_LINE_SEPARATOR + + String.format(RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT, + payment.calculateMembershipDiscount()) + + SYSTEM_LINE_SEPARATOR; + } + + private static String buildFinalPrice(Payment payment) { + return String.format(RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT, + payment.calculateActualPrice()) + + SYSTEM_LINE_SEPARATOR; + } +}
Java
,๋ฅผ ์ด๋ ‡๊ฒŒ๋„ ๋„ฃ์„ ์ˆ˜ ์žˆ๊ตฐ์š”! ์ข‹์€ ๋ฐฉ๋ฒ•์ด๋„ค์š”!
@@ -0,0 +1,20 @@ +package store.util.reader; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RepeatableReader { + public static <T> T handle(Supplier<String> viewMethod, + Function<String, T> converter, + Consumer<String> errorHandler) { + while (true) { + try { + String userInput = viewMethod.get(); + return converter.apply(userInput); + } catch (IllegalArgumentException e) { + errorHandler.accept(e.getMessage()); + } + } + } +}
Java
ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋„ˆ๋ฌด ์ž˜ ์‚ฌ์šฉํ•˜์‹  ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
do-while๋„ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋ฉด ๋” ๊ฐ€๋…์„ฑ์ด ์ข‹์•„์งˆ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,10 @@ +package store.view; + +public class ErrorView { + + private static final String ERROR_PREFIX = "[ERROR] "; + + public void errorPage(String message) { + System.out.println(ERROR_PREFIX + message); + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,44 @@ +package store.util.reader; + +import static store.exception.reader.FileReadErrorStatus.INVALID_FILE_PATH; +import static store.exception.reader.FileReadErrorStatus.UNEXPECTED_IO_ERROR; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import store.exception.reader.FileReadException; + +public class StoreFileReader { + private static final String DELIMITER = ","; + + public static List<List<String>> readFile(String fileName) { + validateFileReadable(fileName); + Path path = Paths.get(fileName); + try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { + return reader.lines().skip(1) + .filter(line -> line != null && !line.trim().isEmpty()) + .map(StoreFileReader::parseLine) + .toList(); + } catch (IOException e) { + throw new FileReadException(UNEXPECTED_IO_ERROR); + } + } + + private static List<String> parseLine(String line) { + return List.of(line.split(DELIMITER)); + } + + public static void validateFileReadable(String fileName) { + if (fileName == null || fileName.trim().isEmpty()) { + throw new FileReadException(INVALID_FILE_PATH); + } + Path path = Paths.get(fileName); + if (!(Files.exists(path) && Files.isReadable(path))) { + throw new FileReadException(INVALID_FILE_PATH); + } + } +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,20 @@ +package store.util.reader; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RepeatableReader { + public static <T> T handle(Supplier<String> viewMethod, + Function<String, T> converter, + Consumer<String> errorHandler) { + while (true) { + try { + String userInput = viewMethod.get(); + return converter.apply(userInput); + } catch (IllegalArgumentException e) { + errorHandler.accept(e.getMessage()); + } + } + } +}
Java
์ €๋„ ์ €๋ฒˆ ๋ฏธ์…˜ ์ฝ”๋“œ๋ฆฌ๋ทฐ ๋‹ค๋‹ˆ๋ฉด์„œ ๋ดค๋Š”๋ฐ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์ด๋ฒˆ ๋ฏธ์…˜์— ์ ์šฉํ•ด๋ณด์•˜์–ด์š”!
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
์—ฌ์ญค๋ณด์‹ ๊ฒŒ ์™„๋ฒฝํžˆ ์ดํ•ด๋ฅผ ๋ชปํ–ˆ์ง€๋งŒ ๋‹ต๋ณ€ ๋“œ๋ฆฌ๋ฉด `๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)`๋ฅผ ๋ฌผ์–ด๋ณด๋Š” ๋ฉ”์„œ๋“œ๋Š” `askMembership`์ด๋ผ๊ณ  ์ง๊ด€์ ์œผ๋กœ ์ž‘์„ฑํ•˜์˜€๊ณ , ๊ทธ๋ฅผ ๋‹ด๋Š” ๋ณ€์ˆ˜๋Š” ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์œ ๋ฌด์ด๊ธฐ ๋•Œ๋ฌธ์— has๋ผ๋Š” ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,29 @@ +package store.exception.store; + +public enum StoreErrorStatus { + + INSUFFICIENT_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + NON_EXIST_PRODUCT("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + DUPLICATE_GENERAL_PRODUCT("์ƒํ’ˆ์ด ์ค‘๋ณต๋˜์—ˆ์Šต๋‹ˆ๋‹ค."), + DUPLICATE_PROMOTION_PRODUCT("ํ•˜๋‚˜์˜ ์ƒํ’ˆ์— ๋‘๊ฐœ์˜ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + + INVALID_PROMOTION_BUY_AMOUNT("๊ตฌ๋งค ๊ฐœ์ˆ˜๋Š” 0 ์ดํ•˜๊ฐ€ ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_PROMOTION_GIVE_AMOUNT("์ถ”๊ฐ€ ์ฆ์ •์€ ํ•˜๋‚˜๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."), + NON_EXIST_PROMOTION("์กด์žฌํ•˜์ง€ ์•Š๋Š” ํ”„๋กœ๋ชจ์…˜์ด ์žˆ์Šต๋‹ˆ๋‹ค."), + DUPLICATE_PROMOTION_NAME("ํ”„๋กœ๋ชจ์…˜์˜ ์ด๋ฆ„์€ ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + + INVALID_PRODUCT_PRICE("๊ฐ€๊ฒฉ์€ 0 ์ดํ•˜๊ฐ€ ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_PRODUCT_STOCK("์žฌ๊ณ ๋Š” ์Œ์ˆ˜๊ฐ€ ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + + PRODUCT_PRICE_INCONSISTENT("์ผ๋ฐ˜ ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์˜ ๊ฐ€๊ฒฉ์€ ๋™์ผํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค."); + + private final String message; + + StoreErrorStatus(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,92 @@ +package store.model.order; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.Map; +import java.util.stream.Collectors; +import store.model.store.StoreRoom; +import store.model.store.product.Product; + +public class Payment { + private final PurchaseOrder purchaseOrder; + private final StoreRoom storeRoom; + private final boolean hasMembership; + + private Payment(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) { + this.purchaseOrder = purchaseOrder; + this.storeRoom = storeRoom; + this.hasMembership = hasMembership; + } + + public static Payment from(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) { + return new Payment(purchaseOrder, storeRoom, hasMembership); + } + + public long calculateActualPrice() { + long promotionalDiscount = calculatePromotionalDiscount(); + long membershipDiscount = calculateMembershipDiscount(); + long totalPrice = calculateTotalPrice(); + return totalPrice - (promotionalDiscount + membershipDiscount); + } + + public long calculatePromotionalDiscount() { + return extractPromotionalProducts().entrySet().stream() + .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue()) + .sum(); + } + + public long calculateMembershipDiscount() { + if (!hasMembership) { + return 0; + } + long promotionAppliedPrice = extractPromotionalProducts().entrySet().stream() + .mapToLong(entry -> { + Product product = storeRoom.getPromotionProducts().findNullableProductByName(entry.getKey()); + return (long) product.getPrice() * entry.getValue() * product.getPromotionUnit(); + }).sum(); + long membershipDiscount = (long) ((calculateTotalPrice() - promotionAppliedPrice) * 0.3); + return Math.min(8000L, membershipDiscount); + } + + public long calculateTotalPrice() { + return purchaseOrder.getPurchaseOrder().entrySet().stream() + .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue()) + .sum(); + } + + public long calculateProductPrice(String productName) { + int buyAmount = purchaseOrder.getPurchaseOrder().get(productName); + int productPrice = storeRoom.getProductPrice(productName); + return (long) buyAmount * productPrice; + } + + public long calculateTotalBuyAmount() { + return purchaseOrder.getPurchaseOrder().values().stream() + .mapToLong(Long::valueOf) + .sum(); + } + + private int calculateGiveawayAmount(String productName, int quantity) { + Product product = storeRoom.getPromotionProducts().findNullableProductByName(productName); + if (product != null + && product.isPromotionPeriod(DateTimes.now()) + && product.getStock() >= product.getPromotionUnit()) { + int promotionalQuantity = quantity - storeRoom.getNonPromotionalQuantity(productName, quantity); + return promotionalQuantity / product.getPromotionUnit(); + } + return 0; + } + + public Map<String, Integer> extractPromotionalProducts() { + return purchaseOrder.getPurchaseOrder().entrySet().stream() + .map(entry -> Map.entry( + entry.getKey(), + calculateGiveawayAmount(entry.getKey(), entry.getValue()) + )) + .filter(entry -> entry.getValue() > 0) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + public PurchaseOrder getPurchaseOrder() { + return purchaseOrder; + } +}
Java
์ €๋„ `of`, `from`๋ฉ”์„œ๋“œ ๋„ค์ด๋ฐ์— ๋Œ€ํ•ด์„œ ๊ณ ๋ฏผ์„ ๋งŽ์ดํ–ˆ๋Š”๋ฐ ์–ด๋–ค ๋ธ”๋กœ๊ทธ์—๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ 2๊ฐœ ์ด์ƒ์ด๋ฉด `of` ํ•˜๋‚˜๋ฉด `from`์œผ๋กœ ํ•œ๋‹ค๋Š” ๊ธ€์„ ๋ดค์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ๊ธ€์—์„œ๋Š” ์ •๋ณด๋ฅผ ์กฐํ•ฉํ•ด์„œ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒฝ์šฐ๋Š” `of`๋ผ ํ•˜๊ณ  ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋“ค์–ด์˜ค๋Š” ์ •๋ณด๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒฝ์šฐ๋Š” `from`์ด๋ผ๊ณ  ๋„ค์ด๋ฐํ•œ๋‹ค๋Š” ๊ธ€๋„ ์žˆ์—ˆ๋Š”๋ฐ ์ €๋Š” ์ด ๊ธ€์— ๋” ๊ณต๊ฐ์„ ๋А๊ปด์„œ ์œ„ ๊ฒฝ์šฐ๋Š” `from`์ด๋ผ๋Š” ๋ฉ”์„œ๋“œ ๋„ค์ž„์ด ์ž˜ ๋งž๋‹ค๋Š” ์ƒ๊ฐ์„ ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,94 @@ +package store.model.store.product; + +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE; +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK; + +import java.time.LocalDateTime; +import store.exception.store.StoreException; +import store.model.store.promotion.Promotion; + +public class Product { + private final String name; + private final int price; + private int stock; + private final Promotion promotion; + + private Product(String name, int price, int stock, Promotion promotion) { + validatePrice(price); + validateStock(stock); + this.name = name; + this.price = price; + this.stock = stock; + this.promotion = promotion; + } + + public static Product of(String name, int price, int stock, Promotion promotion) { + return new Product(name, price, stock, promotion); + } + + public static Product createEmptyGeneralProduct(Product product) { + return new Product(product.name, product.price, 0, null); + } + + public void decreaseStock(int amount) { + stock -= amount; + } + + public boolean isNameEquals(Product product) { + return this.name.equals(product.name); + } + + public boolean isNameEquals(String name) { + return this.name.equals(name); + } + + public boolean isPromotionPeriod(LocalDateTime now) { + if (this.promotion == null) { + return false; + } + return promotion.isPeriod(now); + } + + public boolean isGeneralProduct() { + return promotion == null; + } + + public boolean isPromotionProduct() { + return promotion != null; + } + + private void validatePrice(int price) { + if (price <= 0) { + throw new StoreException(INVALID_PRODUCT_PRICE); + } + } + + private void validateStock(int stock) { + if (stock < 0) { + throw new StoreException(INVALID_PRODUCT_STOCK); + } + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public String getPromotionName() { + if (promotion == null) { + return ""; + } + return promotion.getName(); + } + + public int getPromotionUnit() { + return promotion.getUnit(); + } +}
Java
Product๊ฐ€ ์ด๋ฆ„๊ณผ ๊ฐ€๊ฒฉ๋งŒ์„ ๊ฐ€์ง€๊ณ , Stock์ด๋ผ๋Š” ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด `Product product`, `int stock` ์„ ๊ฐ€์ง€๊ฒŒ ํ• ๊นŒ ์ƒ๊ฐํ–ˆ์ง€๋งŒ, ์ผ๋‹จ ๋น ๋ฅด๊ฒŒ ๊ตฌํ˜„ํ•˜๋Š”๊ฒŒ ๋ชฉํ‘œ๊ธฐ๋„ ํ–ˆ๊ณ  ํฐ ๋ฌธ์ œ๊ฐ€ ์—†์„ ๊ฒƒ ๊ฐ™์•„์„œ ์œ„์™€ ๊ฐ™์ด ์„ค๊ณ„ํ–ˆ์Šต๋‹ˆ๋‹ค. Service ๋ ˆ์ด์–ด์™€ Repository ๋ ˆ์ด์–ด๋ฅผ ๋„์ž…์—†์ด MVC ํŒจํ„ด๋งŒ์œผ๋กœ ์„ค๊ณ„ํ•ด์„œ ๋ชจ๋ธ์ด ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ๋“ค๊ณ  ์žˆ๋Š” ๊ฒƒ์— ๋ฌธ์ œ๋Š” ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,61 @@ +package store.model.store.promotion; + +import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_BUY_AMOUNT; +import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_GIVE_AMOUNT; + +import java.time.LocalDateTime; +import store.exception.store.StoreException; + +public class Promotion { + private final String name; + private final int buyAmount; + private final int giveAmount; + private final LocalDateTime startAt; + private final LocalDateTime endAt; + + private Promotion(String name, int buyAmount, int giveAmount, LocalDateTime startAt, LocalDateTime endAt) { + validateBuyAmount(buyAmount); + validateGiveAmount(giveAmount); + this.name = name; + this.buyAmount = buyAmount; + this.giveAmount = giveAmount; + this.startAt = startAt; + this.endAt = endAt; + } + + public static Promotion of(String name, + int buyAmount, + int giveAmount, + LocalDateTime startAt, + LocalDateTime endAt) { + return new Promotion(name, buyAmount, giveAmount, startAt, endAt); + } + + public boolean isNameEquals(String name) { + return this.name.equals(name); + } + + public boolean isPeriod(LocalDateTime now) { + return startAt.isBefore(now) && endAt.isAfter(now); + } + + private void validateBuyAmount(int buyAmount) { + if (buyAmount < 1) { + throw new StoreException(INVALID_PROMOTION_BUY_AMOUNT); + } + } + + private void validateGiveAmount(int giveAmount) { + if (giveAmount != 1) { + throw new StoreException(INVALID_PROMOTION_GIVE_AMOUNT); + } + } + + public String getName() { + return name; + } + + public int getUnit() { + return buyAmount + giveAmount; + } +}
Java
์šฐํ…Œ์ฝ”์—์„œ ์ œ๊ณตํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ `DateTimes` ํด๋ž˜์Šค์˜ `now()` ๋ฉ”์„œ๋“œ์˜ ๋ฐ˜ํ™˜๊ฐ’์ด LocalDateTime์ด์—ฌ์„œ LocalDate๋กœ ๋ณ€ํ™˜ํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ๋น„๊ตํ•  ์ˆ˜ ์žˆ๊ฒŒ ์œ„์™€ ๊ฐ™์ด ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,20 @@ +package store.util.reader; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RepeatableReader { + public static <T> T handle(Supplier<String> viewMethod, + Function<String, T> converter, + Consumer<String> errorHandler) { + while (true) { + try { + String userInput = viewMethod.get(); + return converter.apply(userInput); + } catch (IllegalArgumentException e) { + errorHandler.accept(e.getMessage()); + } + } + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
์กฐ๊ธˆ ๋” ํ’€์–ด์„œ ๋ง์”€๋“œ๋ฆฌ๋ฉด `boolean ๋ฉค๋ฒ„์‰ฝํ• ์ธ์„๋ฐ›๊ธฐ๋กœํ–ˆ๋Š”๊ฐ€` ๊ฐ€ ์•„๋‹Œ, `boolean ๋ฉค๋ฒ„์‰ฝ์„๊ฐ€์กŒ๋Š”๊ฐ€` ๋กœ ๋ช…๋ช…๋˜์–ด์„œ ์—ฌ์ญค๋ดค์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,94 @@ +package store.model.store.product; + +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE; +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK; + +import java.time.LocalDateTime; +import store.exception.store.StoreException; +import store.model.store.promotion.Promotion; + +public class Product { + private final String name; + private final int price; + private int stock; + private final Promotion promotion; + + private Product(String name, int price, int stock, Promotion promotion) { + validatePrice(price); + validateStock(stock); + this.name = name; + this.price = price; + this.stock = stock; + this.promotion = promotion; + } + + public static Product of(String name, int price, int stock, Promotion promotion) { + return new Product(name, price, stock, promotion); + } + + public static Product createEmptyGeneralProduct(Product product) { + return new Product(product.name, product.price, 0, null); + } + + public void decreaseStock(int amount) { + stock -= amount; + } + + public boolean isNameEquals(Product product) { + return this.name.equals(product.name); + } + + public boolean isNameEquals(String name) { + return this.name.equals(name); + } + + public boolean isPromotionPeriod(LocalDateTime now) { + if (this.promotion == null) { + return false; + } + return promotion.isPeriod(now); + } + + public boolean isGeneralProduct() { + return promotion == null; + } + + public boolean isPromotionProduct() { + return promotion != null; + } + + private void validatePrice(int price) { + if (price <= 0) { + throw new StoreException(INVALID_PRODUCT_PRICE); + } + } + + private void validateStock(int stock) { + if (stock < 0) { + throw new StoreException(INVALID_PRODUCT_STOCK); + } + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public String getPromotionName() { + if (promotion == null) { + return ""; + } + return promotion.getName(); + } + + public int getPromotionUnit() { + return promotion.getUnit(); + } +}
Java
๋งž์Šต๋‹ˆ๋‹ค. ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด์„œ ๋ถˆํŽธํ•จ์ด ์ „ํ˜€ ์—†์—ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,92 @@ +package store.model.order; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.Map; +import java.util.stream.Collectors; +import store.model.store.StoreRoom; +import store.model.store.product.Product; + +public class Payment { + private final PurchaseOrder purchaseOrder; + private final StoreRoom storeRoom; + private final boolean hasMembership; + + private Payment(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) { + this.purchaseOrder = purchaseOrder; + this.storeRoom = storeRoom; + this.hasMembership = hasMembership; + } + + public static Payment from(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) { + return new Payment(purchaseOrder, storeRoom, hasMembership); + } + + public long calculateActualPrice() { + long promotionalDiscount = calculatePromotionalDiscount(); + long membershipDiscount = calculateMembershipDiscount(); + long totalPrice = calculateTotalPrice(); + return totalPrice - (promotionalDiscount + membershipDiscount); + } + + public long calculatePromotionalDiscount() { + return extractPromotionalProducts().entrySet().stream() + .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue()) + .sum(); + } + + public long calculateMembershipDiscount() { + if (!hasMembership) { + return 0; + } + long promotionAppliedPrice = extractPromotionalProducts().entrySet().stream() + .mapToLong(entry -> { + Product product = storeRoom.getPromotionProducts().findNullableProductByName(entry.getKey()); + return (long) product.getPrice() * entry.getValue() * product.getPromotionUnit(); + }).sum(); + long membershipDiscount = (long) ((calculateTotalPrice() - promotionAppliedPrice) * 0.3); + return Math.min(8000L, membershipDiscount); + } + + public long calculateTotalPrice() { + return purchaseOrder.getPurchaseOrder().entrySet().stream() + .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue()) + .sum(); + } + + public long calculateProductPrice(String productName) { + int buyAmount = purchaseOrder.getPurchaseOrder().get(productName); + int productPrice = storeRoom.getProductPrice(productName); + return (long) buyAmount * productPrice; + } + + public long calculateTotalBuyAmount() { + return purchaseOrder.getPurchaseOrder().values().stream() + .mapToLong(Long::valueOf) + .sum(); + } + + private int calculateGiveawayAmount(String productName, int quantity) { + Product product = storeRoom.getPromotionProducts().findNullableProductByName(productName); + if (product != null + && product.isPromotionPeriod(DateTimes.now()) + && product.getStock() >= product.getPromotionUnit()) { + int promotionalQuantity = quantity - storeRoom.getNonPromotionalQuantity(productName, quantity); + return promotionalQuantity / product.getPromotionUnit(); + } + return 0; + } + + public Map<String, Integer> extractPromotionalProducts() { + return purchaseOrder.getPurchaseOrder().entrySet().stream() + .map(entry -> Map.entry( + entry.getKey(), + calculateGiveawayAmount(entry.getKey(), entry.getValue()) + )) + .filter(entry -> entry.getValue() > 0) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + public PurchaseOrder getPurchaseOrder() { + return purchaseOrder; + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ์ฐธ๊ณ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
์•„ํ•˜ ๊ทธ ๋œป์ด์˜€๊ตฐ์š”. ์ €๋Š” ๋ฉค๋ฒ„์‹ญ ์œ ๋ฌด์—๋งŒ ์‹ ๊ฒฝ์จ์„œ ์ €๋ ‡๊ฒŒ ๋„ค์ด๋ฐ์„ ํ–ˆ๋Š”๋ฐ ๋ง์”€์„ ๋“ฃ๊ณ  ๋ณด๋‹ˆ ์˜๋„๊ฐ€ ๋‹ค ๋ณ€์ˆ˜์— ๋‹ด๊ธฐ์ง€ ์•Š์€ ๋“ฏ ๋ณด์ด๋„ค์š”.
@@ -0,0 +1,94 @@ +package store.model.store.product; + +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE; +import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK; + +import java.time.LocalDateTime; +import store.exception.store.StoreException; +import store.model.store.promotion.Promotion; + +public class Product { + private final String name; + private final int price; + private int stock; + private final Promotion promotion; + + private Product(String name, int price, int stock, Promotion promotion) { + validatePrice(price); + validateStock(stock); + this.name = name; + this.price = price; + this.stock = stock; + this.promotion = promotion; + } + + public static Product of(String name, int price, int stock, Promotion promotion) { + return new Product(name, price, stock, promotion); + } + + public static Product createEmptyGeneralProduct(Product product) { + return new Product(product.name, product.price, 0, null); + } + + public void decreaseStock(int amount) { + stock -= amount; + } + + public boolean isNameEquals(Product product) { + return this.name.equals(product.name); + } + + public boolean isNameEquals(String name) { + return this.name.equals(name); + } + + public boolean isPromotionPeriod(LocalDateTime now) { + if (this.promotion == null) { + return false; + } + return promotion.isPeriod(now); + } + + public boolean isGeneralProduct() { + return promotion == null; + } + + public boolean isPromotionProduct() { + return promotion != null; + } + + private void validatePrice(int price) { + if (price <= 0) { + throw new StoreException(INVALID_PRODUCT_PRICE); + } + } + + private void validateStock(int stock) { + if (stock < 0) { + throw new StoreException(INVALID_PRODUCT_STOCK); + } + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public String getPromotionName() { + if (promotion == null) { + return ""; + } + return promotion.getName(); + } + + public int getPromotionUnit() { + return promotion.getUnit(); + } +}
Java
๊ทธ๋ ‡๊ฒŒ ๋ง์”€ํ•ด์ฃผ์‹œ๋‹ˆ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ™
@@ -0,0 +1,100 @@ +package store; + +import java.util.Map; +import store.model.order.Payment; +import store.model.order.PurchaseOrder; +import store.model.store.StoreRoom; +import store.util.parser.ClosedQuestionsParser; +import store.util.parser.PurchaseParser; +import store.util.reader.RepeatableReader; +import store.view.ErrorView; +import store.view.InputView; +import store.view.OutputView; + +public class StoreApplication { + private final InputView inputView; + private final OutputView outputView; + private final ErrorView errorView; + private final StoreRoom storeRoom; + + public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) { + this.inputView = inputView; + this.outputView = outputView; + this.errorView = errorView; + this.storeRoom = storeRoom; + } + + public void run() { + while (true) { + outputView.printProducts(storeRoom); + processPurchase(); + boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase, + ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (!buyMore) { + return; + } + } + } + + private void processPurchase() { + PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom); + purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom); + if (purchaseOrder.getTotalBuyAmount() <= 0) { + return; + } + boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership); + outputView.printReceipt(payment); + storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder()); + } + + private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) { + return RepeatableReader.handle(inputView::readItem, (userInput) -> { + Map<String, Integer> items = PurchaseParser.parseInputItems(userInput); + return PurchaseOrder.from(items, storeRoom); + }, errorView::errorPage); + } + + private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) { + PurchaseOrder result = purchaseOrder; + for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) { + result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue()); + } + return result; + } + + private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder, + StoreRoom storeRoom, + String productName, + int buyAmount) { + int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount); + if (fullPriceAmount > 0) { + purchaseOrder = purchaseOrder + .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount)); + } + if (storeRoom.canGetOneMore(productName, buyAmount)) { + purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName)); + } + return purchaseOrder; + } + + private int getDecreaseAmount(String productName, int fullPriceAmount) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer, + errorView::errorPage); + if (!isAgree) { + return fullPriceAmount; + } + return 0; + } + + private int getIncreaseAmount(String productName) { + boolean isAgree = RepeatableReader.handle(() -> + inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage); + if (isAgree) { + return 1; + } + return 0; + } +}
Java
์•„๋‡จ ์ œ๊ฐ€ ์กฐ๊ธˆ ์–ต์ง€๋กœ ์—ฌ์ญค๋ณธ ๊ฒƒ๋„ ์žˆ์–ด์š”. ํŠน๋ณ„ํ•œ ์˜๋„๊ฐ€ ์žˆ๋‹ค๋ฉด ๋ฐฐ์šฐ๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,16 @@ +package store.view; + +import store.model.order.Payment; +import store.model.store.StoreRoom; +import store.view.formatter.OutputFormatter; + +public class OutputView { + + public void printProducts(StoreRoom storeRoom) { + System.out.println(OutputFormatter.buildStoreStock(storeRoom)); + } + + public void printReceipt(Payment payment) { + System.out.println(OutputFormatter.buildReceipt(payment)); + } +}
Java
`MVC` ๊ด€์ ์—์„œ ๋ทฐ๊ฐ€ ๋ชจ๋ธ์„ ์ฐธ์กฐํ•˜๋Š” ๊ฒƒ์ด ์•ˆ๋˜๋Š” ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ `๋ทฐ๋Š” ๋ชจ๋ธ๊ณผ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ์•Œ ํ•„์š”๊ฐ€ ์—†๋‹ค`๋ผ๋Š” ๋ง์ด ์žˆ๋Š” ๊ฑฐ์ฒ˜๋Ÿผ ๋˜๋„๋ก ๋ชจ๋ฅด๋Š” ๊ฒƒ์ด ์ข‹์€ ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค! ๊ทธ๋Ÿฐ ์ธก๋ฉด์—์„œ `StoreRoom`์„ ์ธ์ž๋กœ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ ๋ณด๋‹ค ๋ฉ”์„ธ์ง€ ํฌ๋งท์„ ์œ„ํ•œ ๋ฐ์ดํ„ฐ๋งŒ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,130 @@ +package store.view.formatter; + +import store.model.order.Payment; +import store.model.store.StoreRoom; +import store.model.store.product.Product; +import store.model.store.product.Products; + +public class OutputFormatter { + private static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\nํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + private static final String PRODUCT_PREFIX = "- "; + private static final String SOLD_OUT = "์žฌ๊ณ  ์—†์Œ"; + private static final String RECEIPT_START_MESSAGE = "==============W ํŽธ์˜์ ================"; + private static final String RECEIPT_COLUMN_MESSAGE = "์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก"; + private static final String RECEIPT_PURCHASE_MESSAGE_FORMAT = "%s\t\t%,d \t%,d"; + private static final String RECEIPT_GIVEAWAY_MESSAGE = "=============์ฆ\t์ •==============="; + private static final String RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT = "%s\t\t%,d"; + private static final String RECEIPT_LINE_SEPARATOR = "===================================="; + private static final String RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT = "์ด๊ตฌ๋งค์•ก\t\t%,d\t%,d"; + private static final String RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT = "ํ–‰์‚ฌํ• ์ธ\t\t\t-%,d"; + private static final String RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT = "๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%,d"; + private static final String RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT = "๋‚ด์‹ค๋ˆ\t\t\t%,d"; + private static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator(); + + private OutputFormatter() { + } + + public static String buildStoreStock(StoreRoom storeRoom) { + StringBuilder sb = new StringBuilder(); + sb.append(WELCOME_MESSAGE).append(SYSTEM_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR); + + String menus = buildProducts(storeRoom.getGeneralProducts(), storeRoom.getPromotionProducts()); + sb.append(menus); + return sb.toString(); + } + + public static String buildReceipt(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(buildReceiptHeader()) + .append(buildPurchaseItems(payment)) + .append(buildGiveawayIems(payment)) + .append(buildReceiptSummary(payment)); + return sb.toString(); + } + + private static String buildProducts(Products generalProducts, Products promotionProducts) { + StringBuilder sb = new StringBuilder(); + for (Product product : generalProducts.getProducts()) { + if (promotionProducts.contains(product.getName())) { + sb.append(buildProductMessage(promotionProducts.findNullableProductByName(product.getName()))); + } + sb.append(buildProductMessage(product)); + } + return sb.toString(); + } + + private static String buildProductMessage(Product product) { + StringBuilder sb = new StringBuilder(); + sb.append(PRODUCT_PREFIX) + .append(product.getName()).append(" ") + .append(String.format("%,d์›", product.getPrice())).append(" ") + .append(buildProductStock(product.getStock())).append(" ") + .append(product.getPromotionName()).append(SYSTEM_LINE_SEPARATOR); + return sb.toString(); + } + + private static String buildProductStock(int stock) { + if (stock == 0) { + return SOLD_OUT; + } + return String.format("%,d๊ฐœ", stock); + } + + private static String buildReceiptHeader() { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_START_MESSAGE).append(SYSTEM_LINE_SEPARATOR) + .append(RECEIPT_COLUMN_MESSAGE).append(SYSTEM_LINE_SEPARATOR); + return sb.toString(); + } + + private static String buildPurchaseItems(Payment payment) { + StringBuilder sb = new StringBuilder(); + payment.getPurchaseOrder().getPurchaseOrder().forEach((name, quantity) -> + sb.append(String.format(RECEIPT_PURCHASE_MESSAGE_FORMAT, + name, quantity, payment.calculateProductPrice(name))) + .append(SYSTEM_LINE_SEPARATOR) + ); + return sb.toString(); + } + + private static String buildGiveawayIems(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_GIVEAWAY_MESSAGE).append(SYSTEM_LINE_SEPARATOR); + + payment.extractPromotionalProducts().forEach((name, quantity) -> + sb.append(String.format(RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT, name, quantity)) + .append(SYSTEM_LINE_SEPARATOR) + ); + return sb.toString(); + } + + private static String buildReceiptSummary(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR) + .append(buildTotalPrice(payment)) + .append(buildDiscounts(payment)) + .append(buildFinalPrice(payment)); + return sb.toString(); + } + + private static String buildTotalPrice(Payment payment) { + return String.format(RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT, + payment.calculateTotalBuyAmount(), payment.calculateTotalPrice()) + + SYSTEM_LINE_SEPARATOR; + } + + private static String buildDiscounts(Payment payment) { + return String.format(RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT, + payment.calculatePromotionalDiscount()) + + SYSTEM_LINE_SEPARATOR + + String.format(RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT, + payment.calculateMembershipDiscount()) + + SYSTEM_LINE_SEPARATOR; + } + + private static String buildFinalPrice(Payment payment) { + return String.format(RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT, + payment.calculateActualPrice()) + + SYSTEM_LINE_SEPARATOR; + } +}
Java
`getPurchaseOrder`๋ผ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ๋‘ ๋ฒˆ ์—ฐ์†๋˜์–ด ๋ชจํ˜ธํ•œ ๊ฐ์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๋‘ ๋ฉ”์†Œ๋“œ์˜ ๋„ค์ด๋ฐ์„ ๋‹ฌ๋ฆฌ ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ถ”๊ฐ€์ ์œผ๋กœ ์ฒซ `getPurchaseOrder` ์—์„œ๋Š” `PurchaseOrder` ๊ฐ์ฒด๊ฐ€ ๋ฐ˜ํ™˜๋˜๊ณ  ๋‘ ๋ฒˆ์งธ์—์„œ๋Š” ์•„์ดํ…œ ์ •๋ณด๋“ค์ด ๋‹ด๊ธด `Map`์ด ๋ฐ˜ํ™˜๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ด๋Š” `๋””๋ฏธํ„ฐ์˜ ๋ฒ•์น™`์— ์œ„๋ฐฐ๋˜๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ด๋Š”๋ฐ์š”! ์šฐํ…Œ์ฝ”์—์„œ ์ œ์‹œํ•˜๋Š” ํด๋ฆฐ์ฝ”๋“œ ์‚ฌํ•ญ์— `๋””๋ฏธํ„ฐ ๋ฒ•์น™`์ด ํฌํ•จ๋œ ๋งŒํผ ์—ฐ์†์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ์ง€์–‘ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,130 @@ +package store.view.formatter; + +import store.model.order.Payment; +import store.model.store.StoreRoom; +import store.model.store.product.Product; +import store.model.store.product.Products; + +public class OutputFormatter { + private static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\nํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + private static final String PRODUCT_PREFIX = "- "; + private static final String SOLD_OUT = "์žฌ๊ณ  ์—†์Œ"; + private static final String RECEIPT_START_MESSAGE = "==============W ํŽธ์˜์ ================"; + private static final String RECEIPT_COLUMN_MESSAGE = "์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก"; + private static final String RECEIPT_PURCHASE_MESSAGE_FORMAT = "%s\t\t%,d \t%,d"; + private static final String RECEIPT_GIVEAWAY_MESSAGE = "=============์ฆ\t์ •==============="; + private static final String RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT = "%s\t\t%,d"; + private static final String RECEIPT_LINE_SEPARATOR = "===================================="; + private static final String RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT = "์ด๊ตฌ๋งค์•ก\t\t%,d\t%,d"; + private static final String RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT = "ํ–‰์‚ฌํ• ์ธ\t\t\t-%,d"; + private static final String RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT = "๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%,d"; + private static final String RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT = "๋‚ด์‹ค๋ˆ\t\t\t%,d"; + private static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator(); + + private OutputFormatter() { + } + + public static String buildStoreStock(StoreRoom storeRoom) { + StringBuilder sb = new StringBuilder(); + sb.append(WELCOME_MESSAGE).append(SYSTEM_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR); + + String menus = buildProducts(storeRoom.getGeneralProducts(), storeRoom.getPromotionProducts()); + sb.append(menus); + return sb.toString(); + } + + public static String buildReceipt(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(buildReceiptHeader()) + .append(buildPurchaseItems(payment)) + .append(buildGiveawayIems(payment)) + .append(buildReceiptSummary(payment)); + return sb.toString(); + } + + private static String buildProducts(Products generalProducts, Products promotionProducts) { + StringBuilder sb = new StringBuilder(); + for (Product product : generalProducts.getProducts()) { + if (promotionProducts.contains(product.getName())) { + sb.append(buildProductMessage(promotionProducts.findNullableProductByName(product.getName()))); + } + sb.append(buildProductMessage(product)); + } + return sb.toString(); + } + + private static String buildProductMessage(Product product) { + StringBuilder sb = new StringBuilder(); + sb.append(PRODUCT_PREFIX) + .append(product.getName()).append(" ") + .append(String.format("%,d์›", product.getPrice())).append(" ") + .append(buildProductStock(product.getStock())).append(" ") + .append(product.getPromotionName()).append(SYSTEM_LINE_SEPARATOR); + return sb.toString(); + } + + private static String buildProductStock(int stock) { + if (stock == 0) { + return SOLD_OUT; + } + return String.format("%,d๊ฐœ", stock); + } + + private static String buildReceiptHeader() { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_START_MESSAGE).append(SYSTEM_LINE_SEPARATOR) + .append(RECEIPT_COLUMN_MESSAGE).append(SYSTEM_LINE_SEPARATOR); + return sb.toString(); + } + + private static String buildPurchaseItems(Payment payment) { + StringBuilder sb = new StringBuilder(); + payment.getPurchaseOrder().getPurchaseOrder().forEach((name, quantity) -> + sb.append(String.format(RECEIPT_PURCHASE_MESSAGE_FORMAT, + name, quantity, payment.calculateProductPrice(name))) + .append(SYSTEM_LINE_SEPARATOR) + ); + return sb.toString(); + } + + private static String buildGiveawayIems(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_GIVEAWAY_MESSAGE).append(SYSTEM_LINE_SEPARATOR); + + payment.extractPromotionalProducts().forEach((name, quantity) -> + sb.append(String.format(RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT, name, quantity)) + .append(SYSTEM_LINE_SEPARATOR) + ); + return sb.toString(); + } + + private static String buildReceiptSummary(Payment payment) { + StringBuilder sb = new StringBuilder(); + sb.append(RECEIPT_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR) + .append(buildTotalPrice(payment)) + .append(buildDiscounts(payment)) + .append(buildFinalPrice(payment)); + return sb.toString(); + } + + private static String buildTotalPrice(Payment payment) { + return String.format(RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT, + payment.calculateTotalBuyAmount(), payment.calculateTotalPrice()) + + SYSTEM_LINE_SEPARATOR; + } + + private static String buildDiscounts(Payment payment) { + return String.format(RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT, + payment.calculatePromotionalDiscount()) + + SYSTEM_LINE_SEPARATOR + + String.format(RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT, + payment.calculateMembershipDiscount()) + + SYSTEM_LINE_SEPARATOR; + } + + private static String buildFinalPrice(Payment payment) { + return String.format(RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT, + payment.calculateActualPrice()) + + SYSTEM_LINE_SEPARATOR; + } +}
Java
`OutputFrmatter`๊ฐ€ ๋‹ค์†Œ ๋ฌด๊ฑฐ์šด ๊ฐ์ฒด๋ผ๋Š” ๋А๋‚Œ์ด ๋“ญ๋‹ˆ๋‹ค! ํฌ๋งคํ„ฐ์—์„œ ๋งŽ์€ ๋กœ์ง์„ ๋‹ด๋‹นํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ์ƒ๊ฐ ๋˜๋Š”๋ฐ์š” ํŠนํžˆ `payment.calculateActualPrice()` ๋“ฑ ๋ชจ๋ธ ๊ฐ์ฒด๋“ค์˜ ๋‚ด๋ถ€ ๊ธฐ๋Šฅ๋“ค์„ ํ™œ์šฉํ•ด์„œ ๋ฐ์ดํ„ฐ๋“ค์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค! ๋‹ค์–‘ํ•œ ๋ชจ๋ธ๋“ค์˜ ๊ธฐ๋Šฅ์„ ํฌ๋งคํ„ฐ ๋‚ด๋ถ€์ ์œผ๋กœ ๋งŽ์ด ์‚ฌ์šฉํ•ด์„œ ๋ทฐ ๊ฐ์ฒด ๋ณด๋‹ค๋Š” ์„œ๋น„์Šค์— ๊ฐ€๊น์ง€ ์•Š์„๊นŒ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“œ๋Š”๋ฐ์š” ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?? ํฌ๋งคํ„ฐ๊ฐ€ ๋ชจ๋ธ ๊ฐ์ฒด๋“ค์„ ๋ฐ›๋Š” ๊ฒƒ์ด ์•„๋‹Œ ์ด๋ฏธ ๊ณ„์‚ฐ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›๋Š” ๊ฒƒ์œผ๋กœ ํ•˜๋ฉด ๋ทฐ ๊ฐ์ฒด๋กœ์„œ ๋ทฐ์˜ ํฌ๋งคํ„ฐ ์—ญํ• ์— ๋” ์ง‘์ค‘๋  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ถ”๊ฐ€์ ์œผ๋กœ ๋ชจ๋ธ ๊ฐ์ฒด๋“ค์— ๋Œ€ํ•œ ์˜์กด์„ฑ๋„ ์ค„์ผ ์ˆ˜ ์žˆ๋Š” ์ด์ ์ด ์žˆ์„ ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -0,0 +1,35 @@ +package calculator.controller.validation + +class UserInputValidator { + fun validateUserInput(numbers: List<String>): List<Int> { + val newNumbers = checkIsEmpty(numbers) + checkIsInteger(newNumbers) + val allNumbers = changeInteger(newNumbers) + changeNegativeNumber(allNumbers) + return allNumbers + } + + private fun checkIsEmpty(numbers: List<String>): List<String> { + return numbers.map { it.ifEmpty { "0" } } + } + + private fun checkIsInteger(newNumbers: List<String>) { + newNumbers.map { + if (it.toIntOrNull() == null) { + throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage) + } + } + } + + private fun changeInteger(newNumbers: List<String>): List<Int> { + return newNumbers.map { it.toInt() } + } + + private fun changeNegativeNumber(allNumbers: List<Int>) { + allNumbers.forEach { + if (it < 0) { + throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage) + } + } + } +} \ No newline at end of file
Kotlin
์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๋Š” ํ•จ์ˆ˜์ธ์ง€๋ผ chane๋ผ๋Š” ๋„ค์ด๋ฐ์€ ์กฐ๊ธˆ ์–ด์ƒ‰ํ•œ๊ฒƒ ๊ฐ™์•„์š” ! ใ…Žใ…Ž any๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•จ์ˆ˜๋ฅผ ์กฐ๊ธˆ ๋” ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ! ``` private fun changeNegativeNumber(allNumbers: List<Int>) { if (allNumbers.any { it < 0 }) { throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage) } } ```
@@ -0,0 +1,45 @@ +package calculator.controller.domain + +import calculator.constants.Delimiter.CLONE +import calculator.constants.Delimiter.COMMA +import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX +import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX + +class DelimiterController( + private val input: String +) { + fun checkDelimiter(): List<String> { + if (hasCustomDelimiter()) { + val customDelimiter = getCustomDelimiter() + val noCustomDelimiter = deleteCustomDelimiter() + val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter) + return numbers + } + val numbers = splitDelimiter() + return numbers + } + + private fun hasCustomDelimiter(): Boolean { + return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3 + } + + private fun getCustomDelimiter(): String { + val customDelimiter = input.substring(2, 3) + return customDelimiter + } + + private fun deleteCustomDelimiter(): String { + val noCustomDelimiter = input.substring(5) + return noCustomDelimiter + } + + private fun splitDelimiter(): List<String> { + val numbers = input.split(COMMA.value, CLONE.value) + return numbers + } + + private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> { + val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter) + return numbers + } +} \ No newline at end of file
Kotlin
์ฑ„์ฑ„๋‹˜! ์ €๋„ ์ฒซ ์ฃผ์ฐจ ๋•Œ ์ปค์Šคํ…€ ๊ตฌ๋ถ„์ž๋ฅผ ์š”๋Ÿฐ์‹์œผ๋กœ ์ถ”์ถœํ–ˆ์—ˆ๋Š”๋ฐ์š” ๋‹ค๋ฅธ ๋ถ„๋“ค ๊ตฌํ˜„ํ•œ๊ฑธ ๋ณด๋‹ˆ๊นŒ ๋‘ ๊ธ€์ž ์ด์ƒ์ผ ๋•Œ ๋„ ๊ตฌ๋ถ„์ž๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๋งŒ๋“œ์…จ๋”๋ผ๊ตฌ์š” ๊ทธ๋ž˜์„œ ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ปค์Šคํ…€ ๊ตฌ๋ถ„์ž๊ฐ€ 2๊ธ€์ž ์ด์ƒ์ผ ๊ฒฝ์šฐ ์˜ˆ์ƒ๊ณผ๋Š” ๋‹ค๋ฅธ ์˜ค๋ฅ˜๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ ๊ฐ™์•„์š” ๋ฌผ๋ก  ! ๋ฌธ์ œ ์š”๊ตฌ ์‚ฌํ•ญ์— ์—†์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฐ์ œํ•˜๊ณ  ๊ตฌํ˜„ํ•ด๋„ ์ „ํ˜€ ๋ฌธ์ œ ์—†์ง€๋งŒ ์ €๋Š” ์ด๋Ÿฐ ๋ถ€๋ถ„์„ ์ฒซ ์ฃผ์ฐจ ๋•Œ ๋†“์ณ์„œ ์ด๋ฒˆ ๋ฆฌํŒฉํ† ๋ง์—์„  ์ ์šฉํ•ด๋ดค๋Š”๋ฐ ํ˜น์‹œ ์ผ๋ถ€๋Ÿฌ ๊ตฌํ˜„์„ ์•ˆํ•˜์‹ ๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž <img width="926" alt="image" src="https://github.com/user-attachments/assets/ec40ef9b-ae02-4dc5-8dac-6420d69ea0c5">
@@ -0,0 +1,45 @@ +package calculator.controller.domain + +import calculator.constants.Delimiter.CLONE +import calculator.constants.Delimiter.COMMA +import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX +import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX + +class DelimiterController( + private val input: String +) { + fun checkDelimiter(): List<String> { + if (hasCustomDelimiter()) { + val customDelimiter = getCustomDelimiter() + val noCustomDelimiter = deleteCustomDelimiter() + val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter) + return numbers + } + val numbers = splitDelimiter() + return numbers + } + + private fun hasCustomDelimiter(): Boolean { + return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3 + } + + private fun getCustomDelimiter(): String { + val customDelimiter = input.substring(2, 3) + return customDelimiter + } + + private fun deleteCustomDelimiter(): String { + val noCustomDelimiter = input.substring(5) + return noCustomDelimiter + } + + private fun splitDelimiter(): List<String> { + val numbers = input.split(COMMA.value, CLONE.value) + return numbers + } + + private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> { + val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter) + return numbers + } +} \ No newline at end of file
Kotlin
์š” 5๋ผ๋Š” ์ƒ์ˆ˜๋„ ์ด๋ฆ„์„ ๋ถ™ํ˜€์ฃผ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š” ?
@@ -0,0 +1,45 @@ +package calculator.controller.domain + +import calculator.constants.Delimiter.CLONE +import calculator.constants.Delimiter.COMMA +import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX +import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX + +class DelimiterController( + private val input: String +) { + fun checkDelimiter(): List<String> { + if (hasCustomDelimiter()) { + val customDelimiter = getCustomDelimiter() + val noCustomDelimiter = deleteCustomDelimiter() + val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter) + return numbers + } + val numbers = splitDelimiter() + return numbers + } + + private fun hasCustomDelimiter(): Boolean { + return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3 + } + + private fun getCustomDelimiter(): String { + val customDelimiter = input.substring(2, 3) + return customDelimiter + } + + private fun deleteCustomDelimiter(): String { + val noCustomDelimiter = input.substring(5) + return noCustomDelimiter + } + + private fun splitDelimiter(): List<String> { + val numbers = input.split(COMMA.value, CLONE.value) + return numbers + } + + private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> { + val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter) + return numbers + } +} \ No newline at end of file
Kotlin
ํ˜น์‹œ ์—ฌ๊ธฐ์„œ 3์ด ์˜๋ฏธํ•˜๋Š”๊ฒŒ ๋ญ”์ง€ ๊ถ๊ธˆํ•˜๋„ค์š”..!
@@ -0,0 +1,35 @@ +package calculator.controller.validation + +class UserInputValidator { + fun validateUserInput(numbers: List<String>): List<Int> { + val newNumbers = checkIsEmpty(numbers) + checkIsInteger(newNumbers) + val allNumbers = changeInteger(newNumbers) + changeNegativeNumber(allNumbers) + return allNumbers + } + + private fun checkIsEmpty(numbers: List<String>): List<String> { + return numbers.map { it.ifEmpty { "0" } } + } + + private fun checkIsInteger(newNumbers: List<String>) { + newNumbers.map { + if (it.toIntOrNull() == null) { + throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage) + } + } + } + + private fun changeInteger(newNumbers: List<String>): List<Int> { + return newNumbers.map { it.toInt() } + } + + private fun changeNegativeNumber(allNumbers: List<Int>) { + allNumbers.forEach { + if (it < 0) { + throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage) + } + } + } +} \ No newline at end of file
Kotlin
check๋ฅผ ํ•˜๊ณ  ์ƒˆ๋กœ์šด ์ˆซ์ž๋“ค์„ ๋ฐ˜ํ™˜ํ•ด๋ณผ ์ƒ๊ฐ์€ ๋ชปํ–ˆ๋Š”๋ฐ, ์ €๋„ ์จ๋ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹คใ…Žใ…Ž ๊ทธ๋Ÿฐ๋ฐ ์ƒˆ๋กœ์šด ์ˆซ์ž๋“ค์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค๋ฉด ๋ฐ‘ ํ•จ์ˆ˜์ฒ˜๋Ÿผ ์ด๋ฆ„์„ change๋กœ ํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹น
@@ -0,0 +1,45 @@ +package calculator.controller.domain + +import calculator.constants.Delimiter.CLONE +import calculator.constants.Delimiter.COMMA +import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX +import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX + +class DelimiterController( + private val input: String +) { + fun checkDelimiter(): List<String> { + if (hasCustomDelimiter()) { + val customDelimiter = getCustomDelimiter() + val noCustomDelimiter = deleteCustomDelimiter() + val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter) + return numbers + } + val numbers = splitDelimiter() + return numbers + } + + private fun hasCustomDelimiter(): Boolean { + return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3 + } + + private fun getCustomDelimiter(): String { + val customDelimiter = input.substring(2, 3) + return customDelimiter + } + + private fun deleteCustomDelimiter(): String { + val noCustomDelimiter = input.substring(5) + return noCustomDelimiter + } + + private fun splitDelimiter(): List<String> { + val numbers = input.split(COMMA.value, CLONE.value) + return numbers + } + + private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> { + val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter) + return numbers + } +} \ No newline at end of file
Kotlin
์˜ค ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ํ™•์ธํ•˜๊ณ , ๊ฒฐ๊ณผ๋Š” number๋กœ ํ†ต์ผํ•˜๋Š” ๋ฐฉ๋ฒ• ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,35 @@ +package calculator.controller.validation + +class UserInputValidator { + fun validateUserInput(numbers: List<String>): List<Int> { + val newNumbers = checkIsEmpty(numbers) + checkIsInteger(newNumbers) + val allNumbers = changeInteger(newNumbers) + changeNegativeNumber(allNumbers) + return allNumbers + } + + private fun checkIsEmpty(numbers: List<String>): List<String> { + return numbers.map { it.ifEmpty { "0" } } + } + + private fun checkIsInteger(newNumbers: List<String>) { + newNumbers.map { + if (it.toIntOrNull() == null) { + throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage) + } + } + } + + private fun changeInteger(newNumbers: List<String>): List<Int> { + return newNumbers.map { it.toInt() } + } + + private fun changeNegativeNumber(allNumbers: List<Int>) { + allNumbers.forEach { + if (it < 0) { + throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage) + } + } + } +} \ No newline at end of file
Kotlin
์•„...! any!! ์ข‹์€ ํ•จ์ˆ˜ ์•Œ๋ ค์ค˜์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,45 @@ +package calculator.controller.domain + +import calculator.constants.Delimiter.CLONE +import calculator.constants.Delimiter.COMMA +import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX +import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX + +class DelimiterController( + private val input: String +) { + fun checkDelimiter(): List<String> { + if (hasCustomDelimiter()) { + val customDelimiter = getCustomDelimiter() + val noCustomDelimiter = deleteCustomDelimiter() + val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter) + return numbers + } + val numbers = splitDelimiter() + return numbers + } + + private fun hasCustomDelimiter(): Boolean { + return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3 + } + + private fun getCustomDelimiter(): String { + val customDelimiter = input.substring(2, 3) + return customDelimiter + } + + private fun deleteCustomDelimiter(): String { + val noCustomDelimiter = input.substring(5) + return noCustomDelimiter + } + + private fun splitDelimiter(): List<String> { + val numbers = input.split(COMMA.value, CLONE.value) + return numbers + } + + private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> { + val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter) + return numbers + } +} \ No newline at end of file
Kotlin
์ •๋‹ต์ž…๋‹ˆ๋‹ค. ์ผ๋ถ€๋Ÿฌ ๊ตฌํ˜„ ์•ˆํ–ˆ์Šต๋‹ˆ๋‹ค! ์ €๋Š” ๋ฌธ์ œ ํ•ด์„ํ•˜๋ฉด์„œ ๊ตฌ๋ถ„์ž๋Š” ํ•œ๊ธ€์ž๋งŒ ์™€์•ผํ•œ๋‹ค๋ผ๊ณ  ์ƒ๊ฐ์„ ํ•ด์„œ ์œ„์™€ ๊ฐ™์ด ์ž…๋ ฅํ•˜๋ฉด ์—๋Ÿฌ๋ผ๊ณ  ํŒ๋‹จํ–ˆ์Šต๋‹ˆ๋‹ค! ๋ฌธ์ œ ํ•ด์„์ด ์ œ์ผ ์–ด๋ ค์šด ๊ฑฐ ๊ฐ™์•„์š” ใ…Žใ…Ž
@@ -0,0 +1,45 @@ +package calculator.controller.domain + +import calculator.constants.Delimiter.CLONE +import calculator.constants.Delimiter.COMMA +import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX +import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX + +class DelimiterController( + private val input: String +) { + fun checkDelimiter(): List<String> { + if (hasCustomDelimiter()) { + val customDelimiter = getCustomDelimiter() + val noCustomDelimiter = deleteCustomDelimiter() + val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter) + return numbers + } + val numbers = splitDelimiter() + return numbers + } + + private fun hasCustomDelimiter(): Boolean { + return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3 + } + + private fun getCustomDelimiter(): String { + val customDelimiter = input.substring(2, 3) + return customDelimiter + } + + private fun deleteCustomDelimiter(): String { + val noCustomDelimiter = input.substring(5) + return noCustomDelimiter + } + + private fun splitDelimiter(): List<String> { + val numbers = input.split(COMMA.value, CLONE.value) + return numbers + } + + private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> { + val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter) + return numbers + } +} \ No newline at end of file
Kotlin
CUSTOM_DELIMITER_SUFFIX์˜ index๊ฐ€ 3์ด๋ฉด CUSTOM_DELIMITER_PREFIX์™€ CUSTOM_DELIMITER_SUFFIX ์‚ฌ์ด์— ์ปค์Šคํ…€ ๊ตฌ๋ถ„์ž๋ฅผ ์ž…๋ ฅ์„ ํ–ˆ๋‹ค๊ณ  ํŒ๋‹จ์„ ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,35 @@ +package calculator.controller.validation + +class UserInputValidator { + fun validateUserInput(numbers: List<String>): List<Int> { + val newNumbers = checkIsEmpty(numbers) + checkIsInteger(newNumbers) + val allNumbers = changeInteger(newNumbers) + changeNegativeNumber(allNumbers) + return allNumbers + } + + private fun checkIsEmpty(numbers: List<String>): List<String> { + return numbers.map { it.ifEmpty { "0" } } + } + + private fun checkIsInteger(newNumbers: List<String>) { + newNumbers.map { + if (it.toIntOrNull() == null) { + throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage) + } + } + } + + private fun changeInteger(newNumbers: List<String>): List<Int> { + return newNumbers.map { it.toInt() } + } + + private fun changeNegativeNumber(allNumbers: List<Int>) { + allNumbers.forEach { + if (it < 0) { + throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage) + } + } + } +} \ No newline at end of file
Kotlin
์•„ ๋งž๋„ค์š”! ๊ทธ๋Ÿผ ํ•จ์ˆ˜๋ช…์ด ๋” ํ†ต์ผ์„ฑ์ด ์žˆ์–ด์„œ ์ข‹์„๊ฑฐ ๊ฐ™์•„์š”! ์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,61 @@ +name: Solution-friend Dev CI/CD + +on: + pull_request: + types: [ closed ] + workflow_dispatch: # (2).์ˆ˜๋™ ์‹คํ–‰๋„ ๊ฐ€๋Šฅํ•˜๋„๋ก + +jobs: + build: + runs-on: ubuntu-latest # (3).OSํ™˜๊ฒฝ + if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'develop' + + steps: + - name: Checkout + uses: actions/checkout@v2 # (4).์ฝ”๋“œ check out + + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + java-version: 11 # (5).์ž๋ฐ” ์„ค์น˜ + distribution: 'adopt' + + - name: Grant execute permission for gradlew + run: chmod +x ./gradlew + shell: bash # (6).๊ถŒํ•œ ๋ถ€์—ฌ + + - name: Build with Gradle + run: ./gradlew clean build -x test + shell: bash # (7).build์‹œ์ž‘ + + - name: Get current time + uses: 1466587594/get-current-time@v2 + id: current-time + with: + format: YYYY-MM-DDTHH-mm-ss + utcOffset: "+09:00" # (8).build์‹œ์ ์˜ ์‹œ๊ฐ„ํ™•๋ณด + + - name: Show Current Time + run: echo "CurrentTime=$" + shell: bash # (9).ํ™•๋ณดํ•œ ์‹œ๊ฐ„ ๋ณด์—ฌ์ฃผ๊ธฐ + + - name: Generate deployment package + run: | + mkdir -p deploy + cp build/libs/*.jar deploy/application.jar + cp Procfile deploy/Procfile + cp -r .ebextensions-dev deploy/.ebextensions + cp -r .platform deploy/.platform + cd deploy && zip -r deploy.zip . + + - name: Beanstalk Deploy + uses: einaregilsson/beanstalk-deploy@v20 + with: + aws_access_key: ${{ secrets.AWS_ACTION_ACCESS_KEY_ID }} + aws_secret_key: ${{ secrets.AWS_ACTION_SECRET_ACCESS_KEY }} + application_name: solution-friend-dev + environment_name: Solution-friend-dev-env-1 + version_label: github-action-${{ steps.current-time.outputs.formattedTime }} + region: ap-northeast-2 + deployment_package: deploy/deploy.zip + wait_for_deployment: false
Unknown
PR์ด ๊ธฐ๊ฐ๋˜์–ด๋„ ํ•ด๋‹น Action์ด ์ˆ˜ํ–‰๋  ๊ฒƒ ๊ฐ™๋„ค์š”.
@@ -0,0 +1,62 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.17' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'friend' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '11' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + implementation 'org.springframework.boot:spring-boot-starter-validation' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'org.springdoc:springdoc-openapi-ui:1.6.15' + implementation 'io.springfox:springfox-swagger2:2.9.2' + implementation 'io.springfox:springfox-swagger-ui:2.9.2' + + //user + implementation 'com.google.code.findbugs:jsr305:3.0.2' + //mail + implementation group: 'com.sun.mail', name: 'javax.mail', version: '1.6.2' + //jwt + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.4' + runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.4' + runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.4' +// redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + //kakao +// implementation 'org.springframework.boot:spring-boot-starter-webflux' + // S3 + implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE' + implementation platform('software.amazon.awssdk:bom:2.20.56') + implementation 'software.amazon.awssdk:s3' + +} + +tasks.named('test') { + useJUnitPlatform() +} + +jar { + enabled = false +}
Unknown
gradle ํ˜•์‹์„ ํ†ต์ผํ•ด ์ฃผ์„ธ์š”. `com.sun.mail:javax.mail:1.6.2` ๋˜ํ•œ, sun ์˜์กด์„ฑ์€ ๋งค์šฐ ์˜›๋‚  ์˜์กด์„ฑ์„ ๊ฐ€๋Šฅ์„ฑ์ด ๋†’์Šต๋‹ˆ๋‹ค. ํ™•์ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package friend.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.scheduling.annotation.EnableScheduling; + +import javax.annotation.PostConstruct; +import java.time.LocalDateTime; +import java.util.TimeZone; + +@SpringBootApplication +@EnableJpaAuditing +@EnableScheduling +public class Application { + + @PostConstruct + public void started() { + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul")); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + System.out.println("ํ˜„์žฌ์‹œ๊ฐ„ " + LocalDateTime.now()); + } + +}
Java
System out ๋ณด๋‹ค๋Š” log ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ ์ถœ๋ ฅํ•˜๋„๋ก ์„ค์ •ํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,15 @@ +package friend.spring.OAuth; + +import lombok.Data; + +@Data +public class OAuthToken { + + private String access_token; + private String token_type; + private String refresh_token; + private String id_token; + private int expires_in; + private String scope; + private int refresh_token_expires_in; +}
Java
`@Data` ๋Š” ์ตœ๋Œ€ํ•œ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ์„ธ์š”. ์˜๋„ํ•˜์ง€ ์•Š์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•„์š”ํ•œ ํ•„๋“œ์— ๋”ฐ๋ผ ์ ์ ˆํ•˜๊ฒŒ ํ•„์š”ํ•œ ์–ด๋…ธํ…Œ์ด์…˜๋งŒ ์‚ฌ์šฉํ•˜๋„๋ก ํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,15 @@ +package friend.spring.OAuth; + +import lombok.Data; + +@Data +public class OAuthToken { + + private String access_token; + private String token_type; + private String refresh_token; + private String id_token; + private int expires_in; + private String scope; + private int refresh_token_expires_in; +}
Java
Java์—์„œ๋Š” ๊ฐ€๋Šฅํ•˜๋ฉด underscore๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋„๋ก ํ•ด ์ฃผ์„ธ์š”. (์บ๋ฉ€ ์ผ€์ด์Šค ๊ถŒ์žฅ) - ์ฐธ๊ณ : https://google.github.io/styleguide/javaguide.html - ์ฐธ๊ณ 2: https://naver.github.io/hackday-conventions-java/ + ๊ฐ€๋Šฅํ•˜๋ฉด checkstyle ๋“ฑ์˜ ๋„๊ตฌ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ฝ”๋“œ ์Šคํƒ€์ผ์„ ์ •์˜ํ•˜๊ณ , ํ•ด๋‹น ์Šคํƒ€์ผ์— ๋งž์ถ”๊ฒŒ ์ฝ”๋“œ ํ˜•ํƒœ๋ฅผ ๊ฐ•์ œํ•˜๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,104 @@ +package friend.spring.OAuth.provider; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import friend.spring.apiPayload.GeneralException; +import friend.spring.apiPayload.code.status.ErrorStatus; +import friend.spring.OAuth.KakaoProfile; +import friend.spring.OAuth.OAuthToken; +import friend.spring.security.PrincipalDetailService; +import org.springframework.beans.factory.annotation.Value; +import friend.spring.repository.UserRepository; +import friend.spring.security.JwtTokenProvider; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +@Component +@RequiredArgsConstructor +public class KakaoAuthProvider { + + private final PrincipalDetailService principalDetailService; + private final UserRepository userRepository; + private final JwtTokenProvider jwtTokenProvider; + + @Value("${kakao.auth.client}") + private String client; + + @Value("${kakao.auth.redirect_uri}") + private String redirect; + + @Value("${kakao.auth.secret_key}") + private String secretKey; + + // code๋กœ access ํ† ํฐ ์š”์ฒญํ•˜๊ธฐ + public OAuthToken requestToken(String code) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + + headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); + + MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); + params.add("grant_type", "authorization_code"); + params.add("client_id", client); + params.add("redirect_uri", redirect); + params.add("secret_key", secretKey); + params.add("code", code); + + HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest = + new HttpEntity<>(params, headers); + + ResponseEntity<String> response = + restTemplate.exchange( + "https://kauth.kakao.com/oauth/token", + HttpMethod.POST, + kakaoTokenRequest, + String.class); + + ObjectMapper objectMapper = new ObjectMapper(); + + OAuthToken oAuthToken = null; + + try { + oAuthToken = objectMapper.readValue(response.getBody(), OAuthToken.class); + } catch (JsonProcessingException e) { + throw new GeneralException(ErrorStatus.INVALID_REQUEST_INFO); + } + + return oAuthToken; + } + + // Token์œผ๋กœ ์ •๋ณด ์š”์ฒญํ•˜๊ธฐ + public KakaoProfile requestKakaoProfile(String token) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); + headers.add("Authorization", "Bearer " + token); + + HttpEntity<MultiValueMap<String, String>> kakaoProfileRequest = new HttpEntity<>(headers); + + ResponseEntity<String> response = + restTemplate.exchange( + "https://kapi.kakao.com/v2/user/me", + HttpMethod.POST, + kakaoProfileRequest, + String.class); + + ObjectMapper objectMapper = new ObjectMapper(); + KakaoProfile kakaoProfile = null; + + try { + kakaoProfile = objectMapper.readValue(response.getBody(), KakaoProfile.class); + } catch (JsonProcessingException e) { + throw new GeneralException(ErrorStatus.INVALID_REQUEST_INFO); + } + + return kakaoProfile; + } +}
Java
์–ด์ฐจํ”ผ ํ•œ ๋ฒˆ ๋งŒ๋“ค๋ฉด ์žฌ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ˆ๊นŒ... - Spring์— ๊ธฐ๋ณธ์œผ๋กœ ๋“ฑ๋ก๋œ ObjectMapper Bean์„ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ (private final ํ•„๋“œ) - ํด๋ž˜์Šค ์ƒ๋‹จ๋ถ€์— new ๋กœ ํ•˜๋‚˜ ๋งŒ๋“ค์–ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,120 @@ +package friend.spring.apiPayload; + +import friend.spring.apiPayload.code.ErrorReasonDTO; +import friend.spring.apiPayload.code.status.ErrorStatus; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.ConstraintViolationException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +@Slf4j +@RestControllerAdvice(annotations = {RestController.class}) +public class ExceptionAdvice extends ResponseEntityExceptionHandler { + + + @org.springframework.web.bind.annotation.ExceptionHandler + public ResponseEntity<Object> validation(ConstraintViolationException e, WebRequest request) { + String errorMessage = e.getConstraintViolations().stream() + .map(constraintViolation -> constraintViolation.getMessage()) + .findFirst() + .orElseThrow(() -> new RuntimeException("ConstraintViolationException ์ถ”์ถœ ๋„์ค‘ ์—๋Ÿฌ ๋ฐœ์ƒ")); + + return handleExceptionInternalConstraint(e, ErrorStatus.valueOf(errorMessage), HttpHeaders.EMPTY, request); + } + + + @Override + public ResponseEntity<Object> handleMethodArgumentNotValid( + MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) { + + Map<String, String> errors = new LinkedHashMap<>(); + + e.getBindingResult().getFieldErrors().stream() + .forEach(fieldError -> { + String fieldName = fieldError.getField(); + String errorMessage = Optional.ofNullable(fieldError.getDefaultMessage()).orElse(""); + errors.merge(fieldName, errorMessage, (existingErrorMessage, newErrorMessage) -> existingErrorMessage + ", " + newErrorMessage); + }); + + return handleExceptionInternalArgs(e, HttpHeaders.EMPTY, ErrorStatus.valueOf("_BAD_REQUEST"), request, errors); + } + + @org.springframework.web.bind.annotation.ExceptionHandler + public ResponseEntity<Object> exception(Exception e, WebRequest request) { + e.printStackTrace(); + + return handleExceptionInternalFalse(e, ErrorStatus._INTERNAL_SERVER_ERROR, HttpHeaders.EMPTY, ErrorStatus._INTERNAL_SERVER_ERROR.getHttpStatus(), request, e.getMessage()); + } + + @ExceptionHandler(value = GeneralException.class) + public ResponseEntity onThrowException(GeneralException generalException, HttpServletRequest request) { + ErrorReasonDTO errorReasonHttpStatus = generalException.getErrorReasonHttpStatus(); + return handleExceptionInternal(generalException, errorReasonHttpStatus, null, request); + } + + private ResponseEntity<Object> handleExceptionInternal(Exception e, ErrorReasonDTO reason, + HttpHeaders headers, HttpServletRequest request) { + + ApiResponse<Object> body = ApiResponse.onFailure(reason.getCode(), reason.getMessage(), null); +// e.printStackTrace(); + + WebRequest webRequest = new ServletWebRequest(request); + return super.handleExceptionInternal( + e, + body, + headers, + reason.getHttpStatus(), + webRequest + ); + } + + private ResponseEntity<Object> handleExceptionInternalFalse(Exception e, ErrorStatus errorCommonStatus, + HttpHeaders headers, HttpStatus status, WebRequest request, String errorPoint) { + ApiResponse<Object> body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), errorPoint); + return super.handleExceptionInternal( + e, + body, + headers, + status, + request + ); + } + + private ResponseEntity<Object> handleExceptionInternalArgs(Exception e, HttpHeaders headers, ErrorStatus errorCommonStatus, + WebRequest request, Map<String, String> errorArgs) { + ApiResponse<Object> body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), errorArgs); + return super.handleExceptionInternal( + e, + body, + headers, + errorCommonStatus.getHttpStatus(), + request + ); + } + + private ResponseEntity<Object> handleExceptionInternalConstraint(Exception e, ErrorStatus errorCommonStatus, + HttpHeaders headers, WebRequest request) { + ApiResponse<Object> body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), null); + return super.handleExceptionInternal( + e, + body, + headers, + errorCommonStatus.getHttpStatus(), + request + ); + } +} \ No newline at end of file
Java
- ๋ฉ”์‹œ์ง€ ์ œ๊ฑฐ (์‚ฌ์œ : ์–ด์ฐจํ”ผ trace ์ฐ์œผ๋ฉด ์–ด๋””์„œ ํ„ฐ์กŒ๋Š”์ง€ ๋‹ค ๋‚˜์˜ต๋‹ˆ๋‹ค.) - ๊ฐ€๋Šฅํ•˜๋ฉด RuntimeException ๋ณด๋‹ค๋Š” ์ข€ ๋” ๊ตฌ์ฒดํ™” ๋œ ์˜ˆ์™ธ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,109 @@ +package friend.spring.apiPayload.code.status; + +import friend.spring.apiPayload.code.BaseErrorCode; +import friend.spring.apiPayload.code.ErrorReasonDTO; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ErrorStatus implements BaseErrorCode { + + // ๊ฐ€์žฅ ์ผ๋ฐ˜์ ์ธ ์‘๋‹ต + _INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON5000", "์„œ๋ฒ„ ์—๋Ÿฌ, ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ ๋ฐ”๋ž๋‹ˆ๋‹ค."), + _BAD_REQUEST(HttpStatus.BAD_REQUEST, "COMMON4000", "์ž˜๋ชป๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค."), + _UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "COMMON4001", "์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."), + _FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON4003", "๊ธˆ์ง€๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค."), + + // ๋ฉค๋ฒ„ ๊ด€๋ จ ์‘๋‹ต + USER_NOT_FOUND(HttpStatus.NOT_FOUND, "USER4001", "ํšŒ์›์ •๋ณด๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + USERS_NOT_FOUND_EMAIL(HttpStatus.NOT_FOUND, "USER4010", "๊ฐ€์ž… ๊ฐ€๋Šฅํ•œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค."), + USER_EXISTS_EMAIL(HttpStatus.NOT_ACCEPTABLE, "USER4002", "์ด๋ฏธ ์กด์žฌํ•˜๋Š” ๋ฉ”์ผ ์ฃผ์†Œ์ž…๋‹ˆ๋‹ค"), + UNABLE_TO_SEND_EMAIL(HttpStatus.BAD_REQUEST, "USER4003", "์ด๋ฉ”์ผ์„ ๋ฐœ์†กํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."), + ERR_MAKE_CODE(HttpStatus.BAD_REQUEST, "USER4004", "์ธ์ฆ ์ฝ”๋“œ ์ƒ์„ฑ์— ์˜ค๋ฅ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค."), + INCORRECT_CODE(HttpStatus.UNAUTHORIZED, "USER4005", "์ธ์ฆ ์ฝ”๋“œ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + EMPTY_JWT(HttpStatus.BAD_REQUEST, "USER4006", "JWT๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."), + INVALID_JWT(HttpStatus.UNAUTHORIZED, "USER4007", "์œ ํšจํ•˜์ง€ ์•Š์€ JWT์ž…๋‹ˆ๋‹ค."), + INVALID_PASSWORD_FORMAT(HttpStatus.NOT_ACCEPTABLE, "USER4077", "๋น„๋ฐ€๋ฒˆํ˜ธ ํ˜•์‹์— ๋งž์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + PASSWORD_INCORRECT(HttpStatus.NOT_FOUND, "USER4008", "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค."), + PASSWORD_CHECK_INCORRECT(HttpStatus.NOT_FOUND, "USER4009", "ํ™•์ธ ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + RTK_INCORREXT(HttpStatus.UNAUTHORIZED, "USER4100", "RefreshToken๊ฐ’์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”."), + NOT_ADMIN(HttpStatus.BAD_REQUEST, "USER4101", "๊ด€๋ฆฌ์ž๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + + // Auth ๊ด€๋ จ + AUTH_EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4101", "ํ† ํฐ์ด ๋งŒ๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."), + AUTH_INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4102", "ํ† ํฐ์ด ์œ ํšจํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + INVALID_LOGIN_REQUEST(HttpStatus.UNAUTHORIZED, "AUTH_4103", "์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ์ด๋‚˜ ํŒจ์Šค์›Œ๋“œ๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + INVALID_REQUEST_INFO(HttpStatus.UNAUTHORIZED, "AUTH_4106", "์นด์นด์˜ค ์ •๋ณด ๋ถˆ๋Ÿฌ์˜ค๊ธฐ์— ์‹คํŒจํ•˜์˜€์Šต๋‹ˆ๋‹ค."), + NOT_EQUAL_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4107", "๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ด ๋‹ค๋ฆ…๋‹ˆ๋‹ค."), + NOT_CONTAIN_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4108", "ํ•ด๋‹นํ•˜๋Š” ํ† ํฐ์ด ์ €์žฅ๋˜์–ด์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + + // ๊ธ€ ๊ด€๋ จ ์‘๋‹ต + POST_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4001", "๊ธ€์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "POST4002", "์˜ฌ๋ฐ”๋ฅธ ์‚ฌ์šฉ์ž(๊ธ€ ์ž‘์„ฑ์ž)๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + POST_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4003", "๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_CATGORY_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_SAVED_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "์ €์žฅํ•œ ๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค."), + POST_SCRAP_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "๊ธ€์— ๋Œ€ํ•œ ์Šคํฌ๋žฉ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_GENERAL_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "๊ธ€์— ๋Œ€ํ•œ ์ผ๋ฐ˜ ํˆฌํ‘œ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_CARD_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4006", "๊ธ€์— ๋Œ€ํ•œ ์นด๋“œ ํˆฌํ‘œ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + TITLE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4007", "์ตœ์†Œ 5์ž ์ด์ƒ, 30์ž ๋ฏธ๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + CONTENT_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4008", "์ตœ์†Œ 5์ž ์ด์ƒ, 1000์ž ๋ฏธ๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + CANDIDATE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4009", "์ตœ์†Œ 1์ž ์ด์ƒ, 30์ž ๋ฏธ๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + DEADLINE_LIMIT(HttpStatus.BAD_REQUEST, "POST4010", "์ตœ์†Œ 1๋ถ„~์ตœ๋Œ€30์ผ๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + CANDIDATE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4011", "ํ›„๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค"), + TOO_MUCH_FIXED(HttpStatus.NOT_FOUND, "POST4012", "์ด๋ฏธ 2ํšŒ ์ด์ƒ ์ˆ˜์ • ํ–ˆ์Šต๋‹ˆ๋‹ค"), + NOT_ENOUGH_POINT(HttpStatus.BAD_REQUEST, "POST4013", "ํ•ด๋‹น ์œ ์ €์˜ ํฌ์ธํŠธ๊ฐ€ ๋ถ€์กฑ ํ•ฉ๋‹ˆ๋‹ค"), + POST_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4014", "๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + POST_SCRAP_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4015", "๊ธ€์— ๋Œ€ํ•œ ์Šคํฌ๋žฉ ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + DEADLINE_OVER(HttpStatus.BAD_REQUEST, "POST4016", "ํˆฌํ‘œ ๋งˆ๊ฐ ์‹œ๊ฐ„์ด ์ง€๋‚ฌ์Šต๋‹ˆ๋‹ค"), + ALREADY_VOTE(HttpStatus.BAD_REQUEST, "POST4017", "์ด๋ฏธ ํˆฌํ‘œ ํ•˜์…จ์Šต๋‹ˆ๋‹ค."), +// USER_VOTE(HttpStatus.BAD_REQUEST,"POST4017","์ž‘์„ฑ์ž๋Š” ํˆฌํ‘œ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅ ํ•ฉ๋‹ˆ๋‹ค ํ•˜์…จ์Šต๋‹ˆ๋‹ค."), // ์ด๊ฑฐ ํ•„์š”์—†์œผ๋ฉด ์ง€์›Œ์•ผ ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! + + POST_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4018", "์ด ์œ ์ €๊ฐ€ ํ•ด๋‹น ๊ธ€์„ ์‹ ๊ณ ํ•œ ์‹ ๊ณ  ๋‚ด์—ญ ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + + // ๋Œ“๊ธ€ ๊ด€๋ จ ์‘๋‹ต + COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4001", "๋Œ“๊ธ€์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + COMMENT_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4002", "๋Œ“๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + COMMENT_CHOICE_OVER_ONE(HttpStatus.BAD_REQUEST, "COMMENT4003", "๋Œ“๊ธ€ ์ฑ„ํƒ์€ 1๊ฐœ ๋Œ“๊ธ€์— ๋Œ€ํ•ด์„œ๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."), + COMMENT_SELECT_MYSELF(HttpStatus.BAD_REQUEST, "COMMENT4004", "์ž๊ธฐ ์ž์‹ ์€ ์ฑ„ํƒํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + COMMENT_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "COMMENT4005", "์˜ฌ๋ฐ”๋ฅธ ์‚ฌ์šฉ์ž(๋Œ“๊ธ€ ์ž‘์„ฑ์ž)๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + COMMENT_POST_NOT_MATCH(HttpStatus.BAD_REQUEST, "COMMENT4006", "ํ•ด๋‹น ๊ธ€์— ์ž‘์„ฑ๋œ ๋Œ“๊ธ€์ด ์•„๋‹™๋‹ˆ๋‹ค."), + COMMENT_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4007", "๋Œ“๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + COMMENT_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4008", "์ด ์œ ์ €๊ฐ€ ํ•ด๋‹น ๋Œ“๊ธ€์„ ์‹ ๊ณ ํ•œ ์‹ ๊ณ  ๋‚ด์—ญ ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + + // ์•Œ๋ฆผ ๊ด€๋ จ ์‘๋‹ต + ALARM_NOT_FOUND(HttpStatus.NOT_FOUND, "ALARM4001", "์•Œ๋ฆผ์ด ์—†์Šต๋‹ˆ๋‹ค"), + + + // ๊ณต์ง€์‚ฌํ•ญ ๊ด€๋ จ ์‘๋‹ต + NOTICE_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTICE4001", "๊ณต์ง€์‚ฌํ•ญ์ด ์—†์Šต๋‹ˆ๋‹ค."); + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + @Override + public ErrorReasonDTO getReason() { + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .build(); + } + + @Override + public ErrorReasonDTO getReasonHttpStatus() { + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .httpStatus(httpStatus) + .build() + ; + + + } +} +
Java
์„œ๋ฒ„์—๋Ÿฌ์ธ๊ฒƒ ๊ฐ™์€๋ฐ, 500์ด ๋‚ซ์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,109 @@ +package friend.spring.apiPayload.code.status; + +import friend.spring.apiPayload.code.BaseErrorCode; +import friend.spring.apiPayload.code.ErrorReasonDTO; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ErrorStatus implements BaseErrorCode { + + // ๊ฐ€์žฅ ์ผ๋ฐ˜์ ์ธ ์‘๋‹ต + _INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON5000", "์„œ๋ฒ„ ์—๋Ÿฌ, ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ ๋ฐ”๋ž๋‹ˆ๋‹ค."), + _BAD_REQUEST(HttpStatus.BAD_REQUEST, "COMMON4000", "์ž˜๋ชป๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค."), + _UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "COMMON4001", "์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."), + _FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON4003", "๊ธˆ์ง€๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค."), + + // ๋ฉค๋ฒ„ ๊ด€๋ จ ์‘๋‹ต + USER_NOT_FOUND(HttpStatus.NOT_FOUND, "USER4001", "ํšŒ์›์ •๋ณด๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + USERS_NOT_FOUND_EMAIL(HttpStatus.NOT_FOUND, "USER4010", "๊ฐ€์ž… ๊ฐ€๋Šฅํ•œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค."), + USER_EXISTS_EMAIL(HttpStatus.NOT_ACCEPTABLE, "USER4002", "์ด๋ฏธ ์กด์žฌํ•˜๋Š” ๋ฉ”์ผ ์ฃผ์†Œ์ž…๋‹ˆ๋‹ค"), + UNABLE_TO_SEND_EMAIL(HttpStatus.BAD_REQUEST, "USER4003", "์ด๋ฉ”์ผ์„ ๋ฐœ์†กํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."), + ERR_MAKE_CODE(HttpStatus.BAD_REQUEST, "USER4004", "์ธ์ฆ ์ฝ”๋“œ ์ƒ์„ฑ์— ์˜ค๋ฅ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค."), + INCORRECT_CODE(HttpStatus.UNAUTHORIZED, "USER4005", "์ธ์ฆ ์ฝ”๋“œ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + EMPTY_JWT(HttpStatus.BAD_REQUEST, "USER4006", "JWT๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."), + INVALID_JWT(HttpStatus.UNAUTHORIZED, "USER4007", "์œ ํšจํ•˜์ง€ ์•Š์€ JWT์ž…๋‹ˆ๋‹ค."), + INVALID_PASSWORD_FORMAT(HttpStatus.NOT_ACCEPTABLE, "USER4077", "๋น„๋ฐ€๋ฒˆํ˜ธ ํ˜•์‹์— ๋งž์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + PASSWORD_INCORRECT(HttpStatus.NOT_FOUND, "USER4008", "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค."), + PASSWORD_CHECK_INCORRECT(HttpStatus.NOT_FOUND, "USER4009", "ํ™•์ธ ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + RTK_INCORREXT(HttpStatus.UNAUTHORIZED, "USER4100", "RefreshToken๊ฐ’์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”."), + NOT_ADMIN(HttpStatus.BAD_REQUEST, "USER4101", "๊ด€๋ฆฌ์ž๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + + // Auth ๊ด€๋ จ + AUTH_EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4101", "ํ† ํฐ์ด ๋งŒ๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."), + AUTH_INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4102", "ํ† ํฐ์ด ์œ ํšจํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + INVALID_LOGIN_REQUEST(HttpStatus.UNAUTHORIZED, "AUTH_4103", "์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ์ด๋‚˜ ํŒจ์Šค์›Œ๋“œ๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + INVALID_REQUEST_INFO(HttpStatus.UNAUTHORIZED, "AUTH_4106", "์นด์นด์˜ค ์ •๋ณด ๋ถˆ๋Ÿฌ์˜ค๊ธฐ์— ์‹คํŒจํ•˜์˜€์Šต๋‹ˆ๋‹ค."), + NOT_EQUAL_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4107", "๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ด ๋‹ค๋ฆ…๋‹ˆ๋‹ค."), + NOT_CONTAIN_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4108", "ํ•ด๋‹นํ•˜๋Š” ํ† ํฐ์ด ์ €์žฅ๋˜์–ด์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + + // ๊ธ€ ๊ด€๋ จ ์‘๋‹ต + POST_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4001", "๊ธ€์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "POST4002", "์˜ฌ๋ฐ”๋ฅธ ์‚ฌ์šฉ์ž(๊ธ€ ์ž‘์„ฑ์ž)๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + POST_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4003", "๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_CATGORY_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_SAVED_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "์ €์žฅํ•œ ๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค."), + POST_SCRAP_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "๊ธ€์— ๋Œ€ํ•œ ์Šคํฌ๋žฉ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_GENERAL_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "๊ธ€์— ๋Œ€ํ•œ ์ผ๋ฐ˜ ํˆฌํ‘œ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + POST_CARD_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4006", "๊ธ€์— ๋Œ€ํ•œ ์นด๋“œ ํˆฌํ‘œ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + TITLE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4007", "์ตœ์†Œ 5์ž ์ด์ƒ, 30์ž ๋ฏธ๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + CONTENT_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4008", "์ตœ์†Œ 5์ž ์ด์ƒ, 1000์ž ๋ฏธ๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + CANDIDATE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4009", "์ตœ์†Œ 1์ž ์ด์ƒ, 30์ž ๋ฏธ๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + DEADLINE_LIMIT(HttpStatus.BAD_REQUEST, "POST4010", "์ตœ์†Œ 1๋ถ„~์ตœ๋Œ€30์ผ๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”"), + CANDIDATE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4011", "ํ›„๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค"), + TOO_MUCH_FIXED(HttpStatus.NOT_FOUND, "POST4012", "์ด๋ฏธ 2ํšŒ ์ด์ƒ ์ˆ˜์ • ํ–ˆ์Šต๋‹ˆ๋‹ค"), + NOT_ENOUGH_POINT(HttpStatus.BAD_REQUEST, "POST4013", "ํ•ด๋‹น ์œ ์ €์˜ ํฌ์ธํŠธ๊ฐ€ ๋ถ€์กฑ ํ•ฉ๋‹ˆ๋‹ค"), + POST_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4014", "๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + POST_SCRAP_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4015", "๊ธ€์— ๋Œ€ํ•œ ์Šคํฌ๋žฉ ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + DEADLINE_OVER(HttpStatus.BAD_REQUEST, "POST4016", "ํˆฌํ‘œ ๋งˆ๊ฐ ์‹œ๊ฐ„์ด ์ง€๋‚ฌ์Šต๋‹ˆ๋‹ค"), + ALREADY_VOTE(HttpStatus.BAD_REQUEST, "POST4017", "์ด๋ฏธ ํˆฌํ‘œ ํ•˜์…จ์Šต๋‹ˆ๋‹ค."), +// USER_VOTE(HttpStatus.BAD_REQUEST,"POST4017","์ž‘์„ฑ์ž๋Š” ํˆฌํ‘œ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅ ํ•ฉ๋‹ˆ๋‹ค ํ•˜์…จ์Šต๋‹ˆ๋‹ค."), // ์ด๊ฑฐ ํ•„์š”์—†์œผ๋ฉด ์ง€์›Œ์•ผ ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! + + POST_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4018", "์ด ์œ ์ €๊ฐ€ ํ•ด๋‹น ๊ธ€์„ ์‹ ๊ณ ํ•œ ์‹ ๊ณ  ๋‚ด์—ญ ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + + // ๋Œ“๊ธ€ ๊ด€๋ จ ์‘๋‹ต + COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4001", "๋Œ“๊ธ€์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + COMMENT_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4002", "๋Œ“๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + COMMENT_CHOICE_OVER_ONE(HttpStatus.BAD_REQUEST, "COMMENT4003", "๋Œ“๊ธ€ ์ฑ„ํƒ์€ 1๊ฐœ ๋Œ“๊ธ€์— ๋Œ€ํ•ด์„œ๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."), + COMMENT_SELECT_MYSELF(HttpStatus.BAD_REQUEST, "COMMENT4004", "์ž๊ธฐ ์ž์‹ ์€ ์ฑ„ํƒํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + COMMENT_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "COMMENT4005", "์˜ฌ๋ฐ”๋ฅธ ์‚ฌ์šฉ์ž(๋Œ“๊ธ€ ์ž‘์„ฑ์ž)๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."), + COMMENT_POST_NOT_MATCH(HttpStatus.BAD_REQUEST, "COMMENT4006", "ํ•ด๋‹น ๊ธ€์— ์ž‘์„ฑ๋œ ๋Œ“๊ธ€์ด ์•„๋‹™๋‹ˆ๋‹ค."), + COMMENT_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4007", "๋Œ“๊ธ€์— ๋Œ€ํ•œ ์ข‹์•„์š” ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + COMMENT_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4008", "์ด ์œ ์ €๊ฐ€ ํ•ด๋‹น ๋Œ“๊ธ€์„ ์‹ ๊ณ ํ•œ ์‹ ๊ณ  ๋‚ด์—ญ ๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค."), + + // ์•Œ๋ฆผ ๊ด€๋ จ ์‘๋‹ต + ALARM_NOT_FOUND(HttpStatus.NOT_FOUND, "ALARM4001", "์•Œ๋ฆผ์ด ์—†์Šต๋‹ˆ๋‹ค"), + + + // ๊ณต์ง€์‚ฌํ•ญ ๊ด€๋ จ ์‘๋‹ต + NOTICE_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTICE4001", "๊ณต์ง€์‚ฌํ•ญ์ด ์—†์Šต๋‹ˆ๋‹ค."); + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + @Override + public ErrorReasonDTO getReason() { + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .build(); + } + + @Override + public ErrorReasonDTO getReasonHttpStatus() { + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .httpStatus(httpStatus) + .build() + ; + + + } +} +
Java
FORBIDDEN์ด ๋‚˜์€ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,108 @@ +package store.contoller; + +import store.Utils; +import store.model.*; +import store.view.InputView; +import store.view.OutputView; + +import java.time.LocalDate; +import java.util.*; + +import camp.nextstep.edu.missionutils.DateTimes; + +public class StoreController { + private static final Map<String, Product> productMap = new LinkedHashMap<>(); + private static final StockManager stockManager = new StockManager(); + private static final MembershipDiscount membershipDiscount = new MembershipDiscount(); + private static final LocalDate today = LocalDate.from(DateTimes.now()); + + public StoreController() { + ProductLoader.initProducts(productMap); + } + + public void run() { + while (true) { + try { + handleCustomerInteraction(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + continue; + } + if (!InputView.askRetry()) { + break; + } + } + } + + private void handleCustomerInteraction() { + OutputView.welcomeStore(); + printProducts(); + Receipt receipt = purchaseItems(); + receipt.print(); + } + + public void printProducts() { + productMap.values().forEach(System.out::println); + } + + public static Receipt purchaseItems() { + String item = readItemInput(); + List<PurchaseItem> purchaseItems = processItemInput(item); + return processItems(purchaseItems); + } + + private static String readItemInput() { + return InputView.readItem(); + } + + private static List<PurchaseItem> processItemInput(String item) { + String cleanedItem = Utils.removeBrackets(item); + return Utils.parseItems(cleanedItem); + } + + public static Receipt processItems(List<PurchaseItem> purchaseItems) { + Map<String, PurchaseItem> purchase = new LinkedHashMap<>(); + Map<String, PurchaseItem> freeItems = new LinkedHashMap<>(); + int totalPrice = 0; + int nonPromotionTotalPrice = 0; + + for (PurchaseItem purchaseItem : purchaseItems) { + Product product = productMap.get(purchaseItem.getName()); + stockManager.validateStock(purchaseItem, product); + int purchaseTotalPrice = processItem(purchaseItem, product, freeItems); + nonPromotionTotalPrice += getNonPromotionTotalPrice(product, purchaseTotalPrice); + totalPrice += purchaseTotalPrice; + purchase.put(purchaseItem.getName(), new PurchaseItem(purchaseItem.getName(), purchaseItem.getQuantity(), purchaseTotalPrice)); + } + + int membershipDiscountPrice = membershipDiscount.applyMembershipDiscount(nonPromotionTotalPrice); + return new Receipt(purchase, freeItems, membershipDiscountPrice, totalPrice); + } + + private static int processItem(PurchaseItem purchaseItem, Product product, Map<String, PurchaseItem> freeItems) { + int purchaseTotalPrice; + Promotion promotion = product.getPromotion(); + + if (isPromotionAvailable(promotion, product)) { + PromotionHandler promotionHandler = new PromotionHandler(product, purchaseItem); + purchaseTotalPrice = promotionHandler.applyPromotion(); + freeItems.putAll(promotionHandler.getFreeItems()); + return purchaseTotalPrice; + } + + NonPromotionHandler nonPromotionHandler = new NonPromotionHandler(product, purchaseItem); + purchaseTotalPrice = nonPromotionHandler.handleNonPromotion(); + return purchaseTotalPrice; + } + + private static boolean isPromotionAvailable(Promotion promotion, Product product) { + return promotion != Promotion.NULL && promotion.isAvailable(today) && product.getPromotionQuantity() > 0; + } + + private static int getNonPromotionTotalPrice(Product product, int purchaseTotalPrice) { + if (isPromotionAvailable(product.getPromotion(), product)) { + return 0; + } + return purchaseTotalPrice; + } +}
Java
์ƒํ’ˆ๋“ค์„ ์ถœ๋ ฅํ•˜๋Š” ๋กœ์ง์„ OutputView ์—์„œ ํ–ˆ์œผ๋ฉด ์–ด๋–จ๊นŒ ์‹ถ์–ด์š”!!!
@@ -0,0 +1,17 @@ +package store.model; + +import store.view.InputView; + +public class MembershipDiscount { + public int applyMembershipDiscount(int totalNonPromotionPrice) { + if (InputView.askMemberShip()) { + return calculateMembershipDiscount(totalNonPromotionPrice); + } + return 0; + } + + public int calculateMembershipDiscount(int totalAmount) { + int membershipDiscount = (int) (totalAmount * 0.3); + return Math.min(membershipDiscount, 8000); + } +} \ No newline at end of file
Java
๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋น„์œจ์„ ์ƒ์ˆ˜๋กœ ๋ฝ‘์œผ๋ฉด ์–ด๋–จ๊นŒ ์‹ถ์Šต๋‹ˆ๋‹ค!!!
@@ -0,0 +1,17 @@ +package store.model; + +import store.view.InputView; + +public class MembershipDiscount { + public int applyMembershipDiscount(int totalNonPromotionPrice) { + if (InputView.askMemberShip()) { + return calculateMembershipDiscount(totalNonPromotionPrice); + } + return 0; + } + + public int calculateMembershipDiscount(int totalAmount) { + int membershipDiscount = (int) (totalAmount * 0.3); + return Math.min(membershipDiscount, 8000); + } +} \ No newline at end of file
Java
์ €๋„ ์ด๋ ‡๊ฒŒ ํ• ๊ฑธ ๊ทธ๋žฌ์Šต๋‹ˆ๋‹ค!! ์ž˜ ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค!!!!
@@ -0,0 +1,81 @@ +package store.model; + +import store.message.ViewMessage; + +import java.text.NumberFormat; +import java.util.Locale; + +public class Product { + private final String name; + private final int price; + private int quantity; + private int promotionQuantity; + private final Promotion promotion; + + public Product(String name, int price, int quantity, String promotion) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = Promotion.fromString(promotion); + } + + // getter ๋ฐ setter + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getQuantity() { + return quantity; + } + + public Promotion getPromotion() { + return promotion; + } + + public int getPromotionQuantity() { + return promotionQuantity; + } + + public int getTotalQuantity() { + return quantity + promotionQuantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public void setPromotionQuantity(int promotionQuantity) { + this.promotionQuantity = promotionQuantity; + } + + + public String formatPrice() { + NumberFormat currencyFormat = NumberFormat.getInstance(Locale.KOREA); + return currencyFormat.format(price); + } + + @Override + public String toString() { + if (quantity > 0 && promotion != Promotion.NULL) { + return ViewMessage.PROMOTION_WITH_STOCK + .format(name, formatPrice(), promotionQuantity, promotion.getName(), + name, formatPrice(), quantity, Promotion.NULL.getName()); + } + if (promotion == Promotion.NULL) { + return ViewMessage.NO_PROMOTION + .format(name, formatPrice(), quantity, Promotion.NULL.getName()); + } + if (quantity == 0 && promotionQuantity == 0) { + return ViewMessage.OUT_OF_STOCK_WITH_PROMOTION + .format(name, formatPrice(), promotion.getName(), + name, formatPrice(), Promotion.NULL.getName()); + } + return ViewMessage.PROMOTION_ONLY_OUT_OF_STOCK + .format(name, formatPrice(), promotionQuantity, promotion.getName(), + name, formatPrice(), Promotion.NULL.getName()); + } +}
Java
์žฌ๊ณ ์ˆ˜๋Ÿ‰์˜ ๋ณ€๋™์„ setter ๋Œ€์‹  ์ˆ˜๋Ÿ‰ ์ฆ๊ฐ€์‹œ `increaseQuantity()` ์žฌ๊ณ  ๊ฐ์†Œ์‹œ 'decreaseQuantiy()` ์ด๋Ÿฐ์‹์œผ๋กœ ์˜๋ฏธ๋ฅผ ๋ถ€์—ฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!!!
@@ -0,0 +1,69 @@ +package store.model; + +import store.message.ReceiptMessage; +import store.view.OutputView; + +import java.text.NumberFormat; +import java.util.Locale; +import java.util.Map; + +public class Receipt { + private final Map<String, PurchaseItem> purchase; + private final Map<String, PurchaseItem> freeItems; + private final int membershipDiscountPrice; + private int totalAmount; + private int totalPromotionDiscount; + private int totalPurchasePrice; + + public Receipt(Map<String, PurchaseItem> purchase, Map<String, PurchaseItem> freeItems, + int membershipDiscountPrice, int totalAmount) { + this.purchase = purchase; + this.freeItems = freeItems; + this.membershipDiscountPrice = membershipDiscountPrice; + this.totalAmount = totalAmount; + this.totalPromotionDiscount = 0; + this.totalPurchasePrice = 0; + + } + + public void print() { + NumberFormat currencyFormat = NumberFormat.getInstance(Locale.KOREA); + + OutputView.printStore(); + + totalPurchasePrice = purchaseItems(currencyFormat, totalPurchasePrice); + totalPromotionDiscount = freeItems(totalPromotionDiscount); + + OutputView.printLine(); + + printPriceDetails(currencyFormat); + } + + private int purchaseItems(NumberFormat currencyFormat, int totalPurchasePrice) { + for (PurchaseItem purchaseItem : purchase.values()) { + totalPurchasePrice += purchaseItem.getPrice(); + OutputView.printProductFormat(purchaseItem, currencyFormat); + } + return totalPurchasePrice; + } + + private int freeItems(int totalPromotionDiscount) { + OutputView.printFreeItem(); + for (PurchaseItem freeItem : freeItems.values()) { + totalPromotionDiscount += freeItem.getQuantity() * freeItem.getPrice(); + if (freeItem.getQuantity() > 0) { + OutputView.printFreeProductFormat(freeItem); + } + } + return totalPromotionDiscount; + } + + private void printPriceDetails(NumberFormat currencyFormat) { + totalAmount -= totalPromotionDiscount; + totalAmount -= membershipDiscountPrice; + OutputView.printTotalAmount(totalPurchasePrice,currencyFormat); + OutputView.printPromotionDiscount(totalPromotionDiscount,currencyFormat); + OutputView.printMembershipDiscount(membershipDiscountPrice,currencyFormat); + OutputView.printFinalAmount(totalAmount,currencyFormat); + } +}
Java
MVC ํŒจํ„ด์— ๋Œ€ํ•œ ๋‚ด์šฉ์„ ์‚ดํŽด๋ณด๋ฉด ๋ชจ๋ธ์€ ๋ทฐ๋‚˜ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ์˜์กดํ•˜๋ฉด ์•ˆ๋œ๋‹ค๊ณ  ๋˜์–ด ์žˆ๋Š” ๊ธ€์„ ๋ณด์•˜์Šต๋‹ˆ๋‹ค!! Recipt ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ DTO ๋กœ ๋งŒ๋“  ๋’ค ์ปจํŠธ๋กค๋Ÿฌ์— ๋„˜๊ฒจ ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ OutputView๋กœ ์˜์ˆ˜์ฆ์— ๋Œ€ํ•œ ๋‚ด์šฉ์„ ๋„˜๊ฒผ์œผ๋ฉด ์–ด๋–จ๊นŒ ์‹ถ์Šต๋‹ˆ๋‹ค!!
@@ -0,0 +1,34 @@ +package store.model; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MembershipTest { + private MembershipDiscount membershipDiscount; + + @BeforeEach + void setUp() { + membershipDiscount = new MembershipDiscount(); + } + + @Test + void applyMembershipDiscount_WithMembership_ReturnsDiscountedAmount() { + int totalNonPromotionPrice = 20000; + int expectedDiscount = 6000; + + int result = membershipDiscount.calculateMembershipDiscount(totalNonPromotionPrice); + + assertEquals(expectedDiscount, result); + } + + @Test + void applyMembershipDiscount_WithMembership_CapsAt8000() { + int totalNonPromotionPrice = 50000; + int expectedDiscount = 8000; + + int result = membershipDiscount.calculateMembershipDiscount(totalNonPromotionPrice); + + assertEquals(expectedDiscount, result); + } +}
Java
ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์— ๋Œ€ํ•œ ๋งŽ์€ ๊ณ ๋ฏผ์ด ๋ณด์ด๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!!! ์ •๋ง ๊ณ ์ƒํ•˜์…จ์Šต๋‹ˆ๋‹ค!!!!
@@ -1,7 +1,17 @@ package store; +import store.controller.StoreController; +import store.global.util.FileUtil; +import store.view.InputView; +import store.view.OutputView; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + FileUtil fileInputView = new FileUtil(); + StoreController storeController = new StoreController( + new OutputView(), + new InputView(fileInputView) + ); + storeController.run(); } }
Java
FileUtil ์ด๋ผ๋Š” ์ž‘๋ช…์ด ์ง๊ด€์ ์ด์–ด์„œ ์ข‹๋„ค์š”! ์ €๋Š” StoreInitializer๋กœ ํ–ˆ๋Š”๋ฐ ๋ญ”๊ฐ€ ์•ˆ ์™€๋‹ฟ์•„์„œ ์•„์‰ฌ์› ์–ด์š”
@@ -1 +1,325 @@ -# java-convenience-store-precourse +# ํŽธ์˜์  ๐Ÿช + +## ๊ธฐ๋Šฅ ๊ตฌํ˜„ ๋ชฉ๋ก + +### โœ… ํŒŒ์ผ ์ฝ๊ธฐ ๊ธฐ๋Šฅ +- [x] ํŒŒ์ผ ๋‚ด์šฉ์„ ์ž…๋ ฅ ๋ฐ›์•„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค + - `products.md`, `promotions.md` ํŒŒ์ผ ์ž…๋ ฅ + - ๋‚ด์šฉ `(,)` ์‰ผํ‘œ๋กœ ๊ตฌ๋ถ„ + - ์ „์ฒด ๋‚ด์šฉ ๋ถ„๋ฆฌ ํ›„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ˜ํ™˜ +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ์ผ์น˜ํ•˜๋Š” ํŒŒ์ผ๋ช…์ด ์—†์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ํŒŒ์ผ์•ˆ์— ๋‚ด์šฉ์ด ์—†์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋ถ„๋ฆฌํ•œ ๋ฐฐ์—ด ์š”์†Œ๊ฐ€ ๊ณต๋ฐฑ์ผ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค + +--- +### โœ… ์ƒํ’ˆ ๋“ฑ๋ก ๊ธฐ๋Šฅ +- [x] ์ƒํ’ˆ ์ •๋ณด ๋ฆฌ์ŠคํŠธ๋กœ ์ƒํ’ˆ์„ ๋“ฑ๋กํ•œ๋‹ค +- [x] ์ „์ฒด ์ƒํ’ˆ ์ •๋ณด ๋ฆฌ์ŠคํŠธ๋กœ ์—ฌ๋Ÿฌ ์ƒํ’ˆ์„ ๋“ฑ๋กํ•œ๋‹ค +- [x] ํ”„๋กœ๋ชจ์…˜์ด ์กด์žฌํ•  ๊ฒฝ์šฐ ๊ธฐ๋ณธ ์ƒํ’ˆ๋„ ๋“ฑ๋ก๋œ๋‹ค +- [x] ํ”„๋กœ๋ชจ์…˜ null ์ผ ๋•Œ ๋นˆ๊ฐ’์„ ๋“ฑ๋กํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ์ƒํ’ˆ ์ •๋ณด ๋ฆฌ์ŠคํŠธ ํฌ๊ธฐ๊ฐ€ 4๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋“ฑ๋ก ๊ฐ€๊ฒฉ์ด ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋“ฑ๋ก ๊ฐ€๊ฒฉ์ด ์ตœ์†Œ๋ณด๋‹ค ์ž‘์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค `์ตœ์†Œ : 0` +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋“ฑ๋ก ๊ฐ€๊ฒฉ์ด ์ตœ๋Œ€๋ณด๋‹ค ํด ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค `์ตœ๋Œ€ : 1,000,000` +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋“ฑ๋ก ์ˆ˜๋Ÿ‰์ด ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋“ฑ๋ก ์ˆ˜๋Ÿ‰์ด ์ตœ์†Œ๋ณด๋‹ค ์ž‘์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค `์ตœ์†Œ : 1` +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๋“ฑ๋ก ์ˆ˜๋Ÿ‰์ด ์ตœ๋Œ€๋ณด๋‹ค ํด ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค `์ตœ๋Œ€ : 1,000,000` + +--- +### โœ… ์ƒํ’ˆ ๋ชฉ๋ก ์ถœ๋ ฅ ๊ธฐ๋Šฅ +- [x] ์ด๋ฆ„ ๊ฐ์ฒด์˜ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค `ex) ์ฝœ๋ผ` +- [x] ๊ฐ€๊ฒฉ ๊ฐ์ฒด์˜ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค `ex) 1,000์›` +- [x] ์ˆ˜๋Ÿ‰ ๊ฐ์ฒด์˜ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค `ex) 1๊ฐœ, 1,000๊ฐœ, ์žฌ๊ณ  ์—†์Œ` + - [x] ์ˆ˜๋Ÿ‰์ด 0๊ฐœ์ผ ๊ฒฝ์šฐ `์žฌ๊ณ  ์—†์Œ`์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค +- [x] ํ”„๋กœ๋ชจ์…˜ ๊ฐ์ฒด์˜ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค `ex) MD์ถ”์ฒœ์ƒํ’ˆ` +- [x] ๋‹จ์ผ ์ƒํ’ˆ์˜ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค `ex) ์ฝœ๋ผ, 1,000์›, 1๊ฐœ, MD์ถ”์ฒœ์ƒํ’ˆ` +- [x] ์ „์ฒด ์ƒํ’ˆ์˜ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค `ex) [์ฝœ๋ผ, 1,000์› ...] [์‚ฌ์ด๋‹ค, 1,200์› ...]` +- [x] ์ „์ฒด ์ƒํ’ˆ์˜ ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค `ex) - ์ฝœ๋ผ 1,000์› 10๊ฐœ ํƒ„์‚ฐ2+1` + +--- +### โœ…๋ฌผํ’ˆ ์ฐพ๊ธฐ ๊ธฐ๋Šฅ +- [x] ์ด๋ฆ„์ด ๊ฐ™์€ ๊ฒฝ์šฐ ์ƒํ’ˆ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค +- [x] ๋ชฉ๋ก์— ์ด๋ฆ„์ด ๊ฐ™์€ ์ƒํ’ˆ์„ ์ฐพ๋Š”๋‹ค +- [x] ๊ตฌ๋งคํ•  ์ƒํ’ˆ์˜ ์ด๋ฆ„๊ณผ ์ˆ˜๋Ÿ‰์„ ๊ตฌ๋ถ„ํ•œ๋‹ค `ex) [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]` + - ์ˆ˜๋Ÿ‰ `(-)` ํ•˜์ดํ”ˆ ๊ตฌ๋ถ„ + - ์ƒํ’ˆ์€ `([])` ๋Œ€๊ด„ํ˜ธ๋กœ ๋ฌถ์ธ `(,)` ๊ตฌ๋ถ„ +- [x] ๊ตฌ๋งคํ•  ์ƒํ’ˆ์ด ์ค‘๋ณต๋  ์‹œ ์ˆ˜๋Ÿ‰์„ ํ•ฉ์‚ฐํ•œ๋‹ค `ex) [์‚ฌ์ด๋‹ค-2],[์‚ฌ์ด๋‹ค-1]` +- [x] ๊ตฌ๋งคํ•  ์ƒํ’ˆ์˜ ๋™์ผํ•œ ๋ชจ๋“  ์ƒํ’ˆ์„ ์ฐพ๋Š”๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ์ƒํ’ˆ์ด ์กด์žฌํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๊ตฌ๋งคํ•  ์ƒํ’ˆ์˜ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค `ex) [์‚ฌ์ด๋‹ค-ํ•œ๊ฐœ] [์‚ฌ์ด๋‹ค-2 ์ด 15๊ฐ€์ง€ ์ผ€์ด์Šค` +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๊ตฌ๋งคํ•  ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰์ด ๋ฒ”์œ„์„ ๋ฒ—์–ด๋‚œ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค `์ตœ์†Œ : 1`, `์ตœ๋Œ€ : 1,000,000` + +--- +### โœ… ๊ณ„์‚ฐ ๊ธฐ๋Šฅ +- [x] ์ƒํ’ˆ๋ณ„ ๊ฐ€๊ฒฉ๊ณผ ์ˆ˜๋Ÿ‰ ๊ณฑ์œผ๋กœ ์ด๊ตฌ๋งค์•ก ๊ณ„์‚ฐ +- [x] ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ ์ •์ฑ… ๊ณ„์‚ฐ +- [x] ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ •์ฑ… ๊ณ„์‚ฐ + +--- +### โœ… ์žฌ๊ณ  ๊ด€๋ฆฌ ๊ธฐ๋Šฅ +- [x] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰ ํ™•์ธ ํ›„, ๊ฒฐ์ œ ๊ฐ€๋Šฅ ์—ฌ๋ถ€ +- [x] ์ƒํ’ˆ ๊ตฌ๋งค ์‹œ ์žฌ๊ณ  ์ฐจ๊ฐ +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฒฝ์šฐ `[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ `[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ๊ตฌ๋งค ์ˆ˜๋Ÿ‰์ด ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•œ ๊ฒฝ์šฐ `[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` + +--- +### โœ… ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ ๊ธฐ๋Šฅ +- [x] ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ๋‚ด์— ํฌํ•จ๋œ ๊ฒฝ์šฐ๋งŒ ํ• ์ธ ์ ์šฉ +- [x] ํ”„๋กœ๋ชจ์…˜์€ ์ง€์ •๋œ ์ƒํ’ˆ์—๋งŒ ์ ์šฉ +- [x] ๋™์ผ ์ƒํ’ˆ์— ์—ฌ๋Ÿฌ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ X +- [x] ํ˜œํƒ์€ ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ ์žฌ๊ณ ๋งŒ ์ ์šฉ +- [x] ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋ถ€์กฑ ์‹œ, ๋™์ผ ์ƒํ’ˆ์˜ ์ผ๋ฐ˜ ์žฌ๊ณ  ์‚ฌ์šฉ +- [x] ํ”„๋กœ๋ชจ์…˜ ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜ฌ ๋•Œ, ์ถ”๊ฐ€ ๊ตฌ๋งค ์‹œ ํ˜œํƒ ์•ˆ๋‚ด +- [x] ํ”„๋กœ๋ชจ์…˜ ์ˆ˜๋Ÿ‰๋ณด๋‹ค ๋งŽ๊ฒŒ ๊ฐ€์ ธ์˜ฌ ๋•Œ, ์ •๊ฐ€ ๊ฒฐ์ œ ์ฃผ์˜ ์•ˆ๋‚ด + +--- +### โœ… ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๊ธฐ๋Šฅ +- [x] ๋ฉค๋ฒ„์‹ญ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ์ƒํ’ˆ์˜ `30%` ํ• ์ธ +- [x] ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ํ›„, ๋‚จ์€ ๊ธˆ์•ก์— ๋Œ€ํ•œ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ +- [x] ํ• ์ธ ์ตœ๋Œ€ ํ•œ๋„ `8,000`์› +- [x] `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ํ• ์ธ ์ ์šฉ ํ›„ `๋‚ด์‹ค๋ˆ` ๊ธˆ์•ก์ด ์Œ์ˆ˜๋ฉด 0์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. + +--- +### โœ… ์˜์ˆ˜์ฆ ์ถœ๋ ฅ ๊ธฐ๋Šฅ +- [x] ๊ตฌ๋งค ๋‚ด์—ญ๊ณผ ํ• ์ธ์„ ์ถœ๋ ฅ + - ๊ตฌ๋งค ๋‚ด์—ญ : ์ƒํ’ˆ๋ช…, ์ˆ˜๋Ÿ‰, ๊ฐ€๊ฒฉ + - ์ฆ์ • ์ƒํ’ˆ ๋‚ด์—ญ : ํ”„๋กœ๋ชจ์…˜ ์ฆ์ • ์ƒํ’ˆ + - ๊ธˆ์•ก ์ •๋ณด + - ์ด๊ตฌ๋งค์•ก : ์ƒํ’ˆ์˜ ์ด ์ˆ˜๋Ÿ‰๊ณผ ๊ธˆ์•ก + - ํ–‰์‚ฌํ• ์ธ : ํ”„๋กœ๋ชจ์…˜์œผ๋กœ ํ• ์ธ๋œ ๊ธˆ์•ก + - ๋ฉค๋ฒ„์‹ญํ• ์ธ : ๋ฉค๋ฒ„์‹ญ์œผ๋กœ ํ• ์ธ๋œ ๊ธˆ์•ก + - ๋‚ด์‹ค๋ˆ : ์ตœ์ข… ๊ฒฐ์ œ ๊ธˆ์•ก +- [x] ์˜์ˆ˜์ฆ ๊ตฌ์„ฑ ์š”์†Œ ์ •๋ ฌ +``` +ex) +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์ฝœ๋ผ 10 10,000 +=============์ฆ ์ •=============== +์ฝœ๋ผ 2 +==================================== +์ด๊ตฌ๋งค์•ก 10 10,000 +ํ–‰์‚ฌํ• ์ธ -2,000 +๋ฉค๋ฒ„์‹ญํ• ์ธ -0 +๋‚ด์‹ค๋ˆ 8,000 +``` + +--- +### โœ… ๊ทธ ์™ธ ๊ธฐ๋Šฅ +- [x] ์˜์ˆ˜์ฆ ์ถœ๋ ฅ ํ›„ ์žฌ์‹œ์ž‘ ์—ฌ๋ถ€ ํ™•์ธ + +--- +### โœ… ์—๋Ÿฌ ์ฒ˜๋ฆฌ +- [x] ์ž˜๋ชป๋œ ๊ฐ’ ์ž…๋ ฅ ์‹œ `[ERROR] ` ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ ํ›„, ๋‹ค์‹œ ์ž…๋ ฅ +- [x] `Exception`์ด ์•„๋‹Œ, `IllegalArgumentException`์™€ `IllegalStateException` ๋ช…ํ™•ํ•œ ์œ ํ˜•์œผ๋กœ ์ฒ˜๋ฆฌ + +--- +### โœ… ์ž…๋ ฅ +- [x] ๊ตฌ๋งค ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ +``` +ex) +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์ฝœ๋ผ-10],[์‚ฌ์ด๋‹ค-3] +``` + +- [x] ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ๊ฐ€๋Šฅํ•œ ์ถ”๊ฐ€ ์ˆ˜๋Ÿ‰ ์—ฌ๋ถ€ +``` +ex) +ํ˜„์žฌ ์˜ค๋ Œ์ง€์ฃผ์Šค์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y +``` +- [x] ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ๋ถˆ๊ฐ€๋Šฅํ•œ ์ˆ˜๋Ÿ‰์˜ ์ •๊ฐ€ ๊ฒฐ์ œ ์—ฌ๋ถ€ +``` +ํ˜„์žฌ ์ฝœ๋ผ 4๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y +``` +- [x] ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ ์—ฌ๋ถ€ +``` +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y +``` +- [x] ์ถ”๊ฐ€ ๊ตฌ๋งค ์—ฌ๋ถ€ +``` +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +N +``` +- `์˜ˆ์™ธ์ฒ˜๋ฆฌ` ์ž˜๋ชป๋œ ์ž…๋ ฅ์˜ ๊ฒฝ์šฐ `[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` + +--- +### โœ… ์ถœ๋ ฅ +- [x] ํ™˜์˜ ์ธ์‚ฌ ์ถœ๋ ฅ `ex) ์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.` +- [x] ๋ณด์œ  ๋ฌผํ’ˆ ์•ˆ๋‚ด ์ถœ๋ ฅ `ex) ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค.` +- [x] ๋ณด์œ  ๋ฌผํ’ˆ ์ถœ๋ ฅ +``` +ex) +- ์ฝœ๋ผ 1,000์› 10๊ฐœ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 10๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› 5๊ฐœ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ +``` +- [x] ๊ตฌ๋งค, ์ฆ์ • ์ƒํ’ˆ ๋‚ด์—ญ - ๊ธˆ์•ก ์ •๋ณด ์ถœ๋ ฅ +``` +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์ฝœ๋ผ 3 3,000 +์—๋„ˆ์ง€๋ฐ” 5 10,000 +=============์ฆ ์ •=============== +์ฝœ๋ผ 1 +==================================== +์ด๊ตฌ๋งค์•ก 8 13,000 +ํ–‰์‚ฌํ• ์ธ -1,000 +๋ฉค๋ฒ„์‹ญํ• ์ธ -3,000 +๋‚ด์‹ค๋ˆ 9,000 +``` + +--- +### โœ… ์‹คํ–‰ ๊ฒฐ๊ณผ +``` +์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. +ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + +- ์ฝœ๋ผ 1,000์› 10๊ฐœ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 10๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› 5๊ฐœ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์ฝœ๋ผ-3],[์—๋„ˆ์ง€๋ฐ”-5] + +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์ฝœ๋ผ 3 3,000 +์—๋„ˆ์ง€๋ฐ” 5 10,000 +=============์ฆ ์ •=============== +์ฝœ๋ผ 1 +==================================== +์ด๊ตฌ๋งค์•ก 8 13,000 +ํ–‰์‚ฌํ• ์ธ -1,000 +๋ฉค๋ฒ„์‹ญํ• ์ธ -3,000 +๋‚ด์‹ค๋ˆ 9,000 + +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +Y + +์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. +ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + +- ์ฝœ๋ผ 1,000์› 7๊ฐœ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 10๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› ์žฌ๊ณ  ์—†์Œ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์ฝœ๋ผ-10] + +ํ˜„์žฌ ์ฝœ๋ผ 4๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +N + +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์ฝœ๋ผ 10 10,000 +=============์ฆ ์ •=============== +์ฝœ๋ผ 2 +==================================== +์ด๊ตฌ๋งค์•ก 10 10,000 +ํ–‰์‚ฌํ• ์ธ -2,000 +๋ฉค๋ฒ„์‹ญํ• ์ธ -0 +๋‚ด์‹ค๋ˆ 8,000 + +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +Y + +์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. +ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + +- ์ฝœ๋ผ 1,000์› ์žฌ๊ณ  ์—†์Œ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 7๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› ์žฌ๊ณ  ์—†์Œ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์˜ค๋ Œ์ง€์ฃผ์Šค-1] + +ํ˜„์žฌ ์˜ค๋ Œ์ง€์ฃผ์Šค์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์˜ค๋ Œ์ง€์ฃผ์Šค 2 3,600 +=============์ฆ ์ •=============== +์˜ค๋ Œ์ง€์ฃผ์Šค 1 +==================================== +์ด๊ตฌ๋งค์•ก 2 3,600 +ํ–‰์‚ฌํ• ์ธ -1,800 +๋ฉค๋ฒ„์‹ญํ• ์ธ -0 +๋‚ด์‹ค๋ˆ 1,800 + +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +N +``` \ No newline at end of file
Unknown
์ƒ๊ฐํ•˜๊ธฐ ์‰ฝ์ง€ ์•Š์„ ์ˆ˜ ์žˆ๋Š” ์—ฃ์ง€ ์ผ€์ด์Šค์˜€์„ํ…๋ฐ ์ž˜ ์งš์œผ์…จ๋„ค์š”!
@@ -0,0 +1,223 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import store.domain.PaymentProductList; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.PromotionsList; +import store.domain.PurchaseProduct; +import store.global.util.ProductParser; +import store.global.util.PromotionParser; +import store.global.util.PurchaseParser; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final OutputView outputView; + private final InputView inputView; + + public StoreController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } + + public void run() { + Products products = loadStoreFiles(); + + do { + displayWelcome(products); + List<PurchaseProduct> purchases = handlePurchases(products); + PaymentProductList paymentProductList = processPurchases(purchases); + + displayPaymentInfo(paymentProductList); + } while (readAdditionalPurchaseConfirmationWithRetry()); + } + + private void displayWelcome(Products products) { + displayWelcomeMessage(); + displayProductsInfo(products); + } + + private Products loadStoreFiles() { + PromotionsList promotionsList = loadPromotions(); + return loadProducts(promotionsList); + } + + private PaymentProductList processPurchases(List<PurchaseProduct> purchases) { + PaymentProductList paymentProductList = new PaymentProductList(); + LocalDateTime now = DateTimes.now(); + + for (PurchaseProduct purchase : purchases) { + processSinglePurchase(paymentProductList, purchase, now); + } + + decreaseProductStock(purchases, paymentProductList); + applyMembershipDiscountIfConfirmed(paymentProductList); + return paymentProductList; + } + + private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) { + List<Integer> quantities = paymentProductList.getAllProductQuantities(); + for (int i = 0; i < purchases.size(); i++) { + purchases.get(i).reduceProductStock(quantities.get(i)); + } + } + + private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase, + LocalDateTime now) { + if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) { + handlePromotionProduct(paymentProductList, purchase); + return; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0)); + } + + + private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) { + int remainingStock = purchase.getRemainingStock(); + if (remainingStock > 0) { + handleRemainingStock(paymentProductList, purchase, remainingStock); + return; + } + if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) { + handleNonZeroRemainingStock(paymentProductList, purchase); + return; + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase, + int remainingStock) { + int quantity = calculateQuantity(purchase, remainingStock); + + if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) { + purchase.decrease(quantity); + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1)); + } + + private int calculateQuantity(PurchaseProduct purchase, int remainingStock) { + int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock)); + return remainingStock + promotionRate; + } + + private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) { + boolean answer = confirmPromotionAddition(purchase.getProductName()); + int promotionUnits = purchase.getPromotionUnits(); + if (answer) { + purchase.increaseQuantityForPromotion(); + promotionUnits += 1; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void displayPaymentInfo(PaymentProductList paymentProductList) { + List<String> productInfos = paymentProductList.infoProduct(); + List<String> promotionInfos = paymentProductList.infoPromotion(); + List<String> finalResults = paymentProductList.finalResult(); + + outputView.printPaymentInfoResult(productInfos); + outputView.printPromotionInfoResult(promotionInfos); + outputView.printFinalResult(finalResults); + } + + private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) { + if (readMembershipConfirmationWithRetry()) { + paymentProductList.applyMembershipDiscount(); + } + } + + private void displayWelcomeMessage() { + outputView.printWelcomeMessage(); + } + + private PromotionsList loadPromotions() { + List<List<String>> inputPromotions = inputView.readPromotionsData(); + List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions); + return new PromotionsList(promotionsList1); + } + + private Products loadProducts(PromotionsList promotionsList) { + List<List<String>> inputProducts = inputView.readProductsData(); + List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList); + return new Products(productList); + } + + private void displayProductsInfo(Products products) { + outputView.printProductsInfo(products.getAllProductsInfo()); + } + + private List<PurchaseProduct> handlePurchases(Products products) { + while (true) { + try { + Map<String, Integer> purchases = readAndParsePurchaseInput(); + return processPurchases(products, purchases); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private Map<String, Integer> readAndParsePurchaseInput() { + String input = inputView.readPurchaseInput(); + return PurchaseParser.parseInputProduct(input); + } + + private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) { + List<PurchaseProduct> purchaseProducts = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : purchases.entrySet()) { + List<Product> foundProducts = products.findProductByName(entry.getKey()); + purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue())); + } + return purchaseProducts; + } + + private boolean confirmPromotionNotApplied(String productName, int quantity) { + while (true) { + try { + outputView.printPromotionNotApplied(productName, quantity); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean confirmPromotionAddition(String productName) { + while (true) { + try { + outputView.printPromotionAddition(productName); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readMembershipConfirmationWithRetry() { + while (true) { + try { + return inputView.readMembershipConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readAdditionalPurchaseConfirmationWithRetry() { + while (true) { + try { + return inputView.readAdditionalPurchaseConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } +}
Java
do {} while์ด ์ž์ฃผ ์•ˆ ์“ฐ์ด๋Š” ๊ตฌ๋ฌธ์ด๋ผ์„œ ์‚ฌ์šฉ ํ•  ์ƒ๊ฐ์„ ํ•˜๋Š”๊ฒƒ์ด ์‰ฝ์ง€ ์•Š์œผ์…จ์„ํ…๋ฐ ์ด๊ฒƒ๋„ ์ž˜ ํ•˜์…จ๋„ค์š”!
@@ -0,0 +1,223 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import store.domain.PaymentProductList; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.PromotionsList; +import store.domain.PurchaseProduct; +import store.global.util.ProductParser; +import store.global.util.PromotionParser; +import store.global.util.PurchaseParser; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final OutputView outputView; + private final InputView inputView; + + public StoreController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } + + public void run() { + Products products = loadStoreFiles(); + + do { + displayWelcome(products); + List<PurchaseProduct> purchases = handlePurchases(products); + PaymentProductList paymentProductList = processPurchases(purchases); + + displayPaymentInfo(paymentProductList); + } while (readAdditionalPurchaseConfirmationWithRetry()); + } + + private void displayWelcome(Products products) { + displayWelcomeMessage(); + displayProductsInfo(products); + } + + private Products loadStoreFiles() { + PromotionsList promotionsList = loadPromotions(); + return loadProducts(promotionsList); + } + + private PaymentProductList processPurchases(List<PurchaseProduct> purchases) { + PaymentProductList paymentProductList = new PaymentProductList(); + LocalDateTime now = DateTimes.now(); + + for (PurchaseProduct purchase : purchases) { + processSinglePurchase(paymentProductList, purchase, now); + } + + decreaseProductStock(purchases, paymentProductList); + applyMembershipDiscountIfConfirmed(paymentProductList); + return paymentProductList; + } + + private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) { + List<Integer> quantities = paymentProductList.getAllProductQuantities(); + for (int i = 0; i < purchases.size(); i++) { + purchases.get(i).reduceProductStock(quantities.get(i)); + } + } + + private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase, + LocalDateTime now) { + if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) { + handlePromotionProduct(paymentProductList, purchase); + return; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0)); + } + + + private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) { + int remainingStock = purchase.getRemainingStock(); + if (remainingStock > 0) { + handleRemainingStock(paymentProductList, purchase, remainingStock); + return; + } + if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) { + handleNonZeroRemainingStock(paymentProductList, purchase); + return; + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase, + int remainingStock) { + int quantity = calculateQuantity(purchase, remainingStock); + + if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) { + purchase.decrease(quantity); + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1)); + } + + private int calculateQuantity(PurchaseProduct purchase, int remainingStock) { + int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock)); + return remainingStock + promotionRate; + } + + private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) { + boolean answer = confirmPromotionAddition(purchase.getProductName()); + int promotionUnits = purchase.getPromotionUnits(); + if (answer) { + purchase.increaseQuantityForPromotion(); + promotionUnits += 1; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void displayPaymentInfo(PaymentProductList paymentProductList) { + List<String> productInfos = paymentProductList.infoProduct(); + List<String> promotionInfos = paymentProductList.infoPromotion(); + List<String> finalResults = paymentProductList.finalResult(); + + outputView.printPaymentInfoResult(productInfos); + outputView.printPromotionInfoResult(promotionInfos); + outputView.printFinalResult(finalResults); + } + + private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) { + if (readMembershipConfirmationWithRetry()) { + paymentProductList.applyMembershipDiscount(); + } + } + + private void displayWelcomeMessage() { + outputView.printWelcomeMessage(); + } + + private PromotionsList loadPromotions() { + List<List<String>> inputPromotions = inputView.readPromotionsData(); + List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions); + return new PromotionsList(promotionsList1); + } + + private Products loadProducts(PromotionsList promotionsList) { + List<List<String>> inputProducts = inputView.readProductsData(); + List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList); + return new Products(productList); + } + + private void displayProductsInfo(Products products) { + outputView.printProductsInfo(products.getAllProductsInfo()); + } + + private List<PurchaseProduct> handlePurchases(Products products) { + while (true) { + try { + Map<String, Integer> purchases = readAndParsePurchaseInput(); + return processPurchases(products, purchases); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private Map<String, Integer> readAndParsePurchaseInput() { + String input = inputView.readPurchaseInput(); + return PurchaseParser.parseInputProduct(input); + } + + private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) { + List<PurchaseProduct> purchaseProducts = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : purchases.entrySet()) { + List<Product> foundProducts = products.findProductByName(entry.getKey()); + purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue())); + } + return purchaseProducts; + } + + private boolean confirmPromotionNotApplied(String productName, int quantity) { + while (true) { + try { + outputView.printPromotionNotApplied(productName, quantity); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean confirmPromotionAddition(String productName) { + while (true) { + try { + outputView.printPromotionAddition(productName); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readMembershipConfirmationWithRetry() { + while (true) { + try { + return inputView.readMembershipConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readAdditionalPurchaseConfirmationWithRetry() { + while (true) { + try { + return inputView.readAdditionalPurchaseConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } +}
Java
```java private <T> T process(Supplier<T> supplier) { while (true) { try { return supplier.get(); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); } } } process(inputView::read~~); //ํ˜ธ์ถœ ``` ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค์™€ ์ œ๋„ค๋ฆญ์„ ํ™œ์šฉํ•˜๋ฉด ์ค‘๋ณต์„ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,223 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import store.domain.PaymentProductList; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.PromotionsList; +import store.domain.PurchaseProduct; +import store.global.util.ProductParser; +import store.global.util.PromotionParser; +import store.global.util.PurchaseParser; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final OutputView outputView; + private final InputView inputView; + + public StoreController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } + + public void run() { + Products products = loadStoreFiles(); + + do { + displayWelcome(products); + List<PurchaseProduct> purchases = handlePurchases(products); + PaymentProductList paymentProductList = processPurchases(purchases); + + displayPaymentInfo(paymentProductList); + } while (readAdditionalPurchaseConfirmationWithRetry()); + } + + private void displayWelcome(Products products) { + displayWelcomeMessage(); + displayProductsInfo(products); + } + + private Products loadStoreFiles() { + PromotionsList promotionsList = loadPromotions(); + return loadProducts(promotionsList); + } + + private PaymentProductList processPurchases(List<PurchaseProduct> purchases) { + PaymentProductList paymentProductList = new PaymentProductList(); + LocalDateTime now = DateTimes.now(); + + for (PurchaseProduct purchase : purchases) { + processSinglePurchase(paymentProductList, purchase, now); + } + + decreaseProductStock(purchases, paymentProductList); + applyMembershipDiscountIfConfirmed(paymentProductList); + return paymentProductList; + } + + private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) { + List<Integer> quantities = paymentProductList.getAllProductQuantities(); + for (int i = 0; i < purchases.size(); i++) { + purchases.get(i).reduceProductStock(quantities.get(i)); + } + } + + private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase, + LocalDateTime now) { + if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) { + handlePromotionProduct(paymentProductList, purchase); + return; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0)); + } + + + private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) { + int remainingStock = purchase.getRemainingStock(); + if (remainingStock > 0) { + handleRemainingStock(paymentProductList, purchase, remainingStock); + return; + } + if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) { + handleNonZeroRemainingStock(paymentProductList, purchase); + return; + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase, + int remainingStock) { + int quantity = calculateQuantity(purchase, remainingStock); + + if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) { + purchase.decrease(quantity); + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1)); + } + + private int calculateQuantity(PurchaseProduct purchase, int remainingStock) { + int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock)); + return remainingStock + promotionRate; + } + + private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) { + boolean answer = confirmPromotionAddition(purchase.getProductName()); + int promotionUnits = purchase.getPromotionUnits(); + if (answer) { + purchase.increaseQuantityForPromotion(); + promotionUnits += 1; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void displayPaymentInfo(PaymentProductList paymentProductList) { + List<String> productInfos = paymentProductList.infoProduct(); + List<String> promotionInfos = paymentProductList.infoPromotion(); + List<String> finalResults = paymentProductList.finalResult(); + + outputView.printPaymentInfoResult(productInfos); + outputView.printPromotionInfoResult(promotionInfos); + outputView.printFinalResult(finalResults); + } + + private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) { + if (readMembershipConfirmationWithRetry()) { + paymentProductList.applyMembershipDiscount(); + } + } + + private void displayWelcomeMessage() { + outputView.printWelcomeMessage(); + } + + private PromotionsList loadPromotions() { + List<List<String>> inputPromotions = inputView.readPromotionsData(); + List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions); + return new PromotionsList(promotionsList1); + } + + private Products loadProducts(PromotionsList promotionsList) { + List<List<String>> inputProducts = inputView.readProductsData(); + List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList); + return new Products(productList); + } + + private void displayProductsInfo(Products products) { + outputView.printProductsInfo(products.getAllProductsInfo()); + } + + private List<PurchaseProduct> handlePurchases(Products products) { + while (true) { + try { + Map<String, Integer> purchases = readAndParsePurchaseInput(); + return processPurchases(products, purchases); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private Map<String, Integer> readAndParsePurchaseInput() { + String input = inputView.readPurchaseInput(); + return PurchaseParser.parseInputProduct(input); + } + + private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) { + List<PurchaseProduct> purchaseProducts = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : purchases.entrySet()) { + List<Product> foundProducts = products.findProductByName(entry.getKey()); + purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue())); + } + return purchaseProducts; + } + + private boolean confirmPromotionNotApplied(String productName, int quantity) { + while (true) { + try { + outputView.printPromotionNotApplied(productName, quantity); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean confirmPromotionAddition(String productName) { + while (true) { + try { + outputView.printPromotionAddition(productName); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readMembershipConfirmationWithRetry() { + while (true) { + try { + return inputView.readMembershipConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readAdditionalPurchaseConfirmationWithRetry() { + while (true) { + try { + return inputView.readAdditionalPurchaseConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } +}
Java
์ด ๋‘๊ฐœ์˜ ๋ฉ”์„œ๋“œ๋ฅผ, purchase.canApplyPromotion() ์œผ๋กœ ๋ฌถ๋Š” ๊ฒƒ๋„ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๋Š”๋ฐ์— ์ข‹์•„ ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,223 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import store.domain.PaymentProductList; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.PromotionsList; +import store.domain.PurchaseProduct; +import store.global.util.ProductParser; +import store.global.util.PromotionParser; +import store.global.util.PurchaseParser; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final OutputView outputView; + private final InputView inputView; + + public StoreController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } + + public void run() { + Products products = loadStoreFiles(); + + do { + displayWelcome(products); + List<PurchaseProduct> purchases = handlePurchases(products); + PaymentProductList paymentProductList = processPurchases(purchases); + + displayPaymentInfo(paymentProductList); + } while (readAdditionalPurchaseConfirmationWithRetry()); + } + + private void displayWelcome(Products products) { + displayWelcomeMessage(); + displayProductsInfo(products); + } + + private Products loadStoreFiles() { + PromotionsList promotionsList = loadPromotions(); + return loadProducts(promotionsList); + } + + private PaymentProductList processPurchases(List<PurchaseProduct> purchases) { + PaymentProductList paymentProductList = new PaymentProductList(); + LocalDateTime now = DateTimes.now(); + + for (PurchaseProduct purchase : purchases) { + processSinglePurchase(paymentProductList, purchase, now); + } + + decreaseProductStock(purchases, paymentProductList); + applyMembershipDiscountIfConfirmed(paymentProductList); + return paymentProductList; + } + + private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) { + List<Integer> quantities = paymentProductList.getAllProductQuantities(); + for (int i = 0; i < purchases.size(); i++) { + purchases.get(i).reduceProductStock(quantities.get(i)); + } + } + + private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase, + LocalDateTime now) { + if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) { + handlePromotionProduct(paymentProductList, purchase); + return; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0)); + } + + + private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) { + int remainingStock = purchase.getRemainingStock(); + if (remainingStock > 0) { + handleRemainingStock(paymentProductList, purchase, remainingStock); + return; + } + if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) { + handleNonZeroRemainingStock(paymentProductList, purchase); + return; + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase, + int remainingStock) { + int quantity = calculateQuantity(purchase, remainingStock); + + if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) { + purchase.decrease(quantity); + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1)); + } + + private int calculateQuantity(PurchaseProduct purchase, int remainingStock) { + int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock)); + return remainingStock + promotionRate; + } + + private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) { + boolean answer = confirmPromotionAddition(purchase.getProductName()); + int promotionUnits = purchase.getPromotionUnits(); + if (answer) { + purchase.increaseQuantityForPromotion(); + promotionUnits += 1; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void displayPaymentInfo(PaymentProductList paymentProductList) { + List<String> productInfos = paymentProductList.infoProduct(); + List<String> promotionInfos = paymentProductList.infoPromotion(); + List<String> finalResults = paymentProductList.finalResult(); + + outputView.printPaymentInfoResult(productInfos); + outputView.printPromotionInfoResult(promotionInfos); + outputView.printFinalResult(finalResults); + } + + private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) { + if (readMembershipConfirmationWithRetry()) { + paymentProductList.applyMembershipDiscount(); + } + } + + private void displayWelcomeMessage() { + outputView.printWelcomeMessage(); + } + + private PromotionsList loadPromotions() { + List<List<String>> inputPromotions = inputView.readPromotionsData(); + List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions); + return new PromotionsList(promotionsList1); + } + + private Products loadProducts(PromotionsList promotionsList) { + List<List<String>> inputProducts = inputView.readProductsData(); + List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList); + return new Products(productList); + } + + private void displayProductsInfo(Products products) { + outputView.printProductsInfo(products.getAllProductsInfo()); + } + + private List<PurchaseProduct> handlePurchases(Products products) { + while (true) { + try { + Map<String, Integer> purchases = readAndParsePurchaseInput(); + return processPurchases(products, purchases); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private Map<String, Integer> readAndParsePurchaseInput() { + String input = inputView.readPurchaseInput(); + return PurchaseParser.parseInputProduct(input); + } + + private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) { + List<PurchaseProduct> purchaseProducts = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : purchases.entrySet()) { + List<Product> foundProducts = products.findProductByName(entry.getKey()); + purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue())); + } + return purchaseProducts; + } + + private boolean confirmPromotionNotApplied(String productName, int quantity) { + while (true) { + try { + outputView.printPromotionNotApplied(productName, quantity); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean confirmPromotionAddition(String productName) { + while (true) { + try { + outputView.printPromotionAddition(productName); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readMembershipConfirmationWithRetry() { + while (true) { + try { + return inputView.readMembershipConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readAdditionalPurchaseConfirmationWithRetry() { + while (true) { + try { + return inputView.readAdditionalPurchaseConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } +}
Java
StoreController์„ ์ญ‰ ์ฝ์œผ๋ฉฐ ๋“  ์ƒ๊ฐ์ด, ๋ฌผ๋ก  ์‹œ๊ฐ„์ด ์ด‰๋ฐ•ํ–ˆ๊ณ  ์–ด์ฉ” ์ˆ˜ ์—†์—ˆ์ง€๋งŒ ์ปจํŠธ๋กค๋Ÿฌ์— ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„๊ณผ ๊ตฌํ˜„์ด ์ง‘์ค‘๋˜์–ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ปจํŠธ๋กค๋Ÿฌ๋Š” ์ •๋ง ๋‹จ์ˆœํ•œ ์ œ์–ด ์—ญํ• ์„ ํ•˜๊ณ , ๋น„์ฆˆ๋‹ˆ์Šค๊ฐ€ ํฌํ•จ๋œ ๊ตฌํ˜„ ๋ถ€๋ถ„์€ Service ๋ ˆ์ด์–ด๋กœ ๋”ฐ๋กœ ๋นผ๋Š” ๋ฐฉ๋ฒ•์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,223 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import store.domain.PaymentProductList; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.PromotionsList; +import store.domain.PurchaseProduct; +import store.global.util.ProductParser; +import store.global.util.PromotionParser; +import store.global.util.PurchaseParser; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final OutputView outputView; + private final InputView inputView; + + public StoreController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } + + public void run() { + Products products = loadStoreFiles(); + + do { + displayWelcome(products); + List<PurchaseProduct> purchases = handlePurchases(products); + PaymentProductList paymentProductList = processPurchases(purchases); + + displayPaymentInfo(paymentProductList); + } while (readAdditionalPurchaseConfirmationWithRetry()); + } + + private void displayWelcome(Products products) { + displayWelcomeMessage(); + displayProductsInfo(products); + } + + private Products loadStoreFiles() { + PromotionsList promotionsList = loadPromotions(); + return loadProducts(promotionsList); + } + + private PaymentProductList processPurchases(List<PurchaseProduct> purchases) { + PaymentProductList paymentProductList = new PaymentProductList(); + LocalDateTime now = DateTimes.now(); + + for (PurchaseProduct purchase : purchases) { + processSinglePurchase(paymentProductList, purchase, now); + } + + decreaseProductStock(purchases, paymentProductList); + applyMembershipDiscountIfConfirmed(paymentProductList); + return paymentProductList; + } + + private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) { + List<Integer> quantities = paymentProductList.getAllProductQuantities(); + for (int i = 0; i < purchases.size(); i++) { + purchases.get(i).reduceProductStock(quantities.get(i)); + } + } + + private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase, + LocalDateTime now) { + if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) { + handlePromotionProduct(paymentProductList, purchase); + return; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0)); + } + + + private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) { + int remainingStock = purchase.getRemainingStock(); + if (remainingStock > 0) { + handleRemainingStock(paymentProductList, purchase, remainingStock); + return; + } + if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) { + handleNonZeroRemainingStock(paymentProductList, purchase); + return; + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase, + int remainingStock) { + int quantity = calculateQuantity(purchase, remainingStock); + + if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) { + purchase.decrease(quantity); + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1)); + } + + private int calculateQuantity(PurchaseProduct purchase, int remainingStock) { + int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock)); + return remainingStock + promotionRate; + } + + private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) { + boolean answer = confirmPromotionAddition(purchase.getProductName()); + int promotionUnits = purchase.getPromotionUnits(); + if (answer) { + purchase.increaseQuantityForPromotion(); + promotionUnits += 1; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void displayPaymentInfo(PaymentProductList paymentProductList) { + List<String> productInfos = paymentProductList.infoProduct(); + List<String> promotionInfos = paymentProductList.infoPromotion(); + List<String> finalResults = paymentProductList.finalResult(); + + outputView.printPaymentInfoResult(productInfos); + outputView.printPromotionInfoResult(promotionInfos); + outputView.printFinalResult(finalResults); + } + + private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) { + if (readMembershipConfirmationWithRetry()) { + paymentProductList.applyMembershipDiscount(); + } + } + + private void displayWelcomeMessage() { + outputView.printWelcomeMessage(); + } + + private PromotionsList loadPromotions() { + List<List<String>> inputPromotions = inputView.readPromotionsData(); + List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions); + return new PromotionsList(promotionsList1); + } + + private Products loadProducts(PromotionsList promotionsList) { + List<List<String>> inputProducts = inputView.readProductsData(); + List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList); + return new Products(productList); + } + + private void displayProductsInfo(Products products) { + outputView.printProductsInfo(products.getAllProductsInfo()); + } + + private List<PurchaseProduct> handlePurchases(Products products) { + while (true) { + try { + Map<String, Integer> purchases = readAndParsePurchaseInput(); + return processPurchases(products, purchases); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private Map<String, Integer> readAndParsePurchaseInput() { + String input = inputView.readPurchaseInput(); + return PurchaseParser.parseInputProduct(input); + } + + private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) { + List<PurchaseProduct> purchaseProducts = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : purchases.entrySet()) { + List<Product> foundProducts = products.findProductByName(entry.getKey()); + purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue())); + } + return purchaseProducts; + } + + private boolean confirmPromotionNotApplied(String productName, int quantity) { + while (true) { + try { + outputView.printPromotionNotApplied(productName, quantity); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean confirmPromotionAddition(String productName) { + while (true) { + try { + outputView.printPromotionAddition(productName); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readMembershipConfirmationWithRetry() { + while (true) { + try { + return inputView.readMembershipConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readAdditionalPurchaseConfirmationWithRetry() { + while (true) { + try { + return inputView.readAdditionalPurchaseConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } +}
Java
๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ด ์ปจํŠธ๋กค๋Ÿฌ์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๊ฒƒ์€ ์ด์ƒํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ปจํŠธ๋กค๋Ÿฌ์™€ ์„œ๋น„์Šค๋ฅผ ๋ถ„๋ฆฌํ–ˆ๋‹ค๋ฉด ๋” ๋‚˜์€ ์ฝ”๋“œ๊ฐ€ ๋˜์—ˆ์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,223 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import store.domain.PaymentProductList; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.PromotionsList; +import store.domain.PurchaseProduct; +import store.global.util.ProductParser; +import store.global.util.PromotionParser; +import store.global.util.PurchaseParser; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final OutputView outputView; + private final InputView inputView; + + public StoreController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } + + public void run() { + Products products = loadStoreFiles(); + + do { + displayWelcome(products); + List<PurchaseProduct> purchases = handlePurchases(products); + PaymentProductList paymentProductList = processPurchases(purchases); + + displayPaymentInfo(paymentProductList); + } while (readAdditionalPurchaseConfirmationWithRetry()); + } + + private void displayWelcome(Products products) { + displayWelcomeMessage(); + displayProductsInfo(products); + } + + private Products loadStoreFiles() { + PromotionsList promotionsList = loadPromotions(); + return loadProducts(promotionsList); + } + + private PaymentProductList processPurchases(List<PurchaseProduct> purchases) { + PaymentProductList paymentProductList = new PaymentProductList(); + LocalDateTime now = DateTimes.now(); + + for (PurchaseProduct purchase : purchases) { + processSinglePurchase(paymentProductList, purchase, now); + } + + decreaseProductStock(purchases, paymentProductList); + applyMembershipDiscountIfConfirmed(paymentProductList); + return paymentProductList; + } + + private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) { + List<Integer> quantities = paymentProductList.getAllProductQuantities(); + for (int i = 0; i < purchases.size(); i++) { + purchases.get(i).reduceProductStock(quantities.get(i)); + } + } + + private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase, + LocalDateTime now) { + if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) { + handlePromotionProduct(paymentProductList, purchase); + return; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0)); + } + + + private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) { + int remainingStock = purchase.getRemainingStock(); + if (remainingStock > 0) { + handleRemainingStock(paymentProductList, purchase, remainingStock); + return; + } + if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) { + handleNonZeroRemainingStock(paymentProductList, purchase); + return; + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase, + int remainingStock) { + int quantity = calculateQuantity(purchase, remainingStock); + + if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) { + purchase.decrease(quantity); + } + int promotionUnits = purchase.getPromotionUnits(); + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1)); + } + + private int calculateQuantity(PurchaseProduct purchase, int remainingStock) { + int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock)); + return remainingStock + promotionRate; + } + + private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) { + boolean answer = confirmPromotionAddition(purchase.getProductName()); + int promotionUnits = purchase.getPromotionUnits(); + if (answer) { + purchase.increaseQuantityForPromotion(); + promotionUnits += 1; + } + paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits)); + } + + private void displayPaymentInfo(PaymentProductList paymentProductList) { + List<String> productInfos = paymentProductList.infoProduct(); + List<String> promotionInfos = paymentProductList.infoPromotion(); + List<String> finalResults = paymentProductList.finalResult(); + + outputView.printPaymentInfoResult(productInfos); + outputView.printPromotionInfoResult(promotionInfos); + outputView.printFinalResult(finalResults); + } + + private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) { + if (readMembershipConfirmationWithRetry()) { + paymentProductList.applyMembershipDiscount(); + } + } + + private void displayWelcomeMessage() { + outputView.printWelcomeMessage(); + } + + private PromotionsList loadPromotions() { + List<List<String>> inputPromotions = inputView.readPromotionsData(); + List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions); + return new PromotionsList(promotionsList1); + } + + private Products loadProducts(PromotionsList promotionsList) { + List<List<String>> inputProducts = inputView.readProductsData(); + List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList); + return new Products(productList); + } + + private void displayProductsInfo(Products products) { + outputView.printProductsInfo(products.getAllProductsInfo()); + } + + private List<PurchaseProduct> handlePurchases(Products products) { + while (true) { + try { + Map<String, Integer> purchases = readAndParsePurchaseInput(); + return processPurchases(products, purchases); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private Map<String, Integer> readAndParsePurchaseInput() { + String input = inputView.readPurchaseInput(); + return PurchaseParser.parseInputProduct(input); + } + + private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) { + List<PurchaseProduct> purchaseProducts = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : purchases.entrySet()) { + List<Product> foundProducts = products.findProductByName(entry.getKey()); + purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue())); + } + return purchaseProducts; + } + + private boolean confirmPromotionNotApplied(String productName, int quantity) { + while (true) { + try { + outputView.printPromotionNotApplied(productName, quantity); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean confirmPromotionAddition(String productName) { + while (true) { + try { + outputView.printPromotionAddition(productName); + return inputView.readYesOrNoInput(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readMembershipConfirmationWithRetry() { + while (true) { + try { + return inputView.readMembershipConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } + + private boolean readAdditionalPurchaseConfirmationWithRetry() { + while (true) { + try { + return inputView.readAdditionalPurchaseConfirmation(); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e.getMessage()); + } + } + } +}
Java
์ด๋Ÿฐ ๋ถ€๋ถ„๋„ remainingStock์ด๋ผ๋Š” ๋กœ์ปฌ ๋ณ€์ˆ˜๊ฐ€ ์‚ฌ์‹ค purchase์˜ ํ•„๋“œ๋‹ˆ๊นŒ if๋ฌธ์˜ &&๋ฅผ ์—†์• ๊ณ  purchase์˜ ํ•˜๋‚˜์˜ ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด๋‚ด๋Š” ์ชฝ์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค๋ฉด ๊ฐ€๋…์„ฑ์ด ํ›จ์”ฌ ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,39 @@ +package store.domain.product; + +import static store.global.constant.ErrorMessage.INVALID_PRICE_NUMERIC; +import static store.global.constant.ErrorMessage.INVALID_PRICE_OUT_OF_RANGE; +import static store.global.validation.CommonValidator.validateNotNumeric; + +import java.text.DecimalFormat; + +public class Price { + + private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###"); + private static final int MINIMUM_PRICE = 1; + private static final int MAXIMUM_PRICE = 1_000_000; + private static final String UNIT = "์›"; + + private final int price; + + public Price(final String inputPrice) { + validateNotNumeric(inputPrice, INVALID_PRICE_NUMERIC); + int price = Integer.parseInt(inputPrice); + validateRange(price); + this.price = price; + } + + public int getPrice() { + return price; + } + + @Override + public String toString() { + return DECIMAL_FORMAT.format(price) + UNIT; + } + + private void validateRange(final int price) { + if (price < MINIMUM_PRICE || price > MAXIMUM_PRICE) { + throw new IllegalArgumentException(INVALID_PRICE_OUT_OF_RANGE.getMessage()); + } + } +}
Java
Price๊ฐ์ฒด์˜ ํ–‰์œ„๊ฐ€ ๋”ฐ๋กœ ์—†๋Š” ๊ฒƒ ๊ฐ™์•„ ๋ณด์ด๋Š”๋ฐ, ๋‹จ์ˆœํžˆ "๊ฐ€๊ฒฉ"์ด๋ผ๋Š” ๋„๋ฉ”์ธ ์ œ์•ฝ ๊ฒ€์ฆ๊ณผ, ๊ด€๋ จ๋œ ์ƒ์ˆ˜๋“ค์„ ๋ฌถ์–ด๋‘๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•˜์‹  ๊ฑด๊ฐ€์š”?