code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,86 @@ +package nextstep.subway.application; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.stream.Collectors; +import nextstep.subway.domain.Line; +import nextstep.subway.domain.LineRepository; +import nextstep.subway.domain.Station; +import nextstep.subway.domain.StationRepository; +import nextstep.subway.dto.LineCreateRequest; +import nextstep.subway.dto.LineResponse; +import nextstep.subway.dto.LineUpdateRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +public class LineService { + private final LineRepository lineRepository; + + private final StationRepository stationRepository; + + public LineService(LineRepository lineRepository, StationRepository stationRepository) { + this.lineRepository = lineRepository; + this.stationRepository = stationRepository; + } + + @Transactional + public LineResponse saveLine(LineCreateRequest lineCreateRequest) { + Line persistLine = lineRepository.save(lineCreateRequest.toLine()); + addStations(persistLine, lineCreateRequest); + return LineResponse.of(persistLine); + } + + public LineResponse findLine(Long id) { + Optional<Line> line = lineRepository.findById(id); + return LineResponse.of(line.get()); + } + + public List<LineResponse> findAllLines() { + return lineRepository.findAll().stream() + .map(LineResponse::of) + .collect(Collectors.toList()); + } + + @Transactional + public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) { + Line line = lineRepository.findById(id).get(); + line.updateLine(lineUpdateRequest); + return LineResponse.of(line); + } + + @Transactional + public void deleteLineById(Long id) { + Optional<Line> line = lineRepository.findById(id); + if (line.isPresent()) { + line.get().clearRelatedLines(); + lineRepository.delete(line.get()); + } + } + + private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) { + addUpLine(persistLine, lineCreateRequest); + addDownLine(persistLine, lineCreateRequest); + } + + private void addUpLine(Line line, LineCreateRequest lineCreateRequest) { + if (lineCreateRequest.hasUpStationsId()) { + Station station = getStation(lineCreateRequest.getUpStationId()); + line.addStation(station); + } + } + + private void addDownLine(Line line, LineCreateRequest lineCreateRequest) { + if (lineCreateRequest.hasDownStationsId()) { + Station station = getStation(lineCreateRequest.getDownStationId()); + line.addStation(station); + } + } + + private Station getStation(Long stationId) { + return stationRepository.findById(stationId) + .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์— ํ•ด๋‹นํ•˜๋Š” ์—ญ์ด ์—†์Šต๋‹ˆ๋‹ค.")); + } +}
Java
id๋กœ ๋ผ์ธ์„ ์ฐพ์•„ ์—ฐ๊ด€๊ด€๊ณ„๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋กœ์ง์„ ๋„ฃ๊ณ ์ž ํ–ˆ๋Š”๋ฐ์š”, ๋ผ์ธ์ด ์žˆ์„ ๊ฒฝ์šฐ์—๋งŒ ์ฒ˜๋ฆฌํ•˜๋ ค๋‹ค ๋ณด๋‹ˆ ๋ฐฉ์–ด์ฝ”๋“œ ์ฐจ์›์œผ๋กœ ๋„ฃ์—ˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ์—๋Š” deleteById ๋ณด๋‹ค๋Š” delete ๋ฉ”์†Œ๋“œ๊ฐ€ ๋” ์ ํ•ฉํ•ด ๋ณด์ด๋„ค์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,86 @@ +package nextstep.subway.application; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.stream.Collectors; +import nextstep.subway.domain.Line; +import nextstep.subway.domain.LineRepository; +import nextstep.subway.domain.Station; +import nextstep.subway.domain.StationRepository; +import nextstep.subway.dto.LineCreateRequest; +import nextstep.subway.dto.LineResponse; +import nextstep.subway.dto.LineUpdateRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +public class LineService { + private final LineRepository lineRepository; + + private final StationRepository stationRepository; + + public LineService(LineRepository lineRepository, StationRepository stationRepository) { + this.lineRepository = lineRepository; + this.stationRepository = stationRepository; + } + + @Transactional + public LineResponse saveLine(LineCreateRequest lineCreateRequest) { + Line persistLine = lineRepository.save(lineCreateRequest.toLine()); + addStations(persistLine, lineCreateRequest); + return LineResponse.of(persistLine); + } + + public LineResponse findLine(Long id) { + Optional<Line> line = lineRepository.findById(id); + return LineResponse.of(line.get()); + } + + public List<LineResponse> findAllLines() { + return lineRepository.findAll().stream() + .map(LineResponse::of) + .collect(Collectors.toList()); + } + + @Transactional + public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) { + Line line = lineRepository.findById(id).get(); + line.updateLine(lineUpdateRequest); + return LineResponse.of(line); + } + + @Transactional + public void deleteLineById(Long id) { + Optional<Line> line = lineRepository.findById(id); + if (line.isPresent()) { + line.get().clearRelatedLines(); + lineRepository.delete(line.get()); + } + } + + private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) { + addUpLine(persistLine, lineCreateRequest); + addDownLine(persistLine, lineCreateRequest); + } + + private void addUpLine(Line line, LineCreateRequest lineCreateRequest) { + if (lineCreateRequest.hasUpStationsId()) { + Station station = getStation(lineCreateRequest.getUpStationId()); + line.addStation(station); + } + } + + private void addDownLine(Line line, LineCreateRequest lineCreateRequest) { + if (lineCreateRequest.hasDownStationsId()) { + Station station = getStation(lineCreateRequest.getDownStationId()); + line.addStation(station); + } + } + + private Station getStation(Long stationId) { + return stationRepository.findById(stationId) + .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์— ํ•ด๋‹นํ•˜๋Š” ์—ญ์ด ์—†์Šต๋‹ˆ๋‹ค.")); + } +}
Java
๋ฆฌํŒฉํ† ๋ง ๋‹จ๊ณ„์—์„œ ๋ฏธ์ฒ˜ ์ˆ˜์ •ํ•˜์ง€ ๋ชปํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค...
@@ -0,0 +1,37 @@ +import { Suspense, useState } from "react"; +import { useSearchParams } from "react-router-dom"; + +import { InputSection } from "./components/InputSection"; +import { ListSection } from "./components/ListSection/ListSection"; + +export const SearchPage = () => { + const [, setSearchParams] = useSearchParams(); + + const [keyword, setKeyword] = useState<string>(""); + + const handleKeywordChange = (keyword: string) => { + setKeyword(keyword); + }; + + const handleSearch = (keyword: string) => { + console.log("๊ฒ€์ƒ‰์–ด: ", keyword); + setSearchParams({ keyword }); + }; + + return ( + <main> + <InputSection + keyword={keyword} + onKeywordChange={handleKeywordChange} + onInputSubmit={handleSearch} + /> + {keyword ? ( + <Suspense fallback={<p>๊ฒ€์ƒ‰์ค‘...</p>}> + <ListSection /> + </Suspense> + ) : ( + <p>๊ฒ€์ƒ‰์–ด๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”</p> + )} + </main> + ); +};
Unknown
url์˜ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ด์šฉํ•ด ๊ฒ€์ƒ‰์–ด ํ‚ค์›Œ๋“œ๋ฅผ ๊ด€๋ฆฌํ•˜๋„๋ก ์„ค์ •ํ•œ ๊ฒƒ์€, url์„ ์ „๋‹ฌํ•˜๋ฉฐ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋„ ํ•จ๊ป˜ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ธฐ ์œ„ํ•จ์ด์—์š”. ๊ทธ๋Ÿฐ๋ฐ ํ˜„์žฌ๋Š” ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๊ฒ€์ƒ‰์–ด์˜ ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ ๋‚ด๋ ค๋ฐ›์ง€ ๋ชปํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ์–ด์š”. TODO: ์„œ์น˜ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’์„ ํ‚ค์›Œ๋“œ ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ ์„ค์ • ```suggestion const [searchParams, setSearchParams] = useSearchParams(); const [keyword, setKeyword] = useState<string>(searchParams.get("keyword") || ""); ```
@@ -0,0 +1,30 @@ +import { useLazyLoadQuery } from "react-relay"; +import { useSearchParams } from "react-router-dom"; + +import { graphql } from "relay-runtime"; + +import { ListSectionRepositorySearchQuery } from "./__generated__/ListSectionRepositorySearchQuery.graphql"; + +import { RepositoryPagination } from "./RepositoryPagination"; + +export const ListSection = () => { + const [searchParams] = useSearchParams(); + const keyword = searchParams.get("keyword") || ""; + + const data = useLazyLoadQuery<ListSectionRepositorySearchQuery>( + graphql` + query ListSectionRepositorySearchQuery($keyword: String!) { + ...RepositoryPagination @arguments(keyword: $keyword) + } + `, + { + keyword, + } + ); + + return ( + <ul> + <RepositoryPagination data={data} /> + </ul> + ); +};
Unknown
TODO: List Section ๋‚ด์—์„œ ํ‚ค์›Œ๋“œ๋ฅผ ์ง์ ‘ ๊ฐ€์ ธ์˜ค์ง€ ๋ง๊ณ , Search Page์—์„œ props๋กœ ํ‚ค์›Œ๋“œ๋ฅผ ์ฃผ์ž…๋ฐ›๋„๋ก ๋ณ€๊ฒฝ
@@ -0,0 +1,87 @@ +import { graphql, useFragment, useMutation } from "react-relay"; + +import { RepositoryItem_repository$key } from "./__generated__/RepositoryItem_repository.graphql"; +import { RepositoryItemAddStarMutation } from "./__generated__/RepositoryItemAddStarMutation.graphql"; +import { RepositoryItemRemoveStarMutation } from "./__generated__/RepositoryItemRemoveStarMutation.graphql"; + +import { StarButton } from "./StarButton"; + +type RepositoryItemProps = { + repository: RepositoryItem_repository$key; +}; + +const RepositoryStarAddMutation = graphql` + mutation RepositoryItemAddStarMutation($id: ID!) { + addStar(input: { starrableId: $id }) { + starrable { + id + viewerHasStarred + } + } + } +`; + +const RepositoryStarRemoveMutation = graphql` + mutation RepositoryItemRemoveStarMutation($id: ID!) { + removeStar(input: { starrableId: $id }) { + starrable { + id + viewerHasStarred + } + } + } +`; + +export const RepositoryItem = (props: RepositoryItemProps) => { + const payload = useFragment( + graphql` + fragment RepositoryItem_repository on Repository { + id + name + url + description + stargazerCount + viewerHasStarred + } + `, + props.repository + ); + + const [add, isAdding] = useMutation<RepositoryItemAddStarMutation>( + RepositoryStarAddMutation + ); + + const [remove, isRemoving] = useMutation<RepositoryItemRemoveStarMutation>( + RepositoryStarRemoveMutation + ); + + if (!payload) { + return null; + } + + const { id, url, name, description, stargazerCount, viewerHasStarred } = + payload; + + const isLoading = isAdding || isRemoving; + + return ( + <li> + <a href={url} target="_blank" rel="noreferrer"> + {name} + </a> + <p>{description}</p> + <p>โญ๏ธ {stargazerCount}</p> + + {isLoading ? ( + <div>...</div> + ) : ( + <StarButton + repositoryId={id} + isStarred={viewerHasStarred} + onAddStar={() => add({ variables: { id } })} + onRemoveStar={() => remove({ variables: { id } })} + /> + )} + </li> + ); +};
Unknown
TODO: add, remove์— ๋Œ€ํ•œ ๋ณ€์ˆ˜๊ฐ’์€ StarButton ๋‚ด์—์„œ ๋„˜๊ฒจ๋ฐ›๋„๋ก ๋ณ€๊ฒฝ
@@ -1 +1,30 @@ -# java-lotto ๊ฒŒ์ž„ +# java-Lotto ๊ฒŒ์ž„ + +# ๊ตฌํ˜„ ๊ธฐ๋Šฅ ๋ชฉ๋ก + +- [x] ๊ตฌ์ž…๊ธˆ์•ก ์ž…๋ ฅ๋ฐ›๊ธฐ + - [x] 1000์› ๋ฏธ๋งŒ ์ž…๋ ฅ ์‹œ ์ฒ˜๋ฆฌ + - [x] 1000์˜ ๋ฐฐ์ˆ˜ ์•„๋‹Œ ๊ฐ’ ์ž…๋ ฅ ์‹œ ์ฒ˜๋ฆฌ + - [x] ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฐ’ (๋ฌธ์ž์—ด) + - [x] ์ •์ƒ๊ฐ’ ์ฒ˜๋ฆฌ + - [x] ๊ณต๋ฐฑ ์ฒ˜๋ฆฌ +- [x] ๊ตฌ๋งค ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ +- [x] ๋žœ๋ค ๋กœ๋˜๋ฒˆํ˜ธ ๊ตฌ๋งค ๊ฐœ์ˆ˜๋งŒํผ ๋งŒ๋“ค๊ธฐ + - [x] defaultNumberSet 1๋ฒˆ๋งŒ ์ƒ์„ฑ๋˜๋„๋ก ๋ณ€๊ฒฝ + - [x] RandomLottoTest ์ƒ์ˆ˜ ๋ฆฌํŒฉํ† ๋ง + - [x] PurchaseCount์˜ 1000 ์ ‘๊ทผ +- [x] ์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ ์ž…๋ ฅ๋ฐ›๊ธฐ + - [x] WinningNumbers ๋ฉค๋ฒ„๋ณ€์ˆ˜ ArrayList ํด๋ž˜์Šค ํ™•์ธ + - [x] ์ˆซ์ž ๊ฐœ์ˆ˜ 6๊ฐœ ํ™•์ธ + - [x] ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฐ’ ํฌํ•จ + - [x] ๋ฒ”์œ„ (1~45) ํ™•์ธ + - [x] ๊ณต๋ฐฑ ์ฒ˜๋ฆฌ +- [x] ๋ณด๋„ˆ์Šค ๋ณผ ์ž…๋ ฅ๋ฐ›๊ธฐ +- [x] ๋‹น์ฒจ ํ†ต๊ณ„ + - [x] ๋‹น์ฒจ ์กฐ๊ฑด์„ enum ์ฒ˜๋ฆฌ + - [x] ์ผ์น˜ ๊ฐœ์ˆ˜ ์ฐพ๊ธฐ + - [x] 5๊ฐœ ์ผ์น˜ ์‹œ ๋ณด๋„ˆ์Šค ๋ณผ ์ผ์น˜ ์—ฌ๋ถ€ ํ™•์ธ + - [x] ๋กœ๋˜ ๋‹น์ฒจ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ + - [x] ๋‹น์ฒจ๊ฐ’์˜ ํ•ฉ ๊ตฌํ•˜๊ธฐ + - [x] ์ˆ˜์ต๋ฅ  ๊ตฌํ•˜๊ธฐ + - [x] ๊ฒฐ๊ณผ ์ถœ๋ ฅ \ No newline at end of file
Unknown
๊ตฌํ˜„ ๊ธฐ๋Šฅ ๋ชฉ๋ก ์ž‘์„ฑ ๐Ÿ‘
@@ -10,6 +10,13 @@ repositories { dependencies { testImplementation('org.junit.jupiter:junit-jupiter:5.6.0') testImplementation('org.assertj:assertj-core:3.15.0') + + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' + + testCompileOnly 'org.projectlombok:lombok:1.18.20' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' + } test {
Unknown
๋กฌ๋ณต ํ”Œ๋Ÿฌ๊ทธ์ธ์„ ํ™œ์šฉํ•˜์…จ๋„ค์š”!
@@ -0,0 +1,24 @@ +package lotto.controller; + +import lotto.domain.dto.LottoResult; +import lotto.domain.dto.PurchaseInput; +import lotto.domain.dto.PurchaseResult; +import lotto.domain.dto.WinningLottoInput; +import lotto.service.LottoService; + +public class LottoController { + + private final LottoService lottoService; + + public LottoController() { + this.lottoService = new LottoService(); + } + + public PurchaseResult purchase(PurchaseInput purchaseInput) throws IllegalArgumentException { + return lottoService.purchase(purchaseInput); + } + + public LottoResult calculateResult(PurchaseResult purchaseResult, WinningLottoInput winningLottoInput) throws IllegalArgumentException { + return lottoService.calculateResult(purchaseResult, winningLottoInput); + } +}
Java
MVC ํŒจํ„ด์„ ์ด์šฉํ•ด ๋ฌธ์ œ๋ฅผ ํ’€๋ ค๊ณ  ์‹œ๋„ํ•˜์…จ๋„ค์š”! ๋‹ค๋งŒ Model - View - Controller ์—ญํ•  ๋ถ„๋ฆฌ๊ฐ€ ๋ช…ํ™•ํ•˜๊ฒŒ ๋˜์–ด์žˆ์ง€ ์•Š์•„ ํ˜„์žฌ Controller๊ฐ€ View๋ฅผ ์ง์ ‘ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ ๊ตฌํ˜„์ด ๋˜์–ด์žˆ๋Š”๋ฐ์š”. ๊ฐ์ž์˜ ์—ญํ• ๊ณผ ์ฑ…์ž„์€ ๋ฌด์—‡์ด๊ณ , ์ด๋ฅผ ์–ด๋–ป๊ฒŒ ๋…๋ฆฝ์ ์œผ๋กœ ๋ถ„๋ฆฌํ•ด๋‚ผ ์ˆ˜ ์žˆ์„ ์ง€, ๋˜ ์™œ ๊ทธ๋Ÿฌํ•˜์—ฌ์•ผ ํ•˜๋Š”์ง€ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค. ํ˜„์žฌ๋Š” `LottoController.start()` ๋Š” `LottoApplication`์˜ main๊ณผ ๊ฐ™์€ ์—ญํ• ๋กœ ๋ณด์ด๋„ค์š”.
@@ -0,0 +1,31 @@ +package lotto.view; + +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Collectors; + +public class ConsoleInputView implements InputView { + + private static final String LOTTO_NUMBERS_INPUT_DELIMITER = ","; + + private final Scanner scanner = new Scanner(System.in); + + public Integer getPurchaseCost() throws NumberFormatException { + String input = scanner.nextLine().trim(); + return Integer.parseInt(input); + } + + public List<Integer> getWinningLottoNumbers() throws NumberFormatException { + String input = scanner.nextLine(); + return Arrays.stream(input.split(LOTTO_NUMBERS_INPUT_DELIMITER)) + .map(String::trim) + .map(Integer::new) + .collect(Collectors.toList()); + } + + public Integer getWinningLottoBonus() throws NumberFormatException { + String input = scanner.nextLine().trim(); + return Integer.parseInt(input); + } +}
Java
๊ณผํ•œ(๋ถˆํ•„์š”ํ•œ) ๋ฉ”์„œ๋“œ ํฌ์žฅ์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,86 @@ +package lotto.view; + +import lotto.domain.*; +import lotto.domain.dto.LottoResult; + +public class ConsoleOutputView implements OutputView { + + private static final String ERROR_HEADER = "[ERROR] "; + + private void print(String contents) { + System.out.println(contents); + } + + public void printLottoCount(PurchaseCount purchaseCount) { + int count = purchaseCount.getPurchaseCount(); + print(count + "๊ฐœ๋ฅผ ๊ตฌ๋งคํ–ˆ์Šต๋‹ˆ๋‹ค."); + } + + public void printLottoSet(LottoSet lottoSet) { + for (Lotto lotto : lottoSet.getLottoSet()) { + printLotto(lotto); + } + } + + private void printLotto(Lotto lotto) { + String result = "["; + for (LottoNumber lottoNumber : lotto.getLottoNumbers()) { + result += lottoNumber.getLottoNumber() + ", "; + } + result = removeCommaAtTheEnd(result) + "]"; + + print(result); + } + + private String removeCommaAtTheEnd(String str) { + return str.substring(0, str.length() - 2); + } + + public void askPurchaseCost() { + print("๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + public void askWinningLottoNumbers() { + print("์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + public void askWinningLottoBonus() { + print("๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + public void printLottoStatistic(LottoResult lottoStatistics) { + String result = "๋‹น์ฒจ ํ†ต๊ณ„\n---------\n" + + generatePrizeResultMessage(Prize.FIFTH, lottoStatistics.getPrizeCount().getFifth()) + + generatePrizeResultMessage(Prize.FOURTH, lottoStatistics.getPrizeCount().getFourth()) + + generatePrizeResultMessage(Prize.THIRD, lottoStatistics.getPrizeCount().getThird()) + + generatePrizeResultMessage(Prize.SECOND, lottoStatistics.getPrizeCount().getSecond()) + + generatePrizeResultMessage(Prize.FIRST, lottoStatistics.getPrizeCount().getFirst()) + + generateProfitRateMessage(lottoStatistics.getProfitRate()); + print(result); + } + + private String generatePrizeResultMessage(Prize prize, int prizeCount) { + return generatePrizeResultMessage(prize) + prizeCount + "๊ฐœ\n"; + } + + private String generatePrizeResultMessage(Prize prize) { + StringBuilder sb = new StringBuilder(); + sb.append(prize.getMatchNumbersCount()) + .append("๊ฐœ ์ผ์น˜"); + if (prize.isBonus()) { + sb.append(", ๋ณด๋„ˆ์Šค ๋ณผ ์ผ์น˜ "); + } + sb.append("(") + .append(prize.getPrizeMoney()) + .append("์›)- "); + return sb.toString(); + } + + private String generateProfitRateMessage(double profitRate) { + return "์ด ์ˆ˜์ต๋ฅ ์€ " + profitRate + "์ž…๋‹ˆ๋‹ค."; + } + + public void printException(String message) { + print(ERROR_HEADER + message); + } +}
Java
line 9 to 13 ๋„ˆ๋ฌด ๋ช…ํ™•ํ•œ ๊ฐ’๋“ค์ด ๊ณผํ•˜๊ฒŒ ์ƒ์ˆ˜๋กœ ๋งŒ๋“ค์–ด์กŒ์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  literal value๊ฐ€ ๋‚˜์œ ๊ฒƒ์€ ์•„๋‹™๋‹ˆ๋‹ค. ^^;
@@ -0,0 +1,33 @@ +package lotto.service; + +import lotto.domain.*; +import lotto.domain.dto.LottoResult; +import lotto.domain.dto.PurchaseInput; +import lotto.domain.dto.PurchaseResult; +import lotto.domain.dto.WinningLottoInput; + +public class LottoService { + + public PurchaseResult purchase(PurchaseInput purchaseInput) throws IllegalArgumentException { + PurchaseCount purchaseCount = new PurchaseCount(purchaseInput.getPrice()); + LottoSet lottoSet = new LottoSet(purchaseCount); + + return PurchaseResult.builder() + .purchaseCount(purchaseCount) + .lottoSet(lottoSet) + .build(); + } + + public LottoResult calculateResult(PurchaseResult purchaseResult, WinningLottoInput winningLottoInput) throws IllegalArgumentException { + LottoMatcher lottoMatcher = new LottoMatcher( + new WinningLotto(winningLottoInput), purchaseResult.getLottoSet() + ); + PrizeCount prizeCount = lottoMatcher.countPrizes(); + LottoStatistics lottoStatistics = new LottoStatistics(prizeCount, purchaseResult.getPurchaseCount()); + + return LottoResult.builder() + .prizeCount(prizeCount) + .profitRate(lottoStatistics.calculateProfitRate()) + .build(); + } +}
Java
PurchaseCount ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ด ์‹œ์ ์— ์œ ํšจ์„ฑ ๊ฒ€์ฆ์ด ํ•ด๋‹น ๊ฐ์ฒด ์ƒ์„ฑ์ž์—์„œ ์ง„ํ–‰๋˜๋Š”๋ฐ์š”, ์ปจํŠธ๋กค๋Ÿฌ ๋ ˆ์ด์–ด์—์„œ ์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ ๊ฐ’์˜ ์œ ํšจ์„ฑ์„ ๋จผ์ € ๊ฒ€์ฆํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? ๊ณ ๋ฏผํ•ด๋ณผ ๊ฑฐ๋ฆฌ: ์œ ํšจ์„ฑ ๊ฒ€์ฆ์€ ์–ด๋–ค ๋ ˆ์ด์–ด์—์„œ ์ง„ํ–‰๋˜์–ด์•ผํ• ๊นŒ?
@@ -0,0 +1,19 @@ +package lotto.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lotto.domain.Lotto; + +@RequiredArgsConstructor +public enum ExceptionMessage { + + NON_NUMBER_INPUT("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."), + LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY("๊ตฌ์ž…๊ธˆ์•ก์€ " + Lotto.PRICE + " ์ด์ƒ์˜ ๊ฐ’์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."), + NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY("๊ตฌ์ž…๊ธˆ์•ก์€ " + Lotto.PRICE + "์˜ ๋ฐฐ์ˆ˜๋กœ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."), + INVALID_LENGTH_INPUT_FOR_LOTTO("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” 6๊ฐœ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"), + DUPLICATE_LOTTO_NUMBER_INPUT_FOR_LOTTO("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋˜์ง€ ์•Š๋Š” 6๊ฐœ์˜ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"), + OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” 1 ์ด์ƒ 45 ์ดํ•˜์˜ ๊ฐ’์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + + @Getter + private final String message; +}
Java
์˜ˆ์™ธ ๋ฉ”์‹œ์ง€๋ฅผ ๋ณ„๋„๋กœ ๋ถ„๋ฆฌํ•ด์„œ ํ•œ ๊ณณ์—์„œ ๊ด€๋ฆฌํ•˜๊ณ  ์žˆ๋„ค์š”! ํ˜„์žฌ๋Š” IllegalArgumentException๋งŒ์„ ์‚ฌ์šฉํ•˜๊ณ  ๋ฉ”์‹œ์ง€๋กœ ํŠน์ • ์˜ˆ์™ธ์— ๋Œ€ํ•ด์„œ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”, ๊ตฌ์ฒด์ ์ธ CustomException์„ ๋งŒ๋“ค๊ณ  ์ƒํ™ฉ์— ๋”ฐ๋ผ ์ด๋ฅผ ๋˜์ ธ ํ•ด๋‹น Exception์„ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์ƒ๊ฐํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,53 @@ +package lotto.domain; + +import lombok.Getter; + +import java.util.Objects; + +import static lotto.exception.ExceptionMessage.OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER; + +public class LottoNumber { + + public static final int LOWER_BOUND = 1; + public static final int UPPER_BOUND = 45; + + @Getter + private final int lottoNumber; + + public LottoNumber(int lottoNumber) throws IllegalArgumentException { + validate(lottoNumber); + + this.lottoNumber = lottoNumber; + } + + private void validate(int lottoNumber) throws IllegalArgumentException { + if (isOutOfBound(lottoNumber)) { + throw new IllegalArgumentException(OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER.getMessage()); + } + } + + private boolean isOutOfBound(int lottoNumber) { + return lottoNumber < LOWER_BOUND || lottoNumber > UPPER_BOUND; + } + + public boolean isGreaterThan(LottoNumber winningNumber) { + return this.getLottoNumber() > winningNumber.getLottoNumber(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNumber that = (LottoNumber) o; + return lottoNumber == that.lottoNumber; + } + + @Override + public int hashCode() { + return Objects.hash(lottoNumber); + } +}
Java
`isInteger` ๋Š” ์ง๋…ํ•˜๋ฉด ์ •์ˆ˜์ธ๊ฐ€? ๋Š” ํŒ๋‹จ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค๋งŒ ๋‚ด์šฉ์„ ๋ณด๋‹ˆ 0~9๊นŒ์ง€ ์ˆซ์ž ์ฆ‰ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜์ธ์ง€๋ฅผ ์ •๊ทœํ‘œํ˜„์‹์„ ์ด์šฉํ•ด ํŒ๋‹จํ•˜๊ณ  ์žˆ๋„ค์š”. isNonNegativeInteger ์ •๋„๋กœ ๋” ์ •ํ™•ํ•˜๊ฒŒ ํ‘œํ˜„ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ```suggestion if (!isNonNegativeInteger(input)) { ```
@@ -0,0 +1,35 @@ +package lotto.domain; + +import lombok.Builder; +import lombok.Getter; + +import static lotto.exception.ExceptionMessage.LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY; +import static lotto.exception.ExceptionMessage.NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY; + +public class PurchaseCount { + + private static final int MINIMUM_INPUT = 1000; + + @Getter + private final Integer purchaseCount; + + @Builder + public PurchaseCount(int purchasePrice) { + validate(purchasePrice); + + this.purchaseCount = purchasePrice / Lotto.PRICE; + } + + private void validate(int purchasePrice) { + if (purchasePrice < MINIMUM_INPUT) { + throw new IllegalArgumentException(LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage()); + } + if (notMultipleOfLottoPrice(purchasePrice)) { + throw new IllegalArgumentException(NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage()); + } + } + + private boolean notMultipleOfLottoPrice(int input) { + return input % Lotto.PRICE != 0; + } +}
Java
`isInteger` ๋Š” ์ง๋…ํ•˜๋ฉด ์ •์ˆ˜์ธ๊ฐ€? ๋Š” ํŒ๋‹จ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค๋งŒ ๋‚ด์šฉ์„ ๋ณด๋‹ˆ 0~9๊นŒ์ง€ ์ˆซ์ž ์ฆ‰ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜์ธ์ง€๋ฅผ ์ •๊ทœํ‘œํ˜„์‹์„ ์ด์šฉํ•ด ํŒ๋‹จํ•˜๊ณ  ์žˆ๋„ค์š”. isNonNegativeInteger ์ •๋„๋กœ ๋” ์ •ํ™•ํ•˜๊ฒŒ ํ‘œํ˜„ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ```suggestion if (!isNonNegativeInteger(input)) { ```
@@ -0,0 +1,35 @@ +package lotto.domain; + +import lombok.Builder; +import lombok.Getter; + +import static lotto.exception.ExceptionMessage.LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY; +import static lotto.exception.ExceptionMessage.NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY; + +public class PurchaseCount { + + private static final int MINIMUM_INPUT = 1000; + + @Getter + private final Integer purchaseCount; + + @Builder + public PurchaseCount(int purchasePrice) { + validate(purchasePrice); + + this.purchaseCount = purchasePrice / Lotto.PRICE; + } + + private void validate(int purchasePrice) { + if (purchasePrice < MINIMUM_INPUT) { + throw new IllegalArgumentException(LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage()); + } + if (notMultipleOfLottoPrice(purchasePrice)) { + throw new IllegalArgumentException(NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage()); + } + } + + private boolean notMultipleOfLottoPrice(int input) { + return input % Lotto.PRICE != 0; + } +}
Java
`notMatchesCondition` ํ‘œํ˜„์ด ๋ชจํ˜ธํ•˜๊ณ  ๋‘ ๊ฐ€์ง€ ์„œ๋กœ ๋‹ค๋ฅธ ์ผ์„ ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. 1. ์ž…๋ ฅ์ด ๋กœ๋˜๋ฅผ ๊ตฌ๋งคํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ์†Œ ๊ฐ’(1000)๋ฏธ๋งŒ์ธ์ง€ ๊ฒ€์ฆ 2. ์ •ํ™•ํžˆ ํ‹ฐ์ผ“ ๊ฐ€๊ฒฉ์˜ ๋ฐฐ์ˆ˜์ธ์ง€ ๊ฒ€์ฆ 1์˜ ์ƒํ™ฉ์„ 2์˜ ๋ถ€๋ถ„์ง‘ํ•ฉ์œผ๋กœ ์ƒ๊ฐํ•˜์—ฌ ๊ตฌํ˜„ํ•˜์‹  ๊ฒƒ์œผ๋กœ ์ถ”์ธก๋˜๋Š”๋ฐ, ์‚ฌ์šฉ์ž์—๊ฒŒ ์‹คํŒจ์— ๋Œ€ํ•œ ๋” ์ •ํ™•ํ•œ ์—๋Ÿฌ๋ฅผ ๊ตฌ๋ถ„ํ•˜์—ฌ ๋…ธ์ถœํ•˜๋Š” ๊ฒƒ์ด ์ข‹์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,17 @@ +package lotto.domain; + +import lombok.Builder; +import lombok.Getter; +import lotto.domain.dto.WinningLottoInput; + +public class WinningLotto extends Lotto { + + @Getter + private final LottoNumber bonusNumber; + + @Builder + public WinningLotto(WinningLottoInput winningLottoInput) throws IllegalArgumentException { + super(winningLottoInput.getNumbers()); + this.bonusNumber = new LottoNumber(winningLottoInput.getBonus()); + } +}
Java
์‚ฌ์šฉ์ž ์ž…๋ ฅ(InputView)์— ๋Œ€ํ•œ ํŒŒ์‹ฑ๊ณผ ๊ฒ€์ฆ์ด ์„œ๋น„์Šค ๋ ˆ์ด์–ด๋ฅผ ํ†ต๊ณผํ•ด ๋„๋ฉ”์ธ ๋ชจ๋ธ๊นŒ์ง€ ์นจํˆฌํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ์˜์—ญ์ธ ์ปจํŠธ๋กค๋Ÿฌ ๋ ˆ์ด์–ด์—์„œ ์„ ์ž‘์—…์„ ๋ชจ๋‘ ๋งˆ๋ฌด๋ฆฌ์ง€์–ด์•ผํ•ฉ๋‹ˆ๋‹ค. ๊ฐ€๊ธ‰์  ๋„๋ฉ”์ธ ๋ชจ๋ธ์€ ์‚ฌ์šฉ์ž ์ž…๋ ฅ ๋ฐฉ์‹๊ณผ ๋…๋ฆฝ์ ์ด์–ด์•ผํ•ฉ๋‹ˆ๋‹ค. ์–ด๋–ค ๋ทฐ๋ฅผ ํ†ตํ•ด ์ ‘๊ทผํ•˜๋“  ๋„๋ฉ”์ธ์€ ๊ทธ ์ž์ฒด๋กœ ๋ฌธ์ œ ์˜์—ญ๋งŒ์„ ํ‘œํ˜„ํ•˜๊ณ  ํ•ด๊ฒฐํ•˜๋Š” ๋ ˆ์ด์–ด์ด์–ด์•ผํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,53 @@ +package lotto.domain; + +import lombok.Getter; + +import java.util.Objects; + +import static lotto.exception.ExceptionMessage.OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER; + +public class LottoNumber { + + public static final int LOWER_BOUND = 1; + public static final int UPPER_BOUND = 45; + + @Getter + private final int lottoNumber; + + public LottoNumber(int lottoNumber) throws IllegalArgumentException { + validate(lottoNumber); + + this.lottoNumber = lottoNumber; + } + + private void validate(int lottoNumber) throws IllegalArgumentException { + if (isOutOfBound(lottoNumber)) { + throw new IllegalArgumentException(OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER.getMessage()); + } + } + + private boolean isOutOfBound(int lottoNumber) { + return lottoNumber < LOWER_BOUND || lottoNumber > UPPER_BOUND; + } + + public boolean isGreaterThan(LottoNumber winningNumber) { + return this.getLottoNumber() > winningNumber.getLottoNumber(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNumber that = (LottoNumber) o; + return lottoNumber == that.lottoNumber; + } + + @Override + public int hashCode() { + return Objects.hash(lottoNumber); + } +}
Java
LottoNumber๋ฅผ ์ƒ์„ฑํ•  ๋•Œ String์œผ๋กœ ์ƒ์„ฑํ•  ํ•„์š”๊ฐ€ ์žˆ์„๊นŒ์š”? String type์œผ๋กœ ๋ฐ›๋‹ค๋ณด๋‹ˆ ํ˜•๋ณ€ํ™˜๊นŒ์ง€ ์ฑ…์ž„์ ธ์•ผํ•˜๋Š” ์ƒํ™ฉ์ด ๋˜์—ˆ๋„ค์š”.
@@ -0,0 +1,17 @@ +package lotto.domain; + +import lombok.Builder; +import lombok.Getter; +import lotto.domain.dto.WinningLottoInput; + +public class WinningLotto extends Lotto { + + @Getter + private final LottoNumber bonusNumber; + + @Builder + public WinningLotto(WinningLottoInput winningLottoInput) throws IllegalArgumentException { + super(winningLottoInput.getNumbers()); + this.bonusNumber = new LottoNumber(winningLottoInput.getBonus()); + } +}
Java
๋ฐ˜๋ณต๋ฌธ๊ณผ ์กฐ๊ฑด๋ฌธ์„ ์ค‘์ฒฉํ•ด์„œ ๋กœ์ง์ด ๋ณต์žกํ•˜๋„ค์š”. ๋” ๋‚˜์€ ๋ฐฉ์‹์œผ๋กœ ๋ฆฌํŒฉํ† ๋ง์„ ํ•ด์•ผ๊ฒ ์ฃ ?
@@ -0,0 +1,55 @@ +package lotto.domain; + +import lombok.Getter; + +@Getter +public enum Prize { + + FIRST(6, false, 2000000000), + SECOND(5, true, 30000000), + THIRD(5, false, 1500000), + FOURTH(4, false, 50000), + FIFTH(3, false, 5000), + LOSE(2, false, 0); + + private final int matchNumbersCount; + private final boolean isBonus; + private final long prizeMoney; + + Prize(int matchNumbersCount, boolean isBonus, long prizeMoney) { + this.matchNumbersCount = matchNumbersCount; + this.isBonus = isBonus; + this.prizeMoney = prizeMoney; + } + + public static Prize getMatchPrize(int matchNumbersCount, boolean isBonus) { + if (matchNumbersCount <= LOSE.matchNumbersCount) { + return LOSE; + } + if (matchNumbersCount == FIFTH.matchNumbersCount) { + return FIFTH; + } + if (matchNumbersCount == FOURTH.matchNumbersCount) { + return FOURTH; + } + if (matchNumbersCount == FIRST.matchNumbersCount) { + return FIRST; + } + return dissolveSecondOrThird(isBonus); + } + + private static Prize dissolveSecondOrThird(boolean isBonus) { + if (isBonus) { + return Prize.SECOND; + } + return Prize.THIRD; + } + + public static long sumOfPrizeMoney(PrizeCount prizeCount) { + return prizeCount.getFirst() * FIRST.prizeMoney + + prizeCount.getSecond() * SECOND.prizeMoney + + prizeCount.getThird() * THIRD.prizeMoney + + prizeCount.getFourth() * FOURTH.prizeMoney + + prizeCount.getFifth() * FIFTH.prizeMoney; + } +}
Java
Enum ํ™œ์šฉ ๐Ÿ‘
@@ -0,0 +1,35 @@ +package lotto.domain; + +import lombok.Getter; + +@Getter +public class PrizeCount { + + private int first; + private int second; + private int third; + private int fourth; + private int fifth; + + public void addPrize(Prize prize) { + if (prize == Prize.FIRST) { + first++; + return; + } + if (prize == Prize.SECOND) { + second++; + return; + } + if (prize == Prize.THIRD) { + third++; + return; + } + if (prize == Prize.FOURTH) { + fourth++; + return; + } + if (prize == Prize.FIFTH) { + fifth++; + } + } +}
Java
์ด ํด๋ž˜์Šค์˜ ์ด๋ฆ„์ด Prize**Count**์ด๋‹ˆ line 9 to 13 count ๋Š” ์ค‘๋ณต์ฒ˜๋Ÿผ ๋А๊ปด์ง€๋„ค์š”. ๋” ๋‹จ์ˆœํ•˜๊ฒŒ ๋„ค์ด๋ฐํ•ด๋„ ์˜๋ฏธ ์ „๋‹ฌ์— ๋ฌด๋ฆฌ ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package lotto.domain; + +import lombok.Builder; +import lombok.Getter; +import lotto.domain.dto.WinningLottoInput; + +public class WinningLotto extends Lotto { + + @Getter + private final LottoNumber bonusNumber; + + @Builder + public WinningLotto(WinningLottoInput winningLottoInput) throws IllegalArgumentException { + super(winningLottoInput.getNumbers()); + this.bonusNumber = new LottoNumber(winningLottoInput.getBonus()); + } +}
Java
1. ๋„ค์ด๋ฐ์—์„œ Condition๊ณผ ๊ฐ™์€ ๋ชจํ˜ธํ•œ ๋‹จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋” ๊ตฌ์ฒด์ ์ธ ํ‘œํ˜„์„ ์‚ฌ์šฉํ•˜๋„๋ก ํ•ฉ์‹œ๋‹ค. 2. find๋ผ๋Š” ํ‘œํ˜„๊ณผ get์ด๋ผ๋Š” ํ‘œํ˜„ ์‚ฌ์ด์— ๋ฏธ๋ฌ˜ํ•œ ์ฐจ์ด๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์–ด๋–ค ์ฐจ์ด์ธ์ง€๋Š” ์ฐพ์•„์„œ ๊ณต๋ถ€ํ•˜๊ณ  ์ €์—๊ฒŒ๋„ ๊ณต์œ ํ•ด์ฃผ์„ธ์š”.
@@ -0,0 +1,22 @@ +package lotto.domain; + +import lombok.Builder; +import lombok.Getter; + +public class LottoStatistics { + + @Getter + private final PrizeCount prizeCount; + private final PurchaseCount purchaseCount; + + @Builder + public LottoStatistics(PrizeCount prizeCount, PurchaseCount purchaseCount) { + this.prizeCount = prizeCount; + this.purchaseCount = purchaseCount; + } + + public double calculateProfitRate() { + return (double) Prize.sumOfPrizeMoney(prizeCount) + / (purchaseCount.getPurchaseCount() * Lotto.PRICE); + } +} \ No newline at end of file
Java
ํ†ต๊ณ„๋ฅผ ๋‹ด๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“  ๊ฒƒ ์•„์ฃผ ์ข‹์Šต๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,31 @@ +package christmas.model.badge.enums; + +import java.util.Arrays; + +public enum BadgeInfo { + + SANTA_BADGE("์‚ฐํƒ€", 20_000), + TREE_BADGE("ํŠธ๋ฆฌ", 10_000), + START_BADGE("๋ณ„", 5_000), + NON_BADGE("์—†์Œ", 0); + + private final String name; + + private final int price; + + BadgeInfo(String name, int price) { + this.name = name; + this.price = price; + } + + public static BadgeInfo findBadgeByPrice(int totalPrice) { + return Arrays.stream(values()) + .filter(badge -> totalPrice >= badge.price) + .findFirst() + .orElse(NON_BADGE); + } + + public String getName() { + return name; + } +}
Java
์‹ค์ˆ˜๋ฅผ ๋ฏธ์…˜์ด ๋๋‚˜๊ณ  ๋ฐœ๊ฒฌํ–ˆ์Šต๋‹ˆ๋‹ค ^^.. START -> STAR
@@ -0,0 +1,32 @@ +package christmas.model.discount; + + +import static christmas.exception.ErrorType.INVALID_ORDER_AMOUNT; +import static christmas.model.discount.enums.DiscountAmount.CAN_GIVEAWAY_DISCOUNT; +import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT; + +import christmas.model.order.enums.MenuInfo; + +public class GiveawayDiscount implements Discount { + + private final int totalOrderAmount; + + public GiveawayDiscount(int totalOrderAmount) { + validateOrderAmount(totalOrderAmount); + this.totalOrderAmount = totalOrderAmount; + } + + private void validateOrderAmount(int totalOrderAmount) { + if (totalOrderAmount < NON_DISCOUNT.getDiscount()) { + throw new IllegalArgumentException(INVALID_ORDER_AMOUNT.getMessage()); + } + } + + @Override + public int calculateDiscount() { + if (totalOrderAmount >= CAN_GIVEAWAY_DISCOUNT.getDiscount()) { + return MenuInfo.CHRISTMAS_PASTA.getPrice(); + } + return NON_DISCOUNT.getDiscount(); + } +}
Java
์‹ค์ˆ˜๋ฅผ ๋ฏธ์…˜์ด ๋๋‚˜๊ณ  ๋ฐœ๊ฒฌํ–ˆ์Šต๋‹ˆ๋‹ค ^^.. ํŒŒ์Šคํƒ€ -> ์ƒดํŽ˜์ธ (๊ฐ€๊ฒฉ์ด ๋˜‘๊ฐ™์•„์„œ ๋ˆˆ์น˜์ฑ„์ง€ ๋ชปํ–ˆ๋„ค์š” (__))
@@ -0,0 +1,61 @@ +package christmas.model.order.enums; + +import static christmas.exception.ErrorType.INVALID_MENU_NOT_EXIST; + +import java.util.Arrays; + +public enum MenuInfo { + + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, Category.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, Category.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, Category.APPETIZER), + + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, Category.MAIN_COURSE), + BARBECUE_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, Category.MAIN_COURSE), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, Category.MAIN_COURSE), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, Category.MAIN_COURSE), + + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, Category.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, Category.DESSERT), + + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3_000, Category.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, Category.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, Category.BEVERAGE); + + private final String name; + + private final int price; + + private final Category category; + + MenuInfo(String name, int price, Category category) { + this.name = name; + this.price = price; + this.category = category; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public Category getCategory() { + return category; + } + + public static boolean isExistMenu(String name) { + return Arrays.stream(MenuInfo.values()) + .map(MenuInfo::getName) + .anyMatch(existMenu -> existMenu.equals(name)); + } + + public static MenuInfo findByMenuName(String name) { + return Arrays.stream(MenuInfo.values()) + .filter(menuInfo -> menuInfo.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(INVALID_MENU_NOT_EXIST.getMessage())); + } +}
Java
๋ฉ”๋‰ด ์ข…๋ฅ˜๋ณ„ ์ฃผ๋ฌธ ์ˆ˜๋Ÿ‰์„ ์ €์žฅํ•˜๋Š” Map์„ ๋งŒ๋“œ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์žˆ์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,54 @@ +package christmas.model.calendar; + +import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS; +import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH; +import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR; +import static christmas.model.calendar.enums.CalendarDate.FRIDAY; +import static christmas.model.calendar.enums.CalendarDate.SATURDAY; +import static christmas.model.calendar.enums.CalendarDate.SUNDAY; + +import java.time.LocalDate; + +public abstract class EventCalendar implements Calendar { + + protected final LocalDate eventDate; + + public EventCalendar(int visitDay) { + validate(visitDay); + this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay); + } + + protected abstract void validateDayRange(int visitDay); + + @Override + public boolean isWeekend() { + int visitDay = getDayOfWeek(); + return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber(); + } + + @Override + public boolean isSpecialDay() { + return isChristmas() || isSunday(); + } + + @Override + public int getDayOfMonth() { + return eventDate.getDayOfMonth(); + } + + private void validate(int visitDay) { + validateDayRange(visitDay); + } + + private boolean isChristmas() { + return getDayOfMonth() == CHRISTMAS.getNumber(); + } + + private boolean isSunday() { + return getDayOfWeek() == SUNDAY.getNumber(); + } + + private int getDayOfWeek() { + return eventDate.getDayOfWeek().getValue(); + } +}
Java
`DayOfWeek`๋Š” `enum` ํƒ€์ž…์ด๊ธฐ์— ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ง์ ‘์ ์ธ ๋™๋“ฑ์„ฑ ๋น„๊ต๋„ ๊ฐ€๋Šฅํ•˜๋ฉฐ, ์ด ๊ฒฝ์šฐ๊ฐ€ ๊ฐ€๋…์„ฑ๋„ ๋” ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ```suggestion DayOfWeek week = eventDate.getDayOfWeek(); return week == DayOfWeek.FRIDAY || week == DayOfWeek.SATURDAY; ```
@@ -0,0 +1,14 @@ +package christmas.model.calendar; + +import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS; + +public class CalendarFactory { + + public static Calendar createCalendar(int day) { + if (day <= CHRISTMAS.getNumber()) { + return new ChristmasEventCalendar(day); + } + + return new GeneralEventCalendar(day); + } +}
Java
์•„ํ•˜, ์ž…๋ ฅ ๋‚ ์งœ๊ฐ€ ํฌ๋ฆฌ์Šค๋งˆ์Šค ์ดํ›„์ธ์ง€์˜ ์—ฌ๋ถ€์— ๋”ฐ๋ผ ๊ฐ๊ฐ ๋‹ค๋ฅธ `Calendar` ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋„๋ก ํ•˜์…จ๋„ค์š”. ์ด๋ ‡๊ฒŒ๋„ ๊ตฌํ˜„์„ ํ•  ์ˆ˜ ์žˆ์—ˆ๊ตฐ์š”!
@@ -0,0 +1,31 @@ +package christmas.model.badge.enums; + +import java.util.Arrays; + +public enum BadgeInfo { + + SANTA_BADGE("์‚ฐํƒ€", 20_000), + TREE_BADGE("ํŠธ๋ฆฌ", 10_000), + START_BADGE("๋ณ„", 5_000), + NON_BADGE("์—†์Œ", 0); + + private final String name; + + private final int price; + + BadgeInfo(String name, int price) { + this.name = name; + this.price = price; + } + + public static BadgeInfo findBadgeByPrice(int totalPrice) { + return Arrays.stream(values()) + .filter(badge -> totalPrice >= badge.price) + .findFirst() + .orElse(NON_BADGE); + } + + public String getName() { + return name; + } +}
Java
๋ฑƒ์ง€๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ํ•˜ํ•œ๊ฐ€ ๊ธˆ์•ก๋งŒ ์„ค์ •ํ•ด ๋‘๊ณ , `enum`์˜ ์ˆœ์„œ๋ฅผ ํ™œ์šฉํ•˜์…จ๋„ค์š”! `enum`์˜ ์ˆœ์„œ์— ์˜ํ–ฅ์„ ๋ฐ›๋Š” ๋กœ์ง์„ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ์˜ณ์€๊ฐ€ ์— ๋Œ€ํ•œ ํ™•์‹ ์ด ์—†์–ด ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜์ง€ ๋ชปํ–ˆ๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์ด ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•˜๊ณ  ์ข‹์•˜์„ ๊ฒƒ๋„ ๊ฐ™๊ตฐ์š”!
@@ -0,0 +1,20 @@ +package christmas.model.badge; + +import christmas.model.badge.enums.BadgeInfo; + +public class Badge { + + private final BadgeInfo badgeInfo; + + public Badge(int totalDiscountAmount) { + this.badgeInfo = selectBadge(totalDiscountAmount); + } + + public String getBadgeName() { + return badgeInfo.getName(); + } + + private BadgeInfo selectBadge(int totalDiscountAmount) { + return BadgeInfo.findBadgeByPrice(totalDiscountAmount); + } +}
Java
ํ•ด๋‹น ํด๋ž˜์Šค๋Š” ์–ด๋–ป๊ฒŒ ๋ณด๋ฉด `BadgeInfo`๋ฅผ ๋ž˜ํ•‘ํ•˜๊ณ  ์žˆ๋Š” ๋ž˜ํ•‘ ํด๋ž˜์Šค์ฒ˜๋Ÿผ ๋ณด์ด๋Š”๋ฐ์š”. ์ด ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์—๋Š” ์–ด๋–ค ์ด์ ์ด ์žˆ์„ ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,15 @@ +package christmas.model.order.enums; + +public enum Category { + + APPETIZER("์—ํ”ผํƒ€์ด์ €"), + MAIN_COURSE("๋ฉ”์ธ"), + DESSERT("๋””์ €ํŠธ"), + BEVERAGE("์Œ๋ฃŒ"); + + private final String category; + + Category(String category) { + this.category = category; + } +}
Java
ํ•ด๋‹น ํ•„๋“œ๋Š” ํ™•์žฅ์„ฑ์„ ์œ„ํ•œ ํ•„๋“œ์ธ๊ฐ€์š”?
@@ -0,0 +1,51 @@ +package christmas.model.order; + +import static christmas.exception.ErrorType.INVALID_MENU_NAME; + +import christmas.model.order.enums.Category; +import christmas.model.order.enums.MenuInfo; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class OrderMenu { + + private final Map<MenuName, MenuQuantity> orderMenu; + + public OrderMenu() { + this.orderMenu = new HashMap<>(); + } + + public Map<MenuName, MenuQuantity> getOrderMenu() { + return Collections.unmodifiableMap(orderMenu); + } + + public int getMenuQuantity(MenuName menuName) { + return orderMenu.get(menuName).getQuantity(); + } + + public boolean containMainMenu(MenuName menuName) { + String menu = menuName.getName(); + return MenuInfo.findByMenuName(menu).getCategory() == Category.MAIN_COURSE; + } + + public boolean containDesertMenu(MenuName menuName) { + String menu = menuName.getName(); + return MenuInfo.findByMenuName(menu).getCategory() == Category.DESSERT; + } + + public void addMenu(MenuName menuName, MenuQuantity menuQuantity) { + validate(menuName); + orderMenu.put(menuName, menuQuantity); + } + + private void validate(MenuName menuName) { + validateDuplicateMenuName(menuName); + } + + private void validateDuplicateMenuName(MenuName menuName) { + if (orderMenu.containsKey(menuName)) { + throw new IllegalArgumentException(INVALID_MENU_NAME.getMessage()); + } + } +}
Java
์ด๋ฆ„์€ `MainMenu`๋ฅผ ํฌํ•จํ•˜๋Š”์ง€๋ฅผ ํŒ๋‹จํ•˜๋Š” ๋ฉ”์„œ๋“œ์ฒ˜๋Ÿผ ๋А๊ปด์ง€๋Š”๋ฐ, ์•„๋ž˜์˜ ๋กœ์ง์€ ์ž…๋ ฅ๋ฐ›์€ ๋ฉ”๋‰ด๊ฐ€ ๋ฉ”์ธ๋ฉ”๋‰ด์ธ์ง€๋ฅผ ํŒ๋‹จํ•˜๋„ค์š”. `contain~`๋ณด๋‹ค `is~`์˜ ๋„ค์ด๋ฐ์ด ์กฐ๊ธˆ ๋” ์ ์ ˆํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,64 @@ +package christmas.model.result; + +import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT; + +public class DiscountResult { + + private int christmasDiscount; + + private int weeksDaysDiscount; + + private int weekendDiscount; + + private int specialDiscount; + + private int giveawayDiscount; + + public DiscountResult() { + this.christmasDiscount = NON_DISCOUNT.getDiscount(); + this.weeksDaysDiscount = NON_DISCOUNT.getDiscount(); + this.weekendDiscount = NON_DISCOUNT.getDiscount(); + this.specialDiscount = NON_DISCOUNT.getDiscount(); + this.giveawayDiscount = NON_DISCOUNT.getDiscount(); + } + + public void updateChristmasDiscount(int christmasDiscount) { + this.christmasDiscount = christmasDiscount; + } + + public void updateWeeksDaysDiscount(int weeksDaysDiscount) { + this.weeksDaysDiscount = weeksDaysDiscount; + } + + public void updateWeekendDiscount(int weekendDiscount) { + this.weekendDiscount = weekendDiscount; + } + + public void updateSpecialDiscount(int specialDiscount) { + this.specialDiscount = specialDiscount; + } + + public void updateGiveawayDiscount(int giveawayDiscount) { + this.giveawayDiscount = giveawayDiscount; + } + + public int getChristmasDiscount() { + return christmasDiscount; + } + + public int getWeeksDaysDiscount() { + return weeksDaysDiscount; + } + + public int getWeekendDiscount() { + return weekendDiscount; + } + + public int getSpecialDiscount() { + return specialDiscount; + } + + public int getGiveawayDiscount() { + return giveawayDiscount; + } +}
Java
์•„ํ•˜, ์ฒ˜์Œ์—” ๋ชจ๋“  ํ• ์ธ ์ ์šฉ์„ 0์œผ๋กœ ๋‘๊ณ  ํ• ์ธ์„ ์ ์šฉํ•  ์ˆ˜ ์žˆ์„ ๋• ๋‚ด๋ถ€์˜ ๊ฐ’๋“ค์„ ์ƒˆ๋กœ ์—…๋ฐ์ดํŠธ ํ•ด์ฃผ๋Š”๊ตฐ์š”! ์ €์™€๋Š” ๋‹ค๋ฅธ ์ ‘๊ทผ์ด๋ผ์„œ ์ •๋ง ์žฌ๋ฏธ์žˆ๊ฒŒ ์ฝ์—ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,81 @@ +package christmas.model.order; + +import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY; +import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK; +import static christmas.utils.Constants.MAX_ORDER_QUANTITY; +import static christmas.utils.Constants.MIN_ORDER_MENU; + +import christmas.model.order.enums.Category; +import christmas.model.order.enums.MenuInfo; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OrderDetail { + + private final OrderMenu orderMenu; + + public OrderDetail(OrderMenu orderMenu) { + validate(orderMenu); + this.orderMenu = orderMenu; + } + + public Map<String, Integer> getOrderMenuName() { + Map<String, Integer> details = new HashMap<>(); + for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) { + String menuName = entry.getKey().getName(); + int quantity = entry.getValue().getQuantity(); + details.put(menuName, quantity); + } + + return Collections.unmodifiableMap(details); + } + + public int getQuantityByMenu(MenuName menuName) { + return orderMenu.getMenuQuantity(menuName); + } + + public List<MenuName> getMainMenu() { + return orderMenu.getOrderMenu().keySet().stream() + .filter(orderMenu::containMainMenu) + .toList(); + } + + public List<MenuName> getDesertMenu() { + return orderMenu.getOrderMenu().keySet().stream() + .filter(orderMenu::containDesertMenu) + .toList(); + } + + private void validate(OrderMenu orderMenu) { + if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) { + validateOnlyBeverage(orderMenu); + } + + validateMaxQuantity(calculateTotalQuantity(orderMenu)); + } + + private void validateOnlyBeverage(OrderMenu orderMenu) { + MenuName menuName = orderMenu.getOrderMenu().keySet().stream() + .findFirst() + .orElseThrow(); + + String name = menuName.getName(); + if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) { + throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage()); + } + } + + private void validateMaxQuantity(int totalQuantity) { + if (totalQuantity > MAX_ORDER_QUANTITY) { + throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage()); + } + } + + private int calculateTotalQuantity(OrderMenu orderMenu) { + return orderMenu.getOrderMenu().values().stream() + .mapToInt(MenuQuantity::getQuantity) + .sum(); + } +}
Java
์ด ์ฝ”๋“œ์˜ ํ๋ฆ„์„ ์ดํ•ดํ•ด ๋ณด๊ณ ์ž ์ •๋ง ์—ด์‹ฌํžˆ ๋…ธ๋ ฅํ–ˆ๋Š”๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค...ใ… ใ…  ์ฃผ๋ฌธ ๋ชฉ๋ก์˜ ์ฒซ ๋ฒˆ์งธ ๋ฉ”๋‰ด๋งŒ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ํ™•์ธํ•˜๋Š” ๊ฒƒ์œผ๋กœ ํ•ด์„์„ ํ–ˆ๋Š”๋ฐ ์ด๊ฒŒ ์–ด๋–ป๊ฒŒ ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•œ ๊ฒฝ์šฐ๋ฅผ ํŒ๋ณ„ํ•  ์ˆ˜ ์žˆ๋Š” ์ง€ ๋ชจ๋ฅด๊ฒ ์–ด์š”... ๊ดœ์ฐฎ์œผ์‹œ๋‹ค๋ฉด ํŽธํ•˜์‹ค ๋•Œ ์„ค๋ช… ํ•œ๋ฒˆ๋งŒ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค..!
@@ -0,0 +1,30 @@ +package christmas.model.calendar; + +import static christmas.exception.ErrorType.INVALID_DAY_OUT_OF_RANGE; +import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS; +import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH; +import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR; +import static christmas.model.calendar.enums.CalendarDate.FRIDAY; +import static christmas.model.calendar.enums.CalendarDate.SATURDAY; +import static christmas.model.calendar.enums.CalendarDate.START_DAY; +import static christmas.model.calendar.enums.CalendarDate.SUNDAY; + +import java.time.LocalDate; + +public class ChristmasEventCalendar extends EventCalendar { + + public ChristmasEventCalendar(int visitDay) { + super(visitDay); + } + + protected void validateDayRange(int visitDay) { + if (visitDay < START_DAY.getNumber() || visitDay > CHRISTMAS.getNumber()) { + throw new IllegalArgumentException(INVALID_DAY_OUT_OF_RANGE.getMessage()); + } + } + + public int calculateVisitDayFromStart() { + int visitDay = getDayOfMonth(); + return visitDay - START_DAY.getNumber(); + } +}
Java
์กฐ๊ฑด๋ฌธ์ด ๊ธธ์–ด์ง„๋‹ค๋ฉด ๋ฉ”์†Œ๋“œ๋กœ ๋”ฐ๋กœ ๋นผ๋‘๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,20 @@ +package christmas.model.badge; + +import christmas.model.badge.enums.BadgeInfo; + +public class Badge { + + private final BadgeInfo badgeInfo; + + public Badge(int totalDiscountAmount) { + this.badgeInfo = selectBadge(totalDiscountAmount); + } + + public String getBadgeName() { + return badgeInfo.getName(); + } + + private BadgeInfo selectBadge(int totalDiscountAmount) { + return BadgeInfo.findBadgeByPrice(totalDiscountAmount); + } +}
Java
์ €๋„ ๊ฐ™์€ ์˜๊ฒฌ์ž…๋‹ˆ๋‹ค ! `Badge` ํด๋ž˜์Šค์—์„œ ์ด๋ค„์ง€๋Š” ๋ชจ๋“  ๋กœ์ง์€ `BadgeInfo`์—์„œ๋„ ๋™์ผํ•˜๊ธฐ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๊ณ  ๊ทธ๋ ‡๊ฒŒ ํ•œ๋‹ค๋ฉด ํด๋ž˜์Šค ๋ช…์— Info ๋ฅผ ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์•„๋„ ๋ผ์„œ ๋”์šฑ ๊น”๋”ํ•œ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š” !
@@ -0,0 +1,54 @@ +package christmas.model.calendar; + +import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS; +import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH; +import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR; +import static christmas.model.calendar.enums.CalendarDate.FRIDAY; +import static christmas.model.calendar.enums.CalendarDate.SATURDAY; +import static christmas.model.calendar.enums.CalendarDate.SUNDAY; + +import java.time.LocalDate; + +public abstract class EventCalendar implements Calendar { + + protected final LocalDate eventDate; + + public EventCalendar(int visitDay) { + validate(visitDay); + this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay); + } + + protected abstract void validateDayRange(int visitDay); + + @Override + public boolean isWeekend() { + int visitDay = getDayOfWeek(); + return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber(); + } + + @Override + public boolean isSpecialDay() { + return isChristmas() || isSunday(); + } + + @Override + public int getDayOfMonth() { + return eventDate.getDayOfMonth(); + } + + private void validate(int visitDay) { + validateDayRange(visitDay); + } + + private boolean isChristmas() { + return getDayOfMonth() == CHRISTMAS.getNumber(); + } + + private boolean isSunday() { + return getDayOfWeek() == SUNDAY.getNumber(); + } + + private int getDayOfWeek() { + return eventDate.getDayOfWeek().getValue(); + } +}
Java
LocalDate๋ฅผ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์—ˆ๊ตฐ์š” ..! ๋” ๋‹ค์–‘ํ•ญ ํ™œ์šฉ์„ ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,45 @@ +package christmas.model.discount; + +import static christmas.model.discount.enums.DiscountAmount.DESERT_DISCOUNT; +import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT; +import static christmas.utils.Constants.MIN_ORDER_MENU; + +import christmas.model.calendar.Calendar; +import christmas.model.order.MenuName; +import christmas.model.order.OrderDetail; +import java.util.List; + +public class WeekdaysDiscount implements Discount { + + private final Calendar calendar; + + private final OrderDetail orderDetail; + + public WeekdaysDiscount(Calendar calendar, OrderDetail orderDetail) { + this.calendar = calendar; + this.orderDetail = orderDetail; + } + + @Override + public int calculateDiscount() { + if (!calendar.isWeekend()) { + return desertDiscountPrice(); + } + return NON_DISCOUNT.getDiscount(); + } + + private int desertDiscountPrice() { + List<MenuName> desertMenu = orderDetail.getDesertMenu(); + int totalPrice = NON_DISCOUNT.getDiscount(); + if (desertMenu.size() < MIN_ORDER_MENU) { + return totalPrice; + } + + for (MenuName menuName : desertMenu) { + int quantityByMenu = orderDetail.getQuantityByMenu(menuName); + totalPrice += (quantityByMenu * DESERT_DISCOUNT.getDiscount()); + } + + return totalPrice; + } +}
Java
`orderDetail.getDesertMenu()` ์—์„œ ๋””์ €ํŠธ ๋ฉ”๋‰ด๊ฐ€ ์—†๋‹ค๋ฉด ๋นˆ ์ปฌ๋ ‰์…˜์ด ๋ฐ˜ํ™˜๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ด ๊ฒ€์ฆ ๋กœ์ง์ด ์—†์–ด๋„ ๊ดœ์ฐฎ์ง€ ์•Š์„๊นŒ? ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”!
@@ -0,0 +1,45 @@ +package christmas.model.discount; + +import static christmas.model.discount.enums.DiscountAmount.MAIN_COURSE_DISCOUNT; +import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT; +import static christmas.utils.Constants.MIN_ORDER_MENU; + +import christmas.model.calendar.Calendar; +import christmas.model.order.MenuName; +import christmas.model.order.OrderDetail; +import java.util.List; + +public class WeekendDiscount implements Discount { + + private final Calendar calendar; + + private final OrderDetail orderDetail; + + public WeekendDiscount(Calendar calendar, OrderDetail orderDetail) { + this.calendar = calendar; + this.orderDetail = orderDetail; + } + + @Override + public int calculateDiscount() { + if (calendar.isWeekend()) { + return mainCourseDiscountPrice(); + } + return NON_DISCOUNT.getDiscount(); + } + + private int mainCourseDiscountPrice() { + List<MenuName> mainMenu = orderDetail.getMainMenu(); + int totalPrice = NON_DISCOUNT.getDiscount(); + if (mainMenu.size() < MIN_ORDER_MENU) { + return totalPrice; + } + + for (MenuName menuName : mainMenu) { + int quantityByMenu = orderDetail.getQuantityByMenu(menuName); + totalPrice += (quantityByMenu * MAIN_COURSE_DISCOUNT.getDiscount()); + } + + return totalPrice; + } +}
Java
~~~java mainMenus.strem() .mapToInt(menu -> orderDetail.getQuantityByMenu(menuName)) .sum() ~~~ ๊ณผ ๊ฐ™์ด ์ŠคํŠธ๋ฆผ์„ ํ™œ์šฉํ•ด ๋ณด๋Š” ๊ฒƒ๋„ ์ข‹์•„๋ณด์—ฌ์š”!
@@ -0,0 +1,83 @@ +package christmas.model.discount.facade; + +import static christmas.model.discount.enums.DiscountAmount.CAN_DISCOUNT_AMOUNT; +import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT; + +import christmas.model.discount.GiveawayDiscount; +import christmas.model.result.DiscountResult; +import christmas.model.calendar.Calendar; +import christmas.model.calendar.ChristmasEventCalendar; +import christmas.model.discount.ChristmasDiscount; +import christmas.model.discount.SpecialDiscount; +import christmas.model.discount.WeekdaysDiscount; +import christmas.model.discount.WeekendDiscount; +import christmas.model.order.OrderDetail; +import christmas.utils.Payment; + +public class DiscountFacade { + + private final Calendar calendar; + + private final OrderDetail orderDetail; + + public DiscountFacade(Calendar calendar, OrderDetail orderDetail) { + this.calendar = calendar; + this.orderDetail = orderDetail; + } + + public int calculateTotalDiscount(Payment payment, DiscountResult discountResult) { + if (!canDiscount(payment)) { + return NON_DISCOUNT.getDiscount(); + } + + if (includeChristmasDiscount()) { + ChristmasDiscount christmasDiscount = new ChristmasDiscount(calendar); + int christmasAmount = christmasDiscount.calculateDiscount(); + discountResult.updateChristmasDiscount(christmasAmount); + return christmasAmount + basicDiscount(payment, discountResult); + } + return basicDiscount(payment, discountResult); + } + + private boolean canDiscount(Payment payment) { + return payment.beforeDiscountPayment(orderDetail) >= CAN_DISCOUNT_AMOUNT.getDiscount(); + } + + private int basicDiscount(Payment payment, DiscountResult discountResult) { + int weekendAmount = calculateWeekendDiscount(); + int weekdaysAmount = calculateWeekdaysDiscount(); + int specialAmount = calculateSpecialDiscount(); + int giveawayAmount = calculateGiveawayDiscount(payment); + + discountResult.updateWeekendDiscount(weekendAmount); + discountResult.updateWeeksDaysDiscount(weekdaysAmount); + discountResult.updateSpecialDiscount(calculateSpecialDiscount()); + discountResult.updateGiveawayDiscount(giveawayAmount); + + return weekendAmount + weekdaysAmount + specialAmount + giveawayAmount; + } + + private int calculateWeekendDiscount() { + WeekendDiscount weekendDiscount = new WeekendDiscount(calendar, orderDetail); + return weekendDiscount.calculateDiscount(); + } + + private int calculateWeekdaysDiscount() { + WeekdaysDiscount weekdaysDiscount = new WeekdaysDiscount(calendar, orderDetail); + return weekdaysDiscount.calculateDiscount(); + } + + private int calculateSpecialDiscount() { + SpecialDiscount specialDiscount = new SpecialDiscount(calendar); + return specialDiscount.calculateDiscount(); + } + + private int calculateGiveawayDiscount(Payment payment) { + GiveawayDiscount giveawayDiscount = new GiveawayDiscount(payment.beforeDiscountPayment(orderDetail)); + return giveawayDiscount.calculateDiscount(); + } + + private boolean includeChristmasDiscount() { + return calendar instanceof ChristmasEventCalendar; + } +}
Java
ํ• ์ธ ํ˜œํƒ๋“ค์„ ๋ชจ๋‘ `Discount`๋กœ ์ถ”์ƒํ™” ํ•ด๋‘์…จ๊ธฐ ๋•Œ๋ฌธ์— ~~~java List<Discount> discounts = List.of( new WeekendDiscount(calendar, orderDetail), new WeekdaysDiscount(calendar, orderDetail), new SpecialDiscount(calendar) ); int discountAmount = discounts.stream() .mapToInt(Discount::calculateDiscount) .sum() ~~~ ์ฒ˜๋Ÿผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ! ์ €๋Š” ๊ทธ๊ฒŒ ์ถ”์ƒํ™”์˜ ๋˜ ๋‹ค๋ฅธ ์žฅ์ ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์š”!
@@ -0,0 +1,81 @@ +package christmas.model.order; + +import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY; +import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK; +import static christmas.utils.Constants.MAX_ORDER_QUANTITY; +import static christmas.utils.Constants.MIN_ORDER_MENU; + +import christmas.model.order.enums.Category; +import christmas.model.order.enums.MenuInfo; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OrderDetail { + + private final OrderMenu orderMenu; + + public OrderDetail(OrderMenu orderMenu) { + validate(orderMenu); + this.orderMenu = orderMenu; + } + + public Map<String, Integer> getOrderMenuName() { + Map<String, Integer> details = new HashMap<>(); + for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) { + String menuName = entry.getKey().getName(); + int quantity = entry.getValue().getQuantity(); + details.put(menuName, quantity); + } + + return Collections.unmodifiableMap(details); + } + + public int getQuantityByMenu(MenuName menuName) { + return orderMenu.getMenuQuantity(menuName); + } + + public List<MenuName> getMainMenu() { + return orderMenu.getOrderMenu().keySet().stream() + .filter(orderMenu::containMainMenu) + .toList(); + } + + public List<MenuName> getDesertMenu() { + return orderMenu.getOrderMenu().keySet().stream() + .filter(orderMenu::containDesertMenu) + .toList(); + } + + private void validate(OrderMenu orderMenu) { + if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) { + validateOnlyBeverage(orderMenu); + } + + validateMaxQuantity(calculateTotalQuantity(orderMenu)); + } + + private void validateOnlyBeverage(OrderMenu orderMenu) { + MenuName menuName = orderMenu.getOrderMenu().keySet().stream() + .findFirst() + .orElseThrow(); + + String name = menuName.getName(); + if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) { + throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage()); + } + } + + private void validateMaxQuantity(int totalQuantity) { + if (totalQuantity > MAX_ORDER_QUANTITY) { + throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage()); + } + } + + private int calculateTotalQuantity(OrderMenu orderMenu) { + return orderMenu.getOrderMenu().values().stream() + .mapToInt(MenuQuantity::getQuantity) + .sum(); + } +}
Java
์ด๋ฏธ `OrderMenu`๊ฐ€ ์ผ๊ธ‰ ์ปฌ๋ ‰์…˜์˜ ์—ญํ• ์„ ํ•˜๊ณ  ์žˆ๋Š”๋ฐ ๊ตณ์ด ํ•œ๋ฒˆ ๋” ๊ฐ์‹ธ์•ผ ํ•˜๋‚˜?? ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ญ๋‹ˆ๋‹ค.. ๊ฐ™์€ ์—ญํ• ์„ `OrderMenu`๊ฐ€ ์ˆ˜ํ–‰ํ•ด๋„ ๋ฌธ๋งฅ์ƒ ์ „ํ˜€ ์ด์ƒํ•˜์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,54 @@ +package christmas.model.calendar; + +import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS; +import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH; +import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR; +import static christmas.model.calendar.enums.CalendarDate.FRIDAY; +import static christmas.model.calendar.enums.CalendarDate.SATURDAY; +import static christmas.model.calendar.enums.CalendarDate.SUNDAY; + +import java.time.LocalDate; + +public abstract class EventCalendar implements Calendar { + + protected final LocalDate eventDate; + + public EventCalendar(int visitDay) { + validate(visitDay); + this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay); + } + + protected abstract void validateDayRange(int visitDay); + + @Override + public boolean isWeekend() { + int visitDay = getDayOfWeek(); + return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber(); + } + + @Override + public boolean isSpecialDay() { + return isChristmas() || isSunday(); + } + + @Override + public int getDayOfMonth() { + return eventDate.getDayOfMonth(); + } + + private void validate(int visitDay) { + validateDayRange(visitDay); + } + + private boolean isChristmas() { + return getDayOfMonth() == CHRISTMAS.getNumber(); + } + + private boolean isSunday() { + return getDayOfWeek() == SUNDAY.getNumber(); + } + + private int getDayOfWeek() { + return eventDate.getDayOfWeek().getValue(); + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,20 @@ +package christmas.model.badge; + +import christmas.model.badge.enums.BadgeInfo; + +public class Badge { + + private final BadgeInfo badgeInfo; + + public Badge(int totalDiscountAmount) { + this.badgeInfo = selectBadge(totalDiscountAmount); + } + + public String getBadgeName() { + return badgeInfo.getName(); + } + + private BadgeInfo selectBadge(int totalDiscountAmount) { + return BadgeInfo.findBadgeByPrice(totalDiscountAmount); + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ฐ์ฒด์—๊ฒŒ ๋ฉ”์„ธ์ง€๋ฅผ ๋˜์ ธ์„œ ์บก์Аํ™” ์‹œํ‚ค๋ ค๊ณ  ์˜๋„ํ–ˆ์—ˆ๋Š”๋ฐ, ์ƒ๋‹นํžˆ ๋ถˆํ•„์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋„ค์š” ใ…Žใ…Ž
@@ -0,0 +1,15 @@ +package christmas.model.order.enums; + +public enum Category { + + APPETIZER("์—ํ”ผํƒ€์ด์ €"), + MAIN_COURSE("๋ฉ”์ธ"), + DESSERT("๋””์ €ํŠธ"), + BEVERAGE("์Œ๋ฃŒ"); + + private final String category; + + Category(String category) { + this.category = category; + } +}
Java
๋„ค ๋งž์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,81 @@ +package christmas.model.order; + +import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY; +import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK; +import static christmas.utils.Constants.MAX_ORDER_QUANTITY; +import static christmas.utils.Constants.MIN_ORDER_MENU; + +import christmas.model.order.enums.Category; +import christmas.model.order.enums.MenuInfo; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OrderDetail { + + private final OrderMenu orderMenu; + + public OrderDetail(OrderMenu orderMenu) { + validate(orderMenu); + this.orderMenu = orderMenu; + } + + public Map<String, Integer> getOrderMenuName() { + Map<String, Integer> details = new HashMap<>(); + for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) { + String menuName = entry.getKey().getName(); + int quantity = entry.getValue().getQuantity(); + details.put(menuName, quantity); + } + + return Collections.unmodifiableMap(details); + } + + public int getQuantityByMenu(MenuName menuName) { + return orderMenu.getMenuQuantity(menuName); + } + + public List<MenuName> getMainMenu() { + return orderMenu.getOrderMenu().keySet().stream() + .filter(orderMenu::containMainMenu) + .toList(); + } + + public List<MenuName> getDesertMenu() { + return orderMenu.getOrderMenu().keySet().stream() + .filter(orderMenu::containDesertMenu) + .toList(); + } + + private void validate(OrderMenu orderMenu) { + if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) { + validateOnlyBeverage(orderMenu); + } + + validateMaxQuantity(calculateTotalQuantity(orderMenu)); + } + + private void validateOnlyBeverage(OrderMenu orderMenu) { + MenuName menuName = orderMenu.getOrderMenu().keySet().stream() + .findFirst() + .orElseThrow(); + + String name = menuName.getName(); + if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) { + throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage()); + } + } + + private void validateMaxQuantity(int totalQuantity) { + if (totalQuantity > MAX_ORDER_QUANTITY) { + throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage()); + } + } + + private int calculateTotalQuantity(OrderMenu orderMenu) { + return orderMenu.getOrderMenu().values().stream() + .mapToInt(MenuQuantity::getQuantity) + .sum(); + } +}
Java
์ƒ๋‹จ์— validate๋ฅผ ๋ณด์‹œ๋ฉด ์ดํ•ดํ•˜์‹ค ์ˆ˜ ์žˆ์„๊ฑฐ์—์š”..!
@@ -0,0 +1,63 @@ +package christmas.controller; + +import christmas.domain.PromotionService; +import christmas.domain.order.Day; +import christmas.domain.order.Order; +import christmas.dto.response.DiscountPreviewResponse; +import christmas.view.InputView; +import christmas.view.OutputView; + +import java.util.function.Supplier; + +public class PromotionController { + + private PromotionController() { + + } + + public static PromotionController create() { + return new PromotionController(); + } + + + public void run() { + printIntroductionMessage(); + + Day day = readWithExceptionHandling(PromotionController::readDay); + Order order = readWithExceptionHandling(PromotionController::readOrder); + PromotionService promotionService = PromotionService.create(order, day); + closeRead(); + + printDiscountPreviewMessage(promotionService); + } + + private static void printIntroductionMessage() { + OutputView.printIntroductionMessage(); + } + + private static <T> T readWithExceptionHandling(Supplier<T> reader) { + while (true) { + try { + return reader.get(); + } catch (IllegalArgumentException exception) { + System.out.println(exception.getMessage()); + } + } + } + + private static Day readDay() throws IllegalArgumentException { + return Day.create(InputView.readEstimatedVisitingDate()); + } + + private static Order readOrder() throws IllegalArgumentException { + return Order.create(InputView.readOrder()); + } + + private static void closeRead() { + InputView.closeRead(); + } + + private static void printDiscountPreviewMessage(PromotionService promotionService) { + OutputView.printDiscountPreviewMessage(DiscountPreviewResponse.from(promotionService)); + } +}
Java
static ๋ฉ”์†Œ๋“œ๊ฐ€ ์†๋„๊ฐ€ ๋นจ๋ผ์ง„๋‹ค๋Š” ์žฅ์ ์ด ์žˆ์ง€๋งŒ ๊ฐ์ฒด์ง€ํ–ฅ์—์„œ ๋ฉ€์–ด์ง€๊ธฐ ๋•Œ๋ฌธ์— ์ง€์–‘ํ•ด์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ํ˜น์‹œ Controller ๋‚ด ๋ฉ”์†Œ๋“œ๋“ค์„ ๋ชจ๋‘ static ๋ฉ”์†Œ๋“œ๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”??
@@ -0,0 +1,40 @@ +package christmas.domain.order; + +import christmas.validator.OrderValidator; + +import java.util.Objects; + +public class Day { + + private final Integer day; + + private Day(Integer day) { + validate(day); + this.day = day; + } + + public static Day create(Integer day) { + return new Day(day); + } + + private void validate(Integer day) { + OrderValidator.validateIsDateInRange(day); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Day day1 = (Day) o; + return Objects.equals(day, day1.day); + } + + @Override + public int hashCode() { + return Objects.hash(day); + } + + public Integer getPrimitiveDay() { + return day; + } +}
Java
Day ๊ฐ์ฒด์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ OrderValidator์—์„œ ์ง„ํ–‰ํ•˜๊ฒŒ ๋˜๋ฉด ๋„๋ฉ”์ธ ๋‚ด๋ถ€ ์ƒํƒœ ๋ฐ์ดํ„ฐ์˜ ์บก์Аํ™”๊ฐ€ ๊นจ์งˆ ๋ฟ๋”๋Ÿฌ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ์˜ ์–‘์ด ๋งŽ์•„์ง€๋ฉด OrderValidator ๊ฐ์ฒด๊ฐ€ ๋น„๋Œ€ํ•ด์ง„๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. Day ๊ฐ์ฒด ๋‚ด๋ถ€์—์„œ ์ง„ํ–‰ํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”??
@@ -0,0 +1,74 @@ +package christmas.domain.order; + +import christmas.domain.order.menu.Menu; +import christmas.domain.order.menu.Quantity; +import christmas.dto.request.OrderRequest; +import christmas.dto.response.OrderResponse; +import christmas.util.InputUtil; +import christmas.validator.OrderValidator; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class Order { + + Map<Menu, Quantity> Order; + + private Order(List<OrderRequest> orderRequests) { + Map<Menu, Quantity> order = InputUtil.parseOrderRequests(orderRequests); + validate(order); + this.Order = new EnumMap<>(order); + } + + public static Order create(List<OrderRequest> orderRequests) { + return new Order(orderRequests); + } + + private void validate(Map<Menu, Quantity> order) { + OrderValidator.validateHasOnlyDrink(order); + OrderValidator.validateIsTotalQuantityValid(order); + } + + public List<OrderResponse> findOrderResponses() { + return Order + .entrySet() + .stream() + .map(entry -> OrderResponse.of(entry.getKey(), entry.getValue())) + .toList(); + } + + public int calculateInitialPrice() { + return Order + .entrySet() + .stream() + .mapToInt(entry -> getMenuPrice(entry) * getEachQuantity(entry)) + .sum(); + } + + private int getMenuPrice(Map.Entry<Menu, Quantity> entry) { + return entry.getKey().getPrice(); + } + + private Integer getEachQuantity(Map.Entry<Menu, Quantity> entry) { + return entry.getValue().getPrimitiveQuantity(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Order order = (Order) o; + return Objects.equals(getOrder(), order.getOrder()); + } + + @Override + public int hashCode() { + return Objects.hash(getOrder()); + } + + public Map<Menu, Quantity> getOrder() { + return new EnumMap<>(Order); + } +}
Java
์ ‘๊ทผ์ œ์–ด์ž๋ฅผ default๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,70 @@ +package christmas.domain.order.menu; + +import java.util.Arrays; +import java.util.Map; + +public enum Menu { + + // ๊ธฐํƒ€ + NONE("์—†์Œ", 0, MenuType.NONE), + + // ์—ํ”ผํƒ€์ด์ € + MUSHROOM_SOUP("์–‘์†ก์ด ์Šคํ”„", 6_000, MenuType.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, MenuType.APPETIZER), + CAESAR_SALAD("์‹œ์ € ์ƒ๋Ÿฌ๋“œ", 8_000, MenuType.APPETIZER), + + // ๋ฉ”์ธ + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, MenuType.MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, MenuType.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, MenuType.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, MenuType.MAIN), + + // ๋””์ €ํŠธ + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, MenuType.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, MenuType.DESSERT), + + // ์Œ๋ฃŒ + ZERO_COKE("์ œ๋กœ์ฝœ๋ผ", 3_000, MenuType.DRINK), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, MenuType.DRINK), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, MenuType.DRINK); + + private final String name; + private final int price; + private final MenuType type; + + Menu(String name, int price, MenuType type) { + this.name = name; + this.price = price; + this.type = type; + } + + public static Menu findByName(String name) { + return Arrays.stream(values()) + .filter(menu -> menu.name.equals(name)) + .findAny() + .orElse(Menu.NONE); + } + + public static boolean isGiftMenu(Menu menu) { + return getGiftMenus() + .keySet() + .stream() + .anyMatch(giftMenu -> giftMenu.equals(menu)); + } + + public static Map<Menu, Quantity> getGiftMenus() { + return Map.of(Menu.CHAMPAGNE, Quantity.create(1)); + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public MenuType getType() { + return type; + } +}
Java
์ œ ๊ฒฝ์šฐ 1์›” ์ƒˆํ•ด ์ด๋ฒคํŠธ์— ์ด๋ฒคํŠธ๊ฐ€ ๋ณ€๊ฒฝ๋  ์ˆ˜ ์žˆ๋‹ค ๊ฐ€์ •ํ•ด Menu ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์„ ์–ธํ•œ ๋’ค ์—ํ”ผํƒ€์ด์ €, ๋ฉ”์ธ, ๋””์ €ํŠธ, ์Œ๋ฃŒ๋ณ„๋กœ ENUM ๊ฐ์ฒด๋ฅผ ๊ฐ๊ฐ ๋”ฐ๋กœ ์„ ์–ธํ–ˆ์Šต๋‹ˆ๋‹ค! ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ``` java public interface Menu { int discount(int day); String getName(); int getPrice(); } ``` ``` java public enum Appetizer implements Menu { MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6000), TAPAS("ํƒ€ํŒŒ์Šค", 5500), CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8000); private final String name; private final int price; Appetizer(String name, int price) { this.name = name; this.price = price; } @Override public int discount(int day) { return 0; } @Override public String getName() { return name; } @Override public int getPrice() { return price; } } ```
@@ -0,0 +1,40 @@ +package christmas.domain.order.menu; + +import christmas.validator.OrderValidator; + +import java.util.Objects; + +public class Quantity { + + private final Integer quantity; + + private Quantity(Integer quantity) { + validate(quantity); + this.quantity = quantity; + } + + public static Quantity create(Integer quantity) { + return new Quantity(quantity); + } + + private void validate(Integer quantity) { + OrderValidator.validateIsEachQuantityGreaterThanCondition(quantity); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Quantity quantity1 = (Quantity) o; + return Objects.equals(quantity, quantity1.quantity); + } + + @Override + public int hashCode() { + return Objects.hash(quantity); + } + + public Integer getPrimitiveQuantity() { + return quantity; + } +}
Java
int๊ฐ€ ์•„๋‹Œ Integer๋กœ ์„ ์–ธํ•ด์ฃผ์‹œ๋Š” ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!๐Ÿค”
@@ -0,0 +1,18 @@ +package christmas.domain.discount; + +import christmas.domain.order.Day; +import christmas.domain.order.Order; + +public interface Discount { + + public void calculateDiscountAmount(Order order, Day day); + + public void checkIsAvailableDiscount(Order order, Day day); + + public String getName(); + + public int getDiscountAmount(); + + public boolean getIsAvailable(); + +}
Java
๋‹คํ˜•์„ฑ์„ ์ด์šฉํ•˜๋Š” ์ •๋ง ์ข‹์€ ๋ฐฉ๋ฒ•์ด๋„ค์š” ๋ฐฐ์šฐ๊ณ ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.domain.order.menu.Menu; +import christmas.dto.request.OrderRequest; +import christmas.util.InputUtil; +import christmas.exception.ErrorMessage; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +public class InputValidator { + + private InputValidator() { + + } + + /* + ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ ์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ + */ + public static void validateEstimatedVisitingDateInput(String input) { + validateIsBlank(input); + validateIsDigit(input); + } + + /* + ์ฃผ๋ฌธ ๋ฉ”๋‰ด ๋ฐ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๊ฐ’ ์ „์ฒด ๊ฒ€์ฆ + */ + public static void validateOrder(String input) { + validateOrderInput(input); + validateOrderRequest(input); + } + + /* + ์ฃผ๋ฌธ ๋ฉ”๋‰ด ๋ฐ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๊ฐ’ ๋ถ„๋ฆฌ ์ „ ๊ฒ€์ฆ + */ + private static void validateOrderInput(String input) { + validateIsBlank(input); + validateIsRightFormat(input); + } + + private static void validateIsRightFormat(String input) { + if (!isRightFormat(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage()); + } + } + + private static boolean isRightFormat(String input) { + String regex = ErrorMessage.ORDER_INPUT_REGEX.getMessage(); + return Pattern.compile(regex) + .matcher(input) + .matches(); + } + + /* + ์ฃผ๋ฌธ ๋ฉ”๋‰ด ๋ฐ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๊ฐ’ ๋ถ„๋ฆฌ ํ›„ ๊ฒ€์ฆ + */ + private static void validateOrderRequest(String input) { + List<OrderRequest> orderRequests = InputUtil.parseOrder(input); + validateIsExistingMenu(orderRequests); + validateHasDuplicatedMenu(orderRequests); + } + + private static void validateIsExistingMenu(List<OrderRequest> orderRequests) { + if (!isExistingMenu(orderRequests)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage()); + } + } + + private static boolean isExistingMenu(List<OrderRequest> orderRequests) { + List<String> menuNames = getMenuNames(); + return orderRequests.stream() + .map(OrderRequest::getMenuName) + .allMatch(menuNames::contains); + } + + private static List<String> getMenuNames() { + return Arrays.stream(Menu.values()) + .map(Menu::getName) + .toList(); + } + + private static void validateHasDuplicatedMenu(List<OrderRequest> orderRequests) { + if (hasDuplicatedMenu(orderRequests)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage()); + } + } + + private static boolean hasDuplicatedMenu(List<OrderRequest> orderRequests) { + return orderRequests.stream() + .map(OrderRequest::getMenuName) + .distinct() + .count() != orderRequests.size(); + } + + /* + ๊ณตํ†ต ๊ฒ€์ฆ + */ + private static void validateIsBlank(String input) { + if (input.isBlank()) { + throw new IllegalArgumentException(ErrorMessage.INPUT_IS_BLANK.getMessage()); + } + } + + private static void validateIsDigit(String input) { + if (!isDigit(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_DATE.getMessage()); + } + } + + private static boolean isDigit(String input) { + try { + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } + } +}
Java
ํ˜„์žฌ InputValidator ๊ฐ์ฒด์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๋ฉ”์†Œ๋“œ๋“ค์€ ๋Œ€๋ถ€๋ถ„ ํŠน์ • ๋„๋ฉ”์ธ์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์œ„ํ•ด ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š”๋ฐ ์ธ์Šคํ„ด์Šค ๋ฉ”์†Œ๋“œ๋กœ ์‚ฌ์šฉํ•˜๋Š”๊ฑด ์–ด๋– ์‹ ๊ฐ€์š”??
@@ -0,0 +1,40 @@ +package christmas.domain.order.menu; + +import christmas.validator.OrderValidator; + +import java.util.Objects; + +public class Quantity { + + private final Integer quantity; + + private Quantity(Integer quantity) { + validate(quantity); + this.quantity = quantity; + } + + public static Quantity create(Integer quantity) { + return new Quantity(quantity); + } + + private void validate(Integer quantity) { + OrderValidator.validateIsEachQuantityGreaterThanCondition(quantity); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Quantity quantity1 = (Quantity) o; + return Objects.equals(quantity, quantity1.quantity); + } + + @Override + public int hashCode() { + return Objects.hash(quantity); + } + + public Integer getPrimitiveQuantity() { + return quantity; + } +}
Java
ํฐ ์˜๋ฏธ๊ฐ€ ์žˆ๋Š” ๊ฒƒ์€ ์•„๋‹ˆ๊ณ , null ์ฒ˜๋ฆฌ์— ๋Œ€๋น„ํ•˜์—ฌ Integer๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ ๋กœ์ง์ด ์ด๋ฏธ ์žˆ์–ด์„œ null์ด ๋“ค์–ด๊ฐˆ ์ผ์€ ์—†์„ ๊ฒƒ ๊ฐ™๊ธฐ๋„ ํ•˜๋„ค์š”!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.domain.order.menu.Menu; +import christmas.dto.request.OrderRequest; +import christmas.util.InputUtil; +import christmas.exception.ErrorMessage; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +public class InputValidator { + + private InputValidator() { + + } + + /* + ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ ์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ + */ + public static void validateEstimatedVisitingDateInput(String input) { + validateIsBlank(input); + validateIsDigit(input); + } + + /* + ์ฃผ๋ฌธ ๋ฉ”๋‰ด ๋ฐ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๊ฐ’ ์ „์ฒด ๊ฒ€์ฆ + */ + public static void validateOrder(String input) { + validateOrderInput(input); + validateOrderRequest(input); + } + + /* + ์ฃผ๋ฌธ ๋ฉ”๋‰ด ๋ฐ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๊ฐ’ ๋ถ„๋ฆฌ ์ „ ๊ฒ€์ฆ + */ + private static void validateOrderInput(String input) { + validateIsBlank(input); + validateIsRightFormat(input); + } + + private static void validateIsRightFormat(String input) { + if (!isRightFormat(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage()); + } + } + + private static boolean isRightFormat(String input) { + String regex = ErrorMessage.ORDER_INPUT_REGEX.getMessage(); + return Pattern.compile(regex) + .matcher(input) + .matches(); + } + + /* + ์ฃผ๋ฌธ ๋ฉ”๋‰ด ๋ฐ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๊ฐ’ ๋ถ„๋ฆฌ ํ›„ ๊ฒ€์ฆ + */ + private static void validateOrderRequest(String input) { + List<OrderRequest> orderRequests = InputUtil.parseOrder(input); + validateIsExistingMenu(orderRequests); + validateHasDuplicatedMenu(orderRequests); + } + + private static void validateIsExistingMenu(List<OrderRequest> orderRequests) { + if (!isExistingMenu(orderRequests)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage()); + } + } + + private static boolean isExistingMenu(List<OrderRequest> orderRequests) { + List<String> menuNames = getMenuNames(); + return orderRequests.stream() + .map(OrderRequest::getMenuName) + .allMatch(menuNames::contains); + } + + private static List<String> getMenuNames() { + return Arrays.stream(Menu.values()) + .map(Menu::getName) + .toList(); + } + + private static void validateHasDuplicatedMenu(List<OrderRequest> orderRequests) { + if (hasDuplicatedMenu(orderRequests)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage()); + } + } + + private static boolean hasDuplicatedMenu(List<OrderRequest> orderRequests) { + return orderRequests.stream() + .map(OrderRequest::getMenuName) + .distinct() + .count() != orderRequests.size(); + } + + /* + ๊ณตํ†ต ๊ฒ€์ฆ + */ + private static void validateIsBlank(String input) { + if (input.isBlank()) { + throw new IllegalArgumentException(ErrorMessage.INPUT_IS_BLANK.getMessage()); + } + } + + private static void validateIsDigit(String input) { + if (!isDigit(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_DATE.getMessage()); + } + } + + private static boolean isDigit(String input) { + try { + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } + } +}
Java
์—ฌํƒœ ํฌ๊ฒŒ ์ƒ๊ฐ์„ ์•ˆ ํ–ˆ๋˜ ๋ถ€๋ถ„์ธ๋ฐ, ์•„๋ฌด๋ž˜๋„ static์„ ๋ถ™์—ฌ์„œ ์•„๋ฌด๋ฐ์„œ๋‚˜ ์“ธ ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค๋Š” ํ•„์š”ํ•œ ๊ณณ์—์„œ๋งŒ ๋ถˆ๋Ÿฌ์™€์„œ ์‚ฌ์šฉํ•˜๋Š” ํŽธ์ด ์žฅ์ ์ด ์žˆ๊ฒ ๋„ค์š”! ์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,63 @@ +package christmas.controller; + +import christmas.domain.PromotionService; +import christmas.domain.order.Day; +import christmas.domain.order.Order; +import christmas.dto.response.DiscountPreviewResponse; +import christmas.view.InputView; +import christmas.view.OutputView; + +import java.util.function.Supplier; + +public class PromotionController { + + private PromotionController() { + + } + + public static PromotionController create() { + return new PromotionController(); + } + + + public void run() { + printIntroductionMessage(); + + Day day = readWithExceptionHandling(PromotionController::readDay); + Order order = readWithExceptionHandling(PromotionController::readOrder); + PromotionService promotionService = PromotionService.create(order, day); + closeRead(); + + printDiscountPreviewMessage(promotionService); + } + + private static void printIntroductionMessage() { + OutputView.printIntroductionMessage(); + } + + private static <T> T readWithExceptionHandling(Supplier<T> reader) { + while (true) { + try { + return reader.get(); + } catch (IllegalArgumentException exception) { + System.out.println(exception.getMessage()); + } + } + } + + private static Day readDay() throws IllegalArgumentException { + return Day.create(InputView.readEstimatedVisitingDate()); + } + + private static Order readOrder() throws IllegalArgumentException { + return Order.create(InputView.readOrder()); + } + + private static void closeRead() { + InputView.closeRead(); + } + + private static void printDiscountPreviewMessage(PromotionService promotionService) { + OutputView.printDiscountPreviewMessage(DiscountPreviewResponse.from(promotionService)); + } +}
Java
์•„...! ์ œ๊ฐ€ ์ธํ…”๋ฆฌ์ œ์ด์˜ ๋ฉ”์†Œ๋“œ ๋ถ„๋ฆฌ ๋‹จ์ถ•ํ‚ค์ธ option + command + v๋ฅผ ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š”๋ฐ, ๊ทธ ๊ณผ์ •์—์„œ ์ž๋™์œผ๋กœ static ๋ฉ”์†Œ๋“œ๋กœ ์„ ์–ธ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ „๋ถ€ ์ง€์›Œ์•ผ๊ฒ ๋„ค์š” ๐Ÿ˜‚
@@ -0,0 +1,40 @@ +package christmas.domain.order; + +import christmas.validator.OrderValidator; + +import java.util.Objects; + +public class Day { + + private final Integer day; + + private Day(Integer day) { + validate(day); + this.day = day; + } + + public static Day create(Integer day) { + return new Day(day); + } + + private void validate(Integer day) { + OrderValidator.validateIsDateInRange(day); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Day day1 = (Day) o; + return Objects.equals(day, day1.day); + } + + @Override + public int hashCode() { + return Objects.hash(day); + } + + public Integer getPrimitiveDay() { + return day; + } +}
Java
๊ฐ VO์—์„œ ์ด๋ฃจ์–ด์ง€๋Š” ๊ฒ€์ฆ์„ ํ•œ ๊ตฐ๋ฐ์—์„œ ๋ชจ์•„ ๊ด€๋ฆฌํ•˜๋ฉด ํŽธ๋ฆฌํ•  ๊ฒƒ์ด๋ผ ์ƒ๊ฐํ•˜์˜€๋Š”๋ฐ, ๋ง์”€์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ์บก์Аํ™”๊ฐ€ ๊นจ์ง€๋Š” ๋ฌธ์ œ๋„ ์žˆ์„ ๋ฟ๋”๋Ÿฌ OrderValidator ๊ฐ์ฒด๊ฐ€ ๋น„๋Œ€ํ•ด์ง„๋‹ค๋ฉด ๊ฒฐ๊ตญ์— ๋กœ์ง์„ ๋ถ„๋ฆฌํ•ด์•ผํ•  ๊ฒƒ์ด๊ณ  ์ด๋Ÿฌ๋ฉด ํ•œ ๊ณณ์—์„œ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์  ๋˜ํ•œ ์‚ฌ๋ผ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฒฐ๊ตญ์—๋Š” ์ œ์ผ ๊ด€๋ จ์„ฑ์ด ๊นŠ์€ VO ๋‚ด๋ถ€์—์„œ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๋Š” ๊ฒƒ์ด ๋งž๊ฒ ๋„ค์š”! ์ข‹์€ ์กฐ์–ธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,74 @@ +package christmas.domain.order; + +import christmas.domain.order.menu.Menu; +import christmas.domain.order.menu.Quantity; +import christmas.dto.request.OrderRequest; +import christmas.dto.response.OrderResponse; +import christmas.util.InputUtil; +import christmas.validator.OrderValidator; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class Order { + + Map<Menu, Quantity> Order; + + private Order(List<OrderRequest> orderRequests) { + Map<Menu, Quantity> order = InputUtil.parseOrderRequests(orderRequests); + validate(order); + this.Order = new EnumMap<>(order); + } + + public static Order create(List<OrderRequest> orderRequests) { + return new Order(orderRequests); + } + + private void validate(Map<Menu, Quantity> order) { + OrderValidator.validateHasOnlyDrink(order); + OrderValidator.validateIsTotalQuantityValid(order); + } + + public List<OrderResponse> findOrderResponses() { + return Order + .entrySet() + .stream() + .map(entry -> OrderResponse.of(entry.getKey(), entry.getValue())) + .toList(); + } + + public int calculateInitialPrice() { + return Order + .entrySet() + .stream() + .mapToInt(entry -> getMenuPrice(entry) * getEachQuantity(entry)) + .sum(); + } + + private int getMenuPrice(Map.Entry<Menu, Quantity> entry) { + return entry.getKey().getPrice(); + } + + private Integer getEachQuantity(Map.Entry<Menu, Quantity> entry) { + return entry.getValue().getPrimitiveQuantity(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Order order = (Order) o; + return Objects.equals(getOrder(), order.getOrder()); + } + + @Override + public int hashCode() { + return Objects.hash(getOrder()); + } + + public Map<Menu, Quantity> getOrder() { + return new EnumMap<>(Order); + } +}
Java
์ €๋„ ์ง€๊ธˆ ๋ดค๋„ค์š”ใ…‹ใ…‹ใ… ใ…  private ์„ ์–ธํ•ด์•ผ ๋˜๋Š”๋ฐ ๊นŒ๋จน์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿคฃ
@@ -0,0 +1,70 @@ +package christmas.domain.order.menu; + +import java.util.Arrays; +import java.util.Map; + +public enum Menu { + + // ๊ธฐํƒ€ + NONE("์—†์Œ", 0, MenuType.NONE), + + // ์—ํ”ผํƒ€์ด์ € + MUSHROOM_SOUP("์–‘์†ก์ด ์Šคํ”„", 6_000, MenuType.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, MenuType.APPETIZER), + CAESAR_SALAD("์‹œ์ € ์ƒ๋Ÿฌ๋“œ", 8_000, MenuType.APPETIZER), + + // ๋ฉ”์ธ + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, MenuType.MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, MenuType.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, MenuType.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, MenuType.MAIN), + + // ๋””์ €ํŠธ + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, MenuType.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, MenuType.DESSERT), + + // ์Œ๋ฃŒ + ZERO_COKE("์ œ๋กœ์ฝœ๋ผ", 3_000, MenuType.DRINK), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, MenuType.DRINK), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, MenuType.DRINK); + + private final String name; + private final int price; + private final MenuType type; + + Menu(String name, int price, MenuType type) { + this.name = name; + this.price = price; + this.type = type; + } + + public static Menu findByName(String name) { + return Arrays.stream(values()) + .filter(menu -> menu.name.equals(name)) + .findAny() + .orElse(Menu.NONE); + } + + public static boolean isGiftMenu(Menu menu) { + return getGiftMenus() + .keySet() + .stream() + .anyMatch(giftMenu -> giftMenu.equals(menu)); + } + + public static Map<Menu, Quantity> getGiftMenus() { + return Map.of(Menu.CHAMPAGNE, Quantity.create(1)); + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public MenuType getType() { + return type; + } +}
Java
๋ฉ”๋‰ด Enum์—๋„ ์ด๋Ÿฐ ์‹์œผ๋กœ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋„ค์š”! ์ฐธ๊ณ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค...!
@@ -0,0 +1,24 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.support.AopUtils; + +import java.lang.reflect.Method; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Method method = invocation.getMethod(); + Class<?> targetClass = AopUtils.getTargetClass(method.getClass()); + Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); + Secured secured = targetMethod.getAnnotation(Secured.class); + + if (authentication.getAuthorities().contains(secured.value())) { + return new AuthorizationDecision(true); + } + + return new AuthorizationDecision(false); + } +}
Java
Spring AOP ํ™˜๊ฒฝ์—์„œ๋Š” ๋Œ€์ƒ ๊ฐ์ฒด๊ฐ€ ํ”„๋ก์‹œ ๊ฐ์ฒด๋กœ ๊ฐ์‹ธ์งˆ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, `method.getAnnotation(Secured.class)`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‹ค์ œ ๊ตฌํ˜„์ฒด์˜ ๋ฉ”์„œ๋“œ์—์„œ ์„ ์–ธ๋œ `@Secured` ์–ด๋…ธํ…Œ์ด์…˜์„ ์ฐพ์ง€ ๋ชปํ•  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ์Šต๋‹ˆ๋‹ค.method.getAnnotation ์™€ AopUtils.getMostSpecificMethod() ์–ด๋–ค ์ฐจ์ด๊ฐ€ ์žˆ์„๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,11 @@ +package nextstep.security.authorization; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; + +public class AuthenticatedAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) { + return new AuthorizationDecision(authentication.isAuthenticated()); + } +}
Java
`AuthenticatedAuthorizationManager`๋Š” ์ธ์ฆ๋œ ์‚ฌ์šฉ์ž์˜ ์ ‘๊ทผ์„ ํ—ˆ์šฉํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ๊ฒฐ์ •ํ•˜๋Š” ์ธ๊ฐ€(Authorization) ์—ญํ• ์„ ํ•˜๋Š”๋ฐ์š”, ๋•Œ๋ฌธ์— `request.setAttribute("username", authentication.getPrincipal());` ๋Š” ์ธ๊ฐ€์˜ ์ฑ…์ž„์„ ๋ฒ—์–ด๋‚œ ๋™์ž‘์œผ๋กœ ๋ณด์—ฌ์ง‘๋‹ˆ๋‹ค. ๊ฐœ์„ ํ•ด ๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ๐Ÿ˜„
@@ -1,13 +1,20 @@ package nextstep.app.ui; +import jakarta.servlet.http.HttpServletRequest; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; +import nextstep.app.exception.UserNotFoundException; +import nextstep.security.authentication.Authentication; import nextstep.security.authorization.Secured; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; +import java.util.Optional; @RestController public class MemberController { @@ -24,6 +31,17 @@ public ResponseEntity<List<Member>> list() { return ResponseEntity.ok(members); } + @GetMapping("/members/me") + public ResponseEntity<Member> get() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + String email = authentication.getPrincipal().toString(); + + Member member = memberRepository.findByEmail(email) + .orElseThrow(UserNotFoundException::new); + + return ResponseEntity.ok(member); + } + @Secured("ADMIN") @GetMapping("/search") public ResponseEntity<List<Member>> search() {
Java
`request.setAttribute`๋ฅผ ํ†ตํ•ด ๊ฐ’์„ ์ €์žฅํ•˜๊ณ  ๋‹ค์‹œ ๊ฐ€์ ธ์˜ค๋Š” ๊ณผ์ •์„ ๊ฑฐ์น˜์ง€ ์•Š๊ณ , SecurityContext์—์„œ ์ง์ ‘ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋„ค์š” ๐Ÿ˜„
@@ -0,0 +1,20 @@ +package nextstep.security.authorization; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpMethod; + +public class MvcRequestMatcher implements RequestMatcher { + + private final HttpMethod method; + private final String uri; + + public MvcRequestMatcher(HttpMethod method, String uri) { + this.method = method; + this.uri = uri; + } + + @Override + public boolean matches(HttpServletRequest request) { + return request.getMethod().equalsIgnoreCase(method.name()) && request.getRequestURI().equalsIgnoreCase(uri); + } +}
Java
`matches()`๋Š” ์ •๊ทœ์‹ ๋งค์นญ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฉ”์„œ๋“œ ์ด๋ฏ€๋กœ, ๋‹จ์ˆœํ•œ ๋ฌธ์ž์—ด ๋น„๊ต์—๋Š” ์ ํ•ฉํ•˜์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์•„์š”. HTTP ๋ฉ”์„œ๋“œ(GET, POST ๋“ฑ)๋Š” ์ •๊ทœ์‹์ด ํ•„์š”ํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ, `equalsIgnoreCase()`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์„ฑ๋Šฅ ๋ฉด์—์„œ๋„ ๋” ํšจ์œจ์ ์ผ ๊ฒƒ ๊ฐ™๋„ค์š” ๐Ÿ˜Š
@@ -0,0 +1,25 @@ +package nextstep.security.authorization; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; + +import java.util.List; + +public class RequestAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + + private final List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries; + + public RequestAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries) { + this.requestMatcherEntries = requestMatcherEntries; + } + + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) { + return requestMatcherEntries.stream() + .filter(requestMatcherEntry -> requestMatcherEntry.matchRequest(request)) + .findFirst() + .map(RequestMatcherEntry::getEntry) + .map(entry -> entry.check(authentication, request)) + .orElseGet(() -> new AuthorizationDecision(false)); + } +}
Java
`orElseGet()` ์™€ `orElse()`๋Š” ์–ด๋–ค ์ฐจ์ด๊ฐ€ ์žˆ์„๊นŒ์š”? ๐Ÿ˜„
@@ -11,29 +11,29 @@ import org.springframework.aop.framework.AopInfrastructureBean; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; -import java.lang.reflect.Method; - public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean { private final Pointcut pointcut; + private final AuthorizationManager<MethodInvocation> securedAuthorizationManager; public SecuredMethodInterceptor() { this.pointcut = new AnnotationMatchingPointcut(null, Secured.class); + this.securedAuthorizationManager = new SecuredAuthorizationManager(); } @Override public Object invoke(MethodInvocation invocation) throws Throwable { - Method method = invocation.getMethod(); - if (method.isAnnotationPresent(Secured.class)) { - Secured secured = method.getAnnotation(Secured.class); - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - throw new AuthenticationException(); - } - if (!authentication.getAuthorities().contains(secured.value())) { - throw new ForbiddenException(); - } + + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + throw new AuthenticationException(); } + + AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation); + if (!authorizationDecision.isGranted()) { + throw new ForbiddenException(); + } + return invocation.proceed(); }
Java
`@Secured` ์–ด๋…ธํ…Œ์ด์…˜์ด ์กด์žฌํ•˜๋Š”์ง€ ๋‹ค์‹œ ๊ฒ€์‚ฌํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”, ์ด๋ฏธ `AnnotationMatchingPointcut`์„ ํ†ตํ•ด `@Secured`์ด ๋ถ™์€ ๋ฉ”์„œ๋“œ๋งŒ ์ธํ„ฐ์…‰ํŠธํ•˜๋„๋ก ์„ค์ •๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, `if (!method.isAnnotationPresent(Secured.class))` ๋ถ€๋ถ„์€ ์ œ๊ฑฐํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”. ๐Ÿ˜Š
@@ -17,6 +17,7 @@ import java.util.Set; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @@ -48,7 +49,7 @@ void request_success_with_admin_user() throws Exception { ); response.andExpect(status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(2)); + .andExpect(jsonPath("$.length()").value(2)); } @DisplayName("์ผ๋ฐ˜ ์‚ฌ์šฉ์ž๊ฐ€ ์š”์ฒญํ•  ๊ฒฝ์šฐ ๊ถŒํ•œ์ด ์—†์–ด์•ผ ํ•œ๋‹ค.") @@ -89,4 +90,32 @@ void request_fail_invalid_password() throws Exception { response.andExpect(status().isUnauthorized()); } + + @DisplayName("์ธ์ฆ๋œ ์‚ฌ์šฉ์ž๋Š” ์ž์‹ ์˜ ์ •๋ณด๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋‹ค.") + @Test + void request_success_members_me() throws Exception { + String token = Base64.getEncoder().encodeToString((TEST_USER_MEMBER.getEmail() + ":" + TEST_USER_MEMBER.getPassword()).getBytes()); + + ResultActions response = mockMvc.perform(get("/members/me") + .header("Authorization", "Basic " + token) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + ); + + response.andExpect(status().isOk()) + .andExpect(jsonPath("$.email").value("b@b.com")) + .andExpect(jsonPath("$.password").value("password")); + } + + @DisplayName("์ธ์ฆ๋˜์ง€ ์•Š์€ ์‚ฌ์šฉ์ž๋Š” ์ž์‹ ์˜ ์ •๋ณด๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์—†๋‹ค.") + @Test + void request_fail_members_me() throws Exception { + String token = Base64.getEncoder().encodeToString((TEST_ADMIN_MEMBER.getEmail() + ":" + "invalid").getBytes()); + + ResultActions response = mockMvc.perform(get("/members/me") + .header("Authorization", "Basic " + token) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + ); + + response.andExpect(status().isUnauthorized()); + } }
Java
ํ…Œ์ŠคํŠธ ์„ค๋ช…์ด ์ž˜๋ชป๋˜์–ด ์žˆ๋„ค์š” ๐Ÿ˜„
@@ -11,29 +11,29 @@ import org.springframework.aop.framework.AopInfrastructureBean; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; -import java.lang.reflect.Method; - public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean { private final Pointcut pointcut; + private final AuthorizationManager<MethodInvocation> securedAuthorizationManager; public SecuredMethodInterceptor() { this.pointcut = new AnnotationMatchingPointcut(null, Secured.class); + this.securedAuthorizationManager = new SecuredAuthorizationManager(); } @Override public Object invoke(MethodInvocation invocation) throws Throwable { - Method method = invocation.getMethod(); - if (method.isAnnotationPresent(Secured.class)) { - Secured secured = method.getAnnotation(Secured.class); - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - throw new AuthenticationException(); - } - if (!authentication.getAuthorities().contains(secured.value())) { - throw new ForbiddenException(); - } + + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + throw new AuthenticationException(); } + + AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation); + if (!authorizationDecision.isGranted()) { + throw new ForbiddenException(); + } + return invocation.proceed(); }
Java
> ๊ณ ๋ฏผํ•œ ๋ถ€๋ถ„ > Q. securedAuthorizationManager ๋กœ์ง์ด ์ˆ˜ํ–‰๋˜๋Š” ์‹œ์ ์ด SecuredMethodInterceptor ์•ˆ์—์„œ ์ˆ˜ํ–‰๋˜๋Š” ๊ฒƒ์ด ๋งž๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. A. AOP๋ฅผ ํ†ตํ•ด ๋ฉ”์„œ๋“œ๊ฐ€ ์‹คํ–‰๋˜๊ธฐ ์ „์— ์ธ๊ฐ€(Authorization) ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•˜๋„๋ก ์ž˜ ๊ตฌํ˜„ํ•ด ์ฃผ์…จ๋„ค์š”! ๐Ÿ‘ ํ˜น์‹œ ๊ณ ๋ฏผํ–ˆ๋˜ ๋ถ€๋ถ„์ด ์žˆ์œผ์…จ๋‹ค๋ฉด ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ์ €๋„ ๊ณ ๋ฏผํ•ด๋ณด๊ณ  ๋‹ต๋ณ€ ๋“œ๋ฆฌ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,24 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.support.AopUtils; + +import java.lang.reflect.Method; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Method method = invocation.getMethod(); + Class<?> targetClass = AopUtils.getTargetClass(method.getClass()); + Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); + Secured secured = targetMethod.getAnnotation(Secured.class); + + if (authentication.getAuthorities().contains(secured.value())) { + return new AuthorizationDecision(true); + } + + return new AuthorizationDecision(false); + } +}
Java
AopUtils.getMostSpecificMethod() ๋กœ ์‹ค์ œ ๋ฉ”์„œ๋“œ์˜ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”! ๊ทธ๋ž˜๋„ ์–ด๋…ธํ…Œ์ด์…˜ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๋ ค๋ฉด getAnnotation ๋ฉ”์„œ๋“œ๋Š” ๊ณ„์† ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฑฐ์ฃ ? ์ˆ˜์ •ํ•ด๋ดค๋Š”๋ฐ ๋งž๋Š” ๋ฐฉ์‹์ธ์ง€ ํ™•์ธ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,20 @@ +package nextstep.security.authorization; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpMethod; + +public class MvcRequestMatcher implements RequestMatcher { + + private final HttpMethod method; + private final String uri; + + public MvcRequestMatcher(HttpMethod method, String uri) { + this.method = method; + this.uri = uri; + } + + @Override + public boolean matches(HttpServletRequest request) { + return request.getMethod().equalsIgnoreCase(method.name()) && request.getRequestURI().equalsIgnoreCase(uri); + } +}
Java
์ œ๊ฐ€ ์™œ matches๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋„ค์š”.. ๊ผผ๊ผผํ•œ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -11,29 +11,29 @@ import org.springframework.aop.framework.AopInfrastructureBean; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; -import java.lang.reflect.Method; - public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean { private final Pointcut pointcut; + private final AuthorizationManager<MethodInvocation> securedAuthorizationManager; public SecuredMethodInterceptor() { this.pointcut = new AnnotationMatchingPointcut(null, Secured.class); + this.securedAuthorizationManager = new SecuredAuthorizationManager(); } @Override public Object invoke(MethodInvocation invocation) throws Throwable { - Method method = invocation.getMethod(); - if (method.isAnnotationPresent(Secured.class)) { - Secured secured = method.getAnnotation(Secured.class); - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - throw new AuthenticationException(); - } - if (!authentication.getAuthorities().contains(secured.value())) { - throw new ForbiddenException(); - } + + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + throw new AuthenticationException(); } + + AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation); + if (!authorizationDecision.isGranted()) { + throw new ForbiddenException(); + } + return invocation.proceed(); }
Java
๋‹ค๋ฅธ AuthorizationManager ๋“ค์€ Filter์—์„œ ์ธ๊ฐ€ ๋กœ์ง์ด ์ˆ˜ํ–‰๋˜๋Š”๋ฐ ์ด์™€ ๋‹ค๋ฅด๊ฒŒ AOP๋ฅผ ํ†ตํ•ด ์ˆ˜ํ–‰๋˜๋Š” ๋กœ์ง์ด์–ด์„œ ๋งž๋Š” ๋ฐฉ์‹์ธ์ง€ ๊ถ๊ธˆํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค..! ๋‹ต๋ณ€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,25 @@ +package nextstep.security.authorization; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; + +import java.util.List; + +public class RequestAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + + private final List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries; + + public RequestAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries) { + this.requestMatcherEntries = requestMatcherEntries; + } + + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) { + return requestMatcherEntries.stream() + .filter(requestMatcherEntry -> requestMatcherEntry.matchRequest(request)) + .findFirst() + .map(RequestMatcherEntry::getEntry) + .map(entry -> entry.check(authentication, request)) + .orElseGet(() -> new AuthorizationDecision(false)); + } +}
Java
orElse๋กœ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋˜๋ฉด, null์ด ์•„๋‹ˆ์–ด๋„ AuthorizationDecision ๊ฐ์ฒด ์ƒ์„ฑ ๋กœ์ง์€ ์ˆ˜ํ–‰๋  ๊ฒƒ ๊ฐ™๋„ค์š”. orElseGet์œผ๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,24 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.support.AopUtils; + +import java.lang.reflect.Method; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Method method = invocation.getMethod(); + Class<?> targetClass = AopUtils.getTargetClass(method.getClass()); + Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); + Secured secured = targetMethod.getAnnotation(Secured.class); + + if (authentication.getAuthorities().contains(secured.value())) { + return new AuthorizationDecision(true); + } + + return new AuthorizationDecision(false); + } +}
Java
method.getClass()๋Š” Method ํด๋ž˜์Šค ์ž์ฒด์˜ ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฏ€๋กœ, ์˜ฌ๋ฐ”๋ฅธ ๋Œ€์ƒ ํด๋ž˜์Šค(Target Class)๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. invocation.getThis()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์‹ค์ œ ๋Œ€์ƒ ๊ฐ์ฒด(Target Object)์˜ ํด๋ž˜์Šค๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ๋„ค์š” ๐Ÿ˜„ `Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());`
@@ -0,0 +1,24 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.support.AopUtils; + +import java.lang.reflect.Method; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Method method = invocation.getMethod(); + Class<?> targetClass = AopUtils.getTargetClass(method.getClass()); + Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); + Secured secured = targetMethod.getAnnotation(Secured.class); + + if (authentication.getAuthorities().contains(secured.value())) { + return new AuthorizationDecision(true); + } + + return new AuthorizationDecision(false); + } +}
Java
๋„ค ๋งž์Šต๋‹ˆ๋‹ค ์–ด๋…ธํ…Œ์ด์…˜ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๊ฒƒ์€ ๋™์ผํ•˜๊ฒŒ getAnnotation(Secured.class)์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๐Ÿ˜„
@@ -11,29 +11,29 @@ import org.springframework.aop.framework.AopInfrastructureBean; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; -import java.lang.reflect.Method; - public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean { private final Pointcut pointcut; + private final AuthorizationManager<MethodInvocation> securedAuthorizationManager; public SecuredMethodInterceptor() { this.pointcut = new AnnotationMatchingPointcut(null, Secured.class); + this.securedAuthorizationManager = new SecuredAuthorizationManager(); } @Override public Object invoke(MethodInvocation invocation) throws Throwable { - Method method = invocation.getMethod(); - if (method.isAnnotationPresent(Secured.class)) { - Secured secured = method.getAnnotation(Secured.class); - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - throw new AuthenticationException(); - } - if (!authentication.getAuthorities().contains(secured.value())) { - throw new ForbiddenException(); - } + + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + throw new AuthenticationException(); } + + AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation); + if (!authorizationDecision.isGranted()) { + throw new ForbiddenException(); + } + return invocation.proceed(); }
Java
Filter ๊ธฐ๋ฐ˜ ์ธ๊ฐ€๋Š” HTTP ์š”์ฒญ ๋‹จ์œ„์—์„œ ์ ์šฉ๋˜์ง€๋งŒ, `@Secured`๋Š” ๊ฐœ๋ณ„ ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ ๋‹จ์œ„์—์„œ ๋ณด์•ˆ ๊ฒ€์‚ฌ๋ฅผ ํ•ด์•ผ ํ•ด์„œ ์ ์ ˆํ•œ ๊ตฌํ˜„ ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
์–ด๋–ค TextField์ธ์ง€ ๋ช…์‹œ ์•ˆํ•ด์ฃผ๊ณ  editing์ด ์‹œ์ž‘๋œ textField์—๋Š” ์ž๋™์œผ๋กœ ์ ์šฉ๋˜๋Š”๊ตฌ๋‚˜ ์˜ค ์ƒ๊ฐ๋ชปํ–ˆ๋Š”๋ฐ ๋ฐฐ์› ์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž๊ฐ์‚ฌํ•ด์š”
@@ -0,0 +1,205 @@ +// +// LoginView.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/16. +// + +import UIKit + +class LoginView: UIView { + + // MARK: - Object Setting + + private let mainLabel = UILabel().then { + $0.text = "TVING ID ๋กœ๊ทธ์ธ" + $0.font = .tvingMedium(ofSize: 23) + $0.textColor = .tvingGray1 + $0.textAlignment = .center + } + + let idTextField = CustomTextField().then { + $0.placeholder = "์ด๋ฉ”์ผ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .emailAddress + } + + let idInvalidLabel = UILabel().then { + $0.textColor = .systemRed + $0.font = .systemFont(ofSize: 12) + $0.text = "* ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ด๋ฉ”์ผ ํ˜•์‹์ž…๋‹ˆ๋‹ค ๐Ÿ˜ญ" + $0.isHidden = true + } + + let passwordTextField = CustomPasswordTextField().then { + $0.placeholder = "๋น„๋ฐ€๋ฒˆํ˜ธ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .asciiCapable + } + + lazy var logInBtn = UIButton().then { + $0.setTitle("๋กœ๊ทธ์ธํ•˜๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.layer.borderColor = UIColor.tvingGray4.cgColor + $0.layer.borderWidth = 1 + $0.layer.cornerRadius = 3 + $0.isEnabled = false + } + + private let idPasswordStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 40 + } + + lazy var findIdBtn = UIButton().then { + $0.setTitle("์•„์ด๋”” ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + lazy var findPasswordBtn = UIButton().then { + $0.setTitle("๋น„๋ฐ€๋ฒˆํ˜ธ ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + private let makeAccountStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 20 + } + + let askExistAccountLabel = UILabel().then { + $0.text = "์•„์ง ๊ณ„์ •์ด ์—†์œผ์‹ ๊ฐ€์š”?" + $0.font = .tvingRegular(ofSize: 14) + $0.textColor = .tvingGray3 + $0.textAlignment = .center + } + + lazy var goToMakeNicknameBtn = UIButton().then { + $0.setTitle("๋‹‰๋„ค์ž„ ๋งŒ๋“ค๋Ÿฌ๊ฐ€๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingRegular(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.setUnderline() + } + + lazy var backBtn = UIButton().then { + $0.setImage(UIImage(named: "btn_before"), for: .normal) + } + + override init(frame: CGRect) { + super.init(frame: frame) + + style() + hierarchy() + setLayout() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + +} + +private extension LoginView { + + func style() { + self.backgroundColor = .black + } + + func hierarchy() { + self.addSubviews(mainLabel, + idTextField, + idInvalidLabel, + passwordTextField, + logInBtn, + idPasswordStackView, + makeAccountStackView, + backBtn) + idPasswordStackView.addArrangedSubviews(findIdBtn, + findPasswordBtn) + makeAccountStackView.addArrangedSubviews(askExistAccountLabel, + goToMakeNicknameBtn) + } + + + func setLayout() { + + mainLabel.snp.makeConstraints{ + $0.height.equalTo(37) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(50) + $0.leading.trailing.equalToSuperview().inset(100) + } + + idTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(mainLabel.snp.bottom).offset(31) + $0.leading.trailing.equalToSuperview().inset(20) + } + + passwordTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + + logInBtn.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(passwordTextField.snp.bottom).offset(21) + $0.leading.trailing.equalToSuperview().inset(20) + } + + idPasswordStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(logInBtn.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(80) + } + + makeAccountStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(50) + } + + backBtn.snp.makeConstraints{ + $0.height.equalTo(15) + $0.width.equalTo(8) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(25) + $0.leading.equalToSuperview().inset(24) + } + + findIdBtn.snp.makeConstraints{ + $0.width.equalTo(70) + $0.height.equalTo(22) + } + + findPasswordBtn.snp.makeConstraints{ + $0.width.equalTo(80) + $0.height.equalTo(22) + } + + askExistAccountLabel.snp.makeConstraints{ + $0.width.equalTo(140) + $0.height.equalTo(22) + } + + goToMakeNicknameBtn.snp.makeConstraints{ + $0.width.equalTo(128) + $0.height.equalTo(22) + } + } +}
Swift
๊ฐ๊ฐ ์ขŒ์šฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํ•˜๋ฉด ๊ธฐ๊ธฐ๋งˆ๋‹ค ์ฐจ์ด๊ฐ€ ์ข€ ๋‚˜ํƒ€๋‚  ๊ฑฐ ๊ฐ™์•„์š”! ๊ฐ€์šด๋ฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฌถ์„ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•(stackview)๋„ ์ข‹์„ ๊ฑฐ๊ฐ™์•„์š” ใ…Žใ…Ž
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
UIView๋ฅผ ๋”ฐ๋กœ ๋นผ๋‹ˆ๊นŒ ํ™• ์ฝ”๋“œ๊ฐ€ ์งง์•„์กŒ๋„ค์š” ์ €๋„ ๋‹ค์Œ์—” ์ด๋Ÿฐ์‹์œผ๋กœ ํ•ด๋ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
targetํ•จ์ˆ˜ ๋”ฐ๋กœ ๋บ€ ๊ฑฐ ์งฑ์ด์—์—ฌ ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
์šฐ์™€ ํ‚ค๋ณด๋“œ ์ฒ˜๋ฆฌ๊นŒ์ง€ !! ์งฑ์ด๊ตฐ์—ฌ
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
์™• ๊ตฌ์กฐ์ฒด๋กœ ๋ฌถ์–ด์ฃผ๋Š” ๊ฑฐ ๊นŒ์ง€!
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
๊ตฌ์กฐ์ฒด์—์„œ ๋ณ€์ˆ˜๋“ค์„ ""๋กœ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์˜ต์…”๋„ ์ฒ˜๋ฆฌํ•ด๋‘๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”? ๋‚˜์ค‘์— ๊ตฌ์กฐ์ฒด ๋ณ€์ˆ˜์— ๊ฐ’์„ ๋„ฃ๋‹ค๋ณด๋ฉด, ๋ณ€์ˆ˜๊ฐ€ ์‹ค์ œ๋กœ ๊ฐ’์ด ์—†๋Š” ์ƒํƒœ์ธ์ง€ ์•„๋‹ˆ๋ฉด ์˜๋„์ ์œผ๋กœ ๋นˆ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”๋œ ๊ฒƒ์ธ์ง€๋ฅผ ๊ตฌ๋ถ„ํ•˜๊ธฐ ์–ด๋ ต๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์ €๋Š” ?(์˜ต์…”๋„)์„ ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์ข‹์„๊ฒƒ ๊ฐ™์•„์š”! `var id: String?` ์ด๋Ÿฐ ์‹์œผ๋กœ์š”
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
์Šค์œ„ํ”„ํŠธ์—์„œ ์ ‘๊ทผ ์ œ์–ด์ž๋ฅผ ๋”ฐ๋กœ ์„ ์–ธํ•˜์ง€ ์•Š์œผ๋ฉด internal ์ ‘๊ทผ์ด ๊ธฐ๋ณธ์ด๋ผ๊ณ  ํ•ด์š”! open-> public -> internal -> file-private -> private ์œผ๋กœ ๊ฐˆ ์ˆ˜๋ก ์ œํ•œ์ ์ธ ์ ‘๊ทผ์ž์ธ๋ฐ ์„œ๋กœ ๋‹ค๋ฅธ ๋ชจ๋“ˆ๋ผ๋ฆฌ ์ ‘๊ทผํ•˜๋Š” ์ƒํ™ฉ์ด ์•„๋‹ˆ๋ผ๋ฉด ๊ตณ์ด public์„ ์„ ์–ธํ•˜์—ฌ ์ ‘๊ทผ ์ˆ˜์ค€์„ ์•ฝํ•˜๊ฒŒ ํ•  ํ•„์š” ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์„ธ์šฉ? https://zeddios.tistory.com/383
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
public์ด ์„œ๋กœ ๋‹ค๋ฅธ ๋ชจ๋“ˆ์—์„œ๋„ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋กํ•˜๋Š” ์ ‘๊ทผ ์ œ์–ด๋ผ๊ณ  ํ•˜๋„ค์š”. ๋ชจ๋“ˆ์ด ์ƒ์†Œํ•ด์„œ ์ฐพ์•„๋ณด๋‹ˆ "Xcode์˜ ๊ฐ ๋นŒ๋“œ ๋Œ€์ƒ"์„ ๋ชจ๋“ˆ์ด๋ผ๊ณ  ํ•˜๋”๋ผ๊ณ ์š”. ํ”„๋กœ์ ํŠธ ํŒŒ์ผ์ด๋ผ๊ณ  ์ €๋Š” ์ดํ•ดํ–ˆ์–ด์š”!
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
?? ๋ฐฉ์‹์œผ๋กœ ์˜ต์…”๋„ ์–ธ๋žฉํ•‘ํ•˜๋Š”๊ฒƒ๋„ ์ข‹์ง€๋งŒ! ๊ฐ€๋…์„ฑ์„ ์œ„ํ•ด if let ์ด๋‚˜ guard let์„ ์“ฐ๋ฉด ๋” ์ข‹์„๊ฒƒ ๊ฐ™์•„์š”~
@@ -0,0 +1,205 @@ +// +// LoginView.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/16. +// + +import UIKit + +class LoginView: UIView { + + // MARK: - Object Setting + + private let mainLabel = UILabel().then { + $0.text = "TVING ID ๋กœ๊ทธ์ธ" + $0.font = .tvingMedium(ofSize: 23) + $0.textColor = .tvingGray1 + $0.textAlignment = .center + } + + let idTextField = CustomTextField().then { + $0.placeholder = "์ด๋ฉ”์ผ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .emailAddress + } + + let idInvalidLabel = UILabel().then { + $0.textColor = .systemRed + $0.font = .systemFont(ofSize: 12) + $0.text = "* ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ด๋ฉ”์ผ ํ˜•์‹์ž…๋‹ˆ๋‹ค ๐Ÿ˜ญ" + $0.isHidden = true + } + + let passwordTextField = CustomPasswordTextField().then { + $0.placeholder = "๋น„๋ฐ€๋ฒˆํ˜ธ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .asciiCapable + } + + lazy var logInBtn = UIButton().then { + $0.setTitle("๋กœ๊ทธ์ธํ•˜๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.layer.borderColor = UIColor.tvingGray4.cgColor + $0.layer.borderWidth = 1 + $0.layer.cornerRadius = 3 + $0.isEnabled = false + } + + private let idPasswordStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 40 + } + + lazy var findIdBtn = UIButton().then { + $0.setTitle("์•„์ด๋”” ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + lazy var findPasswordBtn = UIButton().then { + $0.setTitle("๋น„๋ฐ€๋ฒˆํ˜ธ ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + private let makeAccountStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 20 + } + + let askExistAccountLabel = UILabel().then { + $0.text = "์•„์ง ๊ณ„์ •์ด ์—†์œผ์‹ ๊ฐ€์š”?" + $0.font = .tvingRegular(ofSize: 14) + $0.textColor = .tvingGray3 + $0.textAlignment = .center + } + + lazy var goToMakeNicknameBtn = UIButton().then { + $0.setTitle("๋‹‰๋„ค์ž„ ๋งŒ๋“ค๋Ÿฌ๊ฐ€๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingRegular(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.setUnderline() + } + + lazy var backBtn = UIButton().then { + $0.setImage(UIImage(named: "btn_before"), for: .normal) + } + + override init(frame: CGRect) { + super.init(frame: frame) + + style() + hierarchy() + setLayout() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + +} + +private extension LoginView { + + func style() { + self.backgroundColor = .black + } + + func hierarchy() { + self.addSubviews(mainLabel, + idTextField, + idInvalidLabel, + passwordTextField, + logInBtn, + idPasswordStackView, + makeAccountStackView, + backBtn) + idPasswordStackView.addArrangedSubviews(findIdBtn, + findPasswordBtn) + makeAccountStackView.addArrangedSubviews(askExistAccountLabel, + goToMakeNicknameBtn) + } + + + func setLayout() { + + mainLabel.snp.makeConstraints{ + $0.height.equalTo(37) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(50) + $0.leading.trailing.equalToSuperview().inset(100) + } + + idTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(mainLabel.snp.bottom).offset(31) + $0.leading.trailing.equalToSuperview().inset(20) + } + + passwordTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + + logInBtn.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(passwordTextField.snp.bottom).offset(21) + $0.leading.trailing.equalToSuperview().inset(20) + } + + idPasswordStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(logInBtn.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(80) + } + + makeAccountStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(50) + } + + backBtn.snp.makeConstraints{ + $0.height.equalTo(15) + $0.width.equalTo(8) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(25) + $0.leading.equalToSuperview().inset(24) + } + + findIdBtn.snp.makeConstraints{ + $0.width.equalTo(70) + $0.height.equalTo(22) + } + + findPasswordBtn.snp.makeConstraints{ + $0.width.equalTo(80) + $0.height.equalTo(22) + } + + askExistAccountLabel.snp.makeConstraints{ + $0.width.equalTo(140) + $0.height.equalTo(22) + } + + goToMakeNicknameBtn.snp.makeConstraints{ + $0.width.equalTo(128) + $0.height.equalTo(22) + } + } +}
Swift
๋ฒ„ํŠผ ์ปดํฌ๋„ŒํŠธ๋“ค์—๋งŒ lazy๋ฅผ ๋„ฃ์–ด์ฃผ์…จ๋Š”๋ฐ addTarget์—์„œ (๋…ธ๋ž€์ƒ‰)์›Œ๋‹์„ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋„ฃ์€๊ฑฐ์ฃ ..? ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ ๋ฐฉ์‹์ค‘์— addTarget ๋ฐฉ์‹ ์™ธ์—๋„ addAction ๋ฐฉ์‹๋„ ์žˆ์–ด์š”! addAction ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ ํ•จ์ˆ˜์— @objc๋„ ๋ถ™์ด์ง€ ์•Š์•„๋„ ๋˜๊ณ , ์›Œ๋‹์„ ํ”ผํ•˜๊ธฐ ์œ„ํ•œ lazy๋„ ์•ˆ์จ๋„ ๋ฉ๋‹ˆ๋‹ค! ๊ฐ€๋…์„ฑ ์ธก๋ฉด์ด๋ž‘, ์ตœ๋Œ€ํ•œ objc ์š”์†Œ๋ฅผ ์ œ์™ธํ•˜๊ณ  UIKit ํ†ต์ผ์„ฑ์„ ์œ„ํ•ด addAction ๋ฐฉ์‹๋„ ์•Œ๊ณ  ์žˆ์œผ๋ฉด ์ข‹์„๊ฒƒ ๊ฐ™์•„์š”! ์•„๋ž˜๋Š” addAction ๋ฐฉ์‹์œผ๋กœ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐํ•œ ์˜ˆ์‹œ ์ฝ”๋“œ์—์š”! private func setButtonEvent() { self.datePickerView.setAction() let moveToTodayDateButtonAction = UIAction { [weak self] _ in self?.moveToTodayDate() } let moveToTodayDatePickerButtonAction = UIAction { [weak self] _ in self?.moveToDatePicker() } let moveToSettingViewAction = UIAction { [weak self] _ in self?.moveToSettingView() } self.homeCalenderView.todayButton.addAction(moveToTodayDateButtonAction, for: .touchUpInside) self.homeCalenderView.calendarMonthLabelButton.addAction(moveToTodayDatePickerButtonAction, for: .touchUpInside) self.homeCalenderView.calendarMonthPickButton.addAction(moveToTodayDatePickerButtonAction, for: .touchUpInside) self.profileButton.addAction(moveToSettingViewAction, for: .touchUpInside) }
@@ -0,0 +1,205 @@ +// +// LoginView.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/16. +// + +import UIKit + +class LoginView: UIView { + + // MARK: - Object Setting + + private let mainLabel = UILabel().then { + $0.text = "TVING ID ๋กœ๊ทธ์ธ" + $0.font = .tvingMedium(ofSize: 23) + $0.textColor = .tvingGray1 + $0.textAlignment = .center + } + + let idTextField = CustomTextField().then { + $0.placeholder = "์ด๋ฉ”์ผ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .emailAddress + } + + let idInvalidLabel = UILabel().then { + $0.textColor = .systemRed + $0.font = .systemFont(ofSize: 12) + $0.text = "* ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ด๋ฉ”์ผ ํ˜•์‹์ž…๋‹ˆ๋‹ค ๐Ÿ˜ญ" + $0.isHidden = true + } + + let passwordTextField = CustomPasswordTextField().then { + $0.placeholder = "๋น„๋ฐ€๋ฒˆํ˜ธ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .asciiCapable + } + + lazy var logInBtn = UIButton().then { + $0.setTitle("๋กœ๊ทธ์ธํ•˜๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.layer.borderColor = UIColor.tvingGray4.cgColor + $0.layer.borderWidth = 1 + $0.layer.cornerRadius = 3 + $0.isEnabled = false + } + + private let idPasswordStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 40 + } + + lazy var findIdBtn = UIButton().then { + $0.setTitle("์•„์ด๋”” ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + lazy var findPasswordBtn = UIButton().then { + $0.setTitle("๋น„๋ฐ€๋ฒˆํ˜ธ ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + private let makeAccountStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 20 + } + + let askExistAccountLabel = UILabel().then { + $0.text = "์•„์ง ๊ณ„์ •์ด ์—†์œผ์‹ ๊ฐ€์š”?" + $0.font = .tvingRegular(ofSize: 14) + $0.textColor = .tvingGray3 + $0.textAlignment = .center + } + + lazy var goToMakeNicknameBtn = UIButton().then { + $0.setTitle("๋‹‰๋„ค์ž„ ๋งŒ๋“ค๋Ÿฌ๊ฐ€๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingRegular(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.setUnderline() + } + + lazy var backBtn = UIButton().then { + $0.setImage(UIImage(named: "btn_before"), for: .normal) + } + + override init(frame: CGRect) { + super.init(frame: frame) + + style() + hierarchy() + setLayout() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + +} + +private extension LoginView { + + func style() { + self.backgroundColor = .black + } + + func hierarchy() { + self.addSubviews(mainLabel, + idTextField, + idInvalidLabel, + passwordTextField, + logInBtn, + idPasswordStackView, + makeAccountStackView, + backBtn) + idPasswordStackView.addArrangedSubviews(findIdBtn, + findPasswordBtn) + makeAccountStackView.addArrangedSubviews(askExistAccountLabel, + goToMakeNicknameBtn) + } + + + func setLayout() { + + mainLabel.snp.makeConstraints{ + $0.height.equalTo(37) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(50) + $0.leading.trailing.equalToSuperview().inset(100) + } + + idTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(mainLabel.snp.bottom).offset(31) + $0.leading.trailing.equalToSuperview().inset(20) + } + + passwordTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + + logInBtn.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(passwordTextField.snp.bottom).offset(21) + $0.leading.trailing.equalToSuperview().inset(20) + } + + idPasswordStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(logInBtn.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(80) + } + + makeAccountStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(50) + } + + backBtn.snp.makeConstraints{ + $0.height.equalTo(15) + $0.width.equalTo(8) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(25) + $0.leading.equalToSuperview().inset(24) + } + + findIdBtn.snp.makeConstraints{ + $0.width.equalTo(70) + $0.height.equalTo(22) + } + + findPasswordBtn.snp.makeConstraints{ + $0.width.equalTo(80) + $0.height.equalTo(22) + } + + askExistAccountLabel.snp.makeConstraints{ + $0.width.equalTo(140) + $0.height.equalTo(22) + } + + goToMakeNicknameBtn.snp.makeConstraints{ + $0.width.equalTo(128) + $0.height.equalTo(22) + } + } +}
Swift
์ด๊ฑด ์ œ๊ฐ€ ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์ธ๋ฐ addSubviews ํ•  ๋•Œ ๊ฐ€๋กœ๋กœ ๊ธธ๊ฒŒ ์“ฐ๋Š”๊ฒƒ ๋ณด๋‹ค ์•„๋ž˜ ์ฝ”๋“œ์ฒ˜๋Ÿผ ์„ธ๋กœ๋กœ ๋Š˜๋ฆฌ๋Š”๊ฒŒ ๊ฐ€๋…์„ฑ์— ์ข‹๋”๋ผ๊ณ ์š”. ๋ฌผ๋ก  ์ฝ”๋“œ ์ค„์€ ๋Š˜์–ด๋‚˜์ง€๋งŒ์š”! ๊ฐ์ž ์„ ํ˜ธํ•˜๋Š” ์Šคํƒ€์ผ์ด ์žˆ๋Š”๊ฒƒ ๊ฐ™์€๋ฐ ์กฐ์‹ฌ์Šค๋ ˆ.. ์ œ์•ˆํ•ด๋ด…๋‹ˆ๋‹ค ใ…Žใ…Ž view.addSubviews(toolBarView, titleLabelStackView, houseImageView, homeGroupLabel, homeGroupCollectionView, homeRuleView, homeDivider, datePickerView, homeCalenderView, homeWeekCalendarCollectionView, calendarDailyTableView, emptyHouseWorkImage)
@@ -0,0 +1,45 @@ +// +// WelcomeViewController.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/12. +// + +import UIKit + +final class WelcomeViewController: BaseViewController { + + // MARK: - Property + + private let mainView = WelcomeView() + + // MARK: - Target + + private func target() { + mainView.goToMainBtn.addTarget(self, action: #selector(tappedGoToMainBtn), for: .touchUpInside) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + } +} + +extension WelcomeViewController { + + func idDataBind(idOrNick: String) { + mainView.welcomeLabel.text = "\(idOrNick)๋‹˜\n๋ฐ˜๊ฐ€์›Œ์š”!" + } + + @objc + func tappedGoToMainBtn() { + self.navigationController?.popToRootViewController(animated: true) + } +}
Swift
์ œ๊ฐ€ ์ตœ๊ทผ์— ์ƒ๊ฐ ์—†์ด ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ ํ•จ์ˆ˜ ํ˜ธ์ถœ์„ viewWillAppear ์ชฝ์—์„œ ํ–ˆ๋‹ค๊ฐ€... ๋ฌธ์ œ๊ฐ€ ์ƒ๊ฒผ๋Š”๋ฐ viewDidLoad์— ๋„ˆ๋ฌด ์ž˜ ํ•ด๋‘์…จ๋„ค์š” ^~^
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
๋” ์ด์ƒ ์ƒ์†๋˜์ง€ ์•Š๋Š” ํด๋ž˜์Šค๋ผ๋ฉด final ํ‚ค์›Œ๋“œ ๋ถ™์ด๋ฉด ์ข‹์„๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
์—ฌ๊ธฐ์„œ didSet์„ ์‚ฌ์šฉํ•ด์„œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ์ข‹์„๊ฑฐ ๊ฐ™์•„์šฉ ์•„๋ž˜ ๋Œ€์ถฉ ์˜ˆ์‹œ๋ฅผ ์ ์—ˆ๋Š”๋ฐ ์ € ์ž์‹ ๋„ didSet์„ ์ž˜ ํ™œ์šฉํ•˜์ง€ ๋ชปํ•ด์„œ @meltsplit @seungchan2 ํ™•์ธ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค ```Swift public var nickName: String = โ€œ" { didSet { guard let nickName = nickNameBottomSheet.nickNameTextFeild.text else { return } self.nickName = nickName } } ```
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
์˜ต์…”๋„ ์ฒ˜๋ฆฌ์— ๋Œ€ํ•ด ๊ณต๋ถ€ํ•˜๋Š”๊ฑด ๋ถ„๋ช… ๋‚˜์ค‘์— ์ข‹์€ ์ž์‚ฐ์ด ๋ ๊ฑฐ์—์—ฌ!
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
๋ฒ„ํŠผ ํ™œ์„ฑํ™”์™€ ์ •๊ทœ์‹์— ๋งž๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ถ€๋ถ„์„ ๋‚˜๋ˆ ์ฃผ๋ฉด ๋” ์ข‹์„๊ฑฐ ๊ฐ™์•„์š” ๋ฒ„ํŠผ ํ™œ์„ฑํ™”๋Š” -> textFeild์— ๊ธ€์ด ์ฐจ ์žˆ์„ ๊ฒฝ์šฐ -> textFeildDidChange๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„๊ฑฐ ๊ฐ™๊ณ  ์ •๊ทœ์‹ ํ™•์ธ -> ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ -> ๋ฒ„ํŠผ์— addTarget์„ ํ•ด์„œ ํ™•์ธํ•ด์ฃผ๋Š” toastMessage๋‚˜ print๋ฌธ์„ ์ฐ์–ด์ฃผ๋Š”๊ฒŒ ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,119 @@ +// +// AddNickNameBottomSheetUIView.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/15. +// + +import UIKit + +import SnapKit +import Then + +final class AddNickNameBottomSheetUIView: UIView { + + let bottomSheetHeight = UIScreen.main.bounds.height / 2 + + let dimmendView = UIView().then { + $0.backgroundColor = .black.withAlphaComponent(0.5) + } + + private lazy var dragIndicatior = UIView().then { + $0.backgroundColor = .tvingGray1 + $0.layer.cornerRadius = 3 + } + + let bottomSheetView = UIView().then { + $0.backgroundColor = .white + $0.layer.cornerRadius = 12 + $0.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] // ์ขŒ์šฐ์ธก ํ•˜๋‹จ์€ ๊ทธ๋Œ€๋กœ + } + + private let nickNameMainLabel = UILabel().then { + $0.text = "๋‹‰๋„ค์ž„์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”" + $0.font = .tvingMedium(ofSize: 23) + } + + let nickNameTextField = CustomTextField().then { + $0.placeholder = "๋‹‰๋„ค์ž„" + $0.setPlaceholderColor(.tvingGray1) + $0.textColor = .black + $0.backgroundColor = .tvingGray2 + $0.font = .tvingMedium(ofSize: 14) + } + + lazy var saveNickNameBtn = UIButton().then { + $0.setTitle("์ €์žฅํ•˜๊ธฐ", for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 16) + $0.titleLabel?.textAlignment = .center + $0.titleLabel?.textColor = .tvingGray2 + $0.backgroundColor = .black + $0.layer.cornerRadius = 12 + $0.isEnabled = false + } + + override init(frame: CGRect) { + super.init(frame: frame) + + style() + hierarchy() + setLayout() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +private extension AddNickNameBottomSheetUIView { + + func style() { + + } + + func hierarchy() { + self.addSubviews(dimmendView, + dragIndicatior, + bottomSheetView) + bottomSheetView.addSubviews(nickNameMainLabel, + nickNameTextField, + saveNickNameBtn) + } + + func setLayout() { + + dimmendView.snp.makeConstraints { + $0.edges.equalToSuperview() + } + + bottomSheetView.snp.makeConstraints { + $0.height.equalTo(bottomSheetHeight) + $0.bottom.left.right.equalToSuperview() + $0.top.equalToSuperview().inset(UIScreen.main.bounds.height - bottomSheetHeight) + } + + dragIndicatior.snp.makeConstraints { + $0.height.equalTo(5) + $0.leading.trailing.equalToSuperview().inset(120) + $0.bottom.equalTo(bottomSheetView.snp.top).inset(-10) + } + + nickNameMainLabel.snp.makeConstraints { + $0.top.equalToSuperview().inset(45) + $0.leading.equalToSuperview().inset(20) + } + + nickNameTextField.snp.makeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(nickNameMainLabel.snp.bottom).offset(21) + $0.leading.trailing.equalToSuperview().inset(20) + } + + saveNickNameBtn.snp.makeConstraints { + $0.height.equalTo(52) + $0.bottom.equalToSuperview().inset(20) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + +}
Swift
์ ‘๊ทผ ์ œ์–ด์ž๋ฅผ ํ™œ์šฉํ• ๋•Œ๋Š” ๋‚ด๊ฐ€ ํ•ด๋‹น ๋‚ด์šฉ์„(? ๋ช…์นญ์ด ์• ๋งคํ•จ) ์‚ฌ์šฉํ•  ์ตœ์†Œํ•œ์˜ ๋ฒ”์œ„๋กœ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ์ข‹์•„์š”! ๋งŒ์•ฝ ํ•ด๋‹น ํŒŒ์ผ์—์„œ๋งŒ ์‚ฌ์šฉํ•  component๋ผ๋ฉด private์œผ๋กœ ๋ฐ”๊พธ๋Š”๊ฒƒ๋„ ์ข‹๊ฒ ์ฃ ?
@@ -0,0 +1,205 @@ +// +// LoginView.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/16. +// + +import UIKit + +class LoginView: UIView { + + // MARK: - Object Setting + + private let mainLabel = UILabel().then { + $0.text = "TVING ID ๋กœ๊ทธ์ธ" + $0.font = .tvingMedium(ofSize: 23) + $0.textColor = .tvingGray1 + $0.textAlignment = .center + } + + let idTextField = CustomTextField().then { + $0.placeholder = "์ด๋ฉ”์ผ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .emailAddress + } + + let idInvalidLabel = UILabel().then { + $0.textColor = .systemRed + $0.font = .systemFont(ofSize: 12) + $0.text = "* ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ด๋ฉ”์ผ ํ˜•์‹์ž…๋‹ˆ๋‹ค ๐Ÿ˜ญ" + $0.isHidden = true + } + + let passwordTextField = CustomPasswordTextField().then { + $0.placeholder = "๋น„๋ฐ€๋ฒˆํ˜ธ" + $0.setPlaceholderColor(.tvingGray2) + $0.font = .tvingMedium(ofSize: 15) + $0.textColor = .tvingGray2 + $0.backgroundColor = .tvingGray4 + $0.keyboardType = .asciiCapable + } + + lazy var logInBtn = UIButton().then { + $0.setTitle("๋กœ๊ทธ์ธํ•˜๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.layer.borderColor = UIColor.tvingGray4.cgColor + $0.layer.borderWidth = 1 + $0.layer.cornerRadius = 3 + $0.isEnabled = false + } + + private let idPasswordStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 40 + } + + lazy var findIdBtn = UIButton().then { + $0.setTitle("์•„์ด๋”” ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + lazy var findPasswordBtn = UIButton().then { + $0.setTitle("๋น„๋ฐ€๋ฒˆํ˜ธ ์ฐพ๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingMedium(ofSize: 14) + $0.titleLabel?.textAlignment = .center + } + + private let makeAccountStackView = UIStackView().then { + $0.axis = .horizontal + $0.distribution = .fill + $0.alignment = .center + $0.spacing = 20 + } + + let askExistAccountLabel = UILabel().then { + $0.text = "์•„์ง ๊ณ„์ •์ด ์—†์œผ์‹ ๊ฐ€์š”?" + $0.font = .tvingRegular(ofSize: 14) + $0.textColor = .tvingGray3 + $0.textAlignment = .center + } + + lazy var goToMakeNicknameBtn = UIButton().then { + $0.setTitle("๋‹‰๋„ค์ž„ ๋งŒ๋“ค๋Ÿฌ๊ฐ€๊ธฐ", for: .normal) + $0.setTitleColor(.tvingGray2, for: .normal) + $0.titleLabel?.font = .tvingRegular(ofSize: 14) + $0.titleLabel?.textAlignment = .center + $0.setUnderline() + } + + lazy var backBtn = UIButton().then { + $0.setImage(UIImage(named: "btn_before"), for: .normal) + } + + override init(frame: CGRect) { + super.init(frame: frame) + + style() + hierarchy() + setLayout() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + +} + +private extension LoginView { + + func style() { + self.backgroundColor = .black + } + + func hierarchy() { + self.addSubviews(mainLabel, + idTextField, + idInvalidLabel, + passwordTextField, + logInBtn, + idPasswordStackView, + makeAccountStackView, + backBtn) + idPasswordStackView.addArrangedSubviews(findIdBtn, + findPasswordBtn) + makeAccountStackView.addArrangedSubviews(askExistAccountLabel, + goToMakeNicknameBtn) + } + + + func setLayout() { + + mainLabel.snp.makeConstraints{ + $0.height.equalTo(37) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(50) + $0.leading.trailing.equalToSuperview().inset(100) + } + + idTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(mainLabel.snp.bottom).offset(31) + $0.leading.trailing.equalToSuperview().inset(20) + } + + passwordTextField.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + + logInBtn.snp.makeConstraints{ + $0.height.equalTo(52) + $0.top.equalTo(passwordTextField.snp.bottom).offset(21) + $0.leading.trailing.equalToSuperview().inset(20) + } + + idPasswordStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(logInBtn.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(80) + } + + makeAccountStackView.snp.makeConstraints { + $0.height.equalTo(25) + $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30) + $0.centerX.equalToSuperview().inset(50) + } + + backBtn.snp.makeConstraints{ + $0.height.equalTo(15) + $0.width.equalTo(8) + $0.top.equalTo(self.safeAreaLayoutGuide).inset(25) + $0.leading.equalToSuperview().inset(24) + } + + findIdBtn.snp.makeConstraints{ + $0.width.equalTo(70) + $0.height.equalTo(22) + } + + findPasswordBtn.snp.makeConstraints{ + $0.width.equalTo(80) + $0.height.equalTo(22) + } + + askExistAccountLabel.snp.makeConstraints{ + $0.width.equalTo(140) + $0.height.equalTo(22) + } + + goToMakeNicknameBtn.snp.makeConstraints{ + $0.width.equalTo(128) + $0.height.equalTo(22) + } + } +}
Swift
์–ด์ฉ์ง€ ๋ ˆ์ด์•„์›ƒ ์žก์œผ๋ฉด์„œ๋„ ์ด๊ฒŒ ๋งž๋‚˜.. ์‹ถ์—ˆ์Šด๋ฏธ๋‹ค ์Šคํƒ๋ทฐ๋กœ ๋‹ค์‹œ ์งœ๋ดค์–ด์š”!!!!!!
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
bottomSheet ๋•Œ๋ฌธ์— ์–ด์ฉŒ๋‹ค๋ณด๋‹ˆ.. ์žฅ๋‹จ์ ์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์•„์š”!!! ์ฝ”๋“œ๋Š” ์ง„์งœ ๊ฐ„๊ฒฐํ•ด์กŒ์ฃต
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
bottomSheet๋ฅผ ์˜ฌ๋ฆฌ๋ ค๊ณ  ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ์ด๊ฒŒ ๋งž๋Š”์ง€๋Š” ๋ฉ€๊ฒ ใ……๋„ค์˜..ใ…‹ใ…‹
@@ -0,0 +1,261 @@ +// +// LoginViewController_TVING.swift +// GO_SOPT_Seminar_Assingment +// +// Created by ๊น€๋‹ค์˜ˆ on 2023/04/11. +// + +import UIKit + +import SnapKit +import Then + +struct TvingUserInfo { + var id: String? + var password: String? + var nickName: String? +} + +final class LoginViewController_TVING: BaseViewController { + + // MARK: - Property + + private let mainView = LoginView() + private let nickNameBottomSheet = AddNickNameBottomSheetUIView() + + var user = TvingUserInfo() + + private var bottomSheetKeyboardEnable: Bool = false + + // MARK: - Target + + private func target() { + mainView.idTextField.delegate = self + mainView.passwordTextField.delegate = self + + mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside) + mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside) + } + + private func targetBottomSheet() { + nickNameBottomSheet.nickNameTextField.delegate = self + + nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents) + + nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside) + + let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground)) + nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap) + } + + // MARK: - Lift Cycle + + override func loadView() { + self.view = mainView + view.addSubview(nickNameBottomSheet) + + nickNameBottomSheet.snp.makeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + target() + targetBottomSheet() + setKeyboardObserver() // ํ‚ค๋ณด๋“œ ํ™œ์„ฑํ™”์— ๋”ฐ๋ฅธ bottomSheet ๋†’์ด ์กฐ์ ˆ ์œ„ํ•ด + } + + override func viewWillAppear(_ animated: Bool) { + initView() + } + +} + +private extension LoginViewController_TVING { + + // MARK: - objc func + + @objc + func tappedLogInBtn() { + saveUserEmail() + let welcomViewController = WelcomeViewController() + welcomViewController.idDataBind(idOrNick: getNickNameOrId()) + self.navigationController?.pushViewController(welcomViewController, animated: true) + } + + @objc + func tappedMakeNickNameBtn() { + showBottomSheet() + } + + @objc + func tappedSavedNickNameBtn() { + saveUserNickName() + hideBottomSheet() + } + + @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheet() + } + + @objc func keyboardWillShow(notification: NSNotification) { + guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height) + } + } + + @objc func keyboardWillHide(notification: NSNotification) { + if (nickNameBottomSheet.nickNameTextField.isSelected){ + bottomSheetKeyboardEnable = true + nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight + } + } + + // MARK: - custom func + + func saveUserEmail(){ + guard let id = mainView.idTextField.text else { return } + user.id = id + } + + func saveUserNickName() { + guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return } + user.nickName = nickName + } + + func getNickNameOrId() -> String { + if let nickName = user.nickName { + return nickName + } else { + guard let id = user.id else { return "" } + return id + } + } + + func isIDValid() -> Bool { + guard let id = mainView.idTextField.text else { return false } + return id.isValidEmail() + } + + func showBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = true + nickNameBottomSheet.snp.remakeConstraints { + $0.edges.equalToSuperview() + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height) + }) + } + + func hideBottomSheet() { + nickNameBottomSheet.nickNameTextField.isSelected = false + nickNameBottomSheet.snp.remakeConstraints { + $0.width.equalToSuperview() + $0.top.equalTo(view.snp.bottom) + } + UIView.animate(withDuration: 0.5, animations: { + self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height) + } + ) + } + + func initView() { + mainView.idTextField.text = nil + mainView.passwordTextField.text = nil + nickNameBottomSheet.nickNameTextField.text = nil + user = TvingUserInfo() + mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2) + } + + func setKeyboardObserver() { + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) + } + +} + +// MARK: - TextFieldDelegate + +extension LoginViewController_TVING: UITextFieldDelegate { + + // textField๊ฐ€ ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldDidBeginEditing(_ textField: UITextField) { + textField.layer.borderColor = UIColor.tvingGray2.cgColor + textField.layer.borderWidth = 0.7 + } + + // textField ๋น„ํ™œ์„ฑํ™”๋˜๋ฉด + func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { + textField.layer.borderWidth = 0 + + idValidPrint() + + return true + } + + @objc + private func textFieldDidChange(_ textField: UITextField) { + + if let nickNameText = nickNameBottomSheet.nickNameTextField.text { + if (!nickNameText.isValidNickName()) { + nickNameBottomSheet.nickNameTextField.text = nil + } + } + + let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText + let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid() + + if (saveIdPwBtnEnable) { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + + let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText + + if (saveNickNameBtnEnable) { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white) + }else { + nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2) + } + } + + private func idValidPrint() { + + if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) { + mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor + mainView.idTextField.layer.borderWidth = 0.7 + + mainView.idInvalidLabel.isHidden = false + mainView.idInvalidLabel.snp.remakeConstraints { + $0.leading.equalTo(mainView.idTextField.snp.leading) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5) + } + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30) + $0.leading.trailing.equalToSuperview().inset(20) + } + } else { + mainView.idTextField.layer.borderWidth = 0 + + mainView.idInvalidLabel.isHidden = true + + mainView.passwordTextField.snp.remakeConstraints { + $0.height.equalTo(52) + $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7) + $0.leading.trailing.equalToSuperview().inset(20) + } + } + } + +}
Swift
๋‹ด์—” ๋ฆฌ๋ทฐ ๋ฐ”๋กœ ๋‹ฌ๋Ÿฌ๊ฐˆ๊ฒŒ์šฉ~๐Ÿ˜‹
@@ -0,0 +1,67 @@ +import { Button, Form, Input, Select, Space } from 'antd'; +import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants'; +import useMembers from '@apis/review/useMembers'; +import { ReviewCycleRequest } from '@apis/review/type'; +import { ReviewCycle } from '@apis/review/entities'; + +interface Props { + onFinish: (values: ReviewCycleRequest) => void; + onReset: () => void; + initialValues?: { + name: ReviewCycle['name']; + reviewees: number[]; + title: ReviewCycle['question']['title']; + description: ReviewCycle['question']['description']; + }; + confirmButtonProps?: { text: string }; + deleteButtonProps?: { text: string; handleClick: () => void }; +} + +export default function ReviewCycleForm({ + onFinish, + onReset, + initialValues, + confirmButtonProps = { text: 'ํ™•์ธ' }, + deleteButtonProps, +}: Props) { + const { members, isLoading } = useMembers(); + + return ( + <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}> + <Form.Item label="๋ฆฌ๋ทฐ ์ •์ฑ… ์ด๋ฆ„" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}> + <Input /> + </Form.Item> + + <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ›๋Š” ์‚ฌ๋žŒ" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}> + <Select + mode="multiple" + loading={isLoading} + placeholder="๋ฆฌ๋ทฐ ๋ฐ›๋Š” ์‚ฌ๋žŒ์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”." + optionFilterProp="label" + options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))} + /> + </Form.Item> + + <Form.Item label="์งˆ๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}> + <Input /> + </Form.Item> + + <Form.Item + label="์งˆ๋ฌธ ์„ค๋ช…" + name={REVIEW_CYCLE_FORM_NAMES.question.description} + rules={REVIEW_CYCLE_RULES.questionDescription} + > + <Input /> + </Form.Item> + <Form.Item style={{ textAlign: 'right' }}> + <Space size={10}> + <Button htmlType="reset">์ทจ์†Œ</Button> + {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>} + <Button type="primary" htmlType="submit"> + {confirmButtonProps.text} + </Button> + </Space> + </Form.Item> + </Form> + ); +}
Unknown
์š”๊ธฐ `form`์€ ์—†์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”~
@@ -0,0 +1,67 @@ +import { Button, Form, Input, Select, Space } from 'antd'; +import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants'; +import useMembers from '@apis/review/useMembers'; +import { ReviewCycleRequest } from '@apis/review/type'; +import { ReviewCycle } from '@apis/review/entities'; + +interface Props { + onFinish: (values: ReviewCycleRequest) => void; + onReset: () => void; + initialValues?: { + name: ReviewCycle['name']; + reviewees: number[]; + title: ReviewCycle['question']['title']; + description: ReviewCycle['question']['description']; + }; + confirmButtonProps?: { text: string }; + deleteButtonProps?: { text: string; handleClick: () => void }; +} + +export default function ReviewCycleForm({ + onFinish, + onReset, + initialValues, + confirmButtonProps = { text: 'ํ™•์ธ' }, + deleteButtonProps, +}: Props) { + const { members, isLoading } = useMembers(); + + return ( + <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}> + <Form.Item label="๋ฆฌ๋ทฐ ์ •์ฑ… ์ด๋ฆ„" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}> + <Input /> + </Form.Item> + + <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ›๋Š” ์‚ฌ๋žŒ" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}> + <Select + mode="multiple" + loading={isLoading} + placeholder="๋ฆฌ๋ทฐ ๋ฐ›๋Š” ์‚ฌ๋žŒ์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”." + optionFilterProp="label" + options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))} + /> + </Form.Item> + + <Form.Item label="์งˆ๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}> + <Input /> + </Form.Item> + + <Form.Item + label="์งˆ๋ฌธ ์„ค๋ช…" + name={REVIEW_CYCLE_FORM_NAMES.question.description} + rules={REVIEW_CYCLE_RULES.questionDescription} + > + <Input /> + </Form.Item> + <Form.Item style={{ textAlign: 'right' }}> + <Space size={10}> + <Button htmlType="reset">์ทจ์†Œ</Button> + {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>} + <Button type="primary" htmlType="submit"> + {confirmButtonProps.text} + </Button> + </Space> + </Form.Item> + </Form> + ); +}
Unknown
์˜ค ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ํƒ€์ดํ•‘ ํ•˜๋ฉด `initialValues`์— ๋Œ€ํ•œ ํƒ€์ž…์„ ๋”ฐ๋กœ ๋งŒ๋“ค์–ด์ฃผ์ง€ ์•Š์•„๋„ ๋˜๊ณ  ์ข‹๋„ค์š” ๐Ÿ‘
@@ -0,0 +1,17 @@ +import { Rule } from 'antd/lib/form'; + +export const REVIEW_CYCLE_FORM_NAMES = { + name: 'name', + reviewees: 'reviewees', + question: { + title: 'title', + description: 'description', + }, +} as const; + +export const REVIEW_CYCLE_RULES: Record<string, Rule[]> = { + reviewCycleName: [{ required: true, message: '๋ฆฌ๋ทฐ ์ •์ฑ… ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.' }], + reviewees: [{ required: true, message: '๋ฆฌ๋ทฐ ๋ฐ›๋Š” ์‚ฌ๋žŒ์„ ์„ ํƒํ•˜์„ธ์š”.' }], + questionTitle: [{ required: true, message: '์งˆ๋ฌธ ์ œ๋ชฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”.' }], + questionDescription: [{ required: true, message: '์งˆ๋ฌธ ์„ค๋ช…์„ ์ž…๋ ฅํ•˜์„ธ์š”.' }], +};
TypeScript
์š”๊ธฐ ์ƒ์ˆ˜๋Š” ๋”ฐ๋กœ ๋นผ์‹  ์ด์œ ๊ฐ€ ๋ญ˜๊นŒ์š”? `Form.Item`์˜ `name` ์™ธ์—๋Š” ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ `label`์ฒ˜๋Ÿผ ๋ฐ”๋กœ ๋„ฃ์–ด๋„ ์ข‹์•„๋ณด์—ฌ์š”! ์•„๋‹ˆ๋ฉด label, name, rule์„ ํ•˜๋‚˜๋กœ ๋ฌถ์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™๊ตฌ์š”! ๊ฐ€๋ณ๊ฒŒ ๋“œ๋Š” ์ƒ๊ฐ ๋‚จ๊ฒจ๋ด…๋‹ˆ๋‹ค~
@@ -0,0 +1,90 @@ +import { API_PATH } from '@apis/constants'; +import { useQuery } from '@apis/common/useQuery'; +import { ReviewCycle } from './entities'; +import { ReviewCycleRequest, ReviewCycleResponse } from './type'; +import { useDelete, usePost, usePut } from '@apis/common/useMutation'; +import { get } from 'lodash'; + +export function useGetReviewCycles() { + const { + data, + isLoading, + mutate: refetchReviewCycle, + } = useQuery<{ reviewCycles: ReviewCycle[] }>(API_PATH.REVIEW_CYCLES); + + return { + reviewCycles: data?.reviewCycles, + isLoading, + refetchReviewCycle, + }; +} + +export function useCreateReviewCycle({ + onSuccess, + onError, +}: { + onSuccess: () => void; + onError: (message: string) => void; +}) { + const { trigger, isMutating } = usePost<ReviewCycleRequest, ReviewCycleResponse>({ + endpoint: API_PATH.REVIEW_CYCLES, + onSuccess: onSuccess, + onError: err => { + const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์‚ฌ์ดํด ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.'); + onError(errorMessage); + }, + }); + + return { + createReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle), + isMutating, + }; +} + +export function useUpdateReviewCycle({ + entityId, + onSuccess, + onError, +}: { + entityId?: number; + onSuccess: () => void; + onError: (message: string) => void; +}) { + const { trigger, isMutating } = usePut<ReviewCycleRequest, ReviewCycleResponse>({ + endpoint: entityId ? `${API_PATH.REVIEW_CYCLES}/${entityId}` : null, + onSuccess: onSuccess, + onError: err => { + const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์‚ฌ์ดํด ์ˆ˜์ •์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.'); + onError(errorMessage); + }, + }); + + return { + updateReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle), + isMutating, + }; +} + +export function useDeleteReviewCycle({ + entityId, + onSuccess, + onError, +}: { + entityId: number; + onSuccess: () => void; + onError: (message: string) => void; +}) { + const { trigger, isMutating } = useDelete({ + endpoint: `${API_PATH.REVIEW_CYCLES}/${entityId}`, + onSuccess, + onError: err => { + const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์‚ฌ์ดํด ์‚ญ์ œ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.'); + onError(errorMessage); + }, + }); + + return { + deleteReviewCycle: trigger, + isMutating, + }; +}
TypeScript
[์งˆ๋ฌธ] `trigger`๋ฅผ ๋ฐ”๋กœ ๋„˜๊ธฐ์ง€ ์•Š๊ณ  ํ•จ์ˆ˜๋กœ ๋„˜๊ฒจ์ฃผ๋Š” ์ด์œ ๋Š” ํƒ€์ž…์„ ๊ณ ์ •์‹œํ‚ค๊ธฐ ์œ„ํ•จ์ผ๊นŒ์š”?
@@ -0,0 +1,37 @@ +import useModal from 'hooks/useModal'; +import { Headline4 } from 'styles/typography'; +import ReviewCycleForm from '../ReviewCycleForm'; +import { message } from 'antd'; +import { useCreateReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles'; + +function useReviewCycleCreateModal() { + const modal = useModal(); + + const { refetchReviewCycle } = useGetReviewCycles(); + const { createReviewCycle } = useCreateReviewCycle({ + onSuccess: () => { + message.success('์ƒˆ๋กœ์šด ๋ฆฌ๋ทฐ ์ •์ฑ…์„ ์ƒ์„ฑํ–ˆ์–ด์š”.'); + modal.close(); + refetchReviewCycle(); + }, + onError: message.error, + }); + + function render() { + return modal.render({ + title: <Headline4>์ƒˆ๋กœ์šด ๋ฆฌ๋ทฐ ์ •์ฑ… ๋งŒ๋“ค๊ธฐ</Headline4>, + visible: modal.visible, + children: ( + <ReviewCycleForm onFinish={createReviewCycle} onReset={modal.close} confirmButtonProps={{ text: '์ƒ์„ฑํ•˜๊ธฐ' }} /> + ), + }); + } + + return { + render, + open: modal.open, + close: modal.close, + }; +} + +export default useReviewCycleCreateModal;
Unknown
์š”๋Ÿฐ ์‹์œผ๋กœ ๊ธฐ์กด `modal`์„ ํ™•์žฅํ•˜๋Š” ํ›…์œผ๋กœ ๋งŒ๋“ค์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”~ ```suggestion return { ...modal, render, }; ```
@@ -0,0 +1,25 @@ +import { DeleteOutlined } from '@ant-design/icons'; +import { useDeleteReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles'; +import { message } from 'antd'; + +function DeleteButton({ entityId }: { entityId: number }) { + const { refetchReviewCycle } = useGetReviewCycles(); + const { deleteReviewCycle } = useDeleteReviewCycle({ + entityId, + onSuccess: refetchReviewCycle, + onError: message.error, + }); + + return ( + <button + onClick={e => { + e.stopPropagation(); + deleteReviewCycle(); + }} + > + <DeleteOutlined /> + </button> + ); +} + +export default DeleteButton;
Unknown
[์งˆ๋ฌธ] `e.stopPropagation()`์˜ ์˜๋„๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”?